I am working on the file "0.16/_downloads/plot_info.ipynb".
The first task is:
Channel types
MNE supports different channel types:

eeg : For EEG channels with data stored in Volts (V)
meg (mag) : For MEG magnetometers channels stored in Tesla (T)
meg (grad) : For MEG gradiometers channels stored in Tesla/Meter (T/m)
ecg : For ECG channels stored in Volts (V)
seeg : For Stereotactic EEG channels in Volts (V).
ecog : For Electrocorticography (ECoG) channels in Volts (V).
fnirs (HBO) : Functional near-infrared spectroscopy oxyhemoglobin data.
fnirs (HBR) : Functional near-infrared spectroscopy deoxyhemoglobin data.
emg : For EMG channels stored in Volts (V)
bio : For biological channels (AU).
stim : For the stimulus (a.k.a. trigger) channels (AU)
resp : For the response-trigger channel (AU)
chpi : For HPI coil channels (T).
exci : Flux excitation channel used to be a stimulus channel.
ias : For Internal Active Shielding data (maybe on Triux only).
syst : System status channel information (on Triux systems only).

Get channel indices by type
Can you write Python code for it?

channel_indices = mne.pick_types(info, meg=True)  # MEG only
channel_indices = mne.pick_types(info, eeg=True)  # EEG only


I am working on the file "0.16/_downloads/plot_info.ipynb".
The first task is:
Dropping channels from an info structure
It is possible to limit the info structure to only include a subset of
channels with the :func:mne.pick_info function:
Can you write Python code for it?

# Only keep EEG channels
eeg_indices = mne.pick_types(info, meg=False, eeg=True)
reduced_info = mne.pick_info(info, eeg_indices)

print(reduced_info)


I am working on the file "0.16/_downloads/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.16/_downloads/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.16/_downloads/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.16/_downloads/plot_info.ipynb".
The first task is:
MEG gradiometers and EEG channels
Can you write Python code for it?

channel_indices = mne.pick_types(info, meg='grad', eeg=True)


I am working on the file "0.16/_downloads/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.16/_downloads/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 = mne.pick_channels(info['ch_names'], ['MEG 0312', 'EEG 005'])


I am working on the file "0.16/_downloads/plot_info.ipynb".
The first task is:
The :class:Info <mne.Info> data structure
The :class:Info <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.16/_downloads/plot_introduction.ipynb".
The first task is:
.. topic:: Exercise

Extract the max value of each epoch
Can you write Python code for it?

max_in_each_epoch = [e.max() for e in epochs['aud_l']]  # doctest:+ELLIPSIS
print(max_in_each_epoch[:4])  # doctest:+ELLIPSIS


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

Note

The MNE sample dataset should be downloaded automatically but be
          patient (approx. 2GB)

Read data from file:
Can you write Python code for it?

raw = mne.io.read_raw_fif(raw_fname)
print(raw)
print(raw.info)


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Alternatively one can restrict to magnetometers or gradiometers with:
Can you write Python code for it?

mag_picks = mne.pick_types(raw.info, meg='mag', eog=True, exclude='bads')
grad_picks = mne.pick_types(raw.info, meg='grad', eog=True, exclude='bads')


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Basic MEG and EEG data processing

MNE-Python reimplements most of MNE-C's (the original MNE command line utils)
functionality and offers transparent scripting.
On top of that it extends MNE-C's functionality considerably
(customize events, compute contrasts, group statistics, time-frequency
analysis, EEG-sensor space analyses, etc.) It uses the same files as standard
MNE unix commands: no need to convert your files to a new system or database.
What you can do with MNE Python

Raw data visualization to visualize recordings, can also use
     mne_browse_raw for extended functionality (see ch_browse)
Epoching: Define epochs, baseline correction, handle conditions etc.
Averaging to get Evoked data
Compute SSP projectors to remove ECG and EOG artifacts
Compute ICA to remove artifacts or select latent sources.
Maxwell filtering to remove environmental noise.
Boundary Element Modeling: single and three-layer BEM model
     creation and solution computation.
Forward modeling: BEM computation and mesh creation
     (see ch_forward)
Linear inverse solvers (MNE, dSPM, sLORETA, eLORETA, LCMV, DICS)
Sparse inverse solvers (L1/L2 mixed norm MxNE, Gamma Map,
     Time-Frequency MxNE)
Connectivity estimation in sensor and source space
Visualization of sensor and source space data
Time-frequency analysis with Morlet wavelets (induced power,
     intertrial coherence, phase lock value) also in the source space
Spectrum estimation using multi-taper method
Mixed Source Models combining cortical and subcortical structures
Dipole Fitting
Decoding multivariate pattern analysis of M/EEG topographies
Compute contrasts between conditions, between sensors, across
     subjects etc.
Non-parametric statistics in time, space and frequency
     (including cluster-level)
Scripting (batch and parallel computing)

What you're not supposed to do with MNE Python
- **Brain and head surface segmentation** for use with BEM
  models -- use Freesurfer.

Note

This package is based on the FIF file format from...
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
By default logging messages print to the console, but look at
:func:mne.set_log_file to save output to a file.
Access raw data
^^^^^^^^^^^^^^^
Can you write Python code for it?

from mne.datasets import sample  # noqa
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
print(raw_fname)


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Compute evoked responses for auditory responses by averaging and plot it:
Can you write Python code for it?

evoked = epochs['aud_l'].average()
print(evoked)
evoked.plot(time_unit='s')


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Compute induced power and phase-locking values and plot gradiometers:
Can you write Python code for it?

from mne.time_frequency import tfr_morlet  # noqa
power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles,
                        return_itc=True, decim=3, n_jobs=1)
power.plot([power.ch_names.index('MEG 1332')])


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Compute inverse solution during the first 15s:
Can you write Python code for it?

from mne.minimum_norm import apply_inverse_raw  # noqa
start, stop = raw.time_as_index([0, 15])  # read the first 15s of data
stc = apply_inverse_raw(raw, inverse_operator, lambda2, method, label,
                        start, stop)


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

stc = apply_inverse(evoked, inverse_operator, lambda2, method)


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Define and read epochs
^^^^^^^^^^^^^^^^^^^^^^
First extract events:
Can you write Python code for it?

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


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Define peak-to-peak rejection parameters for gradiometers, magnetometers
and EOG:
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Define the baseline period:
Can you write Python code for it?

baseline = (None, 0)  # means from the first instant to t = 0


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Get single epochs for one condition:
Can you write Python code for it?

epochs_data = epochs['aud_l'].get_data()
print(epochs_data.shape)


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
If you'd like to turn information status messages off:
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
It is also possible to read evoked data stored in a fif file:
Can you write Python code for it?

evoked_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
evoked1 = mne.read_evokeds(
    evoked_fname, condition='Left Auditory', baseline=(None, 0), proj=True)


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Look at the channels in raw:
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Note that the location of the mne-python preferences file (for easier manual
editing) can be found using:
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Note that, by default, we use stim_channel='STI 014'. If you have a different
system (e.g., a newer system that uses channel 'STI101' by default), you can
use the following to set the default stim channel to use for finding events:
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Now, let's compute dSPM on a raw file within a label:
Can you write Python code for it?

fname_label = data_path + '/MEG/sample/labels/Aud-lh.label'
label = mne.read_label(fname_label)


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Or another one stored in the same file:
Can you write Python code for it?

evoked2 = mne.read_evokeds(
    evoked_fname, condition='Right Auditory', baseline=(None, 0), proj=True)


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Read epochs:
Can you write Python code for it?

epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks,
                    baseline=baseline, preload=False, reject=reject)
print(epochs)


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Read the inverse operator:
Can you write Python code for it?

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


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Save a segment of 150s of raw data (MEG only):
Can you write Python code for it?

picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True,
                       exclude='bads')
raw.save('sample_audvis_meg_raw.fif', tmin=0, tmax=150, picks=picks,
         overwrite=True)


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Save the source time courses to disk:
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
The variable raw.info['bads'] is just a python list.
Pick the good channels, excluding raw.info['bads']:
Can you write Python code for it?

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


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
To do a weighted sum based on the number of averages, which will give
you what you would have gotten from pooling all trials together in
:class:mne.Epochs before creating the :class:mne.Evoked instance,
you can use weights='nave':
Can you write Python code for it?

average = mne.combine_evoked([evoked1, evoked2], weights='nave')
print(contrast)


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
Two evoked objects can be contrasted using :func:mne.combine_evoked.
This function can use weights='equal', which provides a simple
element-by-element subtraction (and sets the
mne.Evoked.nave attribute properly based on the underlying number
of trials) using either equivalent call:
Can you write Python code for it?

contrast = mne.combine_evoked([evoked1, evoked2], weights=[0.5, -0.5])
contrast = mne.combine_evoked([evoked1, -evoked2], weights='equal')
print(contrast)


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
What else can you do?
^^^^^^^^^^^^^^^^^^^^^
- detect heart beat QRS component
- detect eye blinks and EOG artifacts
- compute SSP projections to remove ECG or EOG artifacts
- compute Independent Component Analysis (ICA) to remove artifacts or
  select latent sources
- estimate noise covariance matrix from Raw and Epochs
- visualize cross-trial response dynamics using epochs images
- compute forward solutions
- estimate power in the source space
- estimate connectivity in sensor and source space
- morph stc from one brain to another for group studies
- compute mass univariate statistics base on custom contrasts
- visualize source estimates
- export raw, epochs, and evoked data to other python data analysis
  libraries e.g. pandas
- and many more things ...

