I am working on the file "0.20/_downloads/e6e21719275dd1fe5b070e9c49c33bc5/plot_forward.ipynb".
The first task is:
To compute a volume based source space defined with a grid of candidate
dipoles inside a sphere of radius 90mm centered at (0.0, 0.0, 40.0) mm
you can use the following code.
Obviously here, the sphere is not perfect. It is not restricted to the
brain and it can miss some parts of the cortex.
Can you write Python code for it?

sphere = (0.0, 0.0, 0.04, 0.09)
vol_src = mne.setup_volume_source_space(subject, subjects_dir=subjects_dir,
                                        sphere=sphere, sphere_units='m')
print(vol_src)

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


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

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

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


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

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


I am working on the file "0.20/_downloads/e6e21719275dd1fe5b070e9c49c33bc5/plot_forward.ipynb".
The first task is:
Visualizing the coregistration
The coregistration is the operation that allows to position the head and the
sensors in a common coordinate system. In the MNE software the transformation
to align the head and the sensors in stored in a so-called trans file.
It is a FIF file that ends with -trans.fif. It can be obtained with
:func:mne.gui.coregistration (or its convenient command line
equivalent gen_mne_coreg), or mrilab if you're using a Neuromag
system.
Here we assume the coregistration is done, so we just visually check the
alignment with the following code.
Can you write Python code for it?

# The transformation file obtained by coregistration
trans = data_path + '/MEG/sample/sample_audvis_raw-trans.fif'

info = mne.io.read_info(raw_fname)
# Here we look at the dense head, which isn't used for BEM computations but
# is useful for coregistration.
mne.viz.plot_alignment(info, trans, subject=subject, dig=True,
                       meg=['helmet', 'sensors'], subjects_dir=subjects_dir,
                       surfaces='head-dense')


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

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


I am working on the file "0.20/_downloads/e6f2b45ae501bec73cddc70f08093041/plot_40_visualize_raw.ipynb".
The first task is:
Built-in plotting methods for Raw objects
This tutorial shows how to plot continuous data as a time series, how to plot
the spectral density of continuous data, and how to plot the sensor locations
and projectors stored in :class:~mne.io.Raw objects.
   :depth: 2
As usual we'll start by importing the modules we need, loading some
example data <sample-dataset>, and cropping the :class:~mne.io.Raw
object to just 60 seconds before loading it into RAM to save memory:
Can you write Python code for it?

import os
import mne

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


I am working on the file "0.20/_downloads/e6f2b45ae501bec73cddc70f08093041/plot_40_visualize_raw.ipynb".
The first task is:
If the data have been filtered, vertical dashed lines will automatically
indicate filter boundaries. The spectrum for each channel type is drawn in
its own subplot; here we've passed the average=True parameter to get a
summary for each channel type, but it is also possible to plot each channel
individually, with options for how the spectrum should be computed,
color-coding the channels by location, and more. For example, here is a plot
of just a few sensors (specified with the picks parameter), color-coded
by spatial location (via the spatial_colors parameter, see the
documentation of :meth:~mne.io.Raw.plot_psd for full details):
Can you write Python code for it?

midline = ['EEG 002', 'EEG 012', 'EEG 030', 'EEG 048', 'EEG 058', 'EEG 060']
raw.plot_psd(picks=midline)


I am working on the file "0.20/_downloads/e6f2b45ae501bec73cddc70f08093041/plot_40_visualize_raw.ipynb".
The first task is:
It may not be obvious when viewing this tutorial online, but by default, the
:meth:~mne.io.Raw.plot method generates an interactive plot window with
several useful features:

It spaces the channels equally along the y-axis.

20 channels are shown by default; you can scroll through the channels
    using the :kbd:↑ and :kbd:↓ arrow keys, or by clicking on the
    colored scroll bar on the right edge of the plot.

The number of visible channels can be adjusted by the n_channels
    parameter, or changed interactively using :kbd:page up and :kbd:page
    down keys.

You can toggle the display to "butterfly" mode (superimposing all
    channels of the same type on top of one another) by pressing :kbd:b,
    or start in butterfly mode by passing the butterfly=True parameter.

It shows the first 10 seconds of the :class:~mne.io.Raw object.

You can shorten or lengthen the window length using :kbd:home and
    :kbd:end keys, or start with a specific window duration by passing the
    duration parameter.

You can scroll in the time domain using the :kbd:← and
    :kbd:→ arrow keys, or start at a specific point by passing the
    start parameter. Scrolling using :kbd:shift:kbd:→ or
    :kbd:shift:kbd:← scrolls a full window width at a time.

It allows clicking on channels to mark/unmark as "bad".

When the plot window is closed, the :class:~mne.io.Raw object's
    info attribute will be updated, adding or removing the newly
    (un)marked channels to/from the :class:~mne.Info object's bads
    field (A.K.A. raw.info['bads']).

.. TODO: discuss annotation snapping in the below bullets

It allows interactive :term:annotation <annotations> of the raw data.

This allows you to mark time spans that should be excluded from future
    computations due to large movement artifacts, line noise, or other
    distortions of the signal. Annotation mode is entered by pressing
    :kbd:a. See annotations-tutorial for details.

It automatically applies any :term:projectors <projector> before plotting
  the...
Can you write Python code for it?


I am working on the file "0.20/_downloads/e6f2b45ae501bec73cddc70f08093041/plot_40_visualize_raw.ipynb".
The first task is:
Plotting projectors from Raw objects
As seen in the output of :meth:mne.io.read_raw_fif above, there are
:term:projectors <projector> included in the example :class:~mne.io.Raw
file (representing environmental noise in the signal, so it can later be
"projected out" during preprocessing). You can visualize these projectors
using the :meth:~mne.io.Raw.plot_projs_topomap method. By default it will
show one figure per channel type for which projectors are present, and each
figure will have one subplot per projector. The three projectors in this file
were only computed for magnetometers, so one figure with three subplots is
generated. More details on working with and plotting projectors are given in
tut-projectors-background and tut-artifact-ssp.
Can you write Python code for it?


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


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

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

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


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


I am working on the file "0.20/_downloads/e71fac7e5d7784759a26529dd6e63da5/plot_whitened.ipynb".
The first task is:
Evoked data with scaled whitening
The :meth:mne.Evoked.plot_white function takes an additional step of
scaling the whitened plots to show how well the assumption of Gaussian
noise is satisfied by the data:
Can you write Python code for it?


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

evoked = epochs.average()
evoked.plot(time_unit='s')
evoked.plot(noise_cov=noise_cov, time_unit='s')


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

import mne
from mne.datasets import sample


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

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


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

fig, ax = plt.subplots(1)
im = ax.matshow(scores, vmin=0, vmax=1., cmap='RdBu_r', origin='lower',
                extent=epochs.times[[0, -1, 0, -1]])
ax.axhline(0., color='k')
ax.axvline(0., color='k')
ax.xaxis.set_ticks_position('bottom')
ax.set_xlabel('Testing Time (s)')
ax.set_ylabel('Training Time (s)')
ax.set_title('Generalization across time and condition')
plt.colorbar(im, ax=ax)
plt.show()


I am working on the file "0.20/_downloads/ea5d011661d60a36b1834dbd1af606a4/plot_decoding_spatio_temporal_source.ipynb".
The first task is:
Compute inverse solution
Can you write Python code for it?

snr = 3.0
noise_cov = mne.read_cov(fname_cov)
inverse_operator = read_inverse_operator(fname_inv)

stcs = apply_inverse_epochs(epochs, inverse_operator,
                            lambda2=1.0 / snr ** 2, verbose=False,
                            method="dSPM", pick_ori="normal")


I am working on the file "0.20/_downloads/ea5d011661d60a36b1834dbd1af606a4/plot_decoding_spatio_temporal_source.ipynb".
The first task is:
Decoding in sensor space using a logistic regression
Can you write Python code for it?

# Retrieve source space data into an array
X = np.array([stc.lh_data for stc in stcs])  # only keep left hemisphere
y = epochs.events[:, 2]

# prepare a series of classifier applied at each time sample
clf = make_pipeline(StandardScaler(),  # z-score normalization
                    SelectKBest(f_classif, k=500),  # select features for speed
                    LinearModel(LogisticRegression(C=1, solver='liblinear')))
time_decod = SlidingEstimator(clf, scoring='roc_auc')

# Run cross-validated decoding analyses:
scores = cross_val_multiscore(time_decod, X, y, cv=5, n_jobs=1)

# Plot average decoding scores of 5 splits
fig, ax = plt.subplots(1)
ax.plot(epochs.times, scores.mean(0), label='score')
ax.axhline(.5, color='k', linestyle='--', label='chance')
ax.axvline(0, color='k')
plt.legend()


I am working on the file "0.20/_downloads/ea5d011661d60a36b1834dbd1af606a4/plot_decoding_spatio_temporal_source.ipynb".
The first task is:
Decoding source space data
Decoding to MEG data in source space on the left cortical surface. Here
univariate feature selection is employed for speed purposes to confine the
classification to a small number of potentially relevant features. The
classifier then is trained to selected features of epochs in source space.
Can you write Python code for it?

# Author: Denis A. Engemann <denis.engemann@gmail.com>
#         Alexandre Gramfort <alexandre.gramfort@inria.fr>
#         Jean-Remi King <jeanremi.king@gmail.com>
#         Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression

import mne
from mne.minimum_norm import apply_inverse_epochs, read_inverse_operator
from mne.decoding import (cross_val_multiscore, LinearModel, SlidingEstimator,
                          get_coef)

print(__doc__)

data_path = mne.datasets.sample.data_path()
fname_fwd = data_path + 'MEG/sample/sample_audvis-meg-oct-6-fwd.fif'
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
subjects_dir = data_path + '/subjects'


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

raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
fname_cov = data_path + '/MEG/sample/sample_audvis-cov.fif'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'

tmin, tmax = -0.2, 0.8
event_id = dict(aud_r=2, vis_r=4)  # load contra-lateral conditions

# Setup for reading the raw data
raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.filter(None, 10., fir_design='firwin')
events = mne.read_events(event_fname)

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

# Read epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    picks=picks, baseline=(None, 0), preload=True,
                    reject=dict(grad=4000e-13, eog=150e-6),
                    decim=5)  # decimate to save memory and increase speed


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

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


I am working on the file "0.20/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
Converting from optical density to haemoglobin
Next we convert the optical density data to haemoglobin concentration using
the modified Beer-Lambert law.
Can you write Python code for it?

