I am working on the file "0.21/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
And we can plot the comparison at a single time point for two conditions.
Can you write Python code for it?

fig, axes = plt.subplots(nrows=2, ncols=4, figsize=(9, 5),
                         gridspec_kw=dict(width_ratios=[1, 1, 1, 0.1]))
vmin, vmax, ts = -8, 8, 9.0

evoked_left = epochs['Tapping/Left'].average()
evoked_right = epochs['Tapping/Right'].average()

evoked_left.plot_topomap(ch_type='hbo', times=ts, axes=axes[0, 0],
                         vmin=vmin, vmax=vmax, colorbar=False,
                         **topomap_args)
evoked_left.plot_topomap(ch_type='hbr', times=ts, axes=axes[1, 0],
                         vmin=vmin, vmax=vmax, colorbar=False,
                         **topomap_args)
evoked_right.plot_topomap(ch_type='hbo', times=ts, axes=axes[0, 1],
                          vmin=vmin, vmax=vmax, colorbar=False,
                          **topomap_args)
evoked_right.plot_topomap(ch_type='hbr', times=ts, axes=axes[1, 1],
                          vmin=vmin, vmax=vmax, colorbar=False,
                          **topomap_args)

evoked_diff = mne.combine_evoked([evoked_left, evoked_right], weights=[1, -1])

evoked_diff.plot_topomap(ch_type='hbo', times=ts, axes=axes[0, 2:],
                         vmin=vmin, vmax=vmax, colorbar=True,
                         **topomap_args)
evoked_diff.plot_topomap(ch_type='hbr', times=ts, axes=axes[1, 2:],
                         vmin=vmin, vmax=vmax, colorbar=True,
                         **topomap_args)

for column, condition in enumerate(
        ['Tapping Left', 'Tapping Right', 'Left-Right']):
    for row, chroma in enumerate(['HbO', 'HbR']):
        axes[row, column].set_title('{}: {}'.format(chroma, condition))
fig.tight_layout()


I am working on the file "0.21/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
At this stage it is appropriate to inspect your data
(for instructions on how to use the interactive data visualisation tool
see tut-visualize-raw)
to ensure that channels with poor scalp coupling have been removed.
If your data contains lots of artifacts you may decide to apply
artifact reduction techniques as described in ex-fnirs-artifacts.
Converting from optical density to haemoglobin
Next we convert the optical density data to haemoglobin concentration using
the modified Beer-Lambert law.
Can you write Python code for it?

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


I am working on the file "0.21/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
Compare tapping of left and right hands
Finally we generate topo maps for the left and right conditions to view
the location of activity. First we visualise the HbO activity.
Can you write Python code for it?

times = np.arange(4.0, 11.0, 1.0)
epochs['Tapping/Left'].average(picks='hbo').plot_topomap(
    times=times, **topomap_args)
epochs['Tapping/Right'].average(picks='hbo').plot_topomap(
    times=times, **topomap_args)


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

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


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

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


I am working on the file "0.21/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
Extract epochs
Now that the signal has been converted to relative haemoglobin concentration,
and the unwanted heart rate component has been removed, we can extract epochs
related to each of the experimental conditions.
First we extract the events of interest and visualise them to ensure they are
correct.
Can you write Python code for it?

events, _ = mne.events_from_annotations(raw_haemo, event_id={'1.0': 1,
                                                             '2.0': 2,
                                                             '3.0': 3})
event_dict = {'Control': 1, 'Tapping/Left': 2, 'Tapping/Right': 3}
fig = mne.viz.plot_events(events, event_id=event_dict,
                          sfreq=raw_haemo.info['sfreq'])
fig.subplots_adjust(right=0.7)  # make room for the legend


I am working on the file "0.21/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
In this example we will mark all channels with a SCI less than 0.5 as bad
(this dataset is quite clean, so no channels are marked as bad).
Can you write Python code for it?

raw_od.info['bads'] = list(compress(raw_od.ch_names, sci < 0.5))


I am working on the file "0.21/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
Preprocessing functional near-infrared spectroscopy (fNIRS) data
This tutorial covers how to convert functional near-infrared spectroscopy
(fNIRS) data from raw measurements to relative oxyhaemoglobin (HbO) and
deoxyhaemoglobin (HbR) concentration.
   :depth: 2
Here we will work with the fNIRS motor data <fnirs-motor-dataset>.
Can you write Python code for it?

import os
import numpy as np
import matplotlib.pyplot as plt
from itertools import compress

import mne

fnirs_data_folder = mne.datasets.fnirs_motor.data_path()
fnirs_cw_amplitude_dir = os.path.join(fnirs_data_folder, 'Participant-1')
raw_intensity = mne.io.read_raw_nirx(fnirs_cw_amplitude_dir, verbose=True)
raw_intensity.load_data()


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

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


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

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


I am working on the file "0.21/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
View location of sensors over brain surface
Here we validate that the location of sources-detector pairs and channels
are in the expected locations. Source-detector pairs are shown as lines
between the optodes, channels (the mid point of source-detector pairs) are
optionally shown as orange dots. Source are optionally shown as red dots and
detectors as black.
Can you write Python code for it?

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

fig = mne.viz.create_3d_figure(size=(800, 600), bgcolor='white')
fig = mne.viz.plot_alignment(raw_intensity.info, show_axes=True,
                             subject='fsaverage', coord_frame='mri',
                             trans='fsaverage', surfaces=['brain'],
                             fnirs=['channels', 'pairs',
                                    'sources', 'detectors'],
                             subjects_dir=subjects_dir, fig=fig)
mne.viz.set_3d_view(figure=fig, azimuth=20, elevation=60, distance=0.4,
                    focalpoint=(0., -0.01, 0.02))


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

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


I am working on the file "0.21/_downloads/ee17e3e8df43ce4f0119faeeeccc374f/plot_sensors_time_frequency.ipynb".
The first task is:
Frequency analysis
We start by exploring the frequence content of our epochs.
Let's first check out all channel types by averaging across epochs.
Can you write Python code for it?

epochs.plot_psd(fmin=2., fmax=40., average=True, spatial_colors=False)


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

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

import numpy as np
import matplotlib.pyplot as plt

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


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

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


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

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

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

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

# Construct Epochs
event_id, tmin, tmax = 1, -1., 3.
baseline = (None, 0)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=baseline, reject=dict(grad=4000e-13, eog=350e-6),
                    preload=True)

epochs.resample(200., npad='auto')  # resample to reduce computation time


I am working on the file "0.21/_downloads/ef81cbafce45c79dbfcdf37970a37c57/plot_source_space_snr.ipynb".
The first task is:
Computing source space SNR
This example shows how to compute and plot source space SNR as in [1]_.
Can you write Python code for it?

# Author: Padma Sundaram <tottochan@gmail.com>
#         Kaisu Lankinen <klankinen@mgh.harvard.edu>
#
# License: BSD (3-clause)

import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
import numpy as np
import matplotlib.pyplot as plt

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)

# Read inverse operator:
inv_op = make_inverse_operator(evoked.info, fwd, cov, fixed=True, verbose=True)

# Calculate MNE:
snr = 3.0
lambda2 = 1.0 / snr ** 2
stc = apply_inverse(evoked, inv_op, lambda2, 'MNE', verbose=True)

# Calculate SNR in source space:
snr_stc = stc.estimate_snr(evoked.info, fwd, cov)