Want to know more ?
^^^^^^^^^^^^^^^^^^^
Browse the examples gallery <auto_examples/index.html>_.
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
You can set the default level by setting the environment variable
"MNE_LOGGING_LEVEL", or by having mne-python write preferences to a file:
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
and read them later with:
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_introduction.ipynb".
The first task is:
or if you want to keep all the information about the data you can save your
epochs in a fif file:
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_label_from_stc.ipynb".
The first task is:
Generate a functional label from source estimates
Threshold source estimates and produce a functional label. The label
is typically the region of interest that contains high values.
Here we compare the average time course in the anatomical label obtained
by FreeSurfer segmentation and the average time course from the
functional label. As expected the time course in the functional
label yields higher values.
Can you write Python code for it?

# Author: Luke Bloy <luke.bloy@gmail.com>
#         Alex Gramfort <alexandre.gramfort@telecom-paristech.fr>
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

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

print(__doc__)

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
subjects_dir = data_path + '/subjects'
subject = 'sample'

snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

# Compute a label/ROI based on the peak power between 80 and 120 ms.
# The label bankssts-lh is used for the comparison.
aparc_label_name = 'bankssts-lh'
tmin, tmax = 0.080, 0.120

# Load data
evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
inverse_operator = read_inverse_operator(fname_inv)
src = inverse_operator['src']  # get the source space

# Compute inverse solution
stc = apply_inverse(evoked, inverse_operator, lambda2, method,
                    pick_ori='normal')

# Make an STC in the time interval of interest and take the mean
stc_mean = stc.copy().crop(tmin, tmax).mean()

# use the stc_mean to generate a functional label
# region growing is halted at 60% of the peak value within the
# anatomical label / ROI specified by aparc_label_name
label = mne.read_labels_from_annot(subject, parc='aparc',
                                   subjects_dir=subjects_dir,
                                   regexp=aparc_label_name)[0]
stc_mean_label = stc_mean.in_label(label)
data = np.abs(stc_mean_label.data)
stc_mean_label.data[data < 0.6 * np.max(data)] = 0.

# 8.5% of original source space vertices were omitted during forward
# calculation, suppress the warning here with verbose='error'
func_labels, _ = mne.stc_to_label(stc_mean_label, src=src, smooth=True,
                                  subjects_dir=subjects_dir,...


I am working on the file "0.16/_downloads/plot_label_from_stc.ipynb".
The first task is:
plot brain in 3D with PySurfer if available
Can you write Python code for it?

brain = stc_mean.plot(hemi='lh', subjects_dir=subjects_dir)
brain.show_view('lateral')

# show both labels
brain.add_label(anat_label, borders=True, color='k')
brain.add_label(func_label, borders=True, color='b')


I am working on the file "0.16/_downloads/plot_lcmv_beamformer.ipynb".
The first task is:
Compute LCMV beamformer on evoked data
Compute LCMV beamformer solutions on an evoked dataset for three different
choices of source orientation and store the solutions in stc files for
visualisation.
Can you write Python code for it?

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

# sphinx_gallery_thumbnail_number = 3

import matplotlib.pyplot as plt
import numpy as np

import mne
from mne.datasets import sample
from mne.beamformer import make_lcmv, apply_lcmv

print(__doc__)

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'
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
label_name = 'Aud-lh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name
subjects_dir = data_path + '/subjects'


I am working on the file "0.16/_downloads/plot_lcmv_beamformer.ipynb".
The first task is:
Run beamformers and look at maximum outputs
Can you write Python code for it?

pick_oris = [None, 'normal', 'max-power']
names = ['free', 'normal', 'max-power']
descriptions = ['Free orientation, voxel: %i', 'Normal orientation, voxel: %i',
                'Max-power orientation, voxel: %i']
colors = ['b', 'k', 'r']

fig, ax = plt.subplots(1)
max_voxs = list()
for pick_ori, name, desc, color in zip(pick_oris, names, descriptions, colors):
    # compute unit-noise-gain beamformer with whitening of the leadfield and
    # data (enabled by passing a noise covariance matrix)
    filters = make_lcmv(evoked.info, forward, data_cov, reg=0.05,
                        noise_cov=noise_cov, pick_ori=pick_ori,
                        weight_norm='unit-noise-gain')
    # apply this spatial filter to source-reconstruct the evoked data
    stc = apply_lcmv(evoked, filters, max_ori_out='signed')

    # View activation time-series in maximum voxel at 100 ms:
    time_idx = stc.time_as_index(0.1)
    max_idx = np.argmax(stc.data[:, time_idx])
    # we know these are all left hemi, so we can just use vertices[0]
    max_voxs.append(stc.vertices[0][max_idx])
    ax.plot(stc.times, stc.data[max_idx, :], color, label=desc % max_idx)

ax.set(xlabel='Time (ms)', ylabel='LCMV value', ylim=(-0.8, 2.2),
       title='LCMV in maximum voxel')
ax.legend()
mne.viz.utils.plt_show()


I am working on the file "0.16/_downloads/plot_lcmv_beamformer.ipynb".
The first task is:
We can also look at the spatial distribution
Can you write Python code for it?

# take absolute value for plotting
np.abs(stc.data, out=stc.data)

# Plot last stc in the brain in 3D with PySurfer if available
brain = stc.plot(hemi='lh', subjects_dir=subjects_dir,
                 initial_time=0.1, time_unit='s')
brain.show_view('lateral')
for color, vertex in zip(colors, max_voxs):
    brain.add_foci([vertex], coords_as_verts=True, scale_factor=0.5,
                   hemi='lh', color=color)


I am working on the file "0.16/_downloads/plot_lcmv_beamformer_volume.ipynb".
The first task is:
Compute LCMV inverse solution on evoked data in volume source space
Compute LCMV inverse solution on an auditory evoked dataset in a volume source
space. It stores the solution in a nifti file for visualisation, e.g. with
Freeview.
Can you write Python code for it?

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

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.datasets import sample
from mne.beamformer import make_lcmv, apply_lcmv

from nilearn.plotting import plot_stat_map
from nilearn.image import index_img

print(__doc__)

# sphinx_gallery_thumbnail_number = 3


I am working on the file "0.16/_downloads/plot_lcmv_beamformer_volume.ipynb".
The first task is:
Data preprocessing:
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'
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-vol-7-fwd.fif'

# Get epochs
event_id, tmin, tmax = [1, 2], -0.2, 0.5

# Setup for reading the raw data
raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.info['bads'] = ['MEG 2443', 'EEG 053']  # 2 bads channels
events = mne.read_events(event_fname)

# Set up pick list: gradiometers and magnetometers, excluding bad channels
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True,
                       exclude='bads')

# Pick the channels of interest
raw.pick_channels([raw.ch_names[pick] for pick in picks])

# Re-normalize our empty-room projectors, so they are fine after subselection
raw.info.normalize_proj()

# Read epochs
proj = False  # already applied
epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                    baseline=(None, 0), preload=True, proj=proj,
                    reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
evoked = epochs.average()

# Visualize sensor space data
evoked.plot_joint(ts_args=dict(time_unit='s'),
                  topomap_args=dict(time_unit='s'))


I am working on the file "0.16/_downloads/plot_lcmv_beamformer_volume.ipynb".
The first task is:
Plot source space activity:
Can you write Python code for it?

# take absolute values for plotting
stc.data[:, :] = np.abs(stc.data)

# Save result in stc files
stc.save('lcmv-vol')

stc.crop(0.0, 0.2)

# Save result in a 4D nifti file
img = mne.save_stc_as_volume('lcmv_inverse.nii.gz', stc,
                             forward['src'], mri_resolution=False)

t1_fname = data_path + '/subjects/sample/mri/T1.mgz'

# Plotting with nilearn ######################################################
# Based on the visualization of the sensor space data (gradiometers), plot
# activity at 88 ms
idx = stc.time_as_index(0.088)
plot_stat_map(index_img(img, idx), t1_fname, threshold=0.45,
              title='LCMV (t=%.3f s.)' % stc.times[idx])

# plot source time courses with the maximum peak amplitudes at 88 ms
plt.figure()
plt.plot(stc.times, stc.data[np.argsort(np.max(stc.data[:, idx],
                                               axis=1))[-40:]].T)
plt.xlabel('Time (ms)')
plt.ylabel('LCMV value')
plt.show()


I am working on the file "0.16/_downloads/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.16/_downloads/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()))  # 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.16/_downloads/plot_linear_model_patterns.ipynb".
The first task is:
Linear classifier on sensor data with plot patterns and filters
Here decoding, a.k.a MVPA or supervised machine learning, is applied to M/EEG
data in sensor space. Fit a linear classifier with the LinearModel object
providing topographical patterns which are more neurophysiologically
interpretable [1]_ than the classifier filters (weight vectors).
The patterns explain how the MEG and EEG data were generated from the
discriminant neural sources which are extracted by the filters.
Note patterns/filters in MEG data are more similar than EEG data
because the noise is less spatially correlated in MEG than EEG.
References
.. [1] Haufe, S., Meinecke, F., Görgen, K., Dähne, S., Haynes, J.-D.,
       Blankertz, B., & Bießmann, F. (2014). On the interpretation of
       weight vectors of linear models in multivariate neuroimaging.
       NeuroImage, 87, 96–110. doi:10.1016/j.neuroimage.2013.10.067
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Romain Trachel <trachelr@gmail.com>
#          Jean-Remi King <jeanremi.king@gmail.com>
#
# License: BSD (3-clause)

import mne
from mne import io, EvokedArray
from mne.datasets import sample
from mne.decoding import Vectorizer, get_coef

from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline

# import a linear classifier from mne.decoding
from mne.decoding import LinearModel

print(__doc__)

data_path = sample.data_path()


I am working on the file "0.16/_downloads/plot_metadata_epochs.ipynb".
The first task is:

Note

Creating an :class:`mne.Epochs` object with metadata is done by passing
   a :class:`pandas.DataFrame` to the ``metadata`` kwarg as follows:

Can you write Python code for it?

data = epochs.get_data()
metadata = epochs.metadata.copy()
epochs_new = mne.EpochsArray(data, epochs.info, metadata=metadata)


I am working on the file "0.16/_downloads/plot_metadata_epochs.ipynb".
The first task is:
And finally, for the interaction between concreteness and continuous length
in letters:
Can you write Python code for it?

evokeds = dict()
query = "is_concrete == '{0}' & NumberOfLetters == {1}"
for concreteness in ("Concrete", "Abstract"):
    for n_letters in letters:
        subset = epochs[query.format(concreteness, n_letters)]
        evokeds["/".join((concreteness, n_letters))] = subset.average()

style_plot["linestyles"] = {"Concrete": "-", "Abstract": ":"}

fig, ax = plt.subplots(figsize=(6, 4))
mne.viz.plot_compare_evokeds(evokeds, axes=ax, **style_plot)
plt.show()


I am working on the file "0.16/_downloads/plot_metadata_epochs.ipynb".
The first task is:
Next we'll choose a subset of words to keep.
Can you write Python code for it?

words = ['film', 'cent', 'shot', 'cold', 'main']
epochs['WORD in {}'.format(words)].plot_image(show=False)


I am working on the file "0.16/_downloads/plot_metadata_epochs.ipynb".
The first task is:
Note that traditional epochs sub-selection still works. The traditional
MNE methods for selecting epochs will supersede the rich metadata querying.
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_metadata_epochs.ipynb".
The first task is:
Now we can quickly extract (and plot) subsets of the data. For example, to
look at words split by word length and concreteness:
Can you write Python code for it?

query = "is_long == '{0}' & is_concrete == '{1}'"
evokeds = dict()
for concreteness in ("Concrete", "Abstract"):
    for length in ("Long", "Short"):
        subset = epochs[query.format(length, concreteness)]
        evokeds["/".join((concreteness, length))] = list(subset.iter_evoked())

# For the actual visualisation, we store a number of shared parameters.
style_plot = dict(
    colors={"Long": "Crimson", "Short": "Cornflowerblue"},
    linestyles={"Concrete": "-", "Abstract": ":"},
    split_legend=True,
    ci=.68,
    show_sensors='lower right',
    show_legend='lower left',
    truncate_yaxis="max_ticks",
    picks=epochs.ch_names.index("Pz"),
)

fig, ax = plt.subplots(figsize=(6, 4))
mne.viz.plot_compare_evokeds(evokeds, axes=ax, **style_plot)
plt.show()


I am working on the file "0.16/_downloads/plot_metadata_epochs.ipynb".
The first task is:
To compare words which are 4, 5, 6, 7 or 8 letters long:
Can you write Python code for it?

letters = epochs.metadata["NumberOfLetters"].unique().astype(int).astype(str)

evokeds = dict()
for n_letters in letters:
    evokeds[n_letters] = epochs["NumberOfLetters == " + n_letters].average()

style_plot["colors"] = {n_letters: int(n_letters)
                        for n_letters in letters}
style_plot["cmap"] = ("# of Letters", "viridis_r")
del style_plot['linestyles']

fig, ax = plt.subplots(figsize=(6, 4))
mne.viz.plot_compare_evokeds(evokeds, axes=ax, **style_plot)
plt.show()


I am working on the file "0.16/_downloads/plot_metadata_epochs.ipynb".
The first task is:
We can use this metadata attribute to select subsets of Epochs. This
uses the Pandas :meth:pandas.DataFrame.query method under the hood.
Any valid query string will work. Below we'll make two plots to compare
between them:
Can you write Python code for it?

av1 = epochs['Concreteness < 5 and WordFrequency < 2'].average()
av2 = epochs['Concreteness > 5 and WordFrequency > 2'].average()

joint_kwargs = dict(ts_args=dict(time_unit='s'),
                    topomap_args=dict(time_unit='s'))
av1.plot_joint(show=False, **joint_kwargs)
av2.plot_joint(show=False, **joint_kwargs)


I am working on the file "0.16/_downloads/plot_metadata_query.ipynb".
The first task is:
First we'll create our metadata object. This should be a
:class:pandas.DataFrame with each row corresponding to an event.

Warning

Do not set or change the Dataframe index of ``epochs.metadata``.
             It will be controlled by MNE to mirror ``epochs.selection``.
             Also, while some inplace operations on ``epochs.metadata`` are
             possible, do not manually drop or add rows, as this will
             create inconsistency between the metadata and actual data.

Can you write Python code for it?

metadata = {'event_time': events[:, 0] / raw.info['sfreq'],
            'trial_number': range(len(events)),
            'kind': kinds,
            'side': sides}
metadata = pd.DataFrame(metadata)
metadata.head()


I am working on the file "0.16/_downloads/plot_metadata_query.ipynb".
The first task is:
If a column has numeric values, you can also use numeric-style queries:
Can you write Python code for it?

query = 'trial_number < 10'
plot_query_results(query)


I am working on the file "0.16/_downloads/plot_metadata_query.ipynb".
The first task is:
It is possible to chain these queries together, giving you more expressive
ways to select particular epochs:
Can you write Python code for it?

query = 'trial_number < 10 and side == "left"'
plot_query_results(query)


I am working on the file "0.16/_downloads/plot_metadata_query.ipynb".
The first task is:
Querying epochs with rich metadata
Selecting a subset of epochs based on rich metadata.
MNE allows you to include metadata along with your :class:mne.Epochs objects.
This is in the form of a :class:pandas.DataFrame that has one row for each
event, and an arbitrary number of columns corresponding to different
features that were collected. Columns may be of type int, float, or str.
If an :class:mne.Epochs object has a metadata attribute, you can select
subsets of epochs by using pandas query syntax directly. Here we'll show
a few examples of how this looks.
Can you write Python code for it?

# Authors: Chris Holdgraf <choldgraf@gmail.com>
#          Jona Sassenhagen <jona.sassenhagen@gmail.com>
#          Eric Larson <larson.eric.d@gmail.com>

# License: BSD (3-clause)

import os
import pandas as pd
import matplotlib.pyplot as plt
import mne

# First load some data
events = mne.read_events(os.path.join(mne.datasets.sample.data_path(),
                         'MEG/sample/sample_audvis_raw-eve.fif'))
raw = mne.io.read_raw_fif(os.path.join(mne.datasets.sample.data_path(),
                          'MEG/sample/sample_audvis_raw.fif'))

# We'll create some dummy names for each event type
event_id = {'Auditory/Left': 1, 'Auditory/Right': 2,
            'Visual/Left': 3, 'Visual/Right': 4,
            'smiley': 5, 'button': 32}
event_id_rev = {val: key for key, val in event_id.items()}

sides, kinds = [], []
for ev in events:
    split = event_id_rev[ev[2]].lower().split('/')
    if len(split) == 2:
        kind, side = split
    else:
        kind = split[0]
        side = 'both'
    kinds.append(kind)
    sides.append(side)

# Here's a helper function we'll use later
def plot_query_results(query):
    fig = epochs[query].average().plot(show=False, time_unit='s')
    title = fig.axes[0].get_title()
    add = 'Query: {}\nNum Epochs: {}'.format(query, len(epochs[query]))
    fig.axes[0].set(title='\n'.join([add, title]))
    plt.show()


I am working on the file "0.16/_downloads/plot_metadata_query.ipynb".
The first task is:
We can use this metadata object in the construction of an :class:mne.Epochs
object. The metadata will then exist as an attribute:
Can you write Python code for it?

epochs = mne.Epochs(raw, events, metadata=metadata, preload=True)
print(epochs.metadata.head())


I am working on the file "0.16/_downloads/plot_metadata_query.ipynb".
The first task is:
You can select rows by passing various queries to the Epochs object. For
example, you can select a subset of events based on the value of a column.
Can you write Python code for it?

query = 'kind == "auditory"'
plot_query_results(query)


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

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


I am working on the file "0.16/_downloads/plot_mixed_norm_inverse.ipynb".
The first task is:
Morph onto fsaverage brain and view
Can you write Python code for it?

stc_fsaverage = stc.morph(subject_from='sample', subject_to='fsaverage',
                          grade=None, sparse=True, subjects_dir=subjects_dir)
src_fsaverage_fname = subjects_dir + '/fsaverage/bem/fsaverage-ico-5-src.fif'
src_fsaverage = mne.read_source_spaces(src_fsaverage_fname)

plot_sparse_source_estimates(src_fsaverage, stc_fsaverage, bgcolor=(1, 1, 1),
                             fig_name="Morphed %s (cond %s)" % (solver,
                             condition), opacity=0.1)


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

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


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

alpha = 55  # regularization parameter between 0 and 100 (100 is high)
loose, depth = 0.2, 0.9  # loose orientation & depth weighting
n_mxne_iter = 10  # if > 1 use L0.5/L2 reweighted mixed norm solver
# if n_mxne_iter > 1 dSPM weighting can be avoided.

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

# Compute (ir)MxNE inverse solution with dipole output
dipoles, residual = mixed_norm(
    evoked, forward, cov, alpha, loose=loose, depth=depth, maxit=3000,
    tol=1e-4, active_set_size=10, debias=True, weights=stc_dspm,
    weights_min=8., n_mxne_iter=n_mxne_iter, return_residual=True,
    return_as_dipoles=True)


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

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