raw_haemo = mne.preprocessing.nirs.beer_lambert_law(raw_od)
raw_haemo.plot(n_channels=len(raw_haemo.ch_names), duration=500)


I am working on the file "0.20/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
Converting from raw intensity to optical density
The raw intensity values are then converted to optical density.
Can you write Python code for it?

raw_od = mne.preprocessing.nirs.optical_density(raw_intensity)
raw_od.plot(n_channels=len(raw_od.ch_names), duration=500)


I am working on the file "0.20/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
Evaluating the quality of the data
At this stage we can quantify the quality of the coupling
between the scalp and the optodes using the scalp coupling index. This
method looks at the presence of a prominent synchronous signal in the
frequency range of cardiac signals across both photodetected signals.
As this data is clean and the coupling is good for all channels we will
not mark any channels as bad based on the scalp coupling index.
Can you write Python code for it?

sci = mne.preprocessing.nirs.scalp_coupling_index(raw_od)
fig, ax = plt.subplots()
ax.hist(sci)
ax.set(xlabel='Scalp Coupling Index', ylabel='Count', xlim=[0, 1])


I am working on the file "0.20/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
Next we define the range of our epochs, the rejection criteria,
baseline correction, and extract the epochs. We visualise the log of which
epochs were dropped.
Can you write Python code for it?

reject_criteria = dict(hbo=80e-6)
tmin, tmax = -5, 15

epochs = mne.Epochs(raw_haemo, events, event_id=event_dict,
                    tmin=tmin, tmax=tmax,
                    reject=reject_criteria, reject_by_annotation=True,
                    proj=True, baseline=(None, 0), preload=True,
                    detrend=None, verbose=True)
epochs.plot_drop_log()


I am working on the file "0.20/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
Plot standard fNIRS response image
Next we generate the most common visualisation of fNIRS data, plotting
both the HbO and HbR on the same figure to illustrate the relation between
the two signals.
Can you write Python code for it?

evoked_dict = {'Tapping/HbO': epochs['Tapping'].average(picks='hbo'),
               'Tapping/HbR': epochs['Tapping'].average(picks='hbr'),
               'Control/HbO': epochs['Control'].average(picks='hbo'),
               'Control/HbR': epochs['Control'].average(picks='hbr')}

# Rename channels until the encoding of frequency in ch_name is fixed
for condition in evoked_dict:
    evoked_dict[condition].rename_channels(lambda x: x[:-4])

color_dict = dict(HbO='#AA3377', HbR='b')
styles_dict = dict(Control=dict(linestyle='dashed'))

mne.viz.plot_compare_evokeds(evoked_dict, combine="mean", ci=0.95,
                             colors=color_dict, styles=styles_dict)


I am working on the file "0.20/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
View consistency of responses across channels
Similarly we can view how consistent the response was across the optode
pairs that we selected. All the channels in this data were located over the
motor cortex, and all channels show a similar pattern in the data.
Can you write Python code for it?

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(15, 6))
clims = dict(hbo=[-20, 20], hbr=[-20, 20])
epochs['Control'].average().plot_image(axes=axes[:, 0], clim=clims)
epochs['Tapping'].average().plot_image(axes=axes[:, 1], clim=clims)
for column, condition in enumerate(['Control', 'Tapping']):
    for ax in axes[:, column]:
        ax.set_title('{}: {}'.format(condition, ax.get_title()))


I am working on the file "0.20/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
View consistency of responses across trials
Now we can view the haemodynamic response for our tapping condition.
We visualise the response for both the oxy- and deoxyhaemoglobin, and
observe the expected peak in HbO at around 6 seconds consistently across
trials, and the consistent dip in HbR that is slightly delayed relative to
the HbO peak.
Can you write Python code for it?

epochs['Tapping'].plot_image(combine='mean', vmin=-30, vmax=30,
                             ts_args=dict(ylim=dict(hbo=[-15, 15],
                                                    hbr=[-15, 15])))


I am working on the file "0.20/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
View topographic representation of activity
Next we view how the topographic activity changes throughout the response.
Can you write Python code for it?

times = np.arange(-3.5, 13.2, 3.0)
topomap_args = dict(extrapolate='local')
epochs['Tapping'].average(picks='hbo').plot_joint(
    times=times, topomap_args=topomap_args)


I am working on the file "0.20/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
We can also look at the individual waveforms to see what is driving the
topographic plot above.
Can you write Python code for it?

fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(6, 4))
mne.viz.plot_evoked_topo(epochs['Left'].average(picks='hbo'), color='b',
                         axes=axes, legend=False)
mne.viz.plot_evoked_topo(epochs['Right'].average(picks='hbo'), color='r',
                         axes=axes, legend=False)

# Tidy the legend
leg_lines = [line for line in axes.lines if line.get_c() == 'b'][:1]
leg_lines.append([line for line in axes.lines if line.get_c() == 'r'][0])
fig.legend(leg_lines, ['Left', 'Right'], loc='lower right')


I am working on the file "0.20/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
We can also view the epoched data for the control condition and observe
that it does not show the expected morphology.
Can you write Python code for it?

epochs['Control'].plot_image(combine='mean', vmin=-30, vmax=30,
                             ts_args=dict(ylim=dict(hbo=[-15, 15],
                                                    hbr=[-15, 15])))


I am working on the file "0.20/_downloads/ecc882c301a68ccc90d86f64acb4e0a7/plot_stats_cluster_spatio_temporal_2samp.ipynb".
The first task is:
Visualize the clusters
Can you write Python code for it?

print('Visualizing clusters.')

#    Now let's build a convenient representation of each cluster, where each
#    cluster becomes a "time point" in the SourceEstimate
fsave_vertices = [np.arange(10242), np.arange(10242)]
stc_all_cluster_vis = summarize_clusters_stc(clu, tstep=tstep,
                                             vertices=fsave_vertices,
                                             subject='fsaverage')

#    Let's actually plot the first "time point" in the SourceEstimate, which
#    shows all the clusters, weighted by duration
subjects_dir = op.join(data_path, 'subjects')
# blue blobs are for condition A != condition B
brain = stc_all_cluster_vis.plot('fsaverage', hemi='both',
                                 views='lateral', subjects_dir=subjects_dir,
                                 time_label='temporal extent (ms)',
                                 clim=dict(kind='value', lims=[0, 1, 40]))


I am working on the file "0.20/_downloads/ee17e3e8df43ce4f0119faeeeccc374f/plot_sensors_time_frequency.ipynb".
The first task is:
Frequency and time-frequency sensors analysis
The objective is to show you how to explore the spectral content
of your data (frequency and time-frequency). Here we'll work on Epochs.
We will use this dataset: somato-dataset. It contains so-called event
related synchronizations (ERS) / desynchronizations (ERD) in the beta band.
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#          Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#          Richard Höchenberger <richard.hoechenberger@gmail.com>
#
# License: BSD (3-clause)
import os.path as op

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.time_frequency import tfr_morlet, psd_multitaper, psd_welch
from mne.datasets import somato


I am working on the file "0.20/_downloads/ee17e3e8df43ce4f0119faeeeccc374f/plot_sensors_time_frequency.ipynb".
The first task is:
Inspect ITC
Can you write Python code for it?

itc.plot_topo(title='Inter-Trial coherence', vmin=0., vmax=1., cmap='Reds')


I am working on the file "0.20/_downloads/ee17e3e8df43ce4f0119faeeeccc374f/plot_sensors_time_frequency.ipynb".
The first task is:
Inspect power

Note

The generated figures are interactive. In the topo you can click
    on an image to visualize the data for one sensor.
    You can also select a portion in the time-frequency plane to
    obtain a topomap for a certain time-frequency region.

Can you write Python code for it?

power.plot_topo(baseline=(-0.5, 0), mode='logratio', title='Average power')
power.plot([82], baseline=(-0.5, 0), mode='logratio', title=power.ch_names[82])

fig, axis = plt.subplots(1, 2, figsize=(7, 4))
power.plot_topomap(ch_type='grad', tmin=0.5, tmax=1.5, fmin=8, fmax=12,
                   baseline=(-0.5, 0), mode='logratio', axes=axis[0],
                   title='Alpha', show=False)
power.plot_topomap(ch_type='grad', tmin=0.5, tmax=1.5, fmin=13, fmax=25,
                   baseline=(-0.5, 0), mode='logratio', axes=axis[1],
                   title='Beta', show=False)
mne.viz.tight_layout()
plt.show()


I am working on the file "0.20/_downloads/ee17e3e8df43ce4f0119faeeeccc374f/plot_sensors_time_frequency.ipynb".
The first task is:
Lastly, we can also retrieve the unaggregated segments by passing
average=None to :func:mne.time_frequency.psd_welch. The dimensions of
the returned array are (n_epochs, n_sensors, n_freqs, n_segments).
Can you write Python code for it?

psds_welch_unagg, freqs_unagg = psd_welch(epochs, average=None, **kwargs)
print(psds_welch_unagg.shape)


I am working on the file "0.20/_downloads/ee17e3e8df43ce4f0119faeeeccc374f/plot_sensors_time_frequency.ipynb".
The first task is:
Notably, :func:mne.time_frequency.psd_welch supports the keyword argument
average, which specifies how to estimate the PSD based on the individual
windowed segments. The default is average='mean', which simply calculates
the arithmetic mean across segments. Specifying average='median', in
contrast, returns the PSD based on the median of the segments (corrected for
bias relative to the mean), which is a more robust measure.
Can you write Python code for it?

# Estimate PSDs based on "mean" and "median" averaging for comparison.
kwargs = dict(fmin=2, fmax=40, n_jobs=1)
psds_welch_mean, freqs_mean = psd_welch(epochs, average='mean', **kwargs)
psds_welch_median, freqs_median = psd_welch(epochs, average='median', **kwargs)

# Convert power to dB scale.
psds_welch_mean = 10 * np.log10(psds_welch_mean)
psds_welch_median = 10 * np.log10(psds_welch_median)

# We will only plot the PSD for a single sensor in the first epoch.
ch_name = 'MEG 0122'
ch_idx = epochs.info['ch_names'].index(ch_name)
epo_idx = 0

_, ax = plt.subplots()
ax.plot(freqs_mean, psds_welch_mean[epo_idx, ch_idx, :], color='k',
        ls='-', label='mean of segments')
