I am working on the file "0.18/_downloads/b1d326a4c3ddbdebaed097d34d4362a6/plot_dipole_orientations.ipynb".
The first task is:
Restricting the dipole orientations in this manner leads to the following
source estimate for the sample data:
Can you write Python code for it?

# Compute the source estimate for the 'left - auditory' condition in the sample
# dataset.
inv = make_inverse_operator(left_auditory.info, fwd, noise_cov, fixed=True)
stc = apply_inverse(left_auditory, inv, pick_ori=None)

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


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

mlab.figure(size=(600, 400), bgcolor=white)

# Define some more colors
green = (0.0, 1.0, 0.0)
blue = (0.0, 0.0, 1.0)

# Plot the cortex
mlab.triangular_mesh(verts[:, 0], verts[:, 1], verts[:, 2], tris, color=gray)

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

# Show the three dipoles defined at each location in the source space
dip_dir = inv['source_nn'].reshape(-1, 3, 3)
dip_dir = dip_dir[:len(dip_pos)]  # Only select left hemisphere
for ori, color in zip((0, 1, 2), (red, green, blue)):
    mlab.quiver3d(dip_pos[:, 0], dip_pos[:, 1], dip_pos[:, 2],
                  dip_dir[:, ori, 0], dip_dir[:, ori, 1], dip_dir[:, ori, 2],
                  color=color, scale_factor=1E-3)

mlab.view(azimuth=180, distance=0.1)


I am working on the file "0.18/_downloads/b1d326a4c3ddbdebaed097d34d4362a6/plot_dipole_orientations.ipynb".
The first task is:
The role of dipole orientations in distributed source localization
When performing source localization in a distributed manner
(MNE/dSPM/sLORETA/eLORETA),
the source space is defined as a grid of dipoles that spans a large portion of
the cortex. These dipoles have both a position and an orientation. In this
tutorial, we will look at the various options available to restrict the
orientation of the dipoles and the impact on the resulting source estimate.
See inverse_orientation_constrains
Loading data
Load everything we need to perform source localization on the sample dataset.
Can you write Python code for it?

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

data_path = sample.data_path()
evokeds = mne.read_evokeds(data_path + '/MEG/sample/sample_audvis-ave.fif')
left_auditory = evokeds[0].apply_baseline()
fwd = mne.read_forward_solution(
    data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif')
mne.convert_forward_solution(fwd, surf_ori=True, copy=False)
noise_cov = mne.read_cov(data_path + '/MEG/sample/sample_audvis-cov.fif')
subjects_dir = data_path + '/subjects'


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

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

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


I am working on the file "0.18/_downloads/b7f6f07283b8cae86edea831b037ebca/plot_object_raw.ipynb".
The first task is:
And drop channels by name
Can you write Python code for it?

nchan = raw.info['nchan']
raw = raw.drop_channels(['MEG 0241', 'EEG 001'])
print('Number of channels reduced from', nchan, 'to', raw.info['nchan'])


I am working on the file "0.18/_downloads/b7f6f07283b8cae86edea831b037ebca/plot_object_raw.ipynb".
The first task is:
Concatenating :class:~mne.io.Raw objects
:class:~mne.io.Raw objects can be concatenated in time by using the
:func:~mne.io.Raw.append function. For this to work, they must
have the same number of channels and their :class:~mne.Info
structures should be compatible.
Can you write Python code for it?

# Create multiple :class:`~mne.io.Raw` objects
raw1 = raw.copy().crop(0, 10)
raw2 = raw.copy().crop(10, 20)
raw3 = raw.copy().crop(20, 40)

# Concatenate in time (also works without preloading)
raw1.append([raw2, raw3])
print('Time extends from', raw1.times.min(), 's to', raw1.times.max(), 's')


I am working on the file "0.18/_downloads/b7f6f07283b8cae86edea831b037ebca/plot_object_raw.ipynb".
The first task is:
Loading continuous data
Load an example dataset, the preload flag loads the data into memory now:
Can you write Python code for it?

data_path = op.join(mne.datasets.sample.data_path(), 'MEG',
                    'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(data_path, preload=True)
raw.set_eeg_reference('average', projection=True)  # set EEG average reference

# Give the sample rate
print('sample rate:', raw.info['sfreq'], 'Hz')
# Give the size of the data matrix
print('%s channels x %s samples' % (raw.info['nchan'], len(raw.times)))


I am working on the file "0.18/_downloads/b7f6f07283b8cae86edea831b037ebca/plot_object_raw.ipynb".
The first task is:
Selecting subsets of channels and samples
It is possible to use more intelligent indexing to extract data, using
channel names, types or time ranges.
Can you write Python code for it?

# Pull all MEG gradiometer channels:
# Make sure to use .copy() or it will overwrite the data
meg_only = raw.copy().pick_types(meg=True)
eeg_only = raw.copy().pick_types(meg=False, eeg=True)

# The MEG flag in particular lets you specify a string for more specificity
grad_only = raw.copy().pick_types(meg='grad')

# Or you can use custom channel names
pick_chans = ['MEG 0112', 'MEG 0111', 'MEG 0122', 'MEG 0123']
specific_chans = raw.copy().pick_channels(pick_chans)
print(meg_only)
print(eeg_only)
print(grad_only)
print(specific_chans)


I am working on the file "0.18/_downloads/b7f6f07283b8cae86edea831b037ebca/plot_object_raw.ipynb".
The first task is:
The :class:~mne.io.Raw data structure: continuous data
Continuous data is stored in objects of type :class:~mne.io.Raw.
The core data structure is simply a 2D numpy array (channels × samples)
(in memory or loaded on demand) combined with an
:class:~mne.Info object (.info attribute)
(see tut-info-class).
The most common way to load continuous data is from a .fif file. For more
information on loading data from other formats <ch_convert>, or
creating it from scratch <tut_creating_data_structures>.
Can you write Python code for it?

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


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

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
label_name = 'Aud-rh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name

tmin, tmax, event_id = -0.2, 0.5, 2

# Setup for reading the raw data
raw = io.read_raw_fif(raw_fname)
events = mne.find_events(raw, stim_channel='STI 014')
inverse_operator = read_inverse_operator(fname_inv)

include = []
raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more

# Picks MEG channels
picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=True,
                       stim=False, include=include, exclude='bads')
reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)

# Load epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject,
                    preload=True)

# Compute a source estimate per frequency band including and excluding the
# evoked response
freqs = np.arange(7, 30, 2)  # define frequencies of interest
label = mne.read_label(fname_label)
n_cycles = freqs / 3.  # different number of cycle per frequency

# subtract the evoked response in order to exclude evoked activity
epochs_induced = epochs.copy().subtract_evoked()

plt.close('all')