I am working on the file "0.16/_downloads/plot_mixed_source_space_inverse.ipynb".
The first task is:
Export source positions to nift file:
Can you write Python code for it?

nii_fname = op.join(bem_dir, '%s-mixed-src.nii' % subject)
src.export_volume(nii_fname, mri_resolution=True)

plotting.plot_img(nii_fname, cmap='nipy_spectral')
plt.show()

# Compute the fwd matrix
fwd = make_forward_solution(fname_evoked, fname_trans, src, fname_bem,
                            mindist=5.0,  # ignore sources<=5mm from innerskull
                            meg=True, eeg=False, n_jobs=1)

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

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

# Load data
condition = 'Left Auditory'
evoked = mne.read_evokeds(fname_evoked, condition=condition,
                          baseline=(None, 0))
noise_cov = mne.read_cov(fname_cov)

# Compute inverse solution and for each epoch
snr = 3.0           # use smaller SNR for raw data
inv_method = 'MNE'  # sLORETA, MNE, dSPM
parc = 'aparc'      # the parcellation to use, e.g., 'aparc' 'aparc.a2009s'

lambda2 = 1.0 / snr ** 2

# Compute inverse operator
inverse_operator = make_inverse_operator(evoked.info, fwd, noise_cov,
                                         depth=None, fixed=False)

stcs = apply_inverse(evoked, inverse_operator, lambda2, inv_method,
                     pick_ori=None)

# Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi
labels_parc = mne.read_labels_from_annot(subject, parc=parc,
                                         subjects_dir=subjects_dir)

# Average the source estimates within each label of the cortical parcellation
# and each sub structure contained in the src space
# If mode = 'mean_flip' this option is used only for the surface cortical label
src = inverse_operator['src']

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


I am working on the file "0.16/_downloads/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. We could set one up like this::
#
#     >>> src = setup_source_space(subject, fname=None, spacing='oct6',
#                                  add_dist=False, subjects_dir=subjects_dir)
#
# But we already have one saved:

src = mne.read_source_spaces(op.join(bem_dir, 'sample-oct-6-src.fif'))

# 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):

vol_src = setup_volume_source_space(
    subject, mri=fname_aseg, pos=7.0, bem=fname_model,
    volume_label=labels_vol, subjects_dir=subjects_dir, 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))

# We could write the mixed source space with::
#
#    >>> write_source_spaces(fname_mixed_src, src, overwrite=True)
#


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

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

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


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

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

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

del epochs  # to save memory


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

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


I am working on the file "0.16/_downloads/plot_mne_dspm_source_localization.ipynb".
The first task is:
Morph data to average brain
Can you write Python code for it?

fs_vertices = [np.arange(10242)] * 2  # fsaverage is special this way
morph_mat = mne.compute_morph_matrix(
    'sample', 'fsaverage', stc.vertices, fs_vertices, smooth=None,
    subjects_dir=subjects_dir)
stc_fsaverage = stc.morph_precomputed('fsaverage', fs_vertices, morph_mat)
brain = stc_fsaverage.plot(**surfer_kwargs)
brain.add_text(0.1, 0.9, 'Morphed to fsaverage', 'title', font_size=20)
del stc_fsaverage


I am working on the file "0.16/_downloads/plot_mne_dspm_source_localization.ipynb".
The first task is:
Note that there is a relationship between the orientation of the dipoles and
the surface of the cortex. For this reason, we do not use an inflated
cortical surface for visualization, but the original surface used to define
the source space.
For more information about dipole orientations, see
sphx_glr_auto_tutorials_plot_dipole_orientations.py.
Now let's look at each solver:
Can you write Python code for it?

for mi, (method, lims) in enumerate((('dSPM', [8, 12, 15]),
                                     ('sLORETA', [3, 5, 7]),
                                     ('eLORETA', [0.75, 1.25, 1.75]),)):
    surfer_kwargs['clim']['lims'] = lims
    stc = apply_inverse(evoked, inverse_operator, lambda2,
                        method=method, pick_ori=None)
    brain = stc.plot(figure=mi, **surfer_kwargs)
    brain.add_text(0.1, 0.9, method, 'title', font_size=20)
    del stc


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

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

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

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

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


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

import numpy as np
import matplotlib.pyplot as plt

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

# sphinx_gallery_thumbnail_number = 9


I am working on the file "0.16/_downloads/plot_mne_inverse_coherence_epochs.ipynb".
The first task is:
Compute the coherence between sources
Now we are ready to compute the coherence in the alpha and beta band.
fmin and fmax specify the lower and upper freq. for each band, respectively.
To speed things up, we use 2 parallel jobs and use mode='fourier', which
uses a FFT with a Hanning window to compute the spectra (instead of
a multitaper estimation, which has a lower variance but is slower).
By using faverage=True, we directly average the coherence in the alpha and
beta band, i.e., we will only get 2 frequency bins.
Can you write Python code for it?

fmin = (8., 13.)
fmax = (13., 30.)
sfreq = raw.info['sfreq']  # the sampling frequency

coh, freqs, times, n_epochs, n_tapers = spectral_connectivity(
    stcs, method='coh', mode='fourier', indices=indices,
    sfreq=sfreq, fmin=fmin, fmax=fmax, faverage=True, n_jobs=1)

print('Frequencies in Hz over which coherence was averaged for alpha: ')
print(freqs[0])
print('Frequencies in Hz over which coherence was averaged for beta: ')
print(freqs[1])


I am working on the file "0.16/_downloads/plot_mne_inverse_coherence_epochs.ipynb".
The first task is:
Compute the inverse solution for each epoch. By using "return_generator=True"
stcs will be a generator object instead of a list. This allows us so to
compute the coherence without having to keep all source estimates in memory.
Can you write Python code for it?

snr = 1.0  # use lower SNR for single epochs
lambda2 = 1.0 / snr ** 2
stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method,
                            pick_ori="normal", return_generator=True)


I am working on the file "0.16/_downloads/plot_mne_inverse_coherence_epochs.ipynb".
The first task is:
Generate coherence sources and plot
Finally, we'll generate a SourceEstimate with the coherence. This is simple
since we used a single seed. For more than one seed we would have to choose
one of the slices within coh.

Note

We use a hack to save the frequency axis as time.

Finally, we'll plot this source estimate on the brain.
Can you write Python code for it?

tmin = np.mean(freqs[0])
tstep = np.mean(freqs[1]) - tmin
coh_stc = mne.SourceEstimate(coh, vertices=stc.vertices, tmin=1e-3 * tmin,
                             tstep=1e-3 * tstep, subject='sample')

# Now we can visualize the coherence using the plot method.
brain = coh_stc.plot('sample', 'inflated', 'both',
                     time_label='Coherence %0.1f Hz',
                     subjects_dir=subjects_dir,
                     clim=dict(kind='value', lims=(0.25, 0.4, 0.65)))
brain.show_view('lateral')


I am working on the file "0.16/_downloads/plot_mne_inverse_coherence_epochs.ipynb".
The first task is:
Read the data
First we'll read in the sample MEG data that we'll use for computing
coherence between channels. We'll convert this into epochs in order to
compute the event-related coherence.
Can you write Python code for it?

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_raw = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
fname_event = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
label_name_lh = 'Aud-lh'
fname_label_lh = data_path + '/MEG/sample/labels/%s.label' % label_name_lh

event_id, tmin, tmax = 1, -0.2, 0.5
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

# Load data.
inverse_operator = read_inverse_operator(fname_inv)
label_lh = mne.read_label(fname_label_lh)
raw = mne.io.read_raw_fif(fname_raw)
events = mne.read_events(fname_event)

# Add a bad channel.
raw.info['bads'] += ['MEG 2443']

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

# Read epochs.
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0),
                    reject=dict(mag=4e-12, grad=4000e-13, eog=150e-6))


I am working on the file "0.16/_downloads/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.16/_downloads/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.16/_downloads/plot_mne_solutions.ipynb".
The first task is:
And finally eLORETA:
Can you write Python code for it?

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


I am working on the file "0.16/_downloads/plot_mne_solutions.ipynb".
The first task is:
And sLORETA:
Can you write Python code for it?

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


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

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

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

print(__doc__)

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

# Read data
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
evoked = mne.read_evokeds(fname_evoked, condition='Left Auditory',
                          baseline=(None, 0))
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
fname_cov = data_path + '/MEG/sample/sample_audvis-cov.fif'
fwd = mne.read_forward_solution(fname_fwd)
cov = mne.read_cov(fname_cov)


I am working on the file "0.16/_downloads/plot_mne_solutions.ipynb".
The first task is:
Let's look at the current estimates using MNE. We'll take the absolute
value of the source estimates to simplify the visualization.
Can you write Python code for it?

snr = 3.0
lambda2 = 1.0 / snr ** 2
kwargs = dict(initial_time=0.08, hemi='both', subjects_dir=subjects_dir,
              size=(600, 600))

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


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

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


I am working on the file "0.16/_downloads/plot_modifying_data_inplace.ipynb".
The first task is:
Finally, it is possible to apply arbitrary functions to your data to do
what you want. Here we will use this to take the amplitude and phase of
the hilbert transformed data.

Note

You can also use ``amplitude=True`` in the call to
          :meth:`mne.io.Raw.apply_hilbert` to do this automatically.

Can you write Python code for it?

# Take the amplitude and phase
raw_amp = raw_hilb.copy()
raw_amp.apply_function(np.abs, hilb_picks)
raw_phase = raw_hilb.copy()
raw_phase.apply_function(np.angle, hilb_picks)