ax.plot(freqs_median, psds_welch_median[epo_idx, ch_idx, :], color='k',
        ls='--', label='median of segments')

ax.set(title='Welch PSD ({}, Epoch {})'.format(ch_name, epo_idx),
       xlabel='Frequency (Hz)', ylabel='Power Spectral Density (dB)')
ax.legend(loc='upper right')
plt.show()


I am working on the file "0.20/_downloads/ee17e3e8df43ce4f0119faeeeccc374f/plot_sensors_time_frequency.ipynb".
The first task is:
Time-frequency analysis: power and inter-trial coherence
We now compute time-frequency representations (TFRs) from our Epochs.
We'll look at power and inter-trial coherence (ITC).
To this we'll use the function :func:mne.time_frequency.tfr_morlet
but you can also use :func:mne.time_frequency.tfr_multitaper
or :func:mne.time_frequency.tfr_stockwell.
Can you write Python code for it?

# define frequencies of interest (log-spaced)
freqs = np.logspace(*np.log10([6, 35]), num=8)
n_cycles = freqs / 2.  # different number of cycle per frequency
power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True,
                        return_itc=True, decim=3, n_jobs=1)


I am working on the file "0.20/_downloads/eea7e38645d4176f944e2f8d02a34fde/plot_run_ica.ipynb".
The first task is:
Compute ICA components on epochs
ICA is fit to MEG raw data.
We assume that the non-stationary EOG artifacts have already been removed.
The sources matching the ECG are automatically found and displayed.

Note

This example does quite a bit of processing, so even on a
          fast machine it can take about a minute to complete.

Can you write Python code for it?

# Authors: Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)

import mne
from mne.preprocessing import ICA, create_ecg_epochs
from mne.datasets import sample

print(__doc__)


I am working on the file "0.20/_downloads/eea7e38645d4176f944e2f8d02a34fde/plot_run_ica.ipynb".
The first task is:
Fit ICA model using the FastICA algorithm, detect and plot components
explaining ECG artifacts.
Can you write Python code for it?

ica = ICA(n_components=0.95, method='fastica').fit(epochs)

ecg_epochs = create_ecg_epochs(raw, tmin=-.5, tmax=.5)
ecg_inds, scores = ica.find_bads_ecg(ecg_epochs)

ica.plot_components(ecg_inds)


I am working on the file "0.20/_downloads/eea7e38645d4176f944e2f8d02a34fde/plot_run_ica.ipynb".
The first task is:
Plot properties of ECG components:
Can you write Python code for it?


I am working on the file "0.20/_downloads/eea7e38645d4176f944e2f8d02a34fde/plot_run_ica.ipynb".
The first task is:
Read and preprocess the data. Preprocessing consists of:

MEG channel selection
1-30 Hz band-pass filter
epoching -0.2 to 0.5 seconds with respect to events
Can you write Python code for it?

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

raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.pick_types(meg=True, eeg=False, exclude='bads', stim=True)
raw.filter(1, 30, fir_design='firwin')

# longer + more epochs for more artifact exposure
events = mne.find_events(raw, stim_channel='STI 014')
epochs = mne.Epochs(raw, events, event_id=None, tmin=-0.2, tmax=0.5)


I am working on the file "0.20/_downloads/ef81cbafce45c79dbfcdf37970a37c57/plot_source_space_snr.ipynb".
The first task is:
MEG
Finally we do this for MEG:
Can you write Python code for it?

evoked_meg = evoked.copy().pick_types(eeg=False, meg=True)
inv_op_meg = make_inverse_operator(evoked_meg.info, fwd, cov, fixed=True,
                                   verbose=True)
stc_meg = apply_inverse(evoked_meg, inv_op_meg, lambda2, 'MNE', verbose=True)
snr_stc_meg = stc_meg.estimate_snr(evoked_meg.info, fwd, cov)
snr_stc_meg.plot(**kwargs)


I am working on the file "0.20/_downloads/ef89d1f7daeb4e357098461753c3af0f/plot_source_alignment.ipynb".
The first task is:
Coordinate frame definitions
.. raw:: html
<style>
   .pink {color:DarkSalmon; font-weight:bold}
   .blue {color:DeepSkyBlue; font-weight:bold}
   .gray {color:Gray; font-weight:bold}
   .magenta {color:Magenta; font-weight:bold}
   .purple {color:Indigo; font-weight:bold}
   .green {color:LimeGreen; font-weight:bold}
   .red {color:Red; font-weight:bold}
   </style>

.. role:: pink
.. role:: blue
.. role:: gray
.. role:: magenta
.. role:: purple
.. role:: green
.. role:: red

Neuromag/Elekta/MEGIN head coordinate frame ("head", :pink:pink axes)
     The head coordinate frame is defined through the coordinates of
     anatomical landmarks on the subject's head: Usually the Nasion (NAS),
     and the left and right preauricular points (LPA and RPA).
     Different MEG manufacturers may have different definitions of the
     coordinate head frame. A good overview can be seen in the
     FieldTrip FAQ on coordinate systems.
For Neuromag/Elekta/MEGIN, the head coordinate frame is defined by the
 intersection of

the line between the LPA (:red:red sphere) and RPA
    (:purple:purple sphere), and
the line perpendicular to this LPA-RPA line one that goes through
    the Nasion (:green:green sphere).

The axes are oriented as X origin→RPA, Y origin→NAS,
 Z origin→upward (orthogonal to X and Y).
.. note:: The required 3D coordinates for defining the head coordinate
           frame (NAS, LPA, RPA) are measured at a stage separate from
           the MEG data recording. There exist numerous devices to
           perform such measurements, usually called "digitizers". For
           example, see the devices by the company Polhemus_.

MEG device coordinate frame ("meg", :blue:blue axes)
     The MEG device coordinate frame is defined by the respective MEG
     manufacturers. All MEG data is acquired with respect to this coordinate
     frame. To account for the anatomy and position of the subject's head, we
     use so-called head position indicator (HPI) coils. The HPI coils are
     placed at known locations on the...
Can you write Python code for it?

mne.viz.plot_alignment(raw.info, trans=None, subject='sample', src=src,
                       subjects_dir=subjects_dir, dig=True,
                       surfaces=['head-dense', 'white'], coord_frame='meg')


I am working on the file "0.20/_downloads/ef89d1f7daeb4e357098461753c3af0f/plot_source_alignment.ipynb".
The first task is:
Defining the head↔MRI trans using the GUI
You can try creating the head↔MRI transform yourself using
:func:mne.gui.coregistration.

First you must load the digitization data from the raw file
  (Head Shape Source). The MRI data is already loaded if you provide the
  subject and subjects_dir. Toggle Always Show Head Points to see
  the digitization points.
To set the landmarks, toggle Edit radio button in MRI Fiducials.
Set the landmarks by clicking the radio button (LPA, Nasion, RPA) and then
  clicking the corresponding point in the image.
After doing this for all the landmarks, toggle Lock radio button. You
  can omit outlier points, so that they don't interfere with the finetuning.

.. note:: You can save the fiducials to a file and pass
            mri_fiducials=True to plot them in
            :func:mne.viz.plot_alignment. The fiducials are saved to the
            subject's bem folder by default.
* Click Fit Head Shape. This will align the digitization points to the
  head surface. Sometimes the fitting algorithm doesn't find the correct
  alignment immediately. You can try first fitting using LPA/RPA or fiducials
  and then align according to the digitization. You can also finetune
  manually with the controls on the right side of the panel.
* Click Save As... (lower right corner of the panel), set the filename
  and read it with :func:mne.read_trans.
For more information, see step by step instructions
in these slides
<https://www.slideshare.net/mne-python/mnepython-coregistration>_.
Uncomment the following line to align the data yourself.
Can you write Python code for it?


I am working on the file "0.20/_downloads/f01121873dbae065a1740e6c0c20d1d5/plot_eeg_no_mri.ipynb".
The first task is:
Load the data
We use here EEG data from the BCI dataset.

Note

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

Can you write Python code for it?

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

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

# Read and set the EEG electrode locations
montage = mne.channels.make_standard_montage('standard_1005')

raw.set_montage(montage)
raw.set_eeg_reference(projection=True)  # needed for inverse modeling

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


I am working on the file "0.20/_downloads/f01121873dbae065a1740e6c0c20d1d5/plot_eeg_no_mri.ipynb".
The first task is:
Setup source space and compute forward
Can you write Python code for it?

fwd = mne.make_forward_solution(raw.info, trans=trans, src=src,
                                bem=bem, eeg=True, mindist=5.0, n_jobs=1)
print(fwd)

# for illustration purposes use fwd to compute the sensitivity map
eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed')
eeg_map.plot(time_label='EEG sensitivity', subjects_dir=subjects_dir,
             clim=dict(lims=[5, 50, 100]))


I am working on the file "0.20/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Average the source estimates within each label of the cortical parcellation
and each sub structure contained in the src space
Can you write Python code for it?

src = inverse_operator['src']

label_ts = mne.extract_label_time_course(
    [stc], labels_parc, src, mode='mean', allow_empty=True)

# plot the times series of 2 labels
fig, axes = plt.subplots(1)
axes.plot(1e3 * stc.times, label_ts[0][0, :], 'k', label='bankssts-lh')
axes.plot(1e3 * stc.times, label_ts[0][71, :].T, 'r', label='Brain-stem')
axes.set(xlabel='Time (ms)', ylabel='MNE current (nAm)')
axes.legend()
mne.viz.tight_layout()


I am working on the file "0.20/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Compute MNE inverse solution on evoked data in a mixed source space
Create a mixed source space and compute MNE inverse solution on an
evoked dataset.
Can you write Python code for it?

# Author: Annalisa Pascarella <a.pascarella@iac.cnr.it>
#
# License: BSD (3-clause)

import os.path as op
import matplotlib.pyplot as plt

from nilearn import plotting

import mne
from mne.minimum_norm import make_inverse_operator, apply_inverse

# Set dir
data_path = mne.datasets.sample.data_path()
subject = 'sample'
data_dir = op.join(data_path, 'MEG', subject)
subjects_dir = op.join(data_path, 'subjects')
bem_dir = op.join(subjects_dir, subject, 'bem')

# Set file names
fname_mixed_src = op.join(bem_dir, '%s-oct-6-mixed-src.fif' % subject)
fname_aseg = op.join(subjects_dir, subject, 'mri', 'aseg.mgz')