for ii, (this_epochs, title) in enumerate(zip([epochs, epochs_induced],
                                              ['evoked + induced',
                                               'induced only'])):
    # compute the source space power and the inter-trial coherence
    power, itc = source_induced_power(
        this_epochs, inverse_operator, freqs, label, baseline=(-0.1, 0),
        baseline_mode='percent', n_cycles=n_cycles, n_jobs=1)

    power = np.mean(power, axis=0)  # average over sources
    itc = np.mean(itc, axis=0)  # average over sources
    times = epochs.times

    ##########################################################################
    # View time-frequency plots
    plt.subplots_adjust(0.1, 0.08,...


I am working on the file "0.18/_downloads/c1aa88a2be3f4bc4a4552ce39a81e4e1/plot_morph_volume_stc.ipynb".
The first task is:
Apply morph to VolSourceEstimate
The morph can be applied to the source estimate data, by giving it as the
first argument to the :meth:morph.apply() <mne.SourceMorph.apply> method:
Can you write Python code for it?


I am working on the file "0.18/_downloads/c1aa88a2be3f4bc4a4552ce39a81e4e1/plot_morph_volume_stc.ipynb".
The first task is:
Compute example data. For reference see
sphx_glr_auto_examples_inverse_plot_compute_mne_inverse_volume.py
Load data:
Can you write Python code for it?

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

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

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


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

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


I am working on the file "0.18/_downloads/c1aa88a2be3f4bc4a4552ce39a81e4e1/plot_morph_volume_stc.ipynb".
The first task is:
Morph volumetric source estimate
This example demonstrates how to morph an individual subject's
:class:mne.VolSourceEstimate to a common reference space. We achieve this
using :class:mne.SourceMorph. Pre-computed data will be morphed based on
an affine transformation and a nonlinear registration method
known as Symmetric Diffeomorphic Registration (SDR) by Avants et al. [1]_.
Transformation is estimated from the subject's anatomical T1 weighted MRI
(brain) to FreeSurfer's 'fsaverage' T1 weighted MRI (brain)
<https://surfer.nmr.mgh.harvard.edu/fswiki/FsAverage>__.
Afterwards the transformation will be applied to the volumetric source
estimate. The result will be plotted, showing the fsaverage T1 weighted
anatomical MRI, overlaid with the morphed volumetric source estimate.
References
.. [1] Avants, B. B., Epstein, C. L., Grossman, M., & Gee, J. C. (2009).
       Symmetric Diffeomorphic Image Registration with Cross- Correlation:
       Evaluating Automated Labeling of Elderly and Neurodegenerative
       Brain, 12(1), 26-41.

Note

For a tutorial about morphing see `ch_morph`.

Can you write Python code for it?

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

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

print(__doc__)


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

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

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

stc_fsaverage_new = mne.compute_source_morph(
    inverse_operator['src'], subject_from='sample',
    subjects_dir=subjects_dir).apply(stc)


I am working on the file "0.18/_downloads/c23954cac2b3ff3d60af084587dee705/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 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.18/_downloads/c23954cac2b3ff3d60af084587dee705/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.18/_downloads/c252c7618c44ac318ad1e9e85d5b7059/plot_decoding_csp_timefreq.ipynb".
The first task is:
Loop through frequencies and time, apply classifier and save scores
Can you write Python code for it?

# init scores
tf_scores = np.zeros((n_freqs - 1, n_windows))

# Loop through each frequency range of interest
for freq, (fmin, fmax) in enumerate(freq_ranges):

    # Infer window size based on the frequency being used
    w_size = n_cycles / ((fmax + fmin) / 2.)  # in seconds

    # Apply band-pass filter to isolate the specified frequencies
    raw_filter = raw.copy().filter(fmin, fmax, n_jobs=1, fir_design='firwin',
                                   skip_by_annotation='edge')

    # Extract epochs from filtered data, padded by window size
    epochs = Epochs(raw_filter, events, event_id, tmin - w_size, tmax + w_size,
                    proj=False, baseline=None, preload=True)
    epochs.drop_bad()
    y = le.fit_transform(epochs.events[:, 2])

    # Roll covariance, csp and lda over time
    for t, w_time in enumerate(centered_w_times):

        # Center the min and max of the window
        w_tmin = w_time - w_size / 2.
        w_tmax = w_time + w_size / 2.

        # Crop data into time-window of interest
        X = epochs.copy().crop(w_tmin, w_tmax).get_data()

        # Save mean scores over folds for each frequency and time window
        tf_scores[freq, t] = np.mean(cross_val_score(estimator=clf, X=X, y=y,
                                                     scoring='roc_auc', cv=cv,
                                                     n_jobs=1), axis=0)


I am working on the file "0.18/_downloads/c252c7618c44ac318ad1e9e85d5b7059/plot_decoding_csp_timefreq.ipynb".
The first task is:
Plot frequency results
Can you write Python code for it?

plt.bar(freqs[:-1], freq_scores, width=np.diff(freqs)[0],
        align='edge', edgecolor='black')
plt.xticks(freqs)
plt.ylim([0, 1])
plt.axhline(len(epochs['feet']) / len(epochs), color='k', linestyle='--',
            label='chance level')
plt.legend()
plt.xlabel('Frequency (Hz)')
plt.ylabel('Decoding Scores')
plt.title('Frequency Decoding Scores')


I am working on the file "0.18/_downloads/c252c7618c44ac318ad1e9e85d5b7059/plot_decoding_csp_timefreq.ipynb".
The first task is:
Plot time-frequency results
Can you write Python code for it?

# Set up time frequency object
av_tfr = AverageTFR(create_info(['freq'], sfreq), tf_scores[np.newaxis, :],
                    centered_w_times, freqs[1:], 1)

chance = np.mean(y)  # set chance level to white in the plot
av_tfr.plot([0], vmin=chance, title="Time-Frequency Decoding Scores",
            cmap=plt.cm.Reds)


I am working on the file "0.18/_downloads/c252c7618c44ac318ad1e9e85d5b7059/plot_decoding_csp_timefreq.ipynb".
The first task is:
Set parameters and read data
Can you write Python code for it?

event_id = dict(hands=2, feet=3)  # motor imagery: hands vs feet
subject = 1
runs = [6, 10, 14]
raw_fnames = eegbci.load_data(subject, runs)
raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames])

# Extract information from the raw file
sfreq = raw.info['sfreq']
events, _ = events_from_annotations(raw, event_id=dict(T1=2, T2=3))
raw.pick_types(meg=False, eeg=True, stim=False, eog=False, exclude='bads')

# Assemble the classifier using scikit-learn pipeline
clf = make_pipeline(CSP(n_components=4, reg=None, log=True, norm_trace=False),
                    LinearDiscriminantAnalysis())
n_splits = 5  # how many folds to use for cross-validation
cv = StratifiedKFold(n_splits=n_splits, shuffle=True)

# Classification & Time-frequency parameters
tmin, tmax = -.200, 2.000
n_cycles = 10.  # how many complete cycles: used to define window size
min_freq = 5.
max_freq = 25.
n_freqs = 8  # how many frequency bins to use

# Assemble list of frequency range tuples
freqs = np.linspace(min_freq, max_freq, n_freqs)  # assemble frequencies
freq_ranges = list(zip(freqs[:-1], freqs[1:]))  # make freqs list of tuples

# Infer window spacing from the max freq and number of cycles to avoid gaps
window_spacing = (n_cycles / np.max(freqs) / 2.)
centered_w_times = np.arange(tmin, tmax, window_spacing)[1:]
n_windows = len(centered_w_times)

# Instantiate label encoder
le = LabelEncoder()


I am working on the file "0.18/_downloads/c3c186a71be1cfa94a34ecef5331099f/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Brainstorm Elekta phantom dataset tutorial
Here we compute the evoked from raw for the Brainstorm Elekta phantom
tutorial dataset. For comparison, see [1]_ and:
https://neuroimage.usc.edu/brainstorm/Tutorials/PhantomElekta

References
.. [1] Tadel F, Baillet S, Mosher JC, Pantazis D, Leahy RM.
       Brainstorm: A User-Friendly Application for MEG/EEG Analysis.
       Computational Intelligence and Neuroscience, vol. 2011, Article ID
       879716, 13 pages, 2011. doi:10.1155/2011/879716
Can you write Python code for it?

# sphinx_gallery_thumbnail_number = 9

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

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

import mne
from mne import find_events, fit_dipole
from mne.datasets.brainstorm import bst_phantom_elekta
from mne.io import read_raw_fif

from mayavi import mlab
print(__doc__)


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

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


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

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

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


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

def plot_pos_ori(pos, ori, color=(0., 0., 0.), opacity=1.):
    """Plot dipole positions and orientations in 3D."""
    x, y, z = pos.T
    u, v, w = ori.T
    mlab.points3d(x, y, z, scale_factor=0.005, opacity=opacity, color=color)
    q = mlab.quiver3d(x, y, z, u, v, w,
                      scale_factor=0.03, opacity=opacity,
                      color=color, mode='arrow')
    q.glyph.glyph_source.glyph_source.shaft_radius = 0.02
    q.glyph.glyph_source.glyph_source.tip_length = 0.1
    q.glyph.glyph_source.glyph_source.tip_radius = 0.05

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

# Plot the position and the orientation of the actual dipole
plot_pos_ori(actual_pos, actual_ori, color=(0., 0., 0.), opacity=0.5)
# Plot the position and the orientation of the estimated dipole
plot_pos_ori(dip.pos, dip.ori, color=(0.2, 1., 0.5))
mlab.view(70, 80, distance=0.5)


I am working on the file "0.18/_downloads/c3c186a71be1cfa94a34ecef5331099f/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Let's use a sphere head geometry model <ch_forward_spherical_model>
and let's see the coordinate alignment and the sphere location. The phantom
is properly modeled by a single-shell sphere with origin (0., 0., 0.).
Can you write Python code for it?

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

mne.viz.plot_alignment(epochs.info, subject='sample', show_axes=True,
                       bem=sphere, dig=True, surfaces='inner_skull')


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

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

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

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

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

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

fig.tight_layout()
plt.show()


I am working on the file "0.18/_downloads/c3c186a71be1cfa94a34ecef5331099f/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Our phantom produces sinusoidal bursts at 20 Hz:
Can you write Python code for it?


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


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

data_path = bst_phantom_elekta.data_path(verbose=True)

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


I am working on the file "0.18/_downloads/c40536cd7dedfa90e5037eae95a65d33/plot_info.ipynb".
The first task is:
:class:mne.Info behaves as a nested Python dictionary:
Can you write Python code for it?

# Read the info object from an example recording
info = mne.io.read_info(
    op.join(mne.datasets.sample.data_path(), 'MEG', 'sample',
            'sample_audvis_raw.fif'), verbose=False)


I am working on the file "0.18/_downloads/c40536cd7dedfa90e5037eae95a65d33/plot_info.ipynb".
The first task is:
Channel types of a collection of channels
Can you write Python code for it?

meg_channels = mne.pick_types(info, meg=True)[:10]
channel_types = [mne.io.pick.channel_type(info, ch) for ch in meg_channels]
print('First 10 MEG channels are of type:\n', channel_types)


I am working on the file "0.18/_downloads/c40536cd7dedfa90e5037eae95a65d33/plot_info.ipynb".
The first task is:
Get a dictionary of channel indices, grouped by channel type
Can you write Python code for it?

channel_indices_by_type = mne.io.pick.channel_indices_by_type(info)
print('The first three magnetometers:', channel_indices_by_type['mag'][:3])


I am working on the file "0.18/_downloads/c40536cd7dedfa90e5037eae95a65d33/plot_info.ipynb".
The first task is:
Get channel indices by regular expression
Can you write Python code for it?

channel_indices_meg_re = mne.pick_channels_regexp(info['ch_names'], 'MEG *')


I am working on the file "0.18/_downloads/c40536cd7dedfa90e5037eae95a65d33/plot_info.ipynb".
The first task is:
List all information about the first data channel
Can you write Python code for it?