# Plot an average SNR across source points over time:
ave = np.mean(snr_stc.data, axis=0)

fig, ax = plt.subplots()
ax.plot(evoked.times, ave)
ax.set(xlabel='Time (sec)', ylabel='SNR MEG-EEG')
fig.tight_layout()

# Find time point of maximum SNR:
maxidx = np.argmax(ave)

# Plot SNR on source space at the time point of maximum SNR:
kwargs = dict(initial_time=evoked.times[maxidx], hemi='split',
              views=['lat', 'med'], subjects_dir=subjects_dir, size=(600, 600),
              clim=dict(kind='value', lims=(-100, -70, -40)),
              transparent=True, colormap='viridis')
brain = snr_stc.plot(**kwargs)


I am working on the file "0.21/_downloads/ef81cbafce45c79dbfcdf37970a37c57/plot_source_space_snr.ipynb".
The first task is:
EEG
Next we do the same for EEG and plot the result on the cortex:
Can you write Python code for it?

evoked_eeg = evoked.copy().pick_types(eeg=True, meg=False)
inv_op_eeg = make_inverse_operator(evoked_eeg.info, fwd, cov, fixed=True,
                                   verbose=True)
stc_eeg = apply_inverse(evoked_eeg, inv_op_eeg, lambda2, 'MNE', verbose=True)
snr_stc_eeg = stc_eeg.estimate_snr(evoked_eeg.info, fwd, cov)
brain = snr_stc_eeg.plot(**kwargs)


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

.. role:: pink
.. role:: blue
.. role:: gray
.. role:: magenta
.. role:: purple
.. role:: green
.. role:: red
Understanding coordinate frames
For M/EEG source imaging, there are three coordinate frames must be
brought into alignment using two 3D transformation matrices <wiki_xform_>_
that define how to rotate and translate points in one coordinate frame
to their equivalent locations in another. The three main coordinate frames
are:

:blue:"meg": the coordinate frame for the physical locations of MEG
  sensors
:gray:"mri": the coordinate frame for MRI images, and scalp/skull/brain
  surfaces derived from the MRI images
:pink:"head": the coordinate frame for digitized sensor locations and
  scalp landmarks ("fiducials")

Each of these are described in more detail in the next section.
A good way to start visualizing these coordinate frames is to use the
mne.viz.plot_alignment function, which is used for creating or inspecting
the transformations that bring these coordinate frames into alignment, and
displaying the resulting alignment of EEG sensors, MEG sensors, brain
sources, and conductor models. If you provide subjects_dir and
subject parameters, the function automatically loads the subject's
Freesurfer MRI surfaces. Important for our purposes, passing
show_axes=True to ~mne.viz.plot_alignment will draw the origin of each
coordinate frame in a different color, with axes indicated by different sized
arrows:

shortest arrow: (R)ight / X
medium arrow: forward / (A)nterior / Y
longest arrow: up / (S)uperior / Z

Note that all three coordinate systems are RAS coordinate frames and
hence are also right-handed_ coordinate systems. Finally, note that the
coord_frame parameter...
Can you write Python code for it?

fig = mne.viz.plot_alignment(raw.info, trans=trans, subject='sample',
                             subjects_dir=subjects_dir, surfaces='head-dense',
                             show_axes=True, dig=True, eeg=[], meg='sensors',
                             coord_frame='meg')
mne.viz.set_3d_view(fig, 45, 90, distance=0.6, focalpoint=(0., 0., 0.))
print('Distance from head origin to MEG origin: %0.1f mm'
      % (1000 * np.linalg.norm(raw.info['dev_head_t']['trans'][:3, 3])))
print('Distance from head origin to MRI origin: %0.1f mm'
      % (1000 * np.linalg.norm(trans['trans'][:3, 3])))
dists = mne.dig_mri_distances(raw.info, trans, 'sample',
                              subjects_dir=subjects_dir)
print('Distance from %s digitized points to head surface: %0.1f mm'
      % (len(dists), 1000 * np.mean(dists)))


I am working on the file "0.21/_downloads/ef89d1f7daeb4e357098461753c3af0f/plot_source_alignment.ipynb".
The first task is:
A good example
Here is the same plot, this time with the trans properly defined
(using a precomputed transformation matrix).
Can you write Python code for it?

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


I am working on the file "0.21/_downloads/ef89d1f7daeb4e357098461753c3af0f/plot_source_alignment.ipynb".
The first task is:
Alignment without MRI
The surface alignments above are possible if you have the surfaces available
from Freesurfer. :func:mne.viz.plot_alignment automatically searches for
the correct surfaces from the provided subjects_dir. Another option is
to use a spherical conductor model <eeg_sphere_model>. It is
passed through bem parameter.
Can you write Python code for it?

sphere = mne.make_sphere_model(info=raw.info, r0='auto', head_radius='auto')
src = mne.setup_volume_source_space(sphere=sphere, pos=10.)
mne.viz.plot_alignment(
    raw.info, eeg='projected', bem=sphere, src=src, dig=True,
    surfaces=['brain', 'outer_skin'], coord_frame='meg', show_axes=True)


I am working on the file "0.21/_downloads/ef89d1f7daeb4e357098461753c3af0f/plot_source_alignment.ipynb".
The first task is:
Coordinate frame definitions

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

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

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

MEG device coordinate frame ("meg", :blue:blue axes)
     The MEG device coordinate frame is defined by the respective MEG
     manufacturers. All MEG data is acquired with respect to this coordinate
     frame. To account for the anatomy and position of the subject's head, we
     use so-called head position indicator (HPI) coils. The HPI coils are
     placed at known locations on the scalp of the subject and emit
     high-frequency magnetic fields used to coregister the head coordinate
     frame with the device coordinate frame.
From the Neuromag/Elekta/MEGIN user manual:
 The origin of the device coordinate system is located at the center
 of the posterior spherical section of the helmet with X axis going
 from left to right and Y axis pointing front. The Z axis is, again
 normal to the plane with positive direction up.

.....
Can you write Python code for it?

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


I am working on the file "0.21/_downloads/ef89d1f7daeb4e357098461753c3af0f/plot_source_alignment.ipynb".
The first task is:
Source alignment and coordinate frames
This tutorial shows how to visually assess the spatial alignment of MEG sensor
locations, digitized scalp landmark and sensor locations, and MRI volumes. This
alignment process is crucial for computing the forward solution, as is
understanding the different coordinate frames involved in this process.
   :depth: 2
Let's start out by loading some data.
Can you write Python code for it?

import os.path as op

import numpy as np
import nibabel as nib
from scipy import linalg

import mne
from mne.io.constants import FIFF

data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
trans_fname = op.join(data_path, 'MEG', 'sample',
                      'sample_audvis_raw-trans.fif')
raw = mne.io.read_raw_fif(raw_fname)
trans = mne.read_trans(trans_fname)
src = mne.read_source_spaces(op.join(subjects_dir, 'sample', 'bem',
                                     'sample-oct-6-src.fif'))

# load the T1 file and change the header information to the correct units
t1w = nib.load(op.join(data_path, 'subjects', 'sample', 'mri', 'T1.mgz'))
t1w = nib.Nifti1Image(t1w.dataobj, t1w.affine)
t1w.header['xyzt_units'] = np.array(10, dtype='uint8')
t1_mgh = nib.MGHImage(t1w.dataobj, t1w.affine)