fname_model = op.join(bem_dir, '%s-5120-bem.fif' % subject)
fname_bem = op.join(bem_dir, '%s-5120-bem-sol.fif' % subject)

fname_evoked = data_dir + '/sample_audvis-ave.fif'
fname_trans = data_dir + '/sample_audvis_raw-trans.fif'
fname_fwd = data_dir + '/sample_audvis-meg-oct-6-mixed-fwd.fif'
fname_cov = data_dir + '/sample_audvis-shrunk-cov.fif'


I am working on the file "0.20/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Set up our source space.
Can you write Python code for it?

# List substructures we are interested in. We select only the
# sub structures we want to include in the source space
labels_vol = ['Left-Amygdala',
              'Left-Thalamus-Proper',
              'Left-Cerebellum-Cortex',
              'Brain-Stem',
              'Right-Amygdala',
              'Right-Thalamus-Proper',
              'Right-Cerebellum-Cortex']

# Get a surface-based source space, here with few source points for speed
# in this demonstration, in general you should use oct6 spacing!
src = mne.setup_source_space(subject, spacing='oct5',
                             add_dist=False, subjects_dir=subjects_dir)

# Now we create a mixed src space by adding the volume regions specified in the
# list labels_vol. First, read the aseg file and the source space bounds
# using the inner skull surface (here using 10mm spacing to save time,
# we recommend something smaller like 5.0 in actual analyses):

vol_src = mne.setup_volume_source_space(
    subject, mri=fname_aseg, pos=10.0, bem=fname_model,
    volume_label=labels_vol, subjects_dir=subjects_dir,
    add_interpolator=False,  # just for speed, usually this should be True
    verbose=True)

# Generate the mixed source space
src += vol_src

# Visualize the source space.
src.plot(subjects_dir=subjects_dir)

n = sum(src[i]['nuse'] for i in range(len(src)))
print('the src space contains %d spaces and %d points' % (len(src), n))


I am working on the file "0.20/_downloads/f4e0fde886a45c1a46537066c93815f1/plot_parcellation.ipynb".
The first task is:
Plot a cortical parcellation
In this example, we download the HCP-MMP1.0 parcellation [1] and show it
on fsaverage.
We will also download the customized 448-label aparc parcellation from [2]

Note

The HCP-MMP dataset has license terms restricting its use.
          Of particular relevance:

              "I will acknowledge the use of WU-Minn HCP data and data
              derived from WU-Minn HCP data when publicly presenting any
              results or algorithms that benefitted from their use."

References
.. [1] Glasser MF et al. (2016) A multi-modal parcellation of human
       cerebral cortex. Nature 536:171-178.
.. [2] Khan S et al. (2018) Maturation trajectories of cortical
       resting-state networks depend on the mediating frequency band.
       Neuroimage 174 57-68.
Can you write Python code for it?

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

from surfer import Brain

import mne

subjects_dir = mne.datasets.sample.data_path() + '/subjects'
mne.datasets.fetch_hcp_mmp_parcellation(subjects_dir=subjects_dir,
                                        verbose=True)

mne.datasets.fetch_aparc_sub_parcellation(subjects_dir=subjects_dir,
                                          verbose=True)

labels = mne.read_labels_from_annot(
    'fsaverage', 'HCPMMP1', 'lh', subjects_dir=subjects_dir)

brain = Brain('fsaverage', 'lh', 'inflated', subjects_dir=subjects_dir,
              cortex='low_contrast', background='white', size=(800, 600))
brain.add_annotation('HCPMMP1')
aud_label = [label for label in labels if label.name == 'L_A1_ROI-lh'][0]
brain.add_label(aud_label, borders=False)


I am working on the file "0.20/_downloads/f4e0fde886a45c1a46537066c93815f1/plot_parcellation.ipynb".
The first task is:
We can add another custom parcellation
Can you write Python code for it?

brain = Brain('fsaverage', 'lh', 'inflated', subjects_dir=subjects_dir,
              cortex='low_contrast', background='white', size=(800, 600))
brain.add_annotation('aparc_sub')


I am working on the file "0.20/_downloads/f5f9bdd06f90122e3e9f099984de196a/plot_evoked_topomap.ipynb".
The first task is:
Basic plot_topomap options
We plot evoked topographies using :func:mne.Evoked.plot_topomap. The first
argument, times allows to specify time instants (in seconds!) for which
topographies will be shown. We select timepoints from 50 to 150 ms with a
step of 20ms and plot magnetometer data:
Can you write Python code for it?

times = np.arange(0.05, 0.151, 0.02)
evoked.plot_topomap(times, ch_type='mag', time_unit='s')


I am working on the file "0.20/_downloads/f5f9bdd06f90122e3e9f099984de196a/plot_evoked_topomap.ipynb".
The first task is:
If you look at the edges of the head circle of a single topomap you'll see
the effect of extrapolation. By default extrapolate='box' is used which
extrapolates to a large box stretching beyond the head circle.
Compare this with extrapolate='head' (second topography below) where
extrapolation goes to 0 at the head circle and extrapolate='local' where
extrapolation is performed only within some distance from channels:
Can you write Python code for it?

extrapolations = ['box', 'head', 'local']
fig, axes = plt.subplots(figsize=(7.5, 2.5), ncols=3)

# Here we look at EEG channels, and use a custom head sphere to get all the
# sensors to be well within the drawn head surface
for ax, extr in zip(axes, extrapolations):
    evoked.plot_topomap(0.1, ch_type='eeg', size=2, extrapolate=extr, axes=ax,
                        show=False, colorbar=False, sphere=(0., 0., 0., 0.09))
    ax.set_title(extr, fontsize=14)


I am working on the file "0.20/_downloads/f5f9bdd06f90122e3e9f099984de196a/plot_evoked_topomap.ipynb".
The first task is:
More advanced usage
Now we plot magnetometer data as topomap at a single time point: 100 ms
post-stimulus, add channel labels, title and adjust plot margins:
Can you write Python code for it?

evoked.plot_topomap(0.1, ch_type='mag', show_names=True, colorbar=False,
                    size=6, res=128, title='Auditory response',
                    time_unit='s', extrapolate='local', border='mean')
plt.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.88)


I am working on the file "0.20/_downloads/f5f9bdd06f90122e3e9f099984de196a/plot_evoked_topomap.ipynb".
The first task is:
We can plot gradiometer data (plots the RMS for each pair of gradiometers)
Can you write Python code for it?


I am working on the file "0.20/_downloads/f760cc2f1a5d6c625b1e14a0b05176dd/plot_ecog.ipynb".
The first task is:
Sometimes it is useful to make a scatterplot for the current figure view.
This is best accomplished with matplotlib. We can capture an image of the
current mayavi view, along with the xy position of each electrode, with the
snapshot_brain_montage function.
Can you write Python code for it?

# We'll once again plot the surface, then take a snapshot.
fig_scatter = plot_alignment(info, subject='sample', subjects_dir=subjects_dir,
                             surfaces='pial')
mne.viz.set_3d_view(fig_scatter, 200, 70)
xy, im = snapshot_brain_montage(fig_scatter, montage)

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

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

# This allows us to use matplotlib to create arbitrary 2d scatterplots
_, ax = plt.subplots(figsize=(10, 10))
ax.imshow(im)
ax.scatter(*xy_pts.T, c=activity, s=200, cmap='coolwarm')
ax.set_axis_off()
plt.show()


I am working on the file "0.20/_downloads/f760cc2f1a5d6c625b1e14a0b05176dd/plot_ecog.ipynb".
The first task is:
We can then plot the locations of our electrodes on our subject's brain.

Note

These are not real electrodes for this subject, so they
          do not align to the cortical surface perfectly.

Can you write Python code for it?

subjects_dir = mne.datasets.sample.data_path() + '/subjects'
fig = plot_alignment(info, subject='sample', subjects_dir=subjects_dir,
                     surfaces=['pial'])
mne.viz.set_3d_view(fig, 200, 70)


I am working on the file "0.20/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:
Creating :class:~mne.Epochs objects
To create an :class:mne.Epochs object from scratch, you can use the
:class:mne.EpochsArray class, which uses a numpy array directly without
wrapping a raw object. The array must be of shape(n_epochs, n_chans,
n_times). The proper units of measure are listed above.
Can you write Python code for it?

# Generate some random data: 10 epochs, 5 channels, 2 seconds per epoch
sfreq = 100
data = np.random.randn(10, 5, sfreq * 2)

# Initialize an info structure
info = mne.create_info(
    ch_names=['MEG1', 'MEG2', 'EEG1', 'EEG2', 'EOG'],
    ch_types=['grad', 'grad', 'eeg', 'eeg', 'eog'],
    sfreq=sfreq)


I am working on the file "0.20/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:
Creating :class:~mne.Evoked Objects
If you already have data that is collapsed across trials, you may also
directly create an evoked array.  Its constructor accepts an array of
shape(n_chans, n_times) in addition to some bookkeeping parameters.
The proper units of measure for the data are listed above.
Can you write Python code for it?

# The averaged data
data_evoked = data.mean(0)

# The number of epochs that were averaged
nave = data.shape[0]

# A comment to describe to evoked (usually the condition name)
comment = "Smiley faces"

# Create the Evoked object
evoked_array = mne.EvokedArray(data_evoked, info, tmin,
                               comment=comment, nave=nave)
print(evoked_array)
_ = evoked_array.plot(time_unit='s')


I am working on the file "0.20/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:
Creating :class:~mne.Info objects

Note

for full documentation on the :class:`~mne.Info` object, see
          `tut-info-class`. See also `ex-array-classes`.

Normally, :class:mne.Info objects are created by the various
data import functions.
However, if you wish to create one from scratch, you can use the
:func:mne.create_info function to initialize the minimally required
fields. Further fields can be assigned later as one would with a regular
dictionary.
The following creates the absolute minimum info structure:
Can you write Python code for it?

# Create some dummy metadata
n_channels = 32
sampling_rate = 200
info = mne.create_info(n_channels, sampling_rate)
print(info)


I am working on the file "0.20/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:
Creating MNE's data structures from scratch
MNE provides mechanisms for creating various core objects directly from
NumPy arrays.
Can you write Python code for it?


I am working on the file "0.20/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:
Finally, we must specify the beginning of an epoch (the end will be inferred
from the sampling frequency and n_samples)
Can you write Python code for it?

# Trials were cut from -0.1 to 1.0 seconds
tmin = -0.1