I am working on the file "0.18/_downloads/c40536cd7dedfa90e5037eae95a65d33/plot_info.ipynb".
The first task is:
List all the fields in the info object
Can you write Python code for it?

print('Keys in info dictionary:\n', info.keys())


I am working on the file "0.18/_downloads/c40536cd7dedfa90e5037eae95a65d33/plot_info.ipynb".
The first task is:
Obtaining information about channels
Can you write Python code for it?

# Channel type of a specific channel
channel_type = mne.io.pick.channel_type(info, 75)
print('Channel #75 is of type:', channel_type)


I am working on the file "0.18/_downloads/c40536cd7dedfa90e5037eae95a65d33/plot_info.ipynb".
The first task is:
Obtaining subsets of channels
There are a number of convenience functions to obtain channel indices, given
an :class:mne.Info object.
Get channel indices by name
Can you write Python code for it?

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


I am working on the file "0.18/_downloads/c40536cd7dedfa90e5037eae95a65d33/plot_info.ipynb".
The first task is:
The :class:~mne.Info data structure
The :class:~mne.Info data object is typically created
when data is imported into MNE-Python and contains details such as:

date, subject information, and other recording details
the sampling rate
information about the data channels (name, type, position, etc.)
digitized points
sensor–head coordinate transformation matrices

and so forth. See the :class:the API reference <mne.Info>
for a complete list of all data fields. Once created, this object is passed
around throughout the data analysis pipeline.
Can you write Python code for it?


I am working on the file "0.18/_downloads/c608de012990891324ec009155010a24/plot_visualize_raw.ipynb".
The first task is:
Now click the proj button at the lower right corner of the browser
window. A selection dialog should appear, where you can toggle the projectors
on and off. Notice that the first four are already applied to the data and
toggling them does not change the data. However the newly added projectors
modify the data to get rid of the EOG artifacts. Note that toggling the
projectors here doesn't actually modify the data. This is purely for visually
inspecting the effect. See :func:mne.io.Raw.del_proj to actually remove the
projectors.
Raw container also lets us easily plot the power spectra over the raw data.
Here we plot the data using spatial_colors to map the line colors to
channel locations (default in versions >= 0.15.0). Other option is to use the
average (default in < 0.15.0). See the API documentation for more info.
Can you write Python code for it?


I am working on the file "0.18/_downloads/c608de012990891324ec009155010a24/plot_visualize_raw.ipynb".
The first task is:
Plotting channel-wise power spectra is just as easy. The layout is inferred
from the data by default when plotting topo plots. This works for most data,
but it is also possible to define the layouts by hand. Here we select a
layout with only magnetometer channels and plot it. Then we plot the channel
wise spectra of first 30 seconds of the data.
Can you write Python code for it?

layout = mne.channels.read_layout('Vectorview-mag')
layout.plot()
raw.plot_psd_topo(tmax=30., fmin=5., fmax=60., n_fft=1024, layout=layout)


I am working on the file "0.18/_downloads/c608de012990891324ec009155010a24/plot_visualize_raw.ipynb".
The first task is:
The channels are color coded by channel type. Generally MEG channels are
colored in different shades of blue, whereas EEG channels are black. The
scrollbar on right side of the browser window also tells us that two of the
channels are marked as bad. Bad channels are color coded gray. By
clicking the lines or channel names on the left, you can mark or unmark a bad
channel interactively. You can use +/- keys to adjust the scale (also = works
for magnifying the data). Note that the initial scaling factors can be set
with parameter scalings. If you don't know the scaling factor for
channels, you can automatically set them by passing scalings='auto'. With
pageup/pagedown and home/end keys you can adjust the amount of data
viewed at once.
Drawing annotations
You can enter annotation mode by pressing a key. In annotation mode you
can mark segments of data (and modify existing annotations) with the left
mouse button. You can use the description of any existing annotation or
create a new description by typing when the annotation dialog is active.
Notice that the description starting with the keyword 'bad' means that
the segment will be discarded when epoching the data. Existing annotations
can be deleted with the right mouse button.  Annotation mode is exited by
pressing a again or closing the annotation window. See also
:class:mne.Annotations and marking_bad_segments. To see all the
interactive features, hit ? key or click help in the lower left
corner of the browser window.

Warning

Annotations are modified in-place immediately at run-time.
             Deleted annotations cannot be retrieved after deletion.

The channels are sorted by channel type by default. You can use the
group_by parameter of :func:raw.plot <mne.io.Raw.plot> to group the
channels in a different way. group_by='selection' uses the same channel
groups as MNE-C's mne_browse_raw (see CACCJEJD). The selections are
defined in mne-python/mne/data/mne_analyze.sel and by modifying the
channels...
Can you write Python code for it?


I am working on the file "0.18/_downloads/c608de012990891324ec009155010a24/plot_visualize_raw.ipynb".
The first task is:
The first three projectors that we see are the SSP vectors from empty room
measurements to compensate for the noise. The fourth one is the average EEG
reference. These are already applied to the data and can no longer be
removed. The next six are the EOG projections that we added. Every data
channel type has two projection vectors each. Let's try the raw browser
again.
Can you write Python code for it?


I am working on the file "0.18/_downloads/c608de012990891324ec009155010a24/plot_visualize_raw.ipynb".
The first task is:
The visualization module (:mod:mne.viz) contains all the plotting functions
that work in combination with MNE data structures. Usually the easiest way to
use them is to call a method of the data container. All of the plotting
method names start with plot. If you're using Ipython console, you can
just write raw.plot and ask the interpreter for suggestions with a
tab key.
To visually inspect your raw data, you can use the python equivalent of
mne_browse_raw.
Can you write Python code for it?


I am working on the file "0.18/_downloads/c608de012990891324ec009155010a24/plot_visualize_raw.ipynb".
The first task is:
We can check where the channels reside with plot_sensors. Notice that
this method (along with many other MNE plotting functions) is callable using
any MNE data container where the channel information is available.
Can you write Python code for it?


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

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

raw = io.read_raw_fif(raw_fname, preload=True)
raw.filter(1, 40, n_jobs=1, fir_design='firwin')
raw.info['bads'] += ['MEG 2443']  # bads + 1 more
events = mne.read_events(event_fname)

# let's look at rare events, button presses
event_id, tmin, tmax = 2, -0.2, 0.5
reject = dict(mag=4e-12, grad=4000e-13, eeg=80e-6)

epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=('meg', 'eeg'),
                    baseline=None, reject=reject, preload=True)

# Uncomment next line to use fewer samples and study regularization effects
# epochs = epochs[:20]  # For your data, use as many samples as you can!


I am working on the file "0.18/_downloads/c6fd8bd3dc3d461b7f23f0abafd06d22/plot_evoked_whitening.ipynb".
The first task is:
Show the evoked data:
Can you write Python code for it?

evoked = epochs.average()

evoked.plot(time_unit='s')  # plot evoked response


I am working on the file "0.18/_downloads/c6fd8bd3dc3d461b7f23f0abafd06d22/plot_evoked_whitening.ipynb".
The first task is:
Whitening evoked data with a noise covariance
Evoked data are loaded and then whitened using a given noise covariance
matrix. It's an excellent quality check to see if baseline signals match
the assumption of Gaussian white noise during the baseline period.
Covariance estimation and diagnostic plots are based on [1]_.
References
.. [1] Engemann D. and Gramfort A. (2015) Automated model selection in
    covariance estimation and spatial whitening of MEG and EEG signals, vol.
    108, 328-342, NeuroImage.
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Denis A. Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)

import mne

from mne import io
from mne.datasets import sample
from mne.cov import compute_covariance

print(__doc__)


I am working on the file "0.18/_downloads/c92aa91c680730c756234cdbc466c558/plot_introduction.ipynb".
The first task is:
:class:~mne.io.Raw objects also have several built-in plotting methods;
here we show the power spectral density (PSD) for each sensor type with
:meth:~mne.io.Raw.plot_psd, as well as a plot of the raw sensor traces with
:meth:~mne.io.Raw.plot. In the PSD plot, we'll only plot frequencies below
50 Hz (since our data are low-pass filtered at 40 Hz). In interactive Python
sessions, :meth:~mne.io.Raw.plot is interactive and allows scrolling,
scaling, bad channel marking, annotation, projector toggling, etc.
Can you write Python code for it?


I am working on the file "0.18/_downloads/c92aa91c680730c756234cdbc466c558/plot_introduction.ipynb".
The first task is:

Note

Both :class:`~mne.io.Raw` and :class:`~mne.Epochs` objects have
    :meth:`~mne.Epochs.get_data` methods that return the underlying data
    as a :class:`NumPy array <numpy.ndarray>`. Both methods have a ``picks``
    parameter for subselecting which channel(s) to return; ``raw.get_data()``
    has additional parameters for restricting the time domain. The resulting
    matrices have dimension ``(n_channels, n_times)`` for
    :class:`~mne.io.Raw` and ``(n_epochs, n_channels, n_times)`` for
    :class:`~mne.Epochs`.

Time-frequency analysis
^^^^^^^^^^^^^^^^^^^^^^^
The :mod:mne.time_frequency submodule provides implementations of several
algorithms to compute time-frequency representations, power spectral density,
and cross-spectral density. Here, for example, we'll compute for the auditory
epochs the induced power at different frequencies and times, using Morlet
wavelets. On this dataset the result is not especially informative (it just
shows the evoked "auditory N100" response); see here
<inter-trial-coherence> for a more extended example on a dataset with richer
frequency content.
Can you write Python code for it?