I am working on the file "0.21/_downloads/ef89d1f7daeb4e357098461753c3af0f/plot_source_alignment.ipynb".
The first task is:
The relative orientations of the coordinate frames can be inferred by
observing the direction of the subject's nose. Notice also how the origin of
the :green:mri_voxel coordinate frame is in the corner of the volume
(above, behind, and to the left of the subject), whereas the other three
coordinate frames have their origin roughly in the center of the head.
Example: MRI defacing
For a real-world example of using these transforms, consider the task of
defacing the MRI to preserve subject anonymity. If you know the points in
the "head" coordinate frame (as you might if you're basing the defacing on
digitized points) you would need to transform them into "mri" or "mri_voxel"
in order to apply the blurring or smoothing operations to the MRI surfaces or
images. Here's what that would look like (we'll use the nasion landmark as a
representative example):
Can you write Python code for it?

# get the nasion
nasion = [p for p in raw.info['dig'] if
          p['kind'] == FIFF.FIFFV_POINT_CARDINAL and
          p['ident'] == FIFF.FIFFV_POINT_NASION][0]
assert nasion['coord_frame'] == FIFF.FIFFV_COORD_HEAD
nasion = nasion['r']  # get just the XYZ values

# transform it from head to MRI space (recall that `trans` is head → mri)
nasion_mri = mne.transforms.apply_trans(trans, nasion, move=True)
# then transform to voxel space, after converting from meters to millimeters
nasion_vox = mne.transforms.apply_trans(
    mri_to_vox, nasion_mri * 1e3, move=True)
# plot it to make sure the transforms worked
renderer = mne.viz.backends.renderer.create_3d_figure(
    size=(400, 400), bgcolor='w', scene=False)
add_head(renderer, scalp_points_in_vox, 'green', opacity=1)
renderer.sphere(center=nasion_vox, color='orange', scale=10)
mne.viz.set_3d_view(figure=renderer.figure, distance=600.,
                    focalpoint=(0., 125., 250.), elevation=45, azimuth=180)
renderer.show()


I am working on the file "0.21/_downloads/ef89d1f7daeb4e357098461753c3af0f/plot_source_alignment.ipynb".
The first task is:
Visualizing the transformations
Let's visualize these coordinate frames using just the scalp surface; this
will make it easier to see their relative orientations. To do this we'll
first load the Freesurfer scalp surface, then apply a few different
transforms to it. In addition to the three coordinate frames discussed above,
we'll also show the "mri_voxel" coordinate frame. Unlike MRI Surface RAS,
"mri_voxel" has its origin in the corner of the volume (the left-most,
posterior-most coordinate on the inferior-most MRI slice) instead of at the
center of the volume. "mri_voxel" is also not an RAS coordinate system:
rather, its XYZ directions are based on the acquisition order of the T1 image
slices.
Can you write Python code for it?

# the head surface is stored in "mri" coordinate frame
# (origin at center of volume, units=mm)
seghead_rr, seghead_tri = mne.read_surface(
    op.join(subjects_dir, 'sample', 'surf', 'lh.seghead'))

# to put the scalp in the "head" coordinate frame, we apply the inverse of
# the precomputed `trans` (which maps head → mri)
mri_to_head = linalg.inv(trans['trans'])
scalp_pts_in_head_coord = mne.transforms.apply_trans(
    mri_to_head, seghead_rr, move=True)

# to put the scalp in the "meg" coordinate frame, we use the inverse of
# raw.info['dev_head_t']
head_to_meg = linalg.inv(raw.info['dev_head_t']['trans'])
scalp_pts_in_meg_coord = mne.transforms.apply_trans(
    head_to_meg, scalp_pts_in_head_coord, move=True)

# The "mri_voxel"→"mri" transform is embedded in the header of the T1 image
# file. We'll invert it and then apply it to the original `seghead_rr` points.
# No unit conversion necessary: this transform expects mm and the scalp surface
# is defined in mm.
vox_to_mri = t1_mgh.header.get_vox2ras_tkr()
mri_to_vox = linalg.inv(vox_to_mri)
scalp_points_in_vox = mne.transforms.apply_trans(
    mri_to_vox, seghead_rr, move=True)


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

Note

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

Can you write Python code for it?

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

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

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

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

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


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

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

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


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

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

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

from nilearn import plotting

import mne
from mne.minimum_norm import make_inverse_operator, apply_inverse

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

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

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

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


I am working on the file "0.21/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Get a surface-based source space, here with few source points for speed
in this demonstration, in general you should use oct6 spacing!
Can you write Python code for it?

src = mne.setup_source_space(subject, spacing='oct5',
                             add_dist=False, subjects_dir=subjects_dir)


I am working on the file "0.21/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Plot the mixed source estimate
Can you write Python code for it?

initial_time = 0.1
stc_vec = apply_inverse(evoked, inverse_operator, lambda2, inv_method,
                        pick_ori='vector')
brain = stc_vec.plot(
    hemi='both', src=inverse_operator['src'], views='coronal',
    initial_time=initial_time, subjects_dir=subjects_dir)


I am working on the file "0.21/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Plot the surface
Can you write Python code for it?

brain = stc.surface().plot(initial_time=initial_time,
                           subjects_dir=subjects_dir)


I am working on the file "0.21/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Set up our source space
List substructures we are interested in. We select only the
sub structures we want to include in the source space:
Can you write Python code for it?

labels_vol = ['Left-Amygdala',
              'Left-Thalamus-Proper',
              'Left-Cerebellum-Cortex',
              'Brain-Stem',
              'Right-Amygdala',
              'Right-Thalamus-Proper',
              'Right-Cerebellum-Cortex']


I am working on the file "0.21/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Viewing the source space
We could write the mixed source space with::

write_source_spaces(fname_mixed_src, src, overwrite=True)

We can also export source positions to nifti file and visualize it again:
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, overwrite=True)
plotting.plot_img(nii_fname, cmap='nipy_spectral')


I am working on the file "0.21/_downloads/f5f9bdd06f90122e3e9f099984de196a/plot_evoked_topomap.ipynb".
The first task is:
Animating the topomap
Instead of using a still image we can plot magnetometer data as an animation
(animates only in matplotlib interactive mode)
Can you write Python code for it?

times = np.arange(0.05, 0.151, 0.01)
fig, anim = evoked.animate_topomap(
    times=times, ch_type='mag', frame_rate=2, time_unit='s', blit=False)


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

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


I am working on the file "0.21/_downloads/f5f9bdd06f90122e3e9f099984de196a/plot_evoked_topomap.ipynb".
The first task is:
If times is set to None at most 10 regularly spaced topographies will be
shown:
Can you write Python code for it?


I am working on the file "0.21/_downloads/f5f9bdd06f90122e3e9f099984de196a/plot_evoked_topomap.ipynb".
The first task is:
If you look at the edges of the head circle of a single topomap you'll see
the effect of extrapolation. There are three extrapolation modes:

extrapolate='local' extrapolates only to points close to the sensors.
extrapolate='head' extrapolates out to the head head circle.
extrapolate='box' extrapolates to a large box stretching beyond the
  head circle.

The default value extrapolate='auto' will use 'local' for MEG sensors
and 'head' otherwise. Here we show each option:
Can you write Python code for it?

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

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