I am working on the file "0.20/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:
More information about the event codes: subject was either smiling or
frowning
Can you write Python code for it?


I am working on the file "0.20/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:
Now we can create the :class:mne.EpochsArray object
Can you write Python code for it?

custom_epochs = mne.EpochsArray(data, info, events, tmin, event_id)

print(custom_epochs)

# We can treat the epochs object as we would any other
_ = custom_epochs['smiling'].average().plot(time_unit='s')


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

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


I am working on the file "0.20/_downloads/fd92a90eaeac818b497ef44c9c13172a/plot_eeg_csd.ipynb".
The first task is:
First let's look at how CSD affects scalp topography:
Can you write Python code for it?

times = np.array([-0.1, 0., 0.05, 0.1, 0.15])
evoked_csd = mne.preprocessing.compute_current_source_density(evoked)
evoked.plot_joint(title='Average Reference', show=False)
evoked_csd.plot_joint(title='Current Source Density')


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

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


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

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


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

# Authors: Alex Rockhill <aprockhill206@gmail.com>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()


I am working on the file "0.20/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb".
The first task is:
Compute inverse solution
Can you write Python code for it?

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


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

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

# Show whitening:
evoked.plot_white(noise_cov, time_unit='s')

del epochs, raw  # to save memory


I am working on the file "0.20/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb".
The first task is:
Dipole orientations
The pick_ori parameter of the
:func:mne.minimum_norm.apply_inverse function controls
the orientation of the dipoles. One useful setting is pick_ori='vector',
which will return an estimate that does not only contain the source power at
each dipole, but also the orientation of the dipoles.
Can you write Python code for it?

stc_vec = apply_inverse(evoked, inverse_operator, lambda2,
                        method=method, pick_ori='vector')
brain = stc_vec.plot(**surfer_kwargs)
brain.add_text(0.1, 0.9, 'Vector solution', 'title', font_size=20)
del stc_vec


I am working on the file "0.20/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb".
The first task is:
Examine the original data and the residual after fitting:
Can you write Python code for it?

fig, axes = plt.subplots(2, 1)
evoked.plot(axes=axes)
for ax in axes:
    ax.texts = []
    for line in ax.lines:
        line.set_color('#98df81')
residual.plot(axes=axes)


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

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

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


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

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

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

event_id = dict(aud_l=1)  # event trigger and conditions
tmin = -0.2  # start of each epoch (200ms before the trigger)
tmax = 0.5  # end of each epoch (500ms after the trigger)
raw.info['bads'] = ['MEG 2443', 'EEG 053']
baseline = (None, 0)  # means from the first instant to t = 0
reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)

epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    picks=('meg', 'eog'), baseline=baseline, reject=reject)


I am working on the file "0.20/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb".
The first task is:
Source localization with MNE/dSPM/sLORETA/eLORETA
The aim of this tutorial is to teach you how to compute and apply a linear
minimum-norm inverse method on evoked/raw/epochs data.
Can you write Python code for it?

import numpy as np
import matplotlib.pyplot as plt

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


I am working on the file "0.20/_downloads/ff83425ee773d1d588a6994e5560c06c/plot_mne_dspm_source_localization.ipynb".
The first task is:
Visualization
View activation time-series
Can you write Python code for it?

fig, ax = plt.subplots()
ax.plot(1e3 * stc.times, stc.data[::100, :].T)
ax.set(xlabel='time (ms)', ylabel='%s value' % method)


I am working on the file "0.21/_downloads/03c9d71de135994dbf45db72856a1f9a/plot_mne_inverse_envelope_correlation.ipynb".
The first task is:
Compute envelope correlations in source space
Compute envelope correlations of orthogonalized activity [1] [2] in source
space using resting state CTF data.
Can you write Python code for it?

# Authors: Eric Larson <larson.eric.d@gmail.com>
#          Sheraz Khan <sheraz@khansheraz.com>
#          Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)

import os.path as op

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.connectivity import envelope_correlation
from mne.minimum_norm import make_inverse_operator, apply_inverse_epochs
from mne.preprocessing import compute_proj_ecg, compute_proj_eog

data_path = mne.datasets.brainstorm.bst_resting.data_path()
subjects_dir = op.join(data_path, 'subjects')
subject = 'bst_resting'
trans = op.join(data_path, 'MEG', 'bst_resting', 'bst_resting-trans.fif')
src = op.join(subjects_dir, subject, 'bem', subject + '-oct-6-src.fif')
bem = op.join(subjects_dir, subject, 'bem', subject + '-5120-bem-sol.fif')
raw_fname = op.join(data_path, 'MEG', 'bst_resting',
                    'subj002_spontaneous_20111102_01_AUX.ds')


I am working on the file "0.21/_downloads/03c9d71de135994dbf45db72856a1f9a/plot_mne_inverse_envelope_correlation.ipynb".
The first task is:
Compute the forward and inverse
Can you write Python code for it?

src = mne.read_source_spaces(src)
fwd = mne.make_forward_solution(epochs.info, trans, src, bem)
inv = make_inverse_operator(epochs.info, fwd, cov)
del fwd, src


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

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


I am working on the file "0.21/_downloads/04c2d1e64afcdd4e5032afb2212a74e5/plot_objects_from_arrays.ipynb".
The first task is:
Create an :class:info <mne.Info> object.
Can you write Python code for it?

# It is also possible to use info from another raw object.
info = mne.create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)


I am working on the file "0.21/_downloads/04c2d1e64afcdd4e5032afb2212a74e5/plot_objects_from_arrays.ipynb".
The first task is:
Create arbitrary data
Can you write Python code for it?

sfreq = 1000  # Sampling frequency
times = np.arange(0, 10, 0.001)  # Use 10000 samples (10s)

sin = np.sin(times * 10)  # Multiplied by 10 for shorter cycles
cos = np.cos(times * 10)
sinX2 = sin * 2
cosX2 = cos * 2

# Numpy array of size 4 X 10000.
data = np.array([sin, cos, sinX2, cosX2])

# Definition of channel types and names.
ch_types = ['mag', 'mag', 'grad', 'grad']
ch_names = ['sin', 'cos', 'sinX2', 'cosX2']


I am working on the file "0.21/_downloads/04c2d1e64afcdd4e5032afb2212a74e5/plot_objects_from_arrays.ipynb".
The first task is:
Create epochs by windowing the raw data.
Can you write Python code for it?

# The events are spaced evenly every 1 second.
duration = 1.

# create a fixed size events array
# start=0 and stop=None by default
events = mne.make_fixed_length_events(raw, event_id, duration=duration)
print(events)

# for fixed size events no start time before and after event
tmin = 0.
tmax = 0.99  # inclusive tmax, 1 second epochs

# create :class:`Epochs <mne.Epochs>` object
epochs = mne.Epochs(raw, events=events, event_id=event_id, tmin=tmin,
                    tmax=tmax, baseline=None, verbose=True)
epochs.plot(scalings='auto', block=True)


I am working on the file "0.21/_downloads/063df3a44a4ac9d23978d7b307e69a4e/plot_read_evoked.ipynb".
The first task is:
Reading and writing an evoked file
This script shows how to read and write evoked datasets.
Can you write Python code for it?

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

from mne import read_evokeds
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

fname = data_path + '/MEG/sample/sample_audvis-ave.fif'

# Reading
condition = 'Left Auditory'
evoked = read_evokeds(fname, condition=condition, baseline=(None, 0),
                      proj=True)


I am working on the file "0.21/_downloads/063df3a44a4ac9d23978d7b307e69a4e/plot_read_evoked.ipynb".
The first task is:
Show result as a butterfly plot:
By using exclude=[] bad channels are not excluded and are shown in red
Can you write Python code for it?

evoked.plot(exclude=[], time_unit='s')

# Show result as a 2D image (x: time, y: channels, color: amplitude)
evoked.plot_image(exclude=[], time_unit='s')


I am working on the file "0.21/_downloads/075ba1175413b0aa0dc66e721f312729/plot_mixed_norm_inverse.ipynb".
The first task is:
Compute sparse inverse solution with mixed norm: MxNE and irMxNE
Runs an (ir)MxNE (L1/L2 [1] or L0.5/L2 [2] mixed norm) inverse solver.
L0.5/L2 is done with irMxNE which allows for sparser source estimates with less
amplitude bias due to the non-convexity of the L0.5/L2 mixed norm penalty.
Can you write Python code for it?

# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#         Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: BSD (3-clause)

import numpy as np

import mne
from mne.datasets import sample
from mne.inverse_sparse import mixed_norm, make_stc_from_dipoles
from mne.minimum_norm import make_inverse_operator, apply_inverse
from mne.viz import (plot_sparse_source_estimates,
                     plot_dipole_locations, plot_dipole_amplitudes)

print(__doc__)

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

# Read noise covariance matrix
cov = mne.read_cov(cov_fname)
# Handling average file
condition = 'Left Auditory'
evoked = mne.read_evokeds(ave_fname, condition=condition, baseline=(None, 0))
evoked.crop(tmin=0, tmax=0.3)
# Handling forward solution
forward = mne.read_forward_solution(fwd_fname)


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

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


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

ylim = dict(eeg=[-10, 10], grad=[-400, 400], mag=[-600, 600])
evoked.pick_types(meg=True, eeg=True, exclude='bads')
evoked.plot(ylim=ylim, proj=True, time_unit='s')
residual.pick_types(meg=True, eeg=True, exclude='bads')
residual.plot(ylim=ylim, proj=True, time_unit='s')


I am working on the file "0.21/_downloads/075ba1175413b0aa0dc66e721f312729/plot_mixed_norm_inverse.ipynb".
The first task is:
View in 2D and 3D ("glass" brain like 3D plot)
Can you write Python code for it?

solver = "MxNE" if n_mxne_iter == 1 else "irMxNE"
plot_sparse_source_estimates(forward['src'], stc, bgcolor=(1, 1, 1),
                             fig_name="%s (cond %s)" % (solver, condition),
                             opacity=0.1)


I am working on the file "0.21/_downloads/112f45fdd43e503d5a44dfeb8227317e/plot_read_proj.ipynb".
The first task is:
.. TODO: add this when the tutorial is up: "As shown in the tutorial
   :doc:../auto_tutorials/preprocessing/plot_projectors, ..."
The ECG projections can be loaded from a file and added to the raw object
Can you write Python code for it?