frequencies = np.arange(7, 30, 3)
power = mne.time_frequency.tfr_morlet(aud_epochs, n_cycles=2, return_itc=False,
                                      freqs=frequencies, decim=3)
power.plot(['MEG 1332'])


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


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

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

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


I am working on the file "0.18/_downloads/c92aa91c680730c756234cdbc466c558/plot_introduction.ipynb".
The first task is:
Evoked objects can also be combined to show contrasts between conditions,
using the :func:mne.combine_evoked function. A simple difference can be
generated by negating one of the :class:~mne.Evoked objects passed into the
function. We'll then plot the difference wave at each sensor using
:meth:~mne.Evoked.plot_topo:
Can you write Python code for it?

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


I am working on the file "0.18/_downloads/c92aa91c680730c756234cdbc466c558/plot_introduction.ipynb".
The first task is:
Finally, in order to plot the source estimate on the subject's cortical
surface we'll also need the path to the sample subject's structural MRI files
(the subjects_dir):
Can you write Python code for it?

# path to subjects' MRI files
subjects_dir = os.path.join(sample_data_folder, 'subjects')
# plot
stc.plot(initial_time=0.1, hemi='split', views=['lat', 'med'],
         subjects_dir=subjects_dir)


I am working on the file "0.18/_downloads/c92aa91c680730c756234cdbc466c558/plot_introduction.ipynb".
The first task is:
Next we'll pool across left/right stimulus presentations so we can compare
auditory versus visual responses. To avoid biasing our signals to the
left or right, we'll use :meth:~mne.Epochs.equalize_event_counts first to
randomly sample epochs from each condition to match the number of epochs
present in the condition with the fewest good epochs.
Can you write Python code for it?

conds_we_care_about = ['auditory/left', 'auditory/right',
                       'visual/left', 'visual/right']
epochs.equalize_event_counts(conds_we_care_about)  # this operates in-place
aud_epochs = epochs['auditory']
vis_epochs = epochs['visual']
del raw, epochs  # free up memory


I am working on the file "0.18/_downloads/c92aa91c680730c756234cdbc466c558/plot_introduction.ipynb".
The first task is:
Once we're confident about which component(s) we want to remove, we pass them
as the exclude parameter and then apply the ICA to the raw signal. The
:meth:~mne.preprocessing.ICA.apply method requires the raw data to be
loaded into memory (by default it's only read from disk as-needed), so we'll
use :meth:~mne.io.Raw.load_data first. We'll also make a copy of the
:class:~mne.io.Raw object so we can compare the signal before and after
artifact removal side-by-side:
Can you write Python code for it?

orig_raw = raw.copy()
raw.load_data()
ica.apply(raw)

# show some frontal channels to clearly illustrate the artifact removal
chs = ['MEG 0111', 'MEG 0121', 'MEG 0131', 'MEG 0211', 'MEG 0221', 'MEG 0231',
       'MEG 0311', 'MEG 0321', 'MEG 0331', 'MEG 1511', 'MEG 1521', 'MEG 1531',
       'EEG 001', 'EEG 002', 'EEG 003', 'EEG 004', 'EEG 005', 'EEG 006',
       'EEG 007', 'EEG 008']
chan_idxs = [raw.ch_names.index(ch) for ch in chs]
orig_raw.plot(order=chan_idxs, start=12, duration=4)
raw.plot(order=chan_idxs, start=12, duration=4)


I am working on the file "0.18/_downloads/c92aa91c680730c756234cdbc466c558/plot_introduction.ipynb".
The first task is:
Overview of MEG/EEG analysis with MNE-Python
This tutorial covers the basic EEG/MEG pipeline for event-related analysis:
loading data, epoching, averaging, plotting, and estimating cortical activity
from sensor data. It introduces the core MNE-Python data structures
:class:~mne.io.Raw, :class:~mne.Epochs, :class:~mne.Evoked, and
:class:~mne.SourceEstimate, and covers a lot of ground fairly quickly (at the
expense of depth). Subsequent tutorials address each of these topics in greater
detail.
   :depth: 1
We begin by importing the necessary Python modules:
Can you write Python code for it?


event_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
              'visual/right': 4, 'smiley': 5, 'buttonpress': 32}


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

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


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

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


I am working on the file "0.18/_downloads/d043a6f89c85579df811f8d5bf583129/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb".
The first task is:
A stat_fun must deal with a variable number of input arguments.
Inside the clustering function each condition will be passed as flattened
array, necessitated by the clustering procedure. The ANOVA however expects an
input array of dimensions: subjects X conditions X observations (optional).
The following function catches the list input and swaps the first and the
second dimension, and finally calls ANOVA.

Note

For further details on this ANOVA function consider the
          corresponding
          `time-frequency tutorial <tut-timefreq-twoway-anova>`.

Can you write Python code for it?

def stat_fun(*args):
    # get f-values only.
    return f_mway_rm(np.swapaxes(args, 1, 0), factor_levels=factor_levels,
                     effects=effects, return_pvals=return_pvals)[0]


I am working on the file "0.18/_downloads/d043a6f89c85579df811f8d5bf583129/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb".
The first task is:
Compute clustering statistic
To use an algorithm optimized for spatio-temporal clustering, we
just pass the spatial connectivity matrix (instead of spatio-temporal).
Can you write Python code for it?

# as we only have one hemisphere we need only need half the connectivity
print('Computing connectivity.')
connectivity = mne.spatial_src_connectivity(src[:1])

#    Now let's actually do the clustering. Please relax, on a small
#    notebook and one single thread only this will take a couple of minutes ...
pthresh = 0.0005
f_thresh = f_threshold_mway_rm(n_subjects, factor_levels, effects, pthresh)

#    To speed things up a bit we will ...
n_permutations = 128  # ... run fewer permutations (reduces sensitivity)

print('Clustering.')
T_obs, clusters, cluster_p_values, H0 = clu = \
    spatio_temporal_cluster_test(X, connectivity=connectivity, n_jobs=1,
                                 threshold=f_thresh, stat_fun=stat_fun,
                                 n_permutations=n_permutations,
                                 buffer_size=None)
#    Now select the clusters that are sig. at p < 0.05 (note that this value
#    is multiple-comparisons corrected).
good_cluster_inds = np.where(cluster_p_values < 0.05)[0]


I am working on the file "0.18/_downloads/d043a6f89c85579df811f8d5bf583129/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb".
The first task is:
Finally we will pick the interaction effect by passing 'A:B'.
(this notation is borrowed from the R formula language). Without this also
the main effects will be returned.
Can you write Python code for it?

effects = 'A:B'
# Tell the ANOVA not to compute p-values which we don't need for clustering
return_pvals = False

# a few more convenient bindings
n_times = X[0].shape[1]
n_conditions = 4


I am working on the file "0.18/_downloads/d043a6f89c85579df811f8d5bf583129/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb".
The first task is:
Finally, let's investigate interaction effect by reconstructing the time
courses
Can you write Python code for it?

inds_t, inds_v = [(clusters[cluster_ind]) for ii, cluster_ind in
                  enumerate(good_cluster_inds)][0]  # first cluster

times = np.arange(X[0].shape[1]) * tstep * 1e3

plt.figure()
colors = ['y', 'b', 'g', 'purple']
event_ids = ['l_aud', 'r_aud', 'l_vis', 'r_vis']

for ii, (condition, color, eve_id) in enumerate(zip(X, colors, event_ids)):
    # extract time course at cluster vertices
    condition = condition[:, :, inds_v]
    # normally we would normalize values across subjects but
    # here we use data from the same subject so we're good to just
    # create average time series across subjects and vertices.
    mean_tc = condition.mean(axis=2).mean(axis=0)
    std_tc = condition.std(axis=2).std(axis=0)
    plt.plot(times, mean_tc.T, color=color, label=eve_id)
    plt.fill_between(times, mean_tc + std_tc, mean_tc - std_tc, color='gray',
                     alpha=0.5, label='')

ymin, ymax = mean_tc.min() - 5, mean_tc.max() + 5
plt.xlabel('Time (ms)')
plt.ylabel('Activation (F-values)')
plt.xlim(times[[0, -1]])
plt.ylim(ymin, ymax)
plt.fill_betweenx((ymin, ymax), times[inds_t[0]],
                  times[inds_t[-1]], color='orange', alpha=0.3)
plt.legend()
plt.title('Interaction between stimulus-modality and location.')
plt.show()


I am working on the file "0.18/_downloads/d043a6f89c85579df811f8d5bf583129/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb".
The first task is:
It's a good idea to spatially smooth the data, and for visualization
purposes, let's morph these to fsaverage, which is a grade 5 ICO source space
with vertices 0:10242 for each hemisphere. Usually you'd have to morph
each subject's data separately, but here since all estimates are on
'sample' we can use one morph matrix for all the heavy lifting.
Can you write Python code for it?

# Read the source space we are morphing to (just left hemisphere)
src = mne.read_source_spaces(src_fname)
fsave_vertices = [src[0]['vertno'], []]
morph_mat = mne.compute_source_morph(
    src=inverse_operator['src'], subject_to='fsaverage',
    spacing=fsave_vertices, subjects_dir=subjects_dir, smooth=20).morph_mat
morph_mat = morph_mat[:, :n_vertices_sample]  # just left hemi from src
n_vertices_fsave = morph_mat.shape[0]