I am working on the file "0.21/_downloads/f5f9bdd06f90122e3e9f099984de196a/plot_evoked_topomap.ipynb".
The first task is:
Instead of showing topographies at specific time points we can compute
averages of 50 ms bins centered on these time points to reduce the noise in
the topographies:
Can you write Python code for it?

evoked.plot_topomap(times, ch_type='mag', average=0.05, time_unit='s')


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

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


I am working on the file "0.21/_downloads/f5f9bdd06f90122e3e9f099984de196a/plot_evoked_topomap.ipynb".
The first task is:
Plotting topographic maps of evoked data
Load evoked data and plot topomaps for selected time points using multiple
additional options.
Can you write Python code for it?

# Authors: Christian Brodbeck <christianbrodbeck@nyu.edu>
#          Tal Linzen <linzen@nyu.edu>
#          Denis A. Engeman <denis.engemann@gmail.com>
#          Mikołaj Magnuski <mmagnuski@swps.edu.pl>
#          Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

from mne.datasets import sample
from mne import read_evokeds

print(__doc__)

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

# load evoked corresponding to a specific condition
# from the fif file and subtract baseline
condition = 'Left Auditory'
evoked = read_evokeds(fname, condition=condition, baseline=(None, 0))


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


I am working on the file "0.21/_downloads/f5f9bdd06f90122e3e9f099984de196a/plot_evoked_topomap.ipynb".
The first task is:
We can use nrows and ncols parameter to create multiline plots
with more timepoints.
Can you write Python code for it?

all_times = np.arange(-0.2, 0.5, 0.03)
evoked.plot_topomap(all_times, ch_type='mag', time_unit='s',
                    ncols=8, nrows='auto')


I am working on the file "0.21/_downloads/f760cc2f1a5d6c625b1e14a0b05176dd/plot_ecog.ipynb".
The first task is:
Now that we have our montage, we can load in our corresponding
time-series data and set the montage to the raw data.
Can you write Python code for it?

# first we'll load in the sample dataset
raw = mne.io.read_raw_edf(misc_path + '/ecog/sample_ecog.edf')

# drop bad channels
raw.info['bads'].extend([ch for ch in raw.ch_names if ch not in ch_names])
raw.load_data()
raw.drop_channels(raw.info['bads'])
raw.crop(0, 2)  # just process 2 sec of data for speed

# attach montage
raw.set_montage(montage)


I am working on the file "0.21/_downloads/f760cc2f1a5d6c625b1e14a0b05176dd/plot_ecog.ipynb".
The first task is:
Say we want to visualize the evolution of the power in the gamma band,
instead of just plotting the average. We can use
matplotlib.animation.FuncAnimation to create an animation and apply this
to the brain figure.
Can you write Python code for it?

# create an initialization and animation function
# to pass to FuncAnimation
def init():
    """Create an empty frame."""
    return paths,

def animate(i, activity):
    """Animate the plot."""
    paths.set_array(activity[:, i])
    return paths,

# create the figure and apply the animation of the
# gamma frequency band activity
fig, ax = plt.subplots(figsize=(10, 10))
ax.imshow(im)
ax.set_axis_off()
paths = ax.scatter(*xy_pts.T, c=np.zeros(len(xy_pts)), s=200,
                   cmap=cmap, vmin=vmin, vmax=vmax)
fig.colorbar(paths, ax=ax)
ax.set_title('Gamma frequency over time (Hilbert transform)',
             size='large')

# avoid edge artifacts and decimate, showing just a short chunk
show_power = gamma_power_t[:, 100:-1700:2]
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               fargs=(show_power,),
                               frames=show_power.shape[1],
                               interval=100, blit=True)


I am working on the file "0.21/_downloads/f781cba191074d5f4243e5933c1e870d/plot_find_ref_artifacts.ipynb".
The first task is:
Cleaned data:
Can you write Python code for it?


I am working on the file "0.21/_downloads/f781cba191074d5f4243e5933c1e870d/plot_find_ref_artifacts.ipynb".
The first task is:
Cleaned raw data PSD:
Can you write Python code for it?


I am working on the file "0.21/_downloads/f781cba191074d5f4243e5933c1e870d/plot_find_ref_artifacts.ipynb".
The first task is:
Find MEG reference channel artifacts
Use ICA decompositions of MEG reference channels to remove intermittent noise.
Many MEG systems have an array of reference channels which are used to detect
external magnetic noise. However, standard techniques that use reference
channels to remove noise from standard channels often fail when noise is
intermittent. The technique described here (using ICA on the reference
channels) often succeeds where the standard techniques do not.
There are two algorithms to choose from: separate and together (default). In
the "separate" algorithm, two ICA decompositions are made: one on the reference
channels, and one on reference + standard channels. The reference + standard
channel components which correlate with the reference channel components are
removed.
In the "together" algorithm, a single ICA decomposition is made on reference +
standard channels, and those components whose weights are particularly heavy
on the reference channels are removed.
This technique is fully described and validated in :footcite:HannaEtAl2020
Can you write Python code for it?

# Authors: Jeff Hanna <jeff.hanna@gmail.com>
#
# License: BSD (3-clause)

import mne
from mne import io
from mne.datasets import refmeg_noise
from mne.preprocessing import ICA
import numpy as np

print(__doc__)

data_path = refmeg_noise.data_path()


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


I am working on the file "0.21/_downloads/fa9fcfffc497146dd55d06cee6a5ec68/plot_creating_data_structures.ipynb".
The first task is:

Note

When assigning new values to the fields of an
          :class:`mne.Info` object, it is important that the
          fields are consistent:

          - The length of the channel information field ``chs`` must be
            ``nchan``.
          - The length of the ``ch_names`` field must be ``nchan``.
          - The ``ch_names`` field should be consistent with the ``name``
            field of the channel information contained in ``chs``.

Creating :class:~mne.io.Raw objects
To create a :class:mne.io.Raw object from scratch, you can use the
:class:mne.io.RawArray class, which implements raw data that is backed by a
numpy array. The correct units for the data are:

V: eeg, eog, seeg, emg, ecg, bio, ecog
T: mag
T/m: grad
M: hbo, hbr
Am: dipole
AU: misc

The :class:mne.io.RawArray constructor simply takes the data matrix and
:class:mne.Info object:
Can you write Python code for it?

# Generate some random data
data = np.random.randn(5, 1000)

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

custom_raw = mne.io.RawArray(data, info)
print(custom_raw)


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

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

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

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

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


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


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

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

print(custom_epochs)

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


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

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


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

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

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()


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

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

import os.path as op

import numpy as np
import matplotlib.pyplot as plt

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

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


I am working on the file "0.22/_downloads/03c9d71de135994dbf45db72856a1f9a/plot_mne_inverse_envelope_correlation.ipynb".
The first task is:
Now we band-pass filter our data and create epochs.
Can you write Python code for it?

raw.filter(14, 30)
events = mne.make_fixed_length_events(raw, duration=5.)
epochs = mne.Epochs(raw, events=events, tmin=0, tmax=5.,
                    baseline=None, reject=dict(mag=8e-13), preload=True)
del raw


I am working on the file "0.22/_downloads/03db2d983950efa77a26beb0ac22b422/plot_20_rejecting_bad_data.ipynb".
The first task is:
.. sidebar:: Annotating good spans
The default "BAD\_" prefix for new labels can be removed simply by
pressing the backspace key four times before typing your custom
annotation label.