# read the projections
ecg_projs = read_proj(ecg_fname)

# add them to raw and plot everything
raw.add_proj(ecg_projs)
raw.plot_projs_topomap()


I am working on the file "0.21/_downloads/112f45fdd43e503d5a44dfeb8227317e/plot_read_proj.ipynb".
The first task is:
Load the FIF file and display the projections present in the file. Here the
projections are added to the file during the acquisition and are obtained
from empty room recordings.
Can you write Python code for it?

raw = read_raw_fif(fname)
empty_room_proj = raw.info['projs']

# Display the projections stored in `info['projs']` from the raw object
raw.plot_projs_topomap()


I am working on the file "0.21/_downloads/112f45fdd43e503d5a44dfeb8227317e/plot_read_proj.ipynb".
The first task is:
Read and visualize projections (SSP and other)
This example shows how to read and visualize Signal Subspace Projectors (SSP)
vector. Such projections are sometimes referred to as PCA projections.
Can you write Python code for it?

# Author: Joan Massich <mailsik@gmail.com>
#
# License: BSD (3-clause)

import matplotlib.pyplot as plt

import mne
from mne import read_proj
from mne.io import read_raw_fif

from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

subjects_dir = data_path + '/subjects'
fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
ecg_fname = data_path + '/MEG/sample/sample_audvis_ecg-proj.fif'


I am working on the file "0.21/_downloads/13d7770babec232baa9565e74bd766d0/plot_vector_mne_solution.ipynb".
The first task is:
Plot the activation in the direction of maximal power for this data:
Can you write Python code for it?

stc_max, directions = stc.project('pca', src=inv['src'])
# These directions must by design be close to the normals because this
# inverse was computed with loose=0.2:
print('Absolute cosine similarity between source normals and directions: '
      f'{np.abs(np.sum(directions * inv["source_nn"][2::3], axis=-1)).mean()}')
brain_max = stc_max.plot(
    initial_time=peak_time, hemi='lh', subjects_dir=subjects_dir,
    time_label='Max power')
brain_normal = stc.project('normal', inv['src'])[0].plot(
    initial_time=peak_time, hemi='lh', subjects_dir=subjects_dir,
    time_label='Normal')


I am working on the file "0.21/_downloads/142c866d928b3d3a3a76c80e0ef4ea81/plot_rereference_eeg.ipynb".
The first task is:
Re-referencing the EEG signal
This example shows how to load raw data and apply some EEG referencing schemes.
Can you write Python code for it?

# Authors: Marijn van Vliet <w.m.vanvliet@gmail.com>
#          Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)

import mne
from mne.datasets import sample
from matplotlib import pyplot as plt

print(__doc__)

# Setup for reading the raw data
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'
event_id, tmin, tmax = 1, -0.2, 0.5

# Read the raw data
raw = mne.io.read_raw_fif(raw_fname, preload=True)
events = mne.read_events(event_fname)

# The EEG channels will be plotted to visualize the difference in referencing
# schemes.
picks = mne.pick_types(raw.info, meg=False, eeg=True, eog=True, exclude='bads')


I am working on the file "0.21/_downloads/142c866d928b3d3a3a76c80e0ef4ea81/plot_rereference_eeg.ipynb".
The first task is:
We will now apply different EEG referencing schemes and plot the resulting
evoked potentials. Note that when we construct epochs with mne.Epochs, we
supply the proj=True argument. This means that any available projectors
are applied automatically. Specifically, if there is an average reference
projector set by raw.set_eeg_reference('average', projection=True), MNE
applies this projector when creating epochs.
Can you write Python code for it?

reject = dict(eog=150e-6)
epochs_params = dict(events=events, event_id=event_id, tmin=tmin, tmax=tmax,
                     picks=picks, reject=reject, proj=True)

fig, (ax1, ax2, ax3, ax4) = plt.subplots(
    nrows=4, ncols=1, sharex=True, figsize=(6, 10))

# We first want to plot the data without any added reference (i.e., using only
# the reference that was applied during recording of the data).
# However, this particular data already has an average reference projection
# applied that we now need to remove again using :func:`mne.set_eeg_reference`
raw, _ = mne.set_eeg_reference(raw, [])  # use [] to remove average projection
evoked_no_ref = mne.Epochs(raw, **epochs_params).average()

evoked_no_ref.plot(axes=ax1, titles=dict(eeg='Original reference'), show=False,
                   time_unit='s')

# Now we want to plot the data with an average reference, so let's add the
# projection we removed earlier back to the data. Note that we can use
# "set_eeg_reference" as a method on the ``raw`` object as well.
raw.set_eeg_reference('average', projection=True)
evoked_car = mne.Epochs(raw, **epochs_params).average()

evoked_car.plot(axes=ax2, titles=dict(eeg='Average reference'), show=False,
                time_unit='s')

# Re-reference from an average reference to the mean of channels EEG 001 and
# EEG 002.
raw.set_eeg_reference(['EEG 001', 'EEG 002'])
evoked_custom = mne.Epochs(raw, **epochs_params).average()

evoked_custom.plot(axes=ax3, titles=dict(eeg='Custom reference'),
                   time_unit='s', show=False)

# Re-reference using REST :footcite:`Yao2001`. To do this, we need a forward
# solution, which we can quickly create:
sphere = mne.make_sphere_model('auto', 'auto', raw.info)
src = mne.setup_volume_source_space(sphere=sphere, exclude=30.,
                                    pos=15.)  # large "pos" just for speed!