#    We have to change the shape for the dot() to work properly
X = X.reshape(n_vertices_sample, n_times * n_subjects * 4)
print('Morphing data.')
X = morph_mat.dot(X)  # morph_mat is a sparse matrix
X = X.reshape(n_vertices_fsave, n_times, n_subjects, 4)


I am working on the file "0.18/_downloads/d043a6f89c85579df811f8d5bf583129/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb".
The first task is:
Now we need to prepare the group matrix for the ANOVA statistic. To make the
clustering function work correctly with the ANOVA function X needs to be a
list of multi-dimensional arrays (one per condition) of shape: samples
(subjects) x time x space.
First we permute dimensions, then split the array into a list of conditions
and discard the empty dimension resulting from the split using numpy squeeze.
Can you write Python code for it?

X = np.transpose(X, [2, 1, 0, 3])  #
X = [np.squeeze(x) for x in np.split(X, 4, axis=-1)]


I am working on the file "0.18/_downloads/d043a6f89c85579df811f8d5bf583129/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb".
The first task is:
Prepare function for arbitrary contrast
As our ANOVA function is a multi-purpose tool we need to apply a few
modifications to integrate it with the clustering function. This
includes reshaping data, setting default arguments and processing
the return values. For this reason we'll write a tiny dummy function.
We will tell the ANOVA how to interpret the data matrix in terms of
factors. This is done via the factor levels argument which is a list
of the number factor levels for each factor.
Can you write Python code for it?


I am working on the file "0.18/_downloads/d043a6f89c85579df811f8d5bf583129/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb".
The first task is:
Read epochs for all channels, removing a bad one
Can you write Python code for it?

raw.info['bads'] += ['MEG 2443']
picks = mne.pick_types(raw.info, meg=True, eog=True, exclude='bads')
# we'll load all four conditions that make up the 'two ways' of our ANOVA

event_id = dict(l_aud=1, r_aud=2, l_vis=3, r_vis=4)
reject = dict(grad=1000e-13, mag=4000e-15, eog=150e-6)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject, preload=True)

#    Equalize trial counts to eliminate bias (which would otherwise be
#    introduced by the abs() performed below)
epochs.equalize_event_counts(event_id)


I am working on the file "0.18/_downloads/d043a6f89c85579df811f8d5bf583129/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb".
The first task is:
Repeated measures ANOVA on source data with spatio-temporal clustering
This example illustrates how to make use of the clustering functions
for arbitrary, self-defined contrasts beyond standard t-tests. In this
case we will tests if the differences in evoked responses between
stimulation modality (visual VS auditory) depend on the stimulus
location (left vs right) for a group of subjects (simulated here
using one subject's data). For this purpose we will compute an
interaction effect using a repeated measures ANOVA. The multiple
comparisons problem is addressed with a cluster-level permutation test
across space and time.
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Eric Larson <larson.eric.d@gmail.com>
#          Denis Engemannn <denis.engemann@gmail.com>
#
# License: BSD (3-clause)

import os.path as op
import numpy as np
from numpy.random import randn
import matplotlib.pyplot as plt

import mne
from mne.stats import (spatio_temporal_cluster_test, f_threshold_mway_rm,
                       f_mway_rm, summarize_clusters_stc)

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

print(__doc__)


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

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
subjects_dir = data_path + '/subjects'
src_fname = subjects_dir + '/fsaverage/bem/fsaverage-ico-5-src.fif'

tmin = -0.2
tmax = 0.3  # Use a lower tmax to reduce multiple comparisons

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


I am working on the file "0.18/_downloads/d043a6f89c85579df811f8d5bf583129/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb".
The first task is:
Transform to common cortical space
Normally you would read in estimates across several subjects and morph them
to the same cortical space (e.g. fsaverage). For example purposes, we will
simulate this by just having each "subject" have the same response (just
noisy in source space) here.
We'll only consider the left hemisphere in this tutorial.
Can you write Python code for it?

n_vertices_sample, n_times = conditions[0].lh_data.shape
n_subjects = 7
print('Simulating data for %d subjects.' % n_subjects)

#    Let's make sure our results replicate, so set the seed.
np.random.seed(0)
X = randn(n_vertices_sample, n_times, n_subjects, 4) * 10
for ii, condition in enumerate(conditions):
    X[:, :, :, ii] += condition.lh_data[:, :, np.newaxis]


I am working on the file "0.18/_downloads/d043a6f89c85579df811f8d5bf583129/plot_stats_cluster_spatio_temporal_repeated_measures_anova.ipynb".
The first task is:
Transform to source space
Can you write Python code for it?

fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE, sLORETA, or eLORETA)
inverse_operator = read_inverse_operator(fname_inv)

# we'll only use one hemisphere to speed up this example
# instead of a second vertex array we'll pass an empty array
sample_vertices = [inverse_operator['src'][0]['vertno'], np.array([], int)]

#    Let's average and compute inverse, then resample to speed things up
conditions = []
for cond in ['l_aud', 'r_aud', 'l_vis', 'r_vis']:  # order is important
    evoked = epochs[cond].average()
    evoked.resample(50, npad='auto')
    condition = apply_inverse(evoked, inverse_operator, lambda2, method)
    #    Let's only deal with t > 0, cropping to reduce multiple comparisons
    condition.crop(0, None)
    conditions.append(condition)

tmin = conditions[0].tmin
tstep = conditions[0].tstep


I am working on the file "0.18/_downloads/d1b18c3376911723f0257fe5003a8477/plot_linear_model_patterns.ipynb".
The first task is:
Decoding in sensor space using a LogisticRegression classifier
Can you write Python code for it?

clf = LogisticRegression(solver='lbfgs')
scaler = StandardScaler()

# create a linear model with LogisticRegression
model = LinearModel(clf)

# fit the classifier on MEG data
X = scaler.fit_transform(meg_data)
model.fit(X, labels)

# Extract and plot spatial filters and spatial patterns
for name, coef in (('patterns', model.patterns_), ('filters', model.filters_)):
    # We fitted the linear model onto Z-scored data. To make the filters
    # interpretable, we must reverse this normalization step
    coef = scaler.inverse_transform([coef])[0]

    # The data was vectorized to fit a single model across all time points and
    # all channels. We thus reshape it:
    coef = coef.reshape(len(meg_epochs.ch_names), -1)

    # Plot
    evoked = EvokedArray(coef, meg_epochs.info, tmin=epochs.tmin)
    evoked.plot_topomap(title='MEG %s' % name, time_unit='s')


I am working on the file "0.18/_downloads/d1b18c3376911723f0257fe5003a8477/plot_linear_model_patterns.ipynb".
The first task is:
Let's do the same on EEG data using a scikit-learn pipeline
Can you write Python code for it?

X = epochs.pick_types(meg=False, eeg=True)
y = epochs.events[:, 2]

# Define a unique pipeline to sequentially:
clf = make_pipeline(
    Vectorizer(),                       # 1) vectorize across time and channels
    StandardScaler(),                   # 2) normalize features across trials
    LinearModel(
        LogisticRegression(solver='lbfgs')))  # 3) fits a logistic regression
clf.fit(X, y)

# Extract and plot patterns and filters
for name in ('patterns_', 'filters_'):
    # The `inverse_transform` parameter will call this method on any estimator
    # contained in the pipeline, in reverse order.
    coef = get_coef(clf, name, inverse_transform=True)
    evoked = EvokedArray(coef, epochs.info, tmin=epochs.tmin)
    evoked.plot_topomap(title='EEG %s' % name[:-1], time_unit='s')


I am working on the file "0.18/_downloads/d327bd04605fdc3280dac732219b5db7/plot_artifacts_detection.ipynb".
The first task is:
Introduction to artifacts and artifact detection
Since MNE supports the data of many different acquisition systems, the
particular artifacts in your data might behave very differently from the
artifacts you can observe in our tutorials and examples.
Therefore you should be aware of the different approaches and of
the variability of artifact rejection (automatic/manual) procedures described
onwards. At the end consider always to visually inspect your data
after artifact rejection or correction.
Background: what is an artifact?
Artifacts are signal interference that can be
endogenous (biological) and exogenous (environmental).
Typical biological artifacts are head movements, eye blinks
or eye movements, heart beats. The most common environmental
artifact is due to the power line, the so-called line noise.
How to handle artifacts?
MNE deals with artifacts by first identifying them, and subsequently removing
them. Detection of artifacts can be done visually, or using automatic routines
(or a combination of both). After you know what the artifacts are, you need
remove them. This can be done by:
- *ignoring* the piece of corrupted data
- *fixing* the corrupted data

For the artifact detection the functions MNE provides depend on whether
your data is continuous (Raw) or epoch-based (Epochs) and depending on
whether your data is stored on disk or already in memory.
Detecting the artifacts without reading the complete data into memory allows
you to work with datasets that are too large to fit in memory all at once.
Detecting the artifacts in continuous data allows you to apply filters
(e.g. a band-pass filter to zoom in on the muscle artifacts on the temporal
channels) without having to worry about edge effects due to the filter
(i.e. filter ringing). Having the data in memory after segmenting/epoching is
however a very efficient way of browsing through the data which helps
in visualizing. So to conclude, there is not a single most optimal manner
to detect the artifacts: it just depends on the data properties and...
Can you write Python code for it?

import numpy as np

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

# getting some data ready
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'

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