You can see that default annotation label is "BAD_"; this can be edited
prior to pressing the "Add label" button to customize the label. The intent
is that users can annotate with as many or as few labels as makes sense for
their research needs, but that annotations marking spans that should be
excluded from the analysis pipeline should all begin with "BAD" or "bad"
(e.g., "bad_cough", "bad-eyes-closed", "bad door slamming", etc). When this
practice is followed, many processing steps in MNE-Python will automatically
exclude the "bad"-labelled spans of data; this behavior is controlled by a
parameter reject_by_annotation that can be found in many MNE-Python
functions or class constructors, including:

creation of epoched data from continuous data (:class:mne.Epochs)
many methods of the independent components analysis class
  (:class:mne.preprocessing.ICA)
functions for finding heartbeat and blink artifacts
  (:func:~mne.preprocessing.find_ecg_events,
  :func:~mne.preprocessing.find_eog_events)
covariance computations (:func:mne.compute_raw_covariance)
power spectral density computation (:meth:mne.io.Raw.plot_psd,
  :func:mne.time_frequency.psd_welch)

For example, when creating epochs from continuous data, if
reject_by_annotation=True the :class:~mne.Epochs constructor will drop
any epoch that partially or fully overlaps with an annotated span that begins
with "bad".
Generating annotations programmatically
The tut-artifact-overview tutorial introduced the artifact detection
functions :func:~mne.preprocessing.find_eog_events and
:func:~mne.preprocessing.find_ecg_events (although that tutorial mostly
relied on their higher-level wrappers
:func:~mne.preprocessing.create_eog_epochs and
:func:~mne.preprocessing.create_ecg_epochs). Here, for demonstration
purposes, we make use of the lower-level artifact detection function to get
an...
Can you write Python code for it?

eog_events = mne.preprocessing.find_eog_events(raw)
onsets = eog_events[:, 0] / raw.info['sfreq'] - 0.25
durations = [0.5] * len(eog_events)
descriptions = ['bad blink'] * len(eog_events)
blink_annot = mne.Annotations(onsets, durations, descriptions,
                              orig_time=raw.info['meas_date'])
raw.set_annotations(blink_annot)


I am working on the file "0.22/_downloads/03db2d983950efa77a26beb0ac22b422/plot_20_rejecting_bad_data.ipynb".
The first task is:
Annotating bad spans of data
The tutorial tut-events-vs-annotations describes how
:class:~mne.Annotations can be read from embedded events in the raw
recording file, and tut-annotate-raw describes in detail how to
interactively annotate a :class:~mne.io.Raw data object. Here, we focus on
best practices for annotating bad data spans so that they will be excluded
from your analysis pipeline.
The reject_by_annotation parameter
In the interactive raw.plot() window, the annotation controls can be
opened by pressing :kbd:a. Here, new annotation labels can be created or
existing annotation labels can be selected for use.
Can you write Python code for it?

fig = raw.plot()
fig.canvas.key_press_event('a')


I am working on the file "0.22/_downloads/03db2d983950efa77a26beb0ac22b422/plot_20_rejecting_bad_data.ipynb".
The first task is:
Finally, it should be noted that "dropped" epochs are not necessarily deleted
from the :class:~mne.Epochs object right away. Above, we forced the
dropping to happen when we created the :class:~mne.Epochs object by using
the preload=True parameter. If we had not done that, the
:class:~mne.Epochs object would have been memory-mapped_ (not loaded into
RAM), in which case the criteria for dropping epochs are stored, and the
actual dropping happens when the :class:~mne.Epochs data are finally loaded
and used. There are several ways this can get triggered, such as:

explicitly loading the data into RAM with the :meth:~mne.Epochs.load_data
  method
plotting the data (:meth:~mne.Epochs.plot,
  :meth:~mne.Epochs.plot_image, etc)
using the :meth:~mne.Epochs.average method to create an
  :class:~mne.Evoked object

You can also trigger dropping with the :meth:~mne.Epochs.drop_bad method;
if reject and/or flat criteria have already been provided to the
epochs constructor, :meth:~mne.Epochs.drop_bad can be used without
arguments to simply delete the epochs already marked for removal (if the
epochs have already been dropped, nothing further will happen):
Can you write Python code for it?


I am working on the file "0.22/_downloads/03db2d983950efa77a26beb0ac22b422/plot_20_rejecting_bad_data.ipynb".
The first task is:
More importantly, note that many more epochs are rejected (~20% instead of
~2.5%) when rejecting based on the blink labels, underscoring why it is
usually desirable to repair artifacts rather than exclude them.
The :meth:~mne.Epochs.plot_drop_log method is a visualization of an
:class:~mne.Epochs attribute, namely epochs.drop_log, which stores
empty lists for retained epochs and lists of strings for dropped epochs, with
the strings indicating the reason(s) why the epoch was dropped. For example:
Can you write Python code for it?


I am working on the file "0.22/_downloads/03db2d983950efa77a26beb0ac22b422/plot_20_rejecting_bad_data.ipynb".
The first task is:
Notice that we've passed reject_by_annotation=False above, in order to
isolate the effects of the rejection thresholds. If we re-run the epoching
with reject_by_annotation=True (the default) we see that the rejections
due to EEG and EOG channels have disappeared (suggesting that those channel
fluctuations were probably blink-related, and were subsumed by rejections
based on the "bad blink" label).
Can you write Python code for it?

epochs = mne.Epochs(raw, events, tmin=-0.2, tmax=0.5, reject_tmax=0,
                    reject=reject_criteria, flat=flat_criteria, preload=True)
epochs.plot_drop_log()


I am working on the file "0.22/_downloads/03db2d983950efa77a26beb0ac22b422/plot_20_rejecting_bad_data.ipynb".
The first task is:
Rejecting bad data spans
This tutorial covers manual marking of bad spans of data, and automated
rejection of data spans based on signal amplitude.
   :depth: 2
We begin as always by importing the necessary Python modules and loading some
example data <sample-dataset>; to save memory we'll use a pre-filtered
and downsampled version of the example data, and we'll also load an events
array to use when converting the continuous data to epochs:
Can you write Python code for it?

import os
import mne

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_filt-0-40_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)
events_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                           'sample_audvis_filt-0-40_raw-eve.fif')
events = mne.read_events(events_file)


I am working on the file "0.22/_downloads/03db2d983950efa77a26beb0ac22b422/plot_20_rejecting_bad_data.ipynb".
The first task is:
See the section tut-section-programmatic-annotations for more details
on creating annotations programmatically.
Rejecting Epochs based on channel amplitude
Besides "bad" annotations, the :class:mne.Epochs class constructor has
another means of rejecting epochs, based on signal amplitude thresholds for
each channel type. In the overview tutorial
<tut-section-overview-epoching> we saw an example of this: setting maximum
acceptable peak-to-peak amplitudes for each channel type in an epoch, using
the reject parameter. There is also a related parameter, flat, that
can be used to set minimum acceptable peak-to-peak amplitudes for each
channel type in an epoch:
Can you write Python code for it?

reject_criteria = dict(mag=3000e-15,     # 3000 fT
                       grad=3000e-13,    # 3000 fT/cm
                       eeg=100e-6,       # 100 µV
                       eog=200e-6)       # 200 µV

flat_criteria = dict(mag=1e-15,          # 1 fT
                     grad=1e-13,         # 1 fT/cm
                     eeg=1e-6)           # 1 µV