f, (a1, a2) = plt.subplots(2, 1, figsize=(15, 10))
a1.plot(raw_band[hilb_picks[0]][0][0].real)
a1.plot(raw_amp[hilb_picks[0]][0][0].real)
a2.plot(raw_phase[hilb_picks[0]][0][0].real)
a1.set_title('Amplitude of frequency band')
a2.set_title('Phase of frequency band')


I am working on the file "0.16/_downloads/plot_modifying_data_inplace.ipynb".
The first task is:
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 = raw.crop(0, 10)
print(raw)


I am working on the file "0.16/_downloads/plot_modifying_data_inplace.ipynb".
The first task is:
Modifying data in-place
It is often necessary to modify data once you have loaded it into memory.
Common examples of this are signal processing, feature extraction, and data
cleaning. Some functionality is pre-built into MNE-python, though it is also
possible to apply an arbitrary function to the data.
Can you write Python code for it?

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


I am working on the file "0.16/_downloads/plot_movement_compensation.ipynb".
The first task is:
Process our simulated raw data (taking into account head movements).
Can you write Python code for it?

# extract our resulting events
events = mne.find_events(raw, stim_channel='STI 014')
events[:, 2] = 1
raw.plot(events=events)

topo_kwargs = dict(times=[0, 0.1, 0.2], ch_type='mag', vmin=-500, vmax=500,
                   time_unit='s')


I am working on the file "0.16/_downloads/plot_movement_compensation.ipynb".
The first task is:
Second, take a naive average, which averages across epochs that have been
simulated to have different head positions and orientations, thereby
spatially smearing the activity.
Can you write Python code for it?

evoked = mne.Epochs(raw, events, 1, -0.2, 0.8).average()
evoked.plot_topomap(title='Moving: naive average', **topo_kwargs)


I am working on the file "0.16/_downloads/plot_movement_compensation.ipynb".
The first task is:
Third, use raw movement compensation (restores pattern).
Can you write Python code for it?

raw_sss = maxwell_filter(raw, head_pos=head_pos)
evoked_raw_mc = mne.Epochs(raw_sss, events, 1, -0.2, 0.8).average()
evoked_raw_mc.plot_topomap(title='Moving: movement compensated', **topo_kwargs)


I am working on the file "0.16/_downloads/plot_movement_compensation.ipynb".
The first task is:
This can also be visualized using a quiver.
Can you write Python code for it?

mne.viz.plot_head_positions(
    head_pos, mode='field', destination=raw.info['dev_head_t'], info=raw.info)


I am working on the file "0.16/_downloads/plot_movement_compensation.ipynb".
The first task is:
Visualize the "subject" head movements. By providing the measurement
information, the distance to the nearest sensor in each direction
(e.g., left/right for the X direction, forward/backward for Y) can
be shown in blue, and the destination (if given) shown in red.
Can you write Python code for it?

mne.viz.plot_head_positions(
    head_pos, mode='traces', destination=raw.info['dev_head_t'], info=raw.info)


I am working on the file "0.16/_downloads/plot_object_epochs.ipynb".
The first task is:
:class:Epochs <mne.Epochs> objects can be created in three ways:
 1. From a :class:Raw <mne.io.Raw> object, along with event times
 2. From an :class:Epochs <mne.Epochs> object that has been saved as a
    .fif file
 3. From scratch using :class:EpochsArray <mne.EpochsArray>. See
    tut_creating_data_structures
Can you write Python code for it?

data_path = mne.datasets.sample.data_path()
# Load a dataset that contains events
raw = mne.io.read_raw_fif(
    op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif'))

# If your raw object has a stim channel, you can construct an event array
# easily
events = mne.find_events(raw, stim_channel='STI 014')

# Show the number of events (number of rows)
print('Number of events:', len(events))

# Show all unique event codes (3rd column)
print('Unique event codes:', np.unique(events[:, 2]))

# Specify event codes of interest with descriptive labels.
# This dataset also has visual left (3) and right (4) events, but
# to save time and memory we'll just look at the auditory conditions
# for now.
event_id = {'Auditory/Left': 1, 'Auditory/Right': 2}


I am working on the file "0.16/_downloads/plot_object_epochs.ipynb".
The first task is:
Epochs behave similarly to :class:mne.io.Raw objects. They have an
:class:info <mne.Info> attribute that has all of the same
information, as well as a number of attributes unique to the events contained
within the object.
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_object_epochs.ipynb".
The first task is:
It is also possible to iterate through :class:Epochs <mne.Epochs> objects
in this way. Note that behavior is different if you iterate on Epochs
directly rather than indexing:
Can you write Python code for it?

# These will be epochs objects
for i in range(3):
    print(epochs[i])

# These will be arrays
for ep in epochs[:2]:
    print(ep)


I am working on the file "0.16/_downloads/plot_object_epochs.ipynb".
The first task is:
Later on you can read the epochs with :func:mne.read_epochs. For reading
EEGLAB epochs files see :func:mne.read_epochs_eeglab. We can also use
preload=False to save memory, loading the epochs from disk on demand.
Can you write Python code for it?

epochs = mne.read_epochs(epochs_fname, preload=False)


I am working on the file "0.16/_downloads/plot_object_epochs.ipynb".
The first task is:
Now, we can create an :class:mne.Epochs object with the events we've
extracted. Note that epochs constructed in this manner will not have their
data available until explicitly read into memory, which you can do with
:func:get_data <mne.Epochs.get_data>. Alternatively, you can use
preload=True.
Expose the raw data as epochs, cut from -0.1 s to 1.0 s relative to the event
onsets
Can you write Python code for it?

epochs = mne.Epochs(raw, events, event_id, tmin=-0.1, tmax=1,
                    baseline=(None, 0), preload=True)
print(epochs)


I am working on the file "0.16/_downloads/plot_object_epochs.ipynb".
The first task is:
The :class:Epochs <mne.Epochs> data structure: epoched data
:class:Epochs <mne.Epochs> objects are a way of representing continuous
data as a collection of time-locked trials, stored in an array of shape
(n_events, n_channels, n_times). They are useful for many statistical
methods in neuroscience, and make it easy to quickly overview what occurs
during a trial.
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_object_epochs.ipynb".
The first task is:
You can select subsets of epochs by indexing the :class:Epochs <mne.Epochs>
object directly. Alternatively, if you have epoch names specified in
event_id then you may index with strings instead.
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_object_evoked.ipynb".
The first task is:
Here for convenience we read the evoked dataset from a file.
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')
evokeds = mne.read_evokeds(fname, baseline=(None, 0), proj=True)
print(evokeds)


I am working on the file "0.16/_downloads/plot_object_evoked.ipynb".
The first task is:
If you want to import evoked data from some other system and you have it in a
numpy array you can use :class:mne.EvokedArray for that. All you need is
the data and some info about the evoked data. For more information, see
tut_creating_data_structures.
Can you write Python code for it?

evoked = mne.EvokedArray(data, evoked.info, tmin=evoked.times[0])
evoked.plot(time_unit='s')


I am working on the file "0.16/_downloads/plot_object_evoked.ipynb".
The first task is:
If you're gone through the tutorials of raw and epochs datasets, you're
probably already familiar with the :class:Info <mne.Info> attribute.
There is nothing new or special with the evoked.info. All the relevant
info is still there.
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_object_evoked.ipynb".
The first task is:
Notice that the reader function returned a list of evoked instances. This is
because you can store multiple categories into a single file. Here we have
categories of
['Left Auditory', 'Right Auditory', 'Left Visual', 'Right Visual'].
We can also use condition parameter to read in only one category.
Can you write Python code for it?

evoked = mne.read_evokeds(fname, condition='Left Auditory')
evoked.apply_baseline((None, 0)).apply_proj()
print(evoked)


I am working on the file "0.16/_downloads/plot_object_evoked.ipynb".
The first task is:
The data is arranged in an array of shape (n_channels, n_times). Notice
that unlike epochs, evoked object does not support indexing. This means that
to access the data of a specific channel you must use the data array
directly.
Can you write Python code for it?

print('Data from channel {0}:'.format(evoked.ch_names[10]))
print(data[10])


I am working on the file "0.16/_downloads/plot_object_evoked.ipynb".
The first task is:
The evoked data structure also contains some new attributes easily
accessible:
Can you write Python code for it?

print(evoked.nave)  # Number of averaged epochs.
print(evoked.first)  # First time sample.
print(evoked.last)  # Last time sample.
print(evoked.comment)  # Comment on dataset. Usually the condition.
print(evoked.kind)  # Type of data, either average or standard_error.


I am working on the file "0.16/_downloads/plot_object_raw.ipynb".
The first task is:

Note

This size can also be obtained by examining `raw._data.shape`.
          However this is a private attribute as its name starts
          with an `_`. This suggests that you should **not** access this
          variable directly but rely on indexing syntax detailed just below.

Information about the channels contained in the :class:Raw <mne.io.Raw>
object is contained in the :class:Info <mne.Info> attribute.
This is essentially a dictionary with a number of relevant fields (see
tut_info_objects).
Indexing data
To access the data stored within :class:Raw <mne.io.Raw> objects,
it is possible to index the :class:Raw <mne.io.Raw> object.
Indexing a :class:Raw <mne.io.Raw> object will return two arrays: an array
of times, as well as the data representing those timepoints. This works
even if the data is not preloaded, in which case the data will be read from
disk when indexing. The syntax is as follows:
Can you write Python code for it?

# Extract data from the first 5 channels, from 1 s to 3 s.
sfreq = raw.info['sfreq']
data, times = raw[:5, int(sfreq * 1):int(sfreq * 3)]
_ = plt.plot(times, data.T)
_ = plt.title('Sample channels')


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

# Create multiple :class:`Raw <mne.io.RawFIF>` 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.16/_downloads/plot_object_raw.ipynb".
The first task is:
The :class:Raw <mne.io.Raw> data structure: continuous data
Continuous data is stored in objects of type :class:Raw <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:Info <mne.Info> object (.info attribute)
(see tut_info_objects).
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.16/_downloads/plot_objects_from_arrays.ipynb".
The first task is:
Create an :class:info <mne.Info> object.
Can you write Python code for it?

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


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

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

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

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

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


I am working on the file "0.16/_downloads/plot_objects_from_arrays.ipynb".
The first task is:
Creating MNE objects from data arrays
In this simple example, the creation of MNE objects from
numpy arrays is demonstrated. In the last example case, a
NEO file format is used as a source for the data.
Can you write Python code for it?

# Author: Jaakko Leppakangas <jaeilepp@student.jyu.fi>
#
# License: BSD (3-clause)

import numpy as np
import neo

import mne

print(__doc__)


I am working on the file "0.16/_downloads/plot_objects_from_arrays.ipynb".
The first task is:
EpochsArray
Can you write Python code for it?

event_id = 1  # This is used to identify the events.
# First column is for the sample number.
events = np.array([[200, 0, event_id],
                   [1200, 0, event_id],
                   [2000, 0, event_id]])  # List of three arbitrary events

# Here a data set of 700 ms epochs from 2 channels is
# created from sin and cos data.
# Any data in shape (n_epochs, n_channels, n_times) can be used.
epochs_data = np.array([[sin[:700], cos[:700]],
                        [sin[1000:1700], cos[1000:1700]],
                        [sin[1800:2500], cos[1800:2500]]])

ch_names = ['sin', 'cos']
ch_types = ['mag', 'mag']
info = mne.create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)