I am working on the file "0.18/_downloads/d327bd04605fdc3280dac732219b5db7/plot_artifacts_detection.ipynb".
The first task is:
Low frequency drifts and line noise
Can you write Python code for it?

(raw.copy().pick_types(meg='mag')
           .del_proj(0)
           .plot(duration=60, n_channels=100, remove_dc=False))


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

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


I am working on the file "0.18/_downloads/d4c795380277f09ea21841616baceb71/plot_dics_source_power.ipynb".
The first task is:
Compute source power using DICS beamfomer
Compute a Dynamic Imaging of Coherent Sources (DICS) [1]_ filter from
single-trial activity to estimate source power across a frequency band. This
example demonstrates how to source localize the event-related synchronization
(ERS) of beta band activity in the "somato" dataset.
References
.. [1] Gross et al. Dynamic imaging of coherent sources: Studying neural
       interactions in the human brain. PNAS (2001) vol. 98 (2) pp. 694-699
Can you write Python code for it?

# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
#         Roman Goj <roman.goj@gmail.com>
#         Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne.datasets import somato
from mne.time_frequency import csd_morlet
from mne.beamformer import make_dics, apply_dics_csd

print(__doc__)


I am working on the file "0.18/_downloads/d4c795380277f09ea21841616baceb71/plot_dics_source_power.ipynb".
The first task is:
Computing DICS spatial filters using the CSD that was computed on the entire
timecourse.
Can you write Python code for it?

filters = make_dics(epochs.info, fwd, csd.mean(), pick_ori='max-power')


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

data_path = somato.data_path()
raw_fname = data_path + '/MEG/somato/sef_raw_sss.fif'
fname_fwd = data_path + '/MEG/somato/somato-meg-oct-6-fwd.fif'
subjects_dir = data_path + '/subjects'

raw = mne.io.read_raw_fif(raw_fname)

# Set picks, use a single sensor type
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
fwd = mne.read_forward_solution(fname_fwd)


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

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


I am working on the file "0.18/_downloads/d71abe904faddac1a89e44f2986e07fa/plot_mne_inverse_label_connectivity.ipynb".
The first task is:
Compute inverse solutions and their connectivity
Next, we need to compute the inverse solution for this data. This will return
the sources / source activity that we'll use in computing connectivity. We'll
compute the connectivity in the alpha band of these sources. We can specify
particular frequencies to include in the connectivity with the fmin and
fmax flags. Notice from the status messages how mne-python:

reads an epoch from the raw file
applies SSP and baseline correction
computes the inverse to obtain a source estimate
averages the source estimate to obtain a time series for each label
includes the label time series in the connectivity computation
moves to the next epoch.

This behaviour is because we are using generators. Since we only need to
operate on the data one epoch at a time, using a generator allows us to
compute connectivity in a computationally efficient manner where the amount
of memory (RAM) needed is independent from the number of epochs.
Can you write Python code for it?

# Compute inverse solution and for each epoch. By using "return_generator=True"
# stcs will be a generator object instead of a list.
snr = 1.0  # use lower SNR for single epochs
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)
stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method,
                            pick_ori="normal", return_generator=True)

# Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi
labels = mne.read_labels_from_annot('sample', parc='aparc',
                                    subjects_dir=subjects_dir)
label_colors = [label.color for label in labels]

# Average the source estimates within each label using sign-flips to reduce
# signal cancellations, also here we return a generator
src = inverse_operator['src']
label_ts = mne.extract_label_time_course(stcs, labels, src, mode='mean_flip',
                                         return_generator=True)

fmin = 8.
fmax = 13.
sfreq = raw.info['sfreq']  # the sampling frequency
con_methods = ['pli', 'wpli2_debiased']
con, freqs, times, n_epochs, n_tapers = spectral_connectivity(
    label_ts, method=con_methods, mode='multitaper', sfreq=sfreq, fmin=fmin,
    fmax=fmax, faverage=True, mt_adaptive=True, n_jobs=1)

# con is a 3D array, get the connectivity for the first (and only) freq. band
# for each method
con_res = dict()
for method, c in zip(con_methods, con):
    con_res[method] = c[:, :, 0]


I am working on the file "0.18/_downloads/d71abe904faddac1a89e44f2986e07fa/plot_mne_inverse_label_connectivity.ipynb".
The first task is:
Compute source space connectivity and visualize it using a circular graph
This example computes the all-to-all connectivity between 68 regions in
source space based on dSPM inverse solutions and a FreeSurfer cortical
parcellation. The connectivity is visualized using a circular graph which
is ordered based on the locations of the regions in the axial plane.
Can you write Python code for it?

# Authors: Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#          Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Nicolas P. Rougier (graph code borrowed from his matplotlib gallery)
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.datasets import sample
from mne.minimum_norm import apply_inverse_epochs, read_inverse_operator
from mne.connectivity import spectral_connectivity
from mne.viz import circular_layout, plot_connectivity_circle

print(__doc__)


I am working on the file "0.18/_downloads/d71abe904faddac1a89e44f2986e07fa/plot_mne_inverse_label_connectivity.ipynb".
The first task is:
Make a connectivity plot
Now, we visualize this connectivity using a circular graph layout.
Can you write Python code for it?

# First, we reorder the labels based on their location in the left hemi
label_names = [label.name for label in labels]

lh_labels = [name for name in label_names if name.endswith('lh')]

# Get the y-location of the label
label_ypos = list()
for name in lh_labels:
    idx = label_names.index(name)
    ypos = np.mean(labels[idx].pos[:, 1])
    label_ypos.append(ypos)

# Reorder the labels based on their location
lh_labels = [label for (yp, label) in sorted(zip(label_ypos, lh_labels))]

# For the right hemi
rh_labels = [label[:-2] + 'rh' for label in lh_labels]

# Save the plot order and create a circular layout
node_order = list()
node_order.extend(lh_labels[::-1])  # reverse the order
node_order.extend(rh_labels)

node_angles = circular_layout(label_names, node_order, start_pos=90,
                              group_boundaries=[0, len(label_names) / 2])

# Plot the graph using node colors from the FreeSurfer parcellation. We only
# show the 300 strongest connections.
plot_connectivity_circle(con_res['pli'], label_names, n_lines=300,
                         node_angles=node_angles, node_colors=label_colors,
                         title='All-to-All Connectivity left-Auditory '
                               'Condition (PLI)')


I am working on the file "0.18/_downloads/d71abe904faddac1a89e44f2986e07fa/plot_mne_inverse_label_connectivity.ipynb".
The first task is:
Make two connectivity plots in the same figure
We can also assign these connectivity plots to axes in a figure. Below we'll
show the connectivity plot using two different connectivity methods.
Can you write Python code for it?

fig = plt.figure(num=None, figsize=(8, 4), facecolor='black')
no_names = [''] * len(label_names)
for ii, method in enumerate(con_methods):
    plot_connectivity_circle(con_res[method], no_names, n_lines=300,
                             node_angles=node_angles, node_colors=label_colors,
                             title=method, padding=0, fontsize_colorbar=6,
                             fig=fig, subplot=(1, 2, ii + 1))

plt.show()


I am working on the file "0.18/_downloads/d71abe904faddac1a89e44f2986e07fa/plot_mne_inverse_label_connectivity.ipynb".
The first task is:
Save the figure (optional)
By default matplotlib does not save using the facecolor, even though this was
set when the figure was generated. If not set via savefig, the labels, title,
and legend will be cut off from the output png file.
Can you write Python code for it?

# fname_fig = data_path + '/MEG/sample/plot_inverse_connect.png'
# fig.savefig(fname_fig, facecolor='black')


I am working on the file "0.18/_downloads/d9e7f23ac267ddfa6023c7da2df2a984/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
A stat_fun must deal with a variable number of input arguments.
Inside the clustering function each condition will be passed as flattened
array, necessitated by the clustering procedure. The ANOVA however expects an
input array of dimensions: subjects X conditions X observations (optional).
The following function catches the list input and swaps the first and
the second dimension and finally calls the ANOVA function.
Can you write Python code for it?

def stat_fun(*args):
    return f_mway_rm(np.swapaxes(args, 1, 0), factor_levels=factor_levels,
                     effects=effects, return_pvals=False)[0]

# The ANOVA returns a tuple f-values and p-values, we will pick the former.
pthresh = 0.001  # set threshold rather high to save some time
f_thresh = f_threshold_mway_rm(n_replications, factor_levels, effects,
                               pthresh)
tail = 1  # f-test, so tail > 0
n_permutations = 256  # Save some time (the test won't be too sensitive ...)
T_obs, clusters, cluster_p_values, h0 = mne.stats.permutation_cluster_test(
    epochs_power, stat_fun=stat_fun, threshold=f_thresh, tail=tail, n_jobs=1,
    n_permutations=n_permutations, buffer_size=None)


I am working on the file "0.18/_downloads/d9e7f23ac267ddfa6023c7da2df2a984/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
Account for multiple comparisons using FDR versus permutation clustering test
First we need to slightly modify the ANOVA function to be suitable for
the clustering procedure. Also want to set some defaults.
Let's first override effects to confine the analysis to the interaction
Can you write Python code for it?