I am working on the file "0.22/_downloads/03db2d983950efa77a26beb0ac22b422/plot_20_rejecting_bad_data.ipynb".
The first task is:
The values that are appropriate are dataset- and hardware-dependent, so some
trial-and-error may be necessary to find the correct balance between data
quality and loss of power due to too many dropped epochs. Here, we've set the
rejection criteria to be fairly stringent, for illustration purposes.
Two additional parameters, reject_tmin and reject_tmax, are used to
set the temporal window in which to calculate peak-to-peak amplitude for the
purposes of epoch rejection. These default to the same tmin and tmax
of the entire epoch. As one example, if you wanted to only apply the
rejection thresholds to the portion of the epoch that occurs before the
event marker around which the epoch is created, you could set
reject_tmax=0. A summary of the causes of rejected epochs can be
generated with the :meth:~mne.Epochs.plot_drop_log method:
Can you write Python code for it?

epochs = mne.Epochs(raw, events, tmin=-0.2, tmax=0.5, reject_tmax=0,
                    reject=reject_criteria, flat=flat_criteria,
                    reject_by_annotation=False, preload=True)
epochs.plot_drop_log()


I am working on the file "0.22/_downloads/05c57a644672d33707fd1264df7f5617/plot_time_frequency_global_field_power.ipynb".
The first task is:
Now we can compute the Global Field Power
We can track the emergence of spatial patterns compared to baseline
for each frequency band, with a bootstrapped confidence interval.
We see dominant responses in the Alpha and Beta bands.
Can you write Python code for it?

# Helper function for plotting spread
def stat_fun(x):
    """Return sum of squares."""
    return np.sum(x ** 2, axis=0)

# Plot
fig, axes = plt.subplots(4, 1, figsize=(10, 7), sharex=True, sharey=True)
colors = plt.get_cmap('winter_r')(np.linspace(0, 1, 4))
for ((freq_name, fmin, fmax), average), color, ax in zip(
        frequency_map, colors, axes.ravel()[::-1]):
    times = average.times * 1e3
    gfp = np.sum(average.data ** 2, axis=0)
    gfp = mne.baseline.rescale(gfp, times, baseline=(None, 0))
    ax.plot(times, gfp, label=freq_name, color=color, linewidth=2.5)
    ax.axhline(0, linestyle='--', color='grey', linewidth=2)
    ci_low, ci_up = bootstrap_confidence_interval(average.data, random_state=0,
                                                  stat_fun=stat_fun)
    ci_low = rescale(ci_low, average.times, baseline=(None, 0))
    ci_up = rescale(ci_up, average.times, baseline=(None, 0))
    ax.fill_between(times, gfp + ci_up, gfp - ci_low, color=color, alpha=0.3)
    ax.grid(True)
    ax.set_ylabel('GFP')
    ax.annotate('%s (%d-%dHz)' % (freq_name, fmin, fmax),
                xy=(0.95, 0.8),
                horizontalalignment='right',
                xycoords='axes fraction')
    ax.set_xlim(-1000, 3000)

axes.ravel()[-1].set_xlabel('Time [ms]')


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

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

# let's explore some frequency bands
iter_freqs = [
    ('Theta', 4, 7),
    ('Alpha', 8, 12),
    ('Beta', 13, 25),
    ('Gamma', 30, 45)
]


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

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

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

frequency_map = list()

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

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

    # epoch
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, baseline=baseline,
                        reject=dict(grad=4000e-13, eog=350e-6),
                        preload=True)
    # remove evoked response
    epochs.subtract_evoked()

    # get analytic signal (envelope)
    epochs.apply_hilbert(envelope=True)
    frequency_map.append(((band, fmin, fmax), epochs.average()))
    del epochs
del raw


I am working on the file "0.22/_downloads/0f6b60b574bc5e5c341b148b90d0f456/plot_evoked_whitening.ipynb".
The first task is:
Compute covariance using automated regularization
Can you write Python code for it?

method_params = dict(diagonal_fixed=dict(mag=0.01, grad=0.01, eeg=0.01))
noise_covs = compute_covariance(epochs, tmin=None, tmax=0, method='auto',
                                return_estimators=True, verbose=True, n_jobs=1,
                                projs=None, rank=None,
                                method_params=method_params)

# With "return_estimator=True" all estimated covariances sorted
# by log-likelihood are returned.

print('Covariance estimates sorted from best to worst')
for c in noise_covs:
    print("%s : %s" % (c['method'], c['loglik']))


I am working on the file "0.22/_downloads/0f6b60b574bc5e5c341b148b90d0f456/plot_evoked_whitening.ipynb".
The first task is:
We can then show whitening for our various noise covariance estimates.
Here we should look to see if baseline signals match the
assumption of Gaussian white noise. we expect values centered at
0 within 2 standard deviations for 95% of the time points.
For the Global field power we expect a value of 1.
Can you write Python code for it?


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

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

import mne

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

print(__doc__)


I am working on the file "0.22/_downloads/12e915738bb5b40ffcb1157f1c2dee72/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.22/_downloads/12e915738bb5b40ffcb1157f1c2dee72/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.22/_downloads/12e915738bb5b40ffcb1157f1c2dee72/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.
_, (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.22/_downloads/12e915738bb5b40ffcb1157f1c2dee72/plot_receptive_field.ipynb".
The first task is:
Load audio data
We'll read in the audio data from [3]_ in order to simulate a response.
In addition, we'll downsample the data along the time dimension in order to
speed up computation. Note that depending on the input values, this may
not be desired. For example if your input stimulus varies more quickly than
1/2 the sampling rate to which we are downsampling.
Can you write Python code for it?

# Read in audio that's been recorded in epochs.
path_audio = mne.datasets.mtrf.data_path()
data = loadmat(path_audio + '/speech_data.mat')
audio = data['spectrogram'].T
sfreq = float(data['Fs'][0, 0])
n_decim = 2
audio = mne.filter.resample(audio, down=n_decim, npad='auto')
sfreq /= n_decim


I am working on the file "0.22/_downloads/12e915738bb5b40ffcb1157f1c2dee72/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]
_, (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()


I am working on the file "0.22/_downloads/12e915738bb5b40ffcb1157f1c2dee72/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][tuple(put)] = X[tuple(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
_, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 6), sharex=True)
ax1.pcolormesh(time, freqs, X_plt, vmin=0, vmax=4, cmap='Reds',
               shading='gouraud')
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.22/_downloads/12e915738bb5b40ffcb1157f1c2dee72/plot_receptive_field.ipynb".
The first task is:
Spectro-temporal receptive field (STRF) estimation on continuous data
This demonstrates how an encoding model can be fit with multiple continuous
inputs. In this case, we simulate the model behind a spectro-temporal receptive
field (or STRF). First, we create a linear filter that maps patterns in
spectro-temporal space onto an output, representing neural activity. We fit
a receptive field model that attempts to recover the original linear filter
that was used to create this data.
References
Estimation of spectro-temporal and spatio-temporal receptive fields using
modeling with continuous inputs is described in:
.. [1] Theunissen, F. E. et al. Estimating spatio-temporal receptive
       fields of auditory and visual neurons from their responses to
       natural stimuli. Network 12, 289-316 (2001).
.. [2] Willmore, B. & Smyth, D. Methods for first-order kernel
       estimation: simple-cell receptive fields from responses to
       natural scenes. Network 14, 553-77 (2003).