epochs = mne.EpochsArray(epochs_data, info=info, events=events,
                         event_id={'arbitrary': 1})

picks = mne.pick_types(info, meg=True, eeg=False, misc=False)

epochs.plot(picks=picks, scalings='auto', show=True, block=True)


I am working on the file "0.16/_downloads/plot_objects_from_arrays.ipynb".
The first task is:
EvokedArray
Can you write Python code for it?

nave = len(epochs_data)  # Number of averaged epochs
evoked_data = np.mean(epochs_data, axis=0)

evokeds = mne.EvokedArray(evoked_data, info=info, tmin=-0.2,
                          comment='Arbitrary', nave=nave)
evokeds.plot(picks=picks, show=True, units={'mag': '-'},
             titles={'mag': 'sin and cos averaged'}, time_unit='s')


I am working on the file "0.16/_downloads/plot_objects_from_arrays.ipynb".
The first task is:
Extracting data from NEO file
Can you write Python code for it?

# The example here uses the ExampleIO object for creating fake data.
# For actual data and different file formats, consult the NEO documentation.
reader = neo.io.ExampleIO('fakedata.nof')
bl = reader.read(lazy=False)[0]

# Get data from first (and only) segment
seg = bl.segments[0]
title = seg.file_origin

ch_names = list()
data = list()
for ai, asig in enumerate(seg.analogsignals):
    # Since the data does not contain channel names, channel indices are used.
    ch_names.append('Neo %02d' % (ai + 1,))
    # We need the ravel() here because Neo < 0.5 gave 1D, Neo 0.5 gives
    # 2D (but still a single channel).
    data.append(asig.rescale('V').magnitude.ravel())

data = np.array(data, float)

sfreq = int(seg.analogsignals[0].sampling_rate.magnitude)

# By default, the channel types are assumed to be 'misc'.
info = mne.create_info(ch_names=ch_names, sfreq=sfreq)

raw = mne.io.RawArray(data, info)
raw.plot(n_channels=4, scalings={'misc': 1}, title='Data from NEO',
         show=True, block=True, clipping='clamp')


I am working on the file "0.16/_downloads/plot_otp.ipynb".
The first task is:
Plot the phantom data, lowpassed to get rid of high-frequency artifacts.
We also crop to a single 10-second segment for speed.
Notice that there are two large flux jumps on channel 1522 that could
spread to other channels when performing subsequent spatial operations
(e.g., Maxwell filtering, SSP, or ICA).
Can you write Python code for it?

dipole_number = 1
data_path = bst_phantom_elekta.data_path()
raw = read_raw_fif(
    op.join(data_path, 'kojak_all_200nAm_pp_no_chpi_no_ms_raw.fif'))
raw.crop(40., 50.).load_data()
order = list(range(160, 170))
raw.copy().filter(0., 40.).plot(order=order, n_channels=10)


I am working on the file "0.16/_downloads/plot_parcellation.ipynb".
The first task is:
Plot a cortical parcellation
In this example, we download the HCP-MMP1.0 parcellation [1]_ and show it
on fsaverage.

Note

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

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

References
.. [1] Glasser MF et al. (2016) A multi-modal parcellation of human
       cerebral cortex. Nature 536:171-178.
Can you write Python code for it?

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

from surfer import Brain

import mne

subjects_dir = mne.datasets.sample.data_path() + '/subjects'
mne.datasets.fetch_hcp_mmp_parcellation(subjects_dir=subjects_dir,
                                        verbose=True)
labels = mne.read_labels_from_annot(
    'fsaverage', 'HCPMMP1', 'lh', subjects_dir=subjects_dir)

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


I am working on the file "0.16/_downloads/plot_parcellation.ipynb".
The first task is:
We can also plot a combined set of labels (23 per hemisphere).
Can you write Python code for it?

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


I am working on the file "0.16/_downloads/plot_phantom_4DBTi.ipynb".
The first task is:
============================================
4D Neuroimaging/BTi phantom dataset tutorial
============================================
Here we read 4DBTi epochs data obtained with a spherical phantom
using four different dipole locations. For each condition we
compute evoked data and compute dipole fits.
Data are provided by Jean-Michel Badier from MEG center in Marseille, France.
Can you write Python code for it?

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

import os.path as op
import numpy as np
from mayavi import mlab
from mne.datasets import phantom_4dbti
import mne


I am working on the file "0.16/_downloads/plot_phantom_4DBTi.ipynb".
The first task is:
Compute localisation errors
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_phantom_4DBTi.ipynb".
The first task is:
Read data and compute a dipole fit at the peak of the evoked response
Can you write Python code for it?

data_path = phantom_4dbti.data_path()
raw_fname = op.join(data_path, '%d/e,rfhp1.0Hz')

dipoles = list()
sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080)

t0 = 0.07  # peak of the response

pos = np.empty((4, 3))

for ii in range(4):
    raw = mne.io.read_raw_bti(raw_fname % (ii + 1,),
                              rename_channels=False, preload=True)
    raw.info['bads'] = ['A173', 'A213', 'A232']
    events = mne.find_events(raw, 'TRIGGER', mask=4350, mask_type='not_and')
    epochs = mne.Epochs(raw, events=events, event_id=8192, tmin=-0.2, tmax=0.4,
                        preload=True)
    evoked = epochs.average()
    evoked.plot(time_unit='s')
    cov = mne.compute_covariance(epochs, tmax=0.)
    dip = mne.fit_dipole(evoked.copy().crop(t0, t0), cov, sphere)[0]
    pos[ii] = dip.pos[0]


I am working on the file "0.16/_downloads/plot_point_spread.ipynb".
The first task is:
Estimate the background noise covariance from the baseline period
Can you write Python code for it?

cov = mne.compute_covariance(epochs, tmin=None, tmax=0.)


I am working on the file "0.16/_downloads/plot_point_spread.ipynb".
The first task is:
Generate sinusoids in two spatially distant labels
Can you write Python code for it?

# The known signal is all zero-s off of the two labels of interest
signal = np.zeros((n_labels, T))
idx = label_names.index('inferiorparietal-lh')
signal[idx, :] = 1e-7 * np.sin(5 * 2 * np.pi * times)
idx = label_names.index('rostralmiddlefrontal-rh')
signal[idx, :] = 1e-7 * np.sin(7 * 2 * np.pi * times)


I am working on the file "0.16/_downloads/plot_point_spread.ipynb".
The first task is:
Plot the point-spread of corrupted signal
Notice that after applying the forward- and inverse-operators to the known
point sources that the point sources have spread across the source-space.
This spread is due to the minimum norm solution so that the signal leaks to
nearby vertices with similar orientations so that signal ends up crossing the
sulci and gyri.
Can you write Python code for it?

figs = [mlab.figure(5), mlab.figure(6), mlab.figure(7), mlab.figure(8)]
brain_inv = stc_inv.plot(figure=figs, **kwargs)


I am working on the file "0.16/_downloads/plot_point_spread.ipynb".
The first task is:
Simulate sensor-space signals
Use the forward solution and add Gaussian noise to simulate sensor-space
(evoked) data from the known source-space signals. The amount of noise is
controlled by nave (higher values imply less noise).
Can you write Python code for it?

evoked_gen = simulate_evoked(fwd, stc_gen, evoked.info, cov, nave,
                             random_state=seed)

# Map the simulated sensor-space data to source-space using the inverse
# operator.
stc_inv = apply_inverse(evoked_gen, inv_op, lambda2, method=method)


I am working on the file "0.16/_downloads/plot_python_intro.ipynb".
The first task is:
Second, if you have a MATLAB background remember that indexing in Python
starts from zero (and is done with square brackets):
Can you write Python code for it?