forward = mne.make_forward_solution(raw.info, trans=None, src=src, bem=sphere)
raw.set_eeg_reference('REST', forward=forward)
evoked_rest = mne.Epochs(raw,...


I am working on the file "0.21/_downloads/20f35983ef279d1b30aa970c81aafe26/plot_read_events.ipynb".
The first task is:
Events objects are essentially numpy arrays with three columns:
event_sample | previous_event_id | event_id
Can you write Python code for it?

print(events_1[:5], '\n\n---\n\n', events_1_2[:5], '\n\n')

for ind, before, after in events_1[:5]:
    print("At sample %d stim channel went from %d to %d"
          % (ind, before, after))


I am working on the file "0.21/_downloads/20f35983ef279d1b30aa970c81aafe26/plot_read_events.ipynb".
The first task is:
Reading an event file
Read events from a file. For a more detailed discussion of events in
MNE-Python, see tut-events-vs-annotations and tut-event-arrays.
Can you write Python code for it?

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

import matplotlib.pyplot as plt
import mne
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()
fname = data_path + '/MEG/sample/sample_audvis_raw-eve.fif'


I am working on the file "0.21/_downloads/20f35983ef279d1b30aa970c81aafe26/plot_read_events.ipynb".
The first task is:
Reading events
Below we'll read in an events file. We suggest that this file end in
-eve.fif. Note that we can read in the entire events file, or only
events corresponding to particular event types with the include and
exclude parameters.
Can you write Python code for it?

events_1 = mne.read_events(fname, include=1)
events_1_2 = mne.read_events(fname, include=[1, 2])
events_not_4_32 = mne.read_events(fname, exclude=[4, 32])


I am working on the file "0.21/_downloads/2212671cb1d04d466a35eb15470863da/plot_forward_sensitivity_maps.ipynb".
The first task is:
Compute sensitivity maps
Can you write Python code for it?

grad_map = mne.sensitivity_map(fwd, ch_type='grad', mode='fixed')
mag_map = mne.sensitivity_map(fwd, ch_type='mag', mode='fixed')
eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed')


I am working on the file "0.21/_downloads/2567f25ca4c6b483c12d38184d7fe9d7/plot_decoding_xdawn_eeg.ipynb".
The first task is:
The patterns_ attribute of a fitted Xdawn instance (here from the last
cross-validation fold) can be used for visualization.
Can you write Python code for it?

fig, axes = plt.subplots(nrows=len(event_id), ncols=n_filter,
                         figsize=(n_filter, len(event_id) * 2))
fitted_xdawn = clf.steps[0][1]
tmp_info = epochs.info.copy()
tmp_info['sfreq'] = 1.
for ii, cur_class in enumerate(sorted(event_id)):
    cur_patterns = fitted_xdawn.patterns_[cur_class]
    pattern_evoked = EvokedArray(cur_patterns[:n_filter].T, tmp_info, tmin=0)
    pattern_evoked.plot_topomap(
        times=np.arange(n_filter),
        time_format='Component %d' if ii == 0 else '', colorbar=False,
        show_names=False, axes=axes[ii], show=False)
    axes[ii, 0].set(ylabel=cur_class)
fig.tight_layout(h_pad=1.0, w_pad=1.0, pad=0.1)


I am working on the file "0.21/_downloads/2567f25ca4c6b483c12d38184d7fe9d7/plot_decoding_xdawn_eeg.ipynb".
The first task is:
XDAWN Decoding From EEG data
ERP decoding with Xdawn ([1], [2]). For each event type, a set of
spatial Xdawn filters are trained and applied on the signal. Channels are
concatenated and rescaled to create features vectors that will be fed into
a logistic regression.
Can you write Python code for it?

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

import numpy as np
import matplotlib.pyplot as plt

from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.preprocessing import MinMaxScaler

from mne import io, pick_types, read_events, Epochs, EvokedArray
from mne.datasets import sample
from mne.preprocessing import Xdawn
from mne.decoding import Vectorizer

print(__doc__)

data_path = sample.data_path()


I am working on the file "0.21/_downloads/2b710ad55cbf958235c0d74bf0b0d4ae/plot_evoked_ers_source_power.ipynb".
The first task is:
Plot source estimates
Can you write Python code for it?

for method, stc in zip(['DICS', 'LCMV', 'dSPM'],
                       [stc_dics, stc_lcmv, stc_dspm]):
    title = '%s source power in the 12-30 Hz frequency band' % method
    brain = stc.plot(hemi='rh', subjects_dir=subjects_dir,
                     subject=subject, time_label=title)


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

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

raw = mne.io.read_raw_fif(raw_fname)

# We are interested in the beta band (12-30 Hz)
raw.load_data().filter(12, 30)

# The DICS beamformer currently only supports a single sensor type.
# We'll use the gradiometers in this example.
picks = mne.pick_types(raw.info, meg='grad', exclude='bads')

# Read epochs
events = mne.find_events(raw)
epochs = mne.Epochs(raw, events, event_id=1, tmin=-1.5, tmax=2, picks=picks,
                    preload=True)

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

fwd = mne.read_forward_solution(fname_fwd)


I am working on the file "0.21/_downloads/2b9ae87368ee06cd9589fd87e1be1d30/plot_time_frequency_mixed_norm_inverse.ipynb".
The first task is:
Compute MxNE with time-frequency sparse prior
The TF-MxNE solver is a distributed inverse method (like dSPM or sLORETA)
that promotes focal (sparse) sources (such as dipole fitting techniques)
[1] [2]. The benefit of this approach is that:

it is spatio-temporal without assuming stationarity (sources properties
    can vary over time)
activations are localized in space, time and frequency in one step.
with a built-in filtering process based on a short time Fourier
    transform (STFT), data does not need to be low passed (just high pass
    to make the signals zero mean).
the solver solves a convex optimization problem, hence cannot be
    trapped in local minima.

References
.. [1] A. Gramfort, D. Strohmeier, J. Haueisen, M. Hämäläinen, M. Kowalski
   "Time-Frequency Mixed-Norm Estimates: Sparse M/EEG imaging with
   non-stationary source activations",
   Neuroimage, Volume 70, pp. 410-422, 15 April 2013.
   DOI: 10.1016/j.neuroimage.2012.12.051
.. [2] A. Gramfort, D. Strohmeier, J. Haueisen, M. Hämäläinen, M. Kowalski
   "Functional Brain Imaging with M/EEG Using Structured Sparsity in
   Time-Frequency Dictionaries",
   Proceedings Information Processing in Medical Imaging
   Lecture Notes in Computer Science, Volume 6801/2011, pp. 600-611, 2011.
   DOI: 10.1007/978-3-642-22092-0_49
Can you write Python code for it?

# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#         Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: BSD (3-clause)

import numpy as np

import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
from mne.inverse_sparse import tf_mixed_norm, make_stc_from_dipoles
from mne.viz import (plot_sparse_source_estimates,
                     plot_dipole_locations, plot_dipole_amplitudes)

print(__doc__)

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

# Read noise covariance matrix
cov = mne.read_cov(cov_fname)

# Handling average file
condition = 'Left visual'
evoked = mne.read_evokeds(ave_fname, condition=condition, baseline=(None, 0))
evoked = mne.pick_channels_evoked(evoked)
# We make the window slightly larger than what you'll eventually be interested
# in ([-0.05, 0.3]) to avoid edge effects.
evoked.crop(tmin=-0.1, tmax=0.4)

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


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

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


I am working on the file "0.21/_downloads/2b9ae87368ee06cd9589fd87e1be1d30/plot_time_frequency_mixed_norm_inverse.ipynb".
The first task is:
Plot location of the strongest dipole with MRI slices
Can you write Python code for it?

idx = np.argmax([np.max(np.abs(dip.amplitude)) for dip in dipoles])
plot_dipole_locations(dipoles[idx], forward['mri_head_t'], 'sample',
                      subjects_dir=subjects_dir, mode='orthoview',
                      idx='amplitude')

# # Plot dipole locations of all dipoles with MRI slices
# for dip in dipoles:
#     plot_dipole_locations(dip, forward['mri_head_t'], 'sample',
#                           subjects_dir=subjects_dir, mode='orthoview',
#                           idx='amplitude')


I am working on the file "0.21/_downloads/2b9ae87368ee06cd9589fd87e1be1d30/plot_time_frequency_mixed_norm_inverse.ipynb".
The first task is:
Run solver
Can you write Python code for it?

# alpha parameter is between 0 and 100 (100 gives 0 active source)
alpha = 40.  # general regularization parameter
# l1_ratio parameter between 0 and 1 promotes temporal smoothness
# (0 means no temporal regularization)
l1_ratio = 0.03  # temporal regularization parameter

loose, depth = 0.2, 0.9  # loose orientation & depth weighting

# Compute dSPM solution to be used as weights in MxNE
inverse_operator = make_inverse_operator(evoked.info, forward, cov,
                                         loose=loose, depth=depth)
stc_dspm = apply_inverse(evoked, inverse_operator, lambda2=1. / 9.,
                         method='dSPM')

# Compute TF-MxNE inverse solution with dipole output
dipoles, residual = tf_mixed_norm(
    evoked, forward, cov, alpha=alpha, l1_ratio=l1_ratio, loose=loose,
    depth=depth, maxit=200, tol=1e-6, weights=stc_dspm, weights_min=8.,
    debias=True, wsize=16, tstep=4, window=0.05, return_as_dipoles=True,
    return_residual=True)

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


I am working on the file "0.21/_downloads/2fc30e4810d35d643811cc11759b3b9a/plot_resample.ipynb".
The first task is:
Because resampling also affects the stim channels, some trigger onsets might
be lost in this case. While MNE attempts to downsample the stim channels in
an intelligent manner to avoid this, the recommended approach is to find
events on the original data before downsampling.
Can you write Python code for it?

print('Number of events before resampling:', len(mne.find_events(raw)))

# Resample to 100 Hz (suppress the warning that would be emitted)
raw_resampled_100 = raw.copy().resample(100, npad='auto', verbose='error')
print('Number of events after resampling:',
      len(mne.find_events(raw_resampled_100)))

# To avoid losing events, jointly resample the data and event matrix
events = mne.find_events(raw)
raw_resampled, events_resampled = raw.copy().resample(
    100, npad='auto', events=events)
print('Number of events after resampling:', len(events_resampled))


I am working on the file "0.21/_downloads/2fc30e4810d35d643811cc11759b3b9a/plot_resample.ipynb".
The first task is:
Since downsampling reduces the timing precision of events, we recommend
first extracting epochs and downsampling the Epochs object:
Can you write Python code for it?

events = mne.find_events(raw)
epochs = mne.Epochs(raw, events, event_id=2, tmin=-0.1, tmax=0.8, preload=True)

# Downsample to 100 Hz
print('Original sampling rate:', epochs.info['sfreq'], 'Hz')
epochs_resampled = epochs.copy().resample(100, npad='auto')
print('New sampling rate:', epochs_resampled.info['sfreq'], 'Hz')

# Plot a piece of data to see the effects of downsampling
plt.figure(figsize=(7, 3))

n_samples_to_plot = int(0.5 * epochs.info['sfreq'])  # plot 0.5 seconds of data
plt.plot(epochs.times[:n_samples_to_plot],
         epochs.get_data()[0, 0, :n_samples_to_plot], color='black')

n_samples_to_plot = int(0.5 * epochs_resampled.info['sfreq'])
plt.plot(epochs_resampled.times[:n_samples_to_plot],
         epochs_resampled.get_data()[0, 0, :n_samples_to_plot],
         '-o', color='red')

plt.xlabel('time (s)')
plt.legend(['original', 'downsampled'], loc='best')
plt.title('Effect of downsampling')
mne.viz.tight_layout()


I am working on the file "0.21/_downloads/2fc30e4810d35d643811cc11759b3b9a/plot_resample.ipynb".
The first task is:
When resampling epochs is unwanted or impossible, for example when the data
doesn't fit into memory or your analysis pipeline doesn't involve epochs at
all, the alternative approach is to resample the continuous data. This
can only be done on loaded or pre-loaded data.
Can you write Python code for it?

# Resample to 300 Hz
raw_resampled_300 = raw.copy().resample(300, npad='auto')


I am working on the file "0.21/_downloads/306dcf0b43a155a02804528d597e4e81/plot_roi_erpimage_by_rt.ipynb".
The first task is:
Plot single trial activity, grouped by ROI and sorted by RT
This will produce what is sometimes called an event related
potential / field (ERP/ERF) image.
The EEGLAB example file, which contains an experiment with button press
responses to simple visual stimuli, is read in and response times are
calculated.
Regions of Interest are determined by the channel types (in 10/20 channel
notation, even channels are right, odd are left, and 'z' are central). The
median and the Global Field Power within each channel group is calculated,
and the trials are plotted, sorting by response time.
Can you write Python code for it?

# Authors: Jona Sassenhagen <jona.sassenhagen@gmail.com>
#
# License: BSD (3-clause)

import mne
from mne.event import define_target_events
from mne.channels import make_1020_channel_selections

print(__doc__)


I am working on the file "0.21/_downloads/306dcf0b43a155a02804528d597e4e81/plot_roi_erpimage_by_rt.ipynb".
The first task is:
Plot using :term:Global Field Power <GFP>
Can you write Python code for it?

# Parameters for plotting
order = rts.argsort()  # sorting from fast to slow trials

selections = make_1020_channel_selections(epochs.info, midline="12z")

# The actual plots (GFP)
epochs.plot_image(group_by=selections, order=order, sigma=1.5,
                  overlay_times=rts / 1000., combine='gfp',
                  ts_args=dict(vlines=[0, rts.mean() / 1000.]))


I am working on the file "0.21/_downloads/306dcf0b43a155a02804528d597e4e81/plot_roi_erpimage_by_rt.ipynb".
The first task is:
Plot using median
Can you write Python code for it?

epochs.plot_image(group_by=selections, order=order, sigma=1.5,
                  overlay_times=rts / 1000., combine='median',
                  ts_args=dict(vlines=[0, rts.mean() / 1000.]))


I am working on the file "0.21/_downloads/30d3f995eaa317ef564a8fb6d72c22bf/plot_left_cerebellum_volume_source.ipynb".
The first task is:
Plot the positions of each source space
Can you write Python code for it?

fig = mne.viz.plot_alignment(subject=subject, subjects_dir=subjects_dir,
                             surfaces='white', coord_frame='head',
                             src=src)
mne.viz.set_3d_view(fig, azimuth=173.78, elevation=101.75,
                    distance=0.30, focalpoint=(-0.03, -0.01, 0.03))


I am working on the file "0.21/_downloads/30d3f995eaa317ef564a8fb6d72c22bf/plot_left_cerebellum_volume_source.ipynb".
The first task is:
Setup the source spaces
Can you write Python code for it?

# setup a cortical surface source space and extract left hemisphere
surf = setup_source_space(subject, subjects_dir=subjects_dir, add_dist=False)
lh_surf = surf[0]

# setup a volume source space of the left cerebellum cortex
volume_label = 'Left-Cerebellum-Cortex'
sphere = (0, 0, 0, 0.12)
lh_cereb = setup_volume_source_space(
    subject, mri=aseg_fname, sphere=sphere, volume_label=volume_label,
    subjects_dir=subjects_dir, sphere_units='m')

# Combine the source spaces
src = surf + lh_cereb


I am working on the file "0.21/_downloads/31a362832c6e14bb418b12340a063c91/plot_movement_detection.ipynb".
The first task is:
After checking the annotated movement artifacts, calculate the new transform
and plot it:
Can you write Python code for it?

new_dev_head_t = compute_average_dev_head_t(raw, head_pos)
raw.info['dev_head_t'] = new_dev_head_t
mne.viz.plot_alignment(
    raw.info, show_axes=True, subject=subject, trans=trans_fname,
    subjects_dir=subjects_dir)


I am working on the file "0.21/_downloads/31a362832c6e14bb418b12340a063c91/plot_movement_detection.ipynb".
The first task is:
Annotate movement artifacts and reestimate dev_head_t
Periods, where the participant moved considerably, are contaminated by low
amplitude artifacts. When averaging the magnetic fields, the more spread the
head position, the bigger the cancellation due to different locations.
Similarly, the covariance will also be affected by severe head movement,
and source estimation will suffer low/smeared coregistration accuracy.
This example uses the continuous head position indicators (cHPI) times series
to annotate periods of head movement, then the device to head transformation
matrix is estimated from the artifact-free segments. The new head position will
be more representative of the actual head position during the recording.
Can you write Python code for it?

# Authors: Adonay Nunes <adonay.s.nunes@gmail.com>
#          Luke Bloy <luke.bloy@gmail.com>
# License: BSD (3-clause)

import os.path as op

import mne
from mne.datasets.brainstorm import bst_auditory
from mne.io import read_raw_ctf
from mne.preprocessing import annotate_movement, compute_average_dev_head_t

# Load data
data_path = bst_auditory.data_path()
data_path_MEG = op.join(data_path, 'MEG')
subject = 'bst_auditory'
subjects_dir = op.join(data_path, 'subjects')
trans_fname = op.join(data_path, 'MEG', 'bst_auditory',
                      'bst_auditory-trans.fif')
raw_fname1 = op.join(data_path_MEG, 'bst_auditory', 'S01_AEF_20131218_01.ds')
raw_fname2 = op.join(data_path_MEG, 'bst_auditory', 'S01_AEF_20131218_02.ds')

raw = read_raw_ctf(raw_fname1, preload=False)

mne.io.concatenate_raws([raw, read_raw_ctf(raw_fname2, preload=False)])
raw.crop(350, 410).load_data()
raw.resample(100, npad="auto")


I am working on the file "0.21/_downloads/31a362832c6e14bb418b12340a063c91/plot_movement_detection.ipynb".
The first task is:
Plot continuous head position with respect to the mean recording position
Can you write Python code for it?

# get cHPI time series and compute average
chpi_locs = mne.chpi.extract_chpi_locs_ctf(raw)
head_pos = mne.chpi.compute_head_pos(raw.info, chpi_locs)
original_head_dev_t = mne.transforms.invert_transform(
    raw.info['dev_head_t'])
average_head_dev_t = mne.transforms.invert_transform(
    compute_average_dev_head_t(raw, head_pos))
fig = mne.viz.plot_head_positions(head_pos)
for ax, val, val_ori in zip(fig.axes[::2], average_head_dev_t['trans'][:3, 3],
                            original_head_dev_t['trans'][:3, 3]):
    ax.axhline(1000 * val, color='r')
    ax.axhline(1000 * val_ori, color='g')

# The green horizontal lines represent the original head position, whereas the
# red lines are the new head position averaged over all the time points.


I am working on the file "0.21/_downloads/31a362832c6e14bb418b12340a063c91/plot_movement_detection.ipynb".
The first task is:
Plot raw data with annotated movement
Can you write Python code for it?

mean_distance_limit = .0015  # in meters
annotation_movement, hpi_disp = annotate_movement(
    raw, head_pos, mean_distance_limit=mean_distance_limit)
raw.set_annotations(annotation_movement)
raw.plot(n_channels=100, duration=20)


I am working on the file "0.21/_downloads/32ac0c2b9b302521df6384e100fdf1fd/plot_eeglab_head_sphere.ipynb".
The first task is:
Calculate sphere origin and radius
EEGLAB plots head outline at the level where the head circumference is
measured
in the 10-20 system (a line going through Fpz, T8/T4, Oz and T7/T3 channels).
MNE-Python places the head outline lower on the z dimension, at the level of
the anatomical landmarks :term:LPA, RPA, and NAS <fiducial point>.
Therefore to use the EEGLAB layout we
have to move the origin of the reference sphere (a sphere that is used as a
reference when projecting channel locations to a 2d plane) a few centimeters
up.
Instead of approximating this position by eye, as we did in the sensor
locations tutorial <tut-sensor-locations>, here we will calculate it using
the position of Fpz, T8, Oz and T7 channels available in our montage.
Can you write Python code for it?

# first we obtain the 3d positions of selected channels
check_ch = ['Oz', 'Fpz', 'T7', 'T8']
ch_idx = [fake_evoked.ch_names.index(ch) for ch in check_ch]
pos = np.stack([fake_evoked.info['chs'][idx]['loc'][:3] for idx in ch_idx])

# now we calculate the radius from T7 and T8 x position
# (we could use Oz and Fpz y positions as well)
radius = np.abs(pos[[2, 3], 0]).mean()

# then we obtain the x, y, z sphere center this way:
# x: x position of the Oz channel (should be very close to 0)
# y: y position of the T8 channel (should be very close to 0 too)
# z: average z position of Oz, Fpz, T7 and T8 (their z position should be the
#    the same, so we could also use just one of these channels), it should be
#    positive and somewhere around `0.03` (3 cm)
x = pos[0, 0]
y = pos[-1, 1]
z = pos[:, -1].mean()

# lets print the values we got:
print([f'{v:0.5f}' for v in [x, y, z, radius]])


I am working on the file "0.21/_downloads/32ac0c2b9b302521df6384e100fdf1fd/plot_eeglab_head_sphere.ipynb".
The first task is:
Compare MNE and EEGLAB channel layout
We already have the required x, y, z sphere center and its radius — we can
use these values passing them to the sphere argument of many
topo-plotting functions (by passing sphere=(x, y, z, radius)).
Can you write Python code for it?

# create a two-panel figure with some space for the titles at the top
fig, ax = plt.subplots(ncols=2, figsize=(8, 4), gridspec_kw=dict(top=0.9),
                       sharex=True, sharey=True)

# we plot the channel positions with default sphere - the mne way
fake_evoked.plot_sensors(axes=ax[0], show=False)

# in the second panel we plot the positions using the EEGLAB reference sphere
fake_evoked.plot_sensors(sphere=(x, y, z, radius), axes=ax[1], show=False)

# add titles
fig.texts[0].remove()
ax[0].set_title('MNE channel projection', fontweight='bold')
ax[1].set_title('EEGLAB channel projection', fontweight='bold')


I am working on the file "0.21/_downloads/32ac0c2b9b302521df6384e100fdf1fd/plot_eeglab_head_sphere.ipynb".
The first task is:
How to plot topomaps the way EEGLAB does
If you have previous EEGLAB experience you may have noticed that topomaps
(topoplots) generated using MNE-Python look a little different from those
created in EEGLAB. If you prefer the EEGLAB style this example will show you
how to calculate head sphere origin and radius to obtain EEGLAB-like channel
layout in MNE.
Can you write Python code for it?

# Authors: Mikołaj Magnuski <mmagnuski@swps.edu.pl>
#
# License: BSD (3-clause)
import numpy as np
from matplotlib import pyplot as plt

import mne

print(__doc__)


I am working on the file "0.21/_downloads/32ac0c2b9b302521df6384e100fdf1fd/plot_eeglab_head_sphere.ipynb".
The first task is:
Topomaps (topoplots)
As the last step we do the same, but plotting the topomaps. These will not
be particularly interesting as they will show random data but hopefully you
will see the difference.
Can you write Python code for it?

fig, ax = plt.subplots(ncols=2, figsize=(8, 4), gridspec_kw=dict(top=0.9),
                       sharex=True, sharey=True)

mne.viz.plot_topomap(fake_evoked.data[:, 0], fake_evoked.info, axes=ax[0],
                     show=False)
mne.viz.plot_topomap(fake_evoked.data[:, 0], fake_evoked.info, axes=ax[1],
                     show=False, sphere=(x, y, z, radius))

# add titles
ax[0].set_title('MNE', fontweight='bold')
ax[1].set_title('EEGLAB', fontweight='bold')


I am working on the file "0.21/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
Apply the spatial filter
The spatial filter can be applied to different data types: raw, epochs,
evoked data or the data covariance matrix to gain a static image of power.
The function to apply the spatial filter to :class:~mne.Evoked data is
:func:~mne.beamformer.apply_lcmv which is
what we will use here. The other functions are
:func:~mne.beamformer.apply_lcmv_raw,
:func:~mne.beamformer.apply_lcmv_epochs, and
:func:~mne.beamformer.apply_lcmv_cov.
Can you write Python code for it?

stc = apply_lcmv(evoked, filters, max_ori_out='signed')
stc_vec = apply_lcmv(evoked, filters_vec, max_ori_out='signed')
del filters, filters_vec


I am working on the file "0.21/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
Computing the covariance matrices
Spatial filters use the data covariance to estimate the filter
weights. The data covariance matrix will be inverted_ during the spatial
filter computation, so it is valuable to plot the covariance matrix and its
eigenvalues to gauge whether matrix inversion will be possible.
Also, because we want to combine different channel types (magnetometers and
gradiometers), we need to account for the different amplitude scales of these
channel types. To do this we will supply a noise covariance matrix to the
beamformer, which will be used for whitening.
The data covariance matrix should be estimated from a time window that
includes the brain signal of interest,
and incorporate enough samples for a stable estimate. A rule of thumb is to
use more samples than there are channels in the data set; see
:footcite:BrookesEtAl2008 for more detailed advice on covariance estimation
for beamformers. Here, we use a time
window incorporating the expected auditory response at around 100 ms post
stimulus and extend the period to account for a low number of trials (72) and
low sampling rate of 150 Hz.
Can you write Python code for it?

data_cov = mne.compute_covariance(epochs, tmin=0.01, tmax=0.25,
                                  method='empirical')
noise_cov = mne.compute_covariance(epochs, tmin=tmin, tmax=0,
                                   method='empirical')
data_cov.plot(epochs.info)
del epochs