.. [3] Crosse, M. J., Di Liberto, G. M., Bednar, A. & Lalor, E. C. (2016).
       The Multivariate Temporal Response Function (mTRF) Toolbox:
       A MATLAB Toolbox for Relating Neural Signals to Continuous Stimuli.
       Frontiers in Human Neuroscience 10, 604.
       doi:10.3389/fnhum.2016.00604
.. [4] Holdgraf, C. R. et al. Rapid tuning shifts in human auditory cortex
       enhance speech intelligibility. Nature Communications, 7, 13654 (2016).
       doi:10.1038/ncomms13654
Can you write Python code for it?

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

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.decoding import ReceptiveField, TimeDelayingRidge

from scipy.stats import multivariate_normal
from scipy.io import loadmat
from sklearn.preprocessing import scale
rng = np.random.RandomState(1337)  # To make this example reproducible


I am working on the file "0.22/_downloads/12e915738bb5b40ffcb1157f1c2dee72/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.22/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
Adding custom plots to a report
The python interface has greater flexibility compared to the command
line interface <mne report>. For example, custom plots can be added via
the :meth:~mne.Report.add_figs_to_section method:
Can you write Python code for it?

# generate a custom plot:
fname_evoked = os.path.join(path, 'MEG', 'sample', 'sample_audvis-ave.fif')
evoked = mne.read_evokeds(fname_evoked,
                          condition='Left Auditory',
                          baseline=(None, 0),
                          verbose=True)
fig = evoked.plot(show=False)

# add the custom plot to the report:
report.add_figs_to_section(fig, captions='Left Auditory', section='evoked')
report.save('report_custom.html', overwrite=True)


I am working on the file "0.22/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
If you want to actually view the noise covariance in the report, make sure
it is captured by the pattern passed to :meth:~mne.Report.parse_folder, and
also include a source for an :class:~mne.Info object (any of the
:class:~mne.io.Raw, :class:~mne.Epochs or :class:~mne.Evoked
:file:.fif files that contain subject data also contain the measurement
information and should work):
Can you write Python code for it?