I am working on the file "0.18/_downloads/d9e7f23ac267ddfa6023c7da2df2a984/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
Mass-univariate twoway repeated measures ANOVA on single trial power
This script shows how to conduct a mass-univariate repeated measures
ANOVA. As the model to be fitted assumes two fully crossed factors,
we will study the interplay between perceptual modality
(auditory VS visual) and the location of stimulus presentation
(left VS right). Here we use single trials as replications
(subjects) while iterating over time slices plus frequency bands
for to fit our mass-univariate model. For the sake of simplicity we
will confine this analysis to one single channel of which we know
that it exposes a strong induced response. We will then visualize
each effect by creating a corresponding mass-univariate effect
image. We conclude with accounting for multiple comparisons by
performing a permutation clustering test using the ANOVA as
clustering function. The results final will be compared to
multiple comparisons using False Discovery Rate correction.
Can you write Python code for it?

# Authors: Denis Engemann <denis.engemann@gmail.com>
#          Eric Larson <larson.eric.d@gmail.com>
#          Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.time_frequency import tfr_morlet
from mne.stats import f_threshold_mway_rm, f_mway_rm, fdr_correction
from mne.datasets import sample

print(__doc__)


I am working on the file "0.18/_downloads/d9e7f23ac267ddfa6023c7da2df2a984/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
Now we'll assemble the data matrix and swap axes so the trial replications
are the first dimension and the conditions are the second dimension.
Can you write Python code for it?

data = np.swapaxes(np.asarray(epochs_power), 1, 0)
# reshape last two dimensions in one mass-univariate observation-vector
data = data.reshape(n_replications, n_conditions, n_freqs * n_times)

# so we have replications * conditions * observations:
print(data.shape)


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

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_raw-eve.fif'
tmin, tmax = -0.2, 0.5

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

include = []
raw.info['bads'] += ['MEG 2443']  # bads

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

ch_name = 'MEG 1332'

# Load conditions
reject = dict(grad=4000e-13, eog=150e-6)
event_id = dict(aud_l=1, aud_r=2, vis_l=3, vis_r=4)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                    picks=picks, baseline=(None, 0), preload=True,
                    reject=reject)
epochs.pick_channels([ch_name])  # restrict example to one channel


I am working on the file "0.18/_downloads/d9e7f23ac267ddfa6023c7da2df2a984/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
We have to make sure all conditions have the same counts, as the ANOVA
expects a fully balanced data matrix and does not forgive imbalances that
generously (risk of type-I error).
Can you write Python code for it?

epochs.equalize_event_counts(event_id)

# Factor to down-sample the temporal dimension of the TFR computed by
# tfr_morlet.
decim = 2
freqs = np.arange(7, 30, 3)  # define frequencies of interest
n_cycles = freqs / freqs[0]
zero_mean = False  # don't correct morlet wavelet to be of mean zero
# To have a true wavelet zero_mean should be True but here for illustration
# purposes it helps to spot the evoked response.


I am working on the file "0.18/_downloads/d9e7f23ac267ddfa6023c7da2df2a984/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
While the iteration scheme used above for assembling the data matrix
makes sure the first two dimensions are organized as expected (with A =
modality and B = location):
.. table:: Sample data layout
===== ==== ==== ==== ====
   trial A1B1 A1B2 A2B1 B2B2
   ===== ==== ==== ==== ====
   1     1.34 2.53 0.97 1.74
   ...   ...  ...  ...  ...
   56    2.45 7.90 3.09 4.76
   ===== ==== ==== ==== ====
Now we're ready to run our repeated measures ANOVA.
Note. As we treat trials as subjects, the test only accounts for
time locked responses despite the 'induced' approach.
For analysis for induced power at the group level averaged TRFs
are required.
Can you write Python code for it?

fvals, pvals = f_mway_rm(data, factor_levels, effects=effects)

effect_labels = ['modality', 'location', 'modality by location']

# let's visualize our effects by computing f-images
for effect, sig, effect_label in zip(fvals, pvals, effect_labels):
    plt.figure()
    # show naive F-values in gray
    plt.imshow(effect.reshape(8, 211), cmap=plt.cm.gray, extent=[times[0],
               times[-1], freqs[0], freqs[-1]], aspect='auto',
               origin='lower')
    # create mask for significant Time-frequency locations
    effect = np.ma.masked_array(effect, [sig > .05])
    plt.imshow(effect.reshape(8, 211), cmap='RdBu_r', extent=[times[0],
               times[-1], freqs[0], freqs[-1]], aspect='auto',
               origin='lower')
    plt.colorbar()
    plt.xlabel('Time (ms)')
    plt.ylabel('Frequency (Hz)')
    plt.title(r"Time-locked response for '%s' (%s)" % (effect_label, ch_name))
    plt.show()


I am working on the file "0.18/_downloads/db126f84a1b5439712a1d57b1be2255c/plot_time_frequency_global_field_power.ipynb".
The first task is:
We create average power time courses for each frequency band
Can you write Python code for it?

# set epoching parameters
event_id, tmin, tmax = 1, -1., 3.
baseline = None

# get the header to extract events
raw = mne.io.read_raw_fif(raw_fname, preload=False)
events = mne.find_events(raw, stim_channel='STI 014')

frequency_map = list()

for band, fmin, fmax in iter_freqs:
    # (re)load the data to save memory
    raw = mne.io.read_raw_fif(raw_fname, preload=True)
    raw.pick_types(meg='grad', eog=True)  # we just look at gradiometers

    # bandpass filter and compute Hilbert
    raw.filter(fmin, fmax, n_jobs=1,  # use more jobs to speed up.
               l_trans_bandwidth=1,  # make sure filter params are the same
               h_trans_bandwidth=1,  # in each band and skip "auto" option.
               fir_design='firwin')
    raw.apply_hilbert(n_jobs=1, envelope=False)

    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, baseline=baseline,
                        reject=dict(grad=4000e-13, eog=350e-6), preload=True)
    # remove evoked response and get analytic signal (envelope)
    epochs.subtract_evoked()  # for this we need to construct new epochs.
    epochs = mne.EpochsArray(
        data=np.abs(epochs.get_data()), info=epochs.info, tmin=epochs.tmin)
    # now average and move on
    frequency_map.append(((band, fmin, fmax), epochs.average()))


I am working on the file "0.18/_downloads/db1991d3949b36cc336dce254c001fb0/plot_visualize_evoked.ipynb".
The first task is:
All plotting functions of MNE-python return a handle to the figure instance.
When we have the handle, we can customise the plots to our liking. For
example, we can get rid of the empty space with a simple function call.
Can you write Python code for it?


I am working on the file "0.18/_downloads/db1991d3949b36cc336dce254c001fb0/plot_visualize_evoked.ipynb".
The first task is:
Finally we plot the sensor data as a topographical view. In the simple case
we plot only left auditory responses, and then we plot them all in the same
figure for comparison. Click on the individual plots to open them bigger.
Can you write Python code for it?

title = 'MNE sample data\n(condition : %s)'
evoked_l_aud.plot_topo(title=title % evoked_l_aud.comment,
                       background_color='k', color=['white'])
mne.viz.plot_evoked_topo(evoked, title=title % 'Left/Right Auditory/Visual',
                         background_color='w')


I am working on the file "0.18/_downloads/db1991d3949b36cc336dce254c001fb0/plot_visualize_evoked.ipynb".
The first task is:
First we read the evoked object from a file. Check out
tut_epoching_and_averaging to get to this stage from raw data.
Can you write Python code for it?

data_path = mne.datasets.sample.data_path()
fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')
evoked = mne.read_evokeds(fname, baseline=(None, 0), proj=True)
print(evoked)


I am working on the file "0.18/_downloads/db1991d3949b36cc336dce254c001fb0/plot_visualize_evoked.ipynb".
The first task is:
For small numbers of sensors, it is also possible to create a more refined
topoplot. Again, clicking on a sensor opens a single-sensor plot.
Can you write Python code for it?

mne.viz.plot_compare_evokeds(evoked_dict, picks="eeg", colors=colors,
                             linestyles=linestyles, split_legend=True,
                             axes="topo")


I am working on the file "0.18/_downloads/db1991d3949b36cc336dce254c001fb0/plot_visualize_evoked.ipynb".
The first task is:
Let's start with a simple one. We plot event related potentials / fields
(ERP/ERF). The bad channels are not plotted by default. Here we explicitly
set the exclude parameter to show the bad channels in red. All plotting
functions of MNE-python return a handle to the figure instance. When we have
the handle, we can customise the plots to our liking.
Can you write Python code for it?

fig = evoked_l_aud.plot(exclude=(), time_unit='s')


I am working on the file "0.18/_downloads/db1991d3949b36cc336dce254c001fb0/plot_visualize_evoked.ipynb".
The first task is:
Notice that we created five axes, but had only four categories. The fifth
axes was used for drawing the colorbar. You must provide room for it when you
create this kind of custom plots or turn the colorbar off with
colorbar=False. That's what the warnings are trying to tell you. Also, we
used show=False for the three first function calls. This prevents the
showing of the figure prematurely. The behavior depends on the mode you are
using for your Python session. See https://matplotlib.org/users/shell.html
for more information.
We can combine the two kinds of plots in one figure using the
:func:mne.Evoked.plot_joint method of Evoked objects. Called as-is
(evoked.plot_joint()), this function should give an informative display
of spatio-temporal dynamics.
You can directly style the time series part and the topomap part of the plot
using the topomap_args and ts_args parameters. You can pass key-value
pairs as a Python dictionary. These are then passed as parameters to the
topomaps (:func:mne.Evoked.plot_topomap) and time series
(:func:mne.Evoked.plot) of the joint plot.
For an example of specific styling using these topomap_args and
ts_args arguments, here, topomaps at specific time points
(90 and 200 ms) are shown, sensors are not plotted (via an argument
forwarded to plot_topomap), and the Global Field Power is shown:
Can you write Python code for it?