a = [1, 2, 3, 4]
print('This is the zeroth value in the list: {}'.format(a[0]))


I am working on the file "0.16/_downloads/plot_read_and_write_raw_data.ipynb".
The first task is:
Reading and writing raw files
In this example, we read a raw file. Plot a segment of MEG data
restricted to MEG channels. And save these data in a new
raw file.
Can you write Python code for it?

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

import mne
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

fname = data_path + '/MEG/sample/sample_audvis_raw.fif'

raw = mne.io.read_raw_fif(fname)

# Set up pick list: MEG + STI 014 - bad channels
want_meg = True
want_eeg = False
want_stim = False
include = ['STI 014']
raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bad channels + 2 more

picks = mne.pick_types(raw.info, meg=want_meg, eeg=want_eeg, stim=want_stim,
                       include=include, exclude='bads')

some_picks = picks[:5]  # take 5 first
start, stop = raw.time_as_index([0, 15])  # read the first 15s of data
data, times = raw[some_picks, start:(stop + 1)]

# save 150s of MEG data in FIF file
raw.save('sample_audvis_meg_raw.fif', tmin=0, tmax=150, picks=picks,
         overwrite=True)


I am working on the file "0.16/_downloads/plot_read_and_write_raw_data.ipynb".
The first task is:
Show MEG data
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_read_epochs.ipynb".
The first task is:
Reading epochs from a raw FIF file
This script shows how to read the epochs from a raw file given
a list of events. For illustration, we compute the evoked responses
for both MEG and EEG data by averaging all the epochs.
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Matti Hamalainen <msh@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)

import mne
from mne import io
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()


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

raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
event_id, tmin, tmax = 1, -0.2, 0.5

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

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

# Read epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    picks=picks, baseline=(None, 0), preload=True,
                    reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))

evoked = epochs.average()  # average epochs to get the evoked response


I am working on the file "0.16/_downloads/plot_read_epochs.ipynb".
The first task is:
Show result
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_read_events.ipynb".
The first task is:
Writing events
Finally, we can write events to disk. Remember to use the naming convention
-eve.fif for your file.
Can you write Python code for it?


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

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

from mne import read_evokeds
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

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

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


I am working on the file "0.16/_downloads/plot_read_inverse.ipynb".
The first task is:
Reading an inverse operator
The inverse operator's source space is shown in 3D.
Can you write Python code for it?

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

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

print(__doc__)

data_path = sample.data_path()
fname = data_path
fname += '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'

inv = read_inverse_operator(fname)

print("Method: %s" % inv['methods'])
print("fMRI prior: %s" % inv['fmri_prior'])
print("Number of sources: %s" % inv['nsource'])
print("Number of channels: %s" % inv['nchan'])


I am working on the file "0.16/_downloads/plot_read_noise_covariance_matrix.ipynb".
The first task is:
Show covariance
Can you write Python code for it?


I am working on the file "0.16/_downloads/plot_receptive_field.ipynb".
The first task is:
Compare model performance
Below we visualize the model performance of each regularization method
(ridge vs. Laplacian) for different levels of alpha. As you can see, the
Laplacian method performs better in general, because it imposes a smoothness
constraint along the time and feature dimensions of the coefficients.
This matches the "true" receptive field structure and results in a better
model fit.
Can you write Python code for it?

fig = plt.figure(figsize=(10, 6))
ax = plt.subplot2grid([3, len(alphas)], [2, 0], 1, len(alphas))
ax.plot(np.arange(len(alphas)), scores_lap, marker='o', color='r')
ax.plot(np.arange(len(alphas)), scores, marker='o', color='0.5', ls=':')
ax.annotate('Best Laplacian', (ix_best_alpha_lap,
                               scores_lap[ix_best_alpha_lap]),
            (ix_best_alpha_lap, scores_lap[ix_best_alpha_lap] - .1),
            arrowprops={'arrowstyle': '->'})
ax.annotate('Best Ridge', (ix_best_alpha, scores[ix_best_alpha]),
            (ix_best_alpha, scores[ix_best_alpha] - .1),
            arrowprops={'arrowstyle': '->'})
plt.xticks(np.arange(len(alphas)), ["%.0e" % ii for ii in alphas])
ax.set(xlabel="Laplacian regularization value", ylabel="Score ($R^2$)",
       xlim=[-.4, len(alphas) - .6])
mne.viz.tight_layout()

# Plot the STRF of each ridge parameter
xlim = times[[0, -1]]
for ii, (rf_lap, rf, i_alpha) in enumerate(zip(models_lap, models, alphas)):
    ax = plt.subplot2grid([3, len(alphas)], [0, ii], 1, 1)
    ax.pcolormesh(times, rf_lap.feature_names, rf_lap.coef_[0], **kwargs)
    ax.set(xticks=[], yticks=[], xlim=xlim)
    if ii == 0:
        ax.set(ylabel='Laplacian')
    ax = plt.subplot2grid([3, len(alphas)], [1, ii], 1, 1)
    ax.pcolormesh(times, rf.feature_names, rf.coef_[0], **kwargs)
    ax.set(xticks=[], yticks=[], xlim=xlim)
    if ii == 0:
        ax.set(ylabel='Ridge')
fig.suptitle('Model coefficients / scores for laplacian regularization', y=1)
mne.viz.tight_layout()


I am working on the file "0.16/_downloads/plot_receptive_field.ipynb".
The first task is:
Create a receptive field
We'll simulate a linear receptive field for a theoretical neural signal. This
defines how the signal will respond to power in this receptive field space.
Can you write Python code for it?

n_freqs = 20
tmin, tmax = -0.1, 0.4

# To simulate the data we'll create explicit delays here
delays_samp = np.arange(np.round(tmin * sfreq),
                        np.round(tmax * sfreq) + 1).astype(int)
delays_sec = delays_samp / sfreq
freqs = np.linspace(50, 5000, n_freqs)
grid = np.array(np.meshgrid(delays_sec, freqs))

# We need data to be shaped as n_epochs, n_features, n_times, so swap axes here
grid = grid.swapaxes(0, -1).swapaxes(0, 1)

# Simulate a temporal receptive field with a Gabor filter
means_high = [.1, 500]
means_low = [.2, 2500]
cov = [[.001, 0], [0, 500000]]
gauss_high = multivariate_normal.pdf(grid, means_high, cov)
gauss_low = -1 * multivariate_normal.pdf(grid, means_low, cov)
weights = gauss_high + gauss_low  # Combine to create the "true" STRF
kwargs = dict(vmax=np.abs(weights).max(), vmin=-np.abs(weights).max(),
              cmap='RdBu_r', shading='gouraud')

fig, ax = plt.subplots()
ax.pcolormesh(delays_sec, freqs, weights, **kwargs)
ax.set(title='Simulated STRF', xlabel='Time Lags (s)', ylabel='Frequency (Hz)')
plt.setp(ax.get_xticklabels(), rotation=45)
plt.autoscale(tight=True)
mne.viz.tight_layout()


I am working on the file "0.16/_downloads/plot_receptive_field.ipynb".
The first task is:
Fit a model to recover this receptive field
Finally, we'll use the :class:mne.decoding.ReceptiveField class to recover
the linear receptive field of this signal. Note that properties of the
receptive field (e.g. smoothness) will depend on the autocorrelation in the
inputs and outputs.
Can you write Python code for it?

# Create training and testing data
train, test = np.arange(n_epochs - 1), n_epochs - 1
X_train, X_test, y_train, y_test = X[train], X[test], y[train], y[test]
X_train, X_test, y_train, y_test = [np.rollaxis(ii, -1, 0) for ii in
                                    (X_train, X_test, y_train, y_test)]
# Model the simulated data as a function of the spectrogram input
alphas = np.logspace(-3, 3, 7)
scores = np.zeros_like(alphas)
models = []
for ii, alpha in enumerate(alphas):
    rf = ReceptiveField(tmin, tmax, sfreq, freqs, estimator=alpha)
    rf.fit(X_train, y_train)

    # Now make predictions about the model output, given input stimuli.
    scores[ii] = rf.score(X_test, y_test)
    models.append(rf)

times = rf.delays_ / float(rf.sfreq)

# Choose the model that performed best on the held out data
ix_best_alpha = np.argmax(scores)
best_mod = models[ix_best_alpha]
coefs = best_mod.coef_[0]
best_pred = best_mod.predict(X_test)[:, 0]

# Plot the original STRF, and the one that we recovered with modeling.
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(6, 3), sharey=True, sharex=True)
ax1.pcolormesh(delays_sec, freqs, weights, **kwargs)
ax2.pcolormesh(times, rf.feature_names, coefs, **kwargs)
ax1.set_title('Original STRF')
ax2.set_title('Best Reconstructed STRF')
plt.setp([iax.get_xticklabels() for iax in [ax1, ax2]], rotation=45)
plt.autoscale(tight=True)
mne.viz.tight_layout()

# Plot the actual response and the predicted response on a held out stimulus
time_pred = np.arange(best_pred.shape[0]) / sfreq
fig, ax = plt.subplots()
ax.plot(time_pred, y_test, color='k', alpha=.2, lw=4)
ax.plot(time_pred, best_pred, color='r', lw=1)
ax.set(title='Original and predicted activity', xlabel='Time (s)')
ax.legend(['Original', 'Predicted'])
plt.autoscale(tight=True)
mne.viz.tight_layout()


I am working on the file "0.16/_downloads/plot_receptive_field.ipynb".
The first task is:
Plot the original STRF, and the one that we recovered with modeling.
Can you write Python code for it?