pattern = 'sample_audvis-cov.fif'
info_fname = os.path.join(path, 'MEG', 'sample', 'sample_audvis-ave.fif')
report = mne.Report(info_fname=info_fname, verbose=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_cov.html', overwrite=True)


I am working on the file "0.22/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
Managing report sections
The MNE report command internally manages the sections so that plots
belonging to the same section are rendered consecutively. Within a section,
the plots are ordered in the same order that they were added using the
:meth:~mne.Report.add_figs_to_section command. Each section is identified
by a toggle button in the top navigation bar of the report which can be used
to show or hide the contents of the section. To toggle the show/hide state of
all sections in the HTML report, press :kbd:t.

Note

Although we've been generating separate reports in each example, you could
   easily create a single report for all :file:`.fif` files (raw, evoked,
   covariance, etc) by passing ``pattern='*.fif'``.

Editing a saved report
Saving to HTML is a write-only operation, meaning that we cannot read an
.html file back as a :class:~mne.Report object. In order to be able
to edit a report once it's no longer in-memory in an active Python session,
save it as an HDF5 file instead of HTML:
Can you write Python code for it?

report.save('report.h5', overwrite=True)
report_from_disk = mne.open_report('report.h5')
print(report_from_disk)


I am working on the file "0.22/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
Now let's look at how :class:~mne.Report handles :class:~mne.Evoked data
(we'll skip the MRIs to save computation time). The following code will
produce butterfly plots, topomaps, and comparisons of the global field
power (GFP) for different experimental conditions.
Can you write Python code for it?

pattern = 'sample_audvis-no-filter-ave.fif'
report = mne.Report(verbose=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_evoked.html', overwrite=True)


I am working on the file "0.22/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
This allows the possibility of multiple scripts adding figures to the same
report. To make this even easier, :class:mne.Report can be used as a
context manager:
Can you write Python code for it?

with mne.open_report('report.h5') as report:
    report.add_figs_to_section(fig,
                               captions='Left Auditory',
                               section='evoked',
                               replace=True)
    report.save('report_final.html', overwrite=True)


I am working on the file "0.22/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
This report yields a textual summary of the :class:~mne.io.Raw files
selected by the pattern. For a slightly more useful report, we'll ask for the
power spectral density of the :class:~mne.io.Raw files, by passing
raw_psd=True to the :class:~mne.Report constructor. We'll also
visualize the SSP projectors stored in the raw data's ~mne.Info dictionary
by setting projs=True. Lastly, let's also refine our pattern to select
only the filtered raw recording (omitting the unfiltered data and the
empty-room noise recordings):
Can you write Python code for it?

pattern = 'sample_audvis_filt-0-40_raw.fif'
report = mne.Report(raw_psd=True, projs=True, verbose=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_raw_psd.html', overwrite=True)


I am working on the file "0.22/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
This time we'll pass a specific subject and subjects_dir (even though
there's only one subject in the sample dataset) and remove our
render_bem=False parameter so we can see the MRI slices, with BEM
contours overlaid on top if available. Since this is computationally
expensive, we'll also pass the mri_decim parameter for the benefit of our
documentation servers, and skip processing the :file:.fif files:
Can you write Python code for it?

subjects_dir = os.path.join(path, 'subjects')
report = mne.Report(subject='sample', subjects_dir=subjects_dir, verbose=True)
report.parse_folder(path, pattern='', mri_decim=25)
report.save('report_mri_bem.html', overwrite=True)


I am working on the file "0.22/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
To render whitened :class:~mne.Evoked files with baseline correction, pass
the baseline argument we just used, and add the noise covariance file.
This will display ERP/ERF plots for both the original and whitened
:class:~mne.Evoked objects, but scalp topomaps only for the original.
Can you write Python code for it?

cov_fname = os.path.join(path, 'MEG', 'sample', 'sample_audvis-cov.fif')
baseline = (None, 0)
report = mne.Report(cov_fname=cov_fname, baseline=baseline, verbose=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_evoked_whitened.html', overwrite=True)


I am working on the file "0.22/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
You have probably noticed that the EEG recordings look particularly odd. This
is because by default, ~mne.Report does not apply baseline correction
before rendering evoked data. So if the dataset you wish to add to the report
has not been baseline-corrected already, you can request baseline correction
here. The MNE sample dataset we're using in this example has not been
baseline-corrected; so let's do this now for the report!
To request baseline correction, pass a baseline argument to
~mne.Report, which should be a tuple with the starting and ending time of
the baseline period. For more details, see the documentation on
~mne.Evoked.apply_baseline. Here, we will apply baseline correction for a
baseline period from the beginning of the time interval to time point zero.
Can you write Python code for it?

baseline = (None, 0)
pattern = 'sample_audvis-no-filter-ave.fif'
report = mne.Report(baseline=baseline, verbose=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_evoked_baseline.html', overwrite=True)


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

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

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

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

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

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

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

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


I am working on the file "0.22/_downloads/162648d33d7b9ea4f5ce1e8bb494a02d/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.22/_downloads/17295dea468fcedae97ed8a6f9afc520/plot_decoding_csp_timefreq.ipynb".
The first task is:
Loop through frequencies, apply classifier and save scores
Can you write Python code for it?

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

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

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

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

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

    X = epochs.get_data()

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


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

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


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

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

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

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

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

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

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

# Instantiate label encoder
le = LabelEncoder()


I am working on the file "0.22/_downloads/1935e973eb220e31cb4a6a6541231eb1/plot_background_statistics.ipynb".
The first task is:
"Hat" variance adjustment
The "hat" technique regularizes the variance values used in the t-test
calculation [1]_ to compensate for implausibly small variances.
Can you write Python code for it?

ts.append(ttest_1samp_no_p(X, sigma=sigma))
ps.append(stats.distributions.t.sf(np.abs(ts[-1]), len(X) - 1) * 2)
titles.append(r'$\mathrm{t_{hat}}$')
mccs.append(False)
plot_t_p(ts[-1], ps[-1], titles[-1], mccs[-1])


I am working on the file "0.22/_downloads/1935e973eb220e31cb4a6a6541231eb1/plot_background_statistics.ipynb".
The first task is:
"Hat" variance adjustment
This method can also be used in this context to correct for small
variances [1]_:
Can you write Python code for it?

titles.append(r'$\mathbf{C_{hat}}$')
stat_fun_hat = partial(ttest_1samp_no_p, sigma=sigma)
t_hat, clusters, p_values, H0 = permutation_cluster_1samp_test(
    X, n_jobs=1, threshold=threshold, adjacency=None, out_type='mask',
    n_permutations=n_permutations, stat_fun=stat_fun_hat, buffer_size=None)
p_hat = np.ones((width, width))
for cl, p in zip(clusters, p_values):
    p_hat[cl] = p
ts.append(t_hat)
ps.append(p_hat)
mccs.append(True)
plot_t_p(ts[-1], ps[-1], titles[-1], mccs[-1])


I am working on the file "0.22/_downloads/1935e973eb220e31cb4a6a6541231eb1/plot_background_statistics.ipynb".
The first task is:
Clustering
Each of the aforementioned multiple comparisons corrections have the
disadvantage of not fully incorporating the correlation structure of the
data, namely that points close to one another (e.g., in space or time) tend
to be correlated. However, by defining the adjacency/adjacency/neighbor
structure in our data, we can use clustering to compensate.
To use this, we need to rethink our null hypothesis. Instead
of thinking about a null hypothesis about means per voxel (with one
independent test per voxel), we consider a null hypothesis about sizes
of clusters in our data, which could be stated like:
The distribution of spatial cluster sizes observed in two experimental
conditions are drawn from the same probability distribution.

Here we only have a single condition and we contrast to zero, which can
be thought of as:
The distribution of spatial cluster sizes is independent of the sign
of the data.

In this case, we again do permutations with a maximum statistic, but, under
each permutation, we:

Compute the test statistic for each voxel individually.
Threshold the test statistic values.
Cluster voxels that exceed this threshold (with the same sign) based on
   adjacency.
Retain the size of the largest cluster (measured, e.g., by a simple voxel
   count, or by the sum of voxel t-values within the cluster) to build the
   null distribution.

After doing these permutations, the cluster sizes in our veridical data
are compared to this null distribution. The p-value associated with each
cluster is again given by the proportion of smaller null distribution
values. This can then be subjected to a standard p-value threshold
(e.g., p < 0.05) to reject the null hypothesis (i.e., find an effect of
interest).
This reframing to consider cluster sizes rather than individual means
maintains the advantages of the standard non-parametric permutation
test -- namely controlling FWER and making no assumptions of parametric
data distribution.
Critically, though, it also accounts for the correlation structure in the
data...
Can you write Python code for it?

from sklearn.feature_extraction.image import grid_to_graph  # noqa: E402
mini_adjacency = grid_to_graph(3, 3).toarray()
assert mini_adjacency.shape == (9, 9)
print(mini_adjacency[0])


I am working on the file "0.22/_downloads/1935e973eb220e31cb4a6a6541231eb1/plot_background_statistics.ipynb".
The first task is:
False discovery rate (FDR) correction
Typically FDR is performed with the Benjamini-Hochberg procedure, which
is less restrictive than Bonferroni correction for large numbers of
comparisons (fewer type II errors), but provides less strict control of type
I errors.
Can you write Python code for it?

titles.append('FDR')
ts.append(ts[-1])
ps.append(fdr_correction(ps[0])[1])
mccs.append(True)
plot_t_p(ts[-1], ps[-1], titles[-1], mccs[-1])


I am working on the file "0.22/_downloads/1935e973eb220e31cb4a6a6541231eb1/plot_background_statistics.ipynb".
The first task is:
Hypothesis testing
Null hypothesis
^^^^^^^^^^^^^^^
From Wikipedia <https://en.wikipedia.org/wiki/Null_hypothesis>__:
In inferential statistics, a general statement or default position that
there is no relationship between two measured phenomena, or no
association among groups.

We typically want to reject a null hypothesis with
some probability (e.g., p < 0.05). This probability is also called the
significance level $\alpha$.
To think about what this means, let's follow the illustrative example from
[1]_ and construct a toy dataset consisting of a 40 x 40 square with a
"signal" present in the center with white noise added and a Gaussian
smoothing kernel applied.
Can you write Python code for it?

width = 40
n_subjects = 10
signal_mean = 100
signal_sd = 100
noise_sd = 0.01
gaussian_sd = 5
sigma = 1e-3  # sigma for the "hat" method
n_permutations = 'all'  # run an exact test
n_src = width * width

# For each "subject", make a smoothed noisy signal with a centered peak
rng = np.random.RandomState(2)
X = noise_sd * rng.randn(n_subjects, width, width)
# Add a signal at the center
X[:, width // 2, width // 2] = signal_mean + rng.randn(n_subjects) * signal_sd
# Spatially smooth with a 2D Gaussian kernel
size = width // 2 - 1
gaussian = np.exp(-(np.arange(-size, size + 1) ** 2 / float(gaussian_sd ** 2)))
for si in range(X.shape[0]):
    for ri in range(X.shape[1]):
        X[si, ri, :] = np.convolve(X[si, ri, :], gaussian, 'same')
    for ci in range(X.shape[2]):
        X[si, :, ci] = np.convolve(X[si, :, ci], gaussian, 'same')


I am working on the file "0.22/_downloads/1935e973eb220e31cb4a6a6541231eb1/plot_background_statistics.ipynb".
The first task is:
In general the adjacency between voxels can be more complex, such as
those between sensors in 3D space, or time-varying activation at brain
vertices on a cortical surface. MNE provides several convenience functions
for computing adjacency matrices (see the
Statistics API <api_reference_statistics>).
Standard clustering
Here, since our data are on a grid, we can use adjacency=None to
trigger optimized grid-based code, and run the clustering algorithm.
Can you write Python code for it?

titles.append('Clustering')
# Reshape data to what is equivalent to (n_samples, n_space, n_time)
X.shape = (n_subjects, width, width)
# Compute threshold from t distribution (this is also the default)
threshold = stats.distributions.t.ppf(1 - alpha, n_subjects - 1)
t_clust, clusters, p_values, H0 = permutation_cluster_1samp_test(
    X, n_jobs=1, threshold=threshold, adjacency=None,
    n_permutations=n_permutations, out_type='mask')
# Put the cluster data in a viewable format
p_clust = np.ones((width, width))
for cl, p in zip(clusters, p_values):
    p_clust[cl] = p
ts.append(t_clust)
ps.append(p_clust)
mccs.append(True)
plot_t_p(ts[-1], ps[-1], titles[-1], mccs[-1])