ts_args = dict(gfp=True, time_unit='s')
topomap_args = dict(sensors=False, time_unit='s')
evoked_r_aud.plot_joint(title='right auditory', times=[.09, .20],
                        ts_args=ts_args, topomap_args=topomap_args)


I am working on the file "0.18/_downloads/db1991d3949b36cc336dce254c001fb0/plot_visualize_evoked.ipynb".
The first task is:
Notice the legend on the left. The colors would suggest that there may be two
separate sources for the signals. This wasn't obvious from the first figure.
Try painting the slopes with left mouse button. It should open a new window
with topomaps (scalp plots) of the average over the painted area. There is
also a function for drawing topomaps separately.
Can you write Python code for it?


I am working on the file "0.18/_downloads/db1991d3949b36cc336dce254c001fb0/plot_visualize_evoked.ipynb".
The first task is:
Now we will make it a bit fancier and only use MEG channels. Many of the
MNE-functions include a picks parameter to include a selection of
channels. picks is simply a list of channel indices that you can easily
construct with :func:mne.pick_types, :func:mne.pick_channels,
:func:mne.pick_channels_regexp, or a list of strings that can be
interpreted as channel names or channel types.
Using spatial_colors=True, the individual channel lines are color coded
to show the sensor positions - specifically, the x, y, and z locations of
the sensors are transformed into R, G and B values.
Can you write Python code for it?


I am working on the file "0.18/_downloads/db1991d3949b36cc336dce254c001fb0/plot_visualize_evoked.ipynb".
The first task is:
Or we can select automatically the peaks.
Can you write Python code for it?


I am working on the file "0.18/_downloads/db1991d3949b36cc336dce254c001fb0/plot_visualize_evoked.ipynb".
The first task is:
We can also plot the activations as arrow maps on top of the topoplot.
The arrows represent an estimation of the current flow underneath the MEG
sensors. Here, sample number 175 corresponds to the time of the maximum
sensor space activity.
Can you write Python code for it?

evoked_l_aud_mag = evoked_l_aud.copy().pick_types(meg='mag')
mne.viz.plot_arrowmap(evoked_l_aud_mag.data[:, 175], evoked_l_aud_mag.info)


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

Note

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

Can you write Python code for it?

bem = mne.read_bem_solution(bem_fname)
trans = None

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

fwd = mne.read_forward_solution(fwd_fname)

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

mlab.view(45, 60, distance=0.4, focalpoint=(0.02, 0, 0.04))


I am working on the file "0.18/_downloads/dc0d85321d22190ec4d4c4394d0057f4/plot_opm_data.ipynb".
The first task is:
Perform dipole fitting
Can you write Python code for it?

# Fit dipoles on a subset of time points
with mne.use_coil_def(coil_def_fname):
    dip_opm, _ = mne.fit_dipole(evoked.copy().crop(0.015, 0.080),
                                cov, bem, trans, verbose=True)
idx = np.argmax(dip_opm.gof)
print('Best dipole at t=%0.1f ms with %0.1f%% GOF'
      % (1000 * dip_opm.times[idx], dip_opm.gof[idx]))

# Plot N20m dipole as an example
dip_opm.plot_locations(trans, subject, subjects_dir,
                       mode='orthoview', idx=idx)


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

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

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

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


I am working on the file "0.18/_downloads/dfbca5f3282b74a009ea0fd98486439e/make_report.ipynb".
The first task is:
Add a custom section with an evoked slider:
Can you write Python code for it?

# Load the evoked data
evoked = read_evokeds(evoked_fname, condition='Left Auditory',
                      baseline=(None, 0), verbose=False)
evoked.crop(0, .2)
times = evoked.times[::4]
# Create a list of figs for the slider
figs = list()
for t in times:
    figs.append(evoked.plot_topomap(t, vmin=-300, vmax=300, res=100,
                                    show=False))
    plt.close(figs[-1])
report.add_slider_to_section(figs, times, 'Evoked Response',
                             image_format='svg')

# to save report
# report.save('foobar.html', True)


I am working on the file "0.18/_downloads/dfbca5f3282b74a009ea0fd98486439e/make_report.ipynb".
The first task is:
Do standard folder parsing (this can take a couple of minutes):
Can you write Python code for it?

report = Report(image_format='png', subjects_dir=subjects_dir,
                info_fname=evoked_fname, subject='sample', raw_psd=True)
report.parse_folder(meg_path)


I am working on the file "0.18/_downloads/dfbca5f3282b74a009ea0fd98486439e/make_report.ipynb".
The first task is:
Make an MNE-Report with a Slider
In this example, MEG evoked data are plotted in an html slider.
Can you write Python code for it?

# Authors: Teon Brooks <teon.brooks@gmail.com>
#          Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)

from mne.report import Report
from mne.datasets import sample
from mne import read_evokeds
from matplotlib import pyplot as plt

data_path = sample.data_path()
meg_path = data_path + '/MEG/sample'
subjects_dir = data_path + '/subjects'
evoked_fname = meg_path + '/sample_audvis-ave.fif'


I am working on the file "0.18/_downloads/e327516e16a734ff2984dcae335b2433/plot_left_cerebellum_volume_source.ipynb".
The first task is:
Compare volume source locations to segmentation file in freeview
Can you write Python code for it?

# Export source positions to nift file
nii_fname = data_path + '/MEG/sample/mne_sample_lh-cerebellum-cortex.nii'

# Combine the source spaces
src = surf + lh_cereb

src.export_volume(nii_fname, mri_resolution=True)

# Uncomment the following lines to display source positions in freeview.
'''
# display image in freeview
from mne.utils import run_subprocess
mri_fname = subjects_dir + '/sample/mri/brain.mgz'
run_subprocess(['freeview', '-v', mri_fname, '-v',
                '%s:colormap=lut:opacity=0.5' % aseg_fname, '-v',
                '%s:colormap=jet:colorscale=0,2' % nii_fname, '-slice',
                '157 75 105'])
'''


I am working on the file "0.18/_downloads/e327516e16a734ff2984dcae335b2433/plot_left_cerebellum_volume_source.ipynb".
The first task is:
Generate a left cerebellum volume source space
Generate a volume source space of the left cerebellum and plot its vertices
relative to the left cortical surface source space and the freesurfer
segmentation file.
Can you write Python code for it?

# Author: Alan Leggitt <alan.leggitt@ucsf.edu>
#
# License: BSD (3-clause)

import numpy as np
from scipy.spatial import ConvexHull
from mayavi import mlab
from mne import setup_source_space, setup_volume_source_space
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
subj = 'sample'
aseg_fname = subjects_dir + '/sample/mri/aseg.mgz'


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

# extract left cortical surface vertices, triangle faces, and surface normals
x1, y1, z1 = lh_surf['rr'].T
faces = lh_surf['use_tris']
normals = lh_surf['nn']
# normalize for mayavi
normals /= np.sum(normals * normals, axis=1)[:, np.newaxis]

# extract left cerebellum cortex source positions
x2, y2, z2 = lh_cereb[0]['rr'][lh_cereb[0]['inuse'].astype(bool)].T

# open a 3d figure in mayavi
mlab.figure(1, bgcolor=(0, 0, 0))

# plot the left cortical surface
mesh = mlab.pipeline.triangular_mesh_source(x1, y1, z1, faces)
mesh.data.point_data.normals = normals
mlab.pipeline.surface(mesh, color=3 * (0.7,))

# plot the convex hull bounding the left cerebellum
hull = ConvexHull(np.c_[x2, y2, z2])
mlab.triangular_mesh(x2, y2, z2, hull.simplices, color=3 * (0.5,), opacity=0.3)

# plot the left cerebellum sources
mlab.points3d(x2, y2, z2, color=(1, 1, 0), scale_factor=0.001)

# adjust view parameters
mlab.view(173.78, 101.75, 0.30, np.array([-0.03, -0.01,  0.03]))
mlab.roll(85)


I am working on the file "0.18/_downloads/e327516e16a734ff2984dcae335b2433/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(subj, 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, 120)
lh_cereb = setup_volume_source_space(subj, mri=aseg_fname, sphere=sphere,
                                     volume_label=volume_label,
                                     subjects_dir=subjects_dir)


I am working on the file "0.18/_downloads/e52b6a53120d8703a6509530cf6251dc/plot_roi_erpimage_by_rt.ipynb".
The first task is:
Load EEGLAB example data (a small EEG dataset)
Can you write Python code for it?

data_path = mne.datasets.testing.data_path()
fname = data_path + "/EEGLAB/test_raw.set"
montage = data_path + "/EEGLAB/test_chans.locs"

event_id = {"rt": 1, "square": 2}  # must be specified for str events
eog = {"FPz", "EOG1", "EOG2"}
raw = mne.io.read_raw_eeglab(fname, eog=eog, montage=montage,
                             stim_channel=False)
events = mne.events_from_annotations(raw, event_id)[0]


I am working on the file "0.18/_downloads/e52b6a53120d8703a6509530cf6251dc/plot_roi_erpimage_by_rt.ipynb".
The first task is:
Plot using 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.18/_downloads/e52b6a53120d8703a6509530cf6251dc/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.]))