rf = models[ix_best_alpha]
rf_lap = models_lap[ix_best_alpha_lap]
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(9, 3),
                                    sharey=True, sharex=True)
ax1.pcolormesh(delays_sec, freqs, weights, **kwargs)
ax2.pcolormesh(times, rf.feature_names, rf.coef_[0], **kwargs)
ax3.pcolormesh(times, rf_lap.feature_names, rf_lap.coef_[0], **kwargs)
ax1.set_title('Original STRF')
ax2.set_title('Best Ridge STRF')
ax3.set_title('Best Laplacian STRF')
plt.setp([iax.get_xticklabels() for iax in [ax1, ax2, ax3]], rotation=45)
plt.autoscale(tight=True)
mne.viz.tight_layout()
plt.show()


I am working on the file "0.16/_downloads/plot_receptive_field.ipynb".
The first task is:
Simulate a neural response
Using this receptive field, we'll create an artificial neural response to
a stimulus.
To do this, we'll create a time-delayed version of the receptive field, and
then calculate the dot product between this and the stimulus. Note that this
is effectively doing a convolution between the stimulus and the receptive
field. See here <https://en.wikipedia.org/wiki/Convolution>_ for more
information.
Can you write Python code for it?

# Reshape audio to split into epochs, then make epochs the first dimension.
n_epochs, n_seconds = 16, 5
audio = audio[:, :int(n_seconds * sfreq * n_epochs)]
X = audio.reshape([n_freqs, n_epochs, -1]).swapaxes(0, 1)
n_times = X.shape[-1]

# Delay the spectrogram according to delays so it can be combined w/ the STRF
# Lags will now be in axis 1, then we reshape to vectorize
delays = np.arange(np.round(tmin * sfreq),
                   np.round(tmax * sfreq) + 1).astype(int)

# Iterate through indices and append
X_del = np.zeros((len(delays),) + X.shape)
for ii, ix_delay in enumerate(delays):
    # These arrays will take/put particular indices in the data
    take = [slice(None)] * X.ndim
    put = [slice(None)] * X.ndim
    if ix_delay > 0:
        take[-1] = slice(None, -ix_delay)
        put[-1] = slice(ix_delay, None)
    elif ix_delay < 0:
        take[-1] = slice(-ix_delay, None)
        put[-1] = slice(None, ix_delay)
    X_del[ii][put] = X[take]

# Now set the delayed axis to the 2nd dimension
X_del = np.rollaxis(X_del, 0, 3)
X_del = X_del.reshape([n_epochs, -1, n_times])
n_features = X_del.shape[1]
weights_sim = weights.ravel()

# Simulate a neural response to the sound, given this STRF
y = np.zeros((n_epochs, n_times))
for ii, iep in enumerate(X_del):
    # Simulate this epoch and add random noise
    noise_amp = .002
    y[ii] = np.dot(weights_sim, iep) + noise_amp * rng.randn(n_times)

# Plot the first 2 trials of audio and the simulated electrode activity
X_plt = scale(np.hstack(X[:2]).T).T
y_plt = scale(np.hstack(y[:2]))
time = np.arange(X_plt.shape[-1]) / sfreq
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 6), sharex=True)
ax1.pcolormesh(time, freqs, X_plt, vmin=0, vmax=4, cmap='Reds')
ax1.set_title('Input auditory features')
ax1.set(ylim=[freqs.min(), freqs.max()], ylabel='Frequency (Hz)')
ax2.plot(time, y_plt)
ax2.set(xlim=[time.min(), time.max()], title='Simulated response',
        xlabel='Time (s)', ylabel='Activity (a.u.)')
mne.viz.tight_layout()


I am working on the file "0.16/_downloads/plot_receptive_field.ipynb".
The first task is:
Using different regularization types
In addition to the standard ridge regularization, the
:class:mne.decoding.TimeDelayingRidge class also exposes
Laplacian <https://en.wikipedia.org/wiki/Laplacian_matrix>_ regularization
term as:
\begin{align}\left[\begin{matrix}
        1 & -1 &   &   & & \
       -1 &  2 & -1 &   & & \
          & -1 & 2 & -1 & & \
          & & \ddots & \ddots & \ddots & \
          & & & -1 & 2 & -1 \
          & & &    & -1 & 1\end{matrix}\right]\end{align}
This imposes a smoothness constraint of nearby time samples and/or features.
Quoting [5]_:
Tikhonov [identity] regularization (Equation 5) reduces overfitting by
   smoothing the TRF estimate in a way that is insensitive to
   the amplitude of the signal of interest. However, the Laplacian
   approach (Equation 6) reduces off-sample error whilst preserving
   signal amplitude (Lalor et al., 2006). As a result, this approach
   usually leads to an improved estimate of the system’s response (as
   indexed by MSE) compared to Tikhonov regularization.
Can you write Python code for it?

scores_lap = np.zeros_like(alphas)
models_lap = []
for ii, alpha in enumerate(alphas):
    estimator = TimeDelayingRidge(tmin, tmax, sfreq, reg_type='laplacian',
                                  alpha=alpha)
    rf = ReceptiveField(tmin, tmax, sfreq, freqs, estimator=estimator)
    rf.fit(X_train, y_train)

    # Now make predictions about the model output, given input stimuli.
    scores_lap[ii] = rf.score(X_test, y_test)
    models_lap.append(rf)

ix_best_alpha_lap = np.argmax(scores_lap)


I am working on the file "0.16/_downloads/plot_receptive_field.ipynb".
The first task is:
Visualize the effects of regularization
Above we fit a :class:mne.decoding.ReceptiveField model for one of many
values for the ridge regularization parameter. Here we will plot the model
score as well as the model coefficients for each value, in order to
visualize how coefficients change with different levels of regularization.
These issues as well as the STRF pipeline are described in detail
in [1], [2], and [4]_.
Can you write Python code for it?

# Plot model score for each ridge parameter
fig = plt.figure(figsize=(10, 4))
ax = plt.subplot2grid([2, len(alphas)], [1, 0], 1, len(alphas))
ax.plot(np.arange(len(alphas)), scores, marker='o', color='r')
ax.annotate('Best parameter', (ix_best_alpha, scores[ix_best_alpha]),
            (ix_best_alpha, scores[ix_best_alpha] - .1),
            arrowprops={'arrowstyle': '->'})
plt.xticks(np.arange(len(alphas)), ["%.0e" % ii for ii in alphas])
ax.set(xlabel="Ridge regularization value", ylabel="Score ($R^2$)",
       xlim=[-.4, len(alphas) - .6])
mne.viz.tight_layout()

# Plot the STRF of each ridge parameter
for ii, (rf, i_alpha) in enumerate(zip(models, alphas)):
    ax = plt.subplot2grid([2, len(alphas)], [0, ii], 1, 1)
    ax.pcolormesh(times, rf.feature_names, rf.coef_[0], **kwargs)
    plt.xticks([], [])
    plt.yticks([], [])
    plt.autoscale(tight=True)
fig.suptitle('Model coefficients / scores for many ridge parameters', y=1)
mne.viz.tight_layout()


I am working on the file "0.16/_downloads/plot_receptive_field_mtrf.ipynb".
The first task is:
Create and fit a stimulus reconstruction model
We will now demonstrate another use case for the for the
:class:mne.decoding.ReceptiveField class as we try to predict the stimulus
activity from the EEG data. This is known in the literature as a decoding, or
stimulus reconstruction model [1]_. A decoding model aims to find the
relationship between the speech signal and a time-delayed version of the EEG.
This can be useful as we exploit all of the available neural data in a
multivariate context, compared to the encoding case which treats each M/EEG
channel as an independent feature. Therefore, decoding models might provide a
better quality of fit (at the expense of not controlling for stimulus
covariance), especially for low SNR stimuli such as speech.
Can you write Python code for it?

# We use the same lags as in [1]. Negative lags now index the relationship
# between the neural response and the speech envelope earlier in time, whereas
# positive lags would index how a unit change in the amplitude of the EEG would
# affect later stimulus activity (obviously this should have an amplitude of
# zero).
tmin, tmax = -.2, 0.

# Initialize the model. Here the features are the EEG data. We also specify
# ``patterns=True`` to compute inverse-transformed coefficients during model
# fitting (cf. next section). We'll use a ridge regression estimator with an
# alpha value similar to [1].
sr = ReceptiveField(tmin, tmax, sfreq, feature_names=raw.ch_names,
                    estimator=1e4, scoring='corrcoef', patterns=True)
# We'll have (tmax - tmin) * sfreq delays
# and an extra 2 delays since we are inclusive on the beginning / end index
n_delays = int((tmax - tmin) * sfreq) + 2

n_splits = 3
cv = KFold(n_splits)

# Iterate through splits, fit the model, and predict/test on held-out data
coefs = np.zeros((n_splits, n_channels, n_delays))
patterns = coefs.copy()
scores = np.zeros((n_splits,))
for ii, (train, test) in enumerate(cv.split(speech)):
    print('split %s / %s' % (ii + 1, n_splits))
    sr.fit(Y[train], speech[train])
    scores[ii] = sr.score(Y[test], speech[test])[0]
    # coef_ is shape (n_outputs, n_features, n_delays). We have 128 features
    coefs[ii] = sr.coef_[0, :, :]
    patterns[ii] = sr.patterns_[0, :, :]
times = sr.delays_ / float(sr.sfreq)

# Average scores and coefficients across CV splits
mean_coefs = coefs.mean(axis=0)
mean_patterns = patterns.mean(axis=0)
mean_scores = scores.mean(axis=0)
max_coef = np.abs(mean_coefs).max()
max_patterns = np.abs(mean_patterns).max()