I am working on the file "0.19/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
Plotting events and raw data together
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Events can also be plotted alongside the :class:~mne.io.Raw object they
were extracted from, by passing the Event array as the events parameter
of :meth:raw.plot <mne.io.Raw.plot>:
Can you write Python code for it?

raw.plot(events=events, start=5, duration=10, color='gray',
         event_color={1: 'r', 2: 'g', 3: 'b', 4: 'm', 5: 'y', 32: 'k'})


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

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


I am working on the file "0.19/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
And to change the name of the EOG channel
Can you write Python code for it?


I am working on the file "0.19/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
Average reference: This is normally added by default, but can also
be added explicitly.
Can you write Python code for it?

raw.del_proj()
raw_car, _ = mne.set_eeg_reference(raw, 'average', projection=True)
evoked_car = mne.Epochs(raw_car, **epochs_params).average()
del raw_car  # save memory

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


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


I am working on the file "0.19/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
Custom reference: Use the mean of channels EEG 001 and EEG 002 as
a reference
Can you write Python code for it?

raw_custom, _ = mne.set_eeg_reference(raw, ['EEG 001', 'EEG 002'])
evoked_custom = mne.Epochs(raw_custom, **epochs_params).average()
del raw_custom  # save memory

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


I am working on the file "0.19/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
EEG processing and Event Related Potentials (ERPs)
For a generic introduction to the computation of ERP and ERF
see tut_epoching_and_averaging.
   :depth: 1
Can you write Python code for it?

import mne
from mne.datasets import sample


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


I am working on the file "0.19/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
Next, we create averages of stimulation-left vs stimulation-right trials.
We can use basic arithmetic to, for example, construct and plot
difference ERPs.
Can you write Python code for it?

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

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


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

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

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

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


I am working on the file "0.19/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
Setting EEG reference
Let's first remove the reference from our Raw object.
This explicitly prevents MNE from adding a default EEG average reference
required for source localization.
Can you write Python code for it?

raw_no_ref, _ = mne.set_eeg_reference(raw, [])


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


I am working on the file "0.19/_downloads/5f84ce88b4773e5ca1f9b3502aef334a/plot_eeg_erp.ipynb".
The first task is:
We next define Epochs and compute an ERP for the left auditory condition.
Can you write Python code for it?

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

evoked_no_ref = mne.Epochs(raw_no_ref, **epochs_params).average()
del raw_no_ref  # save memory

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


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

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

Preprocessing
Can you write Python code for it?

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

import os.path as op

from mne.filter import next_fast_len

import mne

print(__doc__)

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

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


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

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


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

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


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

fig_gamma, brain_gamma = plot_band('vv', 'gamma')


I am working on the file "0.19/_downloads/6035dcef33422511928bd2247a3d092d/plot_source_power_spectrum_opm.ipynb".
The first task is:
Now we can make some plots of each frequency band. Note that the OPM head
coverage is only over right motor cortex, so only localization
of beta is likely to be worthwhile.
Theta
Can you write Python code for it?

def plot_band(kind, band):
    """Plot activity within a frequency band on the subject's brain."""
    title = "%s %s\n(%d-%d Hz)" % ((titles[kind], band,) + freq_bands[band])
    topos[kind][band].plot_topomap(
        times=0., scalings=1., cbar_fmt='%0.1f', vmin=0, cmap='inferno',
        time_format=title)
    brain = stcs[kind][band].plot(
        subject=subject, subjects_dir=subjects_dir, views='cau', hemi='both',
        time_label=title, title=title, colormap='inferno',
        clim=dict(kind='percent', lims=(70, 85, 99)))
    brain.show_view(dict(azimuth=0, elevation=0), roll=0)
    return fig, brain

fig_theta, brain_theta = plot_band('vv', 'theta')


I am working on the file "0.19/_downloads/638c39682b0791ce4e430e4d2fcc4c45/plot_tf_dics.ipynb".
The first task is:
Read raw data
Can you write Python code for it?

raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.info['bads'] = ['MEG 2443']  # 1 bad MEG channel

# Pick a selection of magnetometer channels. A subset of all channels was used
# to speed up the example. For a solution based on all MEG channels use
# meg=True, selection=None and add mag=4e-12 to the reject dictionary.
left_temporal_channels = mne.read_selection('Left-temporal')
picks = mne.pick_types(raw.info, meg='mag', eeg=False, eog=False,
                       stim=False, exclude='bads',
                       selection=left_temporal_channels)
raw.pick_channels([raw.ch_names[pick] for pick in picks])
reject = dict(mag=4e-12)
# Re-normalize our empty-room projectors, which should be fine after
# subselection
raw.info.normalize_proj()

# Setting time windows. Note that tmin and tmax are set so that time-frequency
# beamforming will be performed for a wider range of time points than will
# later be displayed on the final spectrogram. This ensures that all time bins
# displayed represent an average of an equal number of time windows.
tmin, tmax, tstep = -0.5, 0.75, 0.05  # s
tmin_plot, tmax_plot = -0.3, 0.5  # s

# Read epochs
event_id = 1
events = mne.read_events(event_fname)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                    baseline=None, preload=True, proj=True, reject=reject)

# Read empty room noise raw data
raw_noise = mne.io.read_raw_fif(noise_fname, preload=True)
raw_noise.info['bads'] = ['MEG 2443']  # 1 bad MEG channel
raw_noise.pick_channels([raw_noise.ch_names[pick] for pick in picks])
raw_noise.info.normalize_proj()

# Create noise epochs and make sure the number of noise epochs corresponds to
# the number of data epochs
events_noise = make_fixed_length_events(raw_noise, event_id)
epochs_noise = mne.Epochs(raw_noise, events_noise, event_id, tmin_plot,
                          tmax_plot, baseline=None, preload=True, proj=True,
                          reject=reject)
epochs_noise.info.normalize_proj()
epochs_noise.apply_proj()
# then make sure the number of epochs...


I am working on the file "0.19/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb".
The first task is:
Making multiple events per annotation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
As mentioned above, you can generate equally-spaced events from an
:class:~mne.Annotations object using the chunk_duration parameter of
:func:~mne.events_from_annotations. For example, suppose we have an
annotation in our :class:~mne.io.Raw object indicating when the subject was
in REM sleep, and we want to perform a resting-state analysis on those spans
of data. We can create an Events array with a series of equally-spaced events
within each "REM" span, and then use those events to generate (potentially
overlapping) epochs that we can analyze further.
Can you write Python code for it?

# create the REM annotations
rem_annot = mne.Annotations(onset=[5, 41],
                            duration=[16, 11],
                            description=['REM'] * 2)
raw.set_annotations(rem_annot)
(rem_events,
 rem_event_dict) = mne.events_from_annotations(raw, chunk_duration=1.5)


I am working on the file "0.19/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb".
The first task is:
More information on working with :class:~mne.Annotations objects, including
how to add annotations to :class:~mne.io.Raw objects interactively, and how
to plot, concatenate, load, save, and export :class:~mne.Annotations
objects can be found in the tutorial tut-annotate-raw.
Converting between Events arrays and Annotations objects
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Once your experimental events are read into MNE-Python (as either an Events
array or an :class:~mne.Annotations object), you can easily convert between
the two formats as needed. You might do this because, e.g., an Events array
is needed for epoching continuous data, or because you want to take advantage
of the "annotation-aware" capability of some functions, which automatically
omit spans of data if they overlap with certain annotations.
To convert an :class:~mne.Annotations object to an Events array, use the
function :func:mne.events_from_annotations on the :class:~mne.io.Raw file
containing the annotations. This function will assign an integer Event ID to
each unique element of raw.annotations.description, and will return the
mapping of descriptions to integer Event IDs along with the derived Event
array. By default, one event will be created at the onset of each annotation;
this can be modified via the chunk_duration parameter of
:func:~mne.events_from_annotations to create equally spaced events within
each annotation span (see chunk-duration, below, or see
fixed-length-events for direct creation of an Events array of
equally-spaced events).
Can you write Python code for it?

events_from_annot, event_dict = mne.events_from_annotations(eeglab_raw)
print(event_dict)
print(events_from_annot[:5])


I am working on the file "0.19/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb".
The first task is:
Now we can check that our events indeed fall in the ranges 5-21 seconds and
41-52 seconds, and are ~1.5 seconds apart (modulo some jitter due to the
sampling frequency). Here are the event times rounded to the nearest
millisecond:
Can you write Python code for it?

print(np.round((rem_events[:, 0] - raw.first_samp) / raw.info['sfreq'], 3))


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


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

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

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


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


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

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

# Setup for reading the raw data
raw = io.read_raw_fif(raw_fname, verbose=False)
events = mne.find_events(raw, stim_channel='STI 014')
inverse_operator = read_inverse_operator(fname_inv)
raw.info['bads'] = ['MEG 2443', 'EEG 053']

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

tmin, tmax = 0, 120  # use the first 120s of data
fmin, fmax = 4, 100  # look at frequencies between 4 and 100Hz
n_fft = 2048  # the FFT size (n_fft). Ideally a power of 2
label = mne.read_label(fname_label)

stc = compute_source_psd(raw, inverse_operator, lambda2=1. / 9., method="dSPM",
                         tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax,
                         pick_ori="normal", n_fft=n_fft, label=label,
                         dB=True)

stc.save('psd_dSPM')


I am working on the file "0.19/_downloads/69a53f341b5a9d09407d309924aa4d14/plot_source_power_spectrum.ipynb".
The first task is:
View PSD of sources in label
Can you write Python code for it?

plt.plot(1e3 * stc.times, stc.data.T)
plt.xlabel('Frequency (Hz)')
plt.ylabel('PSD (dB)')
plt.title('Source Power Spectrum (PSD)')
plt.show()


I am working on the file "0.19/_downloads/6adc37621218f72fa2a5246bc470de2f/plot_source_label_time_frequency.ipynb".
The first task is:
Compute power and phase lock in label of the source space
Compute time-frequency maps of power and phase lock in the source space.
The inverse method is linear based on dSPM inverse operator.
The example also shows the difference in the time-frequency maps
when they are computed with and without subtracting the evoked response
from each epoch. The former results in induced activity only while the
latter also includes evoked (stimulus-locked) activity.
Can you write Python code for it?

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

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne import io
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, source_induced_power

print(__doc__)


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

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

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

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

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

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

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

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

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

plt.close('all')

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

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

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


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

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


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

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

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

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


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

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


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


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

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

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

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

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


I am working on the file "0.19/_downloads/70d3a0e5dfbb415abf141d93f82df981/plot_55_setting_eeg_reference.ipynb".
The first task is:
If a scalp electrode was used as reference but was not saved alongside the
raw data (reference channels often aren't), you may wish to add it back to
the dataset before re-referencing. For example, if your EEG system recorded
with channel Fp1 as the reference but did not include Fp1 in the data
file, using :meth:~mne.io.Raw.set_eeg_reference to set (say) Cz as the
new reference will then subtract out the signal at Cz without restoring
the signal at Fp1. In this situation, you can add back Fp1 as a flat
channel prior to re-referencing using :func:~mne.add_reference_channels.
(Since our example data doesn't use the 10-20 electrode naming system_, the
example below adds EEG 999 as the missing reference, then sets the
reference to EEG 050.) Here's how the data looks in its original state:
Can you write Python code for it?


I am working on the file "0.19/_downloads/70d3a0e5dfbb415abf141d93f82df981/plot_55_setting_eeg_reference.ipynb".
The first task is:
Setting the EEG reference
This tutorial describes how to set or change the EEG reference in MNE-Python.
   :depth: 2
As usual we'll start by importing the modules we need, loading some
example data <sample-dataset>, and cropping it to save memory. Since
this tutorial deals specifically with EEG, we'll also restrict the dataset to
just a few EEG channels so the plots are easier to see:
Can you write Python code for it?

import os
import mne

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)
raw.crop(tmax=60).load_data()
raw.pick(['EEG 0{:02}'.format(n) for n in range(41, 60)])


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


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


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

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

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


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

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


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

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


I am working on the file "0.19/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
For paradigms that are not event-related (e.g., analysis of resting-state
data), you can extract regularly spaced (possibly overlapping) spans of data
by creating events using :func:mne.make_fixed_length_events and then
proceeding with epoching as described in the next section.
Epoching continuous data
^^^^^^^^^^^^^^^^^^^^^^^^
The :class:~mne.io.Raw object and the events array are the bare minimum
needed to create an :class:~mne.Epochs object, which we create with the
:class:mne.Epochs class constructor. Here we'll also specify some data
quality constraints: we'll reject any epoch where peak-to-peak signal
amplitude is beyond reasonable limits for that channel type. This is done
with a rejection dictionary; you may include or omit thresholds for any of
the channel types present in your data. The values given here are reasonable
for this particular dataset, but may need to be adapted for different
hardware or recording conditions. For a more automated approach, consider
using the autoreject package_.
Can you write Python code for it?


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

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


I am working on the file "0.19/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
Loading data
^^^^^^^^^^^^
MNE-Python data structures are based around the FIF file format from
Neuromag, but there are reader functions for a wide variety of other
data formats <data-formats>. MNE-Python also has interfaces to a
variety of publicly available datasets <datasets>,
which MNE-Python can download and manage for you.
We'll start this tutorial by loading one of the example datasets (called
"sample-dataset"), which contains EEG and MEG data from one subject
performing an audiovisual experiment, along with structural MRI scans for
that subject. The :func:mne.datasets.sample.data_path function will
automatically download the dataset if it isn't found in one of the expected
locations, then return the directory path to the dataset (see the
documentation of :func:~mne.datasets.sample.data_path for a list of places
it checks before downloading). Note also that for this tutorial to run
smoothly on our servers, we're using a filtered and downsampled version of
the data (:file:sample_audvis_filt-0-40_raw.fif), but an unfiltered version
(:file:sample_audvis_raw.fif) is also included in the sample dataset and
could be substituted here when running the tutorial locally.
Can you write Python code for it?

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


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

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


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

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

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


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


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

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


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

Note

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

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


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

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

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

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


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

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

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

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


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

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

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


I am working on the file "0.19/_downloads/7b0095430c62d9ef92be2dd3af2614f6/plot_30_annotate_raw.ipynb".
The first task is:
Reading and writing Annotations to/from a file
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:class:~mne.Annotations objects have a :meth:~mne.Annotations.save method
which can write :file:.fif, :file:.csv, and :file:.txt formats (the
format to write is inferred from the file extension in the filename you
provide). There is a corresponding :func:~mne.read_annotations function to
load them from disk:
Can you write Python code for it?

raw.annotations.save('saved-annotations.csv')
annot_from_file = mne.read_annotations('saved-annotations.csv')
print(annot_from_file)


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

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


I am working on the file "0.19/_downloads/7b0095430c62d9ef92be2dd3af2614f6/plot_30_annotate_raw.ipynb".
The first task is:
The colored rings are clickable, and determine which existing label will be
created by the next click-and-drag operation in the main plot window. New
annotation descriptions can be added by typing the new description,
clicking the :guilabel:Add label button; the new description will be added
to the list of descriptions and automatically selected.
During interactive annotation it is also possible to adjust the start and end
times of existing annotations, by clicking-and-dragging on the left or right
edges of the highlighting rectangle corresponding to that annotation.

Warning

Calling :meth:`~mne.io.Raw.set_annotations` **replaces** any annotations
    currently stored in the :class:`~mne.io.Raw` object, so be careful when
    working with annotations that were created interactively (you could lose
    a lot of work if you accidentally overwrite your interactive
    annotations). A good safeguard is to run
    ``interactive_annot = raw.annotations`` after you finish an interactive
    annotation session, so that the annotations are stored in a separate
    variable outside the :class:`~mne.io.Raw` object.

How annotations affect preprocessing and analysis
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
You may have noticed that the description for new labels in the annotation
controls window defaults to BAD_. The reason for this is that annotation
is often used to mark bad temporal spans of data (such as movement artifacts
or environmental interference that cannot be removed in other ways such as
projection <tut-projectors-background> or filtering). Several
MNE-Python operations
are "annotation aware" and will avoid using data that is annotated with a
description that begins with "bad" or "BAD"; such operations typically have a
boolean reject_by_annotation parameter. Examples of such operations are
independent components analysis (:class:mne.preprocessing.ICA), functions
for finding heartbeat and blink...
Can you write Python code for it?

new_annot = mne.Annotations(onset=3.75, duration=0.75, description='AAA')
raw.set_annotations(my_annot + new_annot)
raw.plot(start=2, duration=6)


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


I am working on the file "0.19/_downloads/7b0095430c62d9ef92be2dd3af2614f6/plot_30_annotate_raw.ipynb".
The first task is:
You can also iterate over the annotations within an :class:~mne.Annotations
object:
Can you write Python code for it?

for ann in raw.annotations:
    descr = ann['description']
    start = ann['onset']
    end = ann['onset'] + ann['duration']
    print("'{}' goes from {} to {}".format(descr, start, end))


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

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

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

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


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

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


I am working on the file "0.19/_downloads/7bbeb6a728b7d16c6e61cd487ba9e517/plot_morph_volume_stc.ipynb".
The first task is:
Get a SourceMorph object for VolSourceEstimate
subject_from can typically be inferred from
:class:src <mne.SourceSpaces>,
and subject_to is  set to 'fsaverage' by default. subjects_dir can be
None when set in the environment. In that case SourceMorph can be initialized
taking src as only argument. See :class:mne.SourceMorph for more
details.
The default parameter setting for spacing will cause the reference volumes
to be resliced before computing the transform. A value of '5' would cause
the function to reslice to an isotropic voxel size of 5 mm. The higher this
value the less accurate but faster the computation will be.
A standard usage for volumetric data reads:
Can you write Python code for it?

morph = mne.compute_source_morph(inverse_operator['src'],
                                 subject_from='sample', subject_to='fsaverage',
                                 subjects_dir=subjects_dir)


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

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

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

print(__doc__)


I am working on the file "0.19/_downloads/7bbeb6a728b7d16c6e61cd487ba9e517/plot_morph_volume_stc.ipynb".
The first task is:
Plot results
Can you write Python code for it?

# Load fsaverage anatomical image
t1_fsaverage = nib.load(fname_t1_fsaverage)

# Plot glass brain (change to plot_anat to display an overlaid anatomical T1)
display = plot_glass_brain(t1_fsaverage,
                           title='subject results to fsaverage',
                           draw_cross=False,
                           annotate=True)

# Add functional data as overlay
display.add_overlay(img_fsaverage, alpha=0.75)


I am working on the file "0.19/_downloads/7bbeb6a728b7d16c6e61cd487ba9e517/plot_morph_volume_stc.ipynb".
The first task is:
Setup paths
Can you write Python code for it?

sample_dir_raw = sample.data_path()
sample_dir = os.path.join(sample_dir_raw, 'MEG', 'sample')
subjects_dir = os.path.join(sample_dir_raw, 'subjects')

fname_evoked = os.path.join(sample_dir, 'sample_audvis-ave.fif')
fname_inv = os.path.join(sample_dir, 'sample_audvis-meg-vol-7-meg-inv.fif')

fname_t1_fsaverage = os.path.join(subjects_dir, 'fsaverage', 'mri',
                                  'brain.mgz')


I am working on the file "0.19/_downloads/7c31b7bed6ff2a9686e321d607181951/plot_background_ica.ipynb".
The first task is:
==================================================
Background on Independent Component Analysis (ICA)
==================================================
   :depth: 2
Many M/EEG signals including biological artifacts reflect non-Gaussian
processes. Therefore PCA-based artifact rejection will likely perform worse at
separating the signal from noise sources.
MNE-Python supports identifying artifacts and latent components using temporal ICA.
MNE-Python implements the :class:mne.preprocessing.ICA class that facilitates applying ICA
to MEG and EEG data. Here we discuss some
basics of ICA.
Concepts
ICA finds directions in the feature space corresponding to projections with high non-Gaussianity.

not necessarily orthogonal in the original feature space, but orthogonal in the whitened feature space.
In contrast, PCA finds orthogonal directions in the raw feature
  space that correspond to directions accounting for maximum variance.
or differently, if data only reflect Gaussian processes ICA and PCA are equivalent.

Example: Imagine 3 instruments playing simultaneously and 3 microphones
recording mixed signals. ICA can be used to recover the sources ie. what is played by each instrument.
ICA employs a very simple model: $X = AS$ where $X$ is our observations, $A$ is the mixing matrix and $S$ is the vector of independent (latent) sources.
The challenge is to recover $A$ and $S$ from $X$.
First generate simulated data
Can you write Python code for it?

import numpy as np
import matplotlib.pyplot as plt
from scipy import signal

from sklearn.decomposition import FastICA, PCA

np.random.seed(0)  # set seed for reproducible results
n_samples = 2000
time = np.linspace(0, 8, n_samples)

s1 = np.sin(2 * time)  # Signal 1 : sinusoidal signal
s2 = np.sign(np.sin(3 * time))  # Signal 2 : square signal
s3 = signal.sawtooth(2 * np.pi * time)  # Signal 3: sawtooth signal

S = np.c_[s1, s2, s3]
S += 0.2 * np.random.normal(size=S.shape)  # Add noise

S /= S.std(axis=0)  # Standardize data
# Mix data
A = np.array([[1, 1, 1], [0.5, 2, 1.0], [1.5, 1.0, 2.0]])  # Mixing matrix
X = np.dot(S, A.T)  # Generate observations


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

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

import numpy as np
import matplotlib.pyplot as plt

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

print(__doc__)

data_path = sample.data_path()

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

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

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

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

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

# Initialize EMS transformer
ems = EMS()

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

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

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


I am working on the file "0.19/_downloads/7e2bcdd12e5e1163023780ef6bd1e852/plot_evoked_arrowmap.ipynb".
The first task is:
Plot magnetometer data as an arrowmap along with the topoplot at the time
of the maximum sensor space activity:
Can you write Python code for it?

max_time_idx = np.abs(evoked_mag.data).mean(axis=0).argmax()
plot_arrowmap(evoked_mag.data[:, max_time_idx], evoked_mag.info)

# Since planar gradiometers takes gradients along latitude and longitude,
# they need to be projected to the flatten manifold span by magnetometer
# or radial gradiometers before taking the gradients in the 2D Cartesian
# coordinate system for visualization on the 2D topoplot. You can use the
# ``info_from`` and ``info_to`` parameters to interpolate from
# gradiometer data to magnetometer data.


I am working on the file "0.19/_downloads/7e2bcdd12e5e1163023780ef6bd1e852/plot_evoked_arrowmap.ipynb".
The first task is:
Since Vectorview 102 system perform sparse spatial sampling of the magnetic
field, data from the Vectorview (info_from) can be projected to the high
density CTF 272 system (info_to) for visualization
Plot gradiometer data as an arrowmap along with the topoplot at the time
of the maximum sensor space activity:
Can you write Python code for it?

path = bst_raw.data_path()
raw_fname = path + '/MEG/bst_raw/' \
                   'subj001_somatosensory_20111109_01_AUX-f.ds'
raw_ctf = mne.io.read_raw_ctf(raw_fname)
raw_ctf_info = mne.pick_info(
    raw_ctf.info, mne.pick_types(raw_ctf.info, meg=True, ref_meg=False))
plot_arrowmap(evoked_grad.data[:, max_time_idx], info_from=evoked_grad.info,
              info_to=raw_ctf_info, scale=2e-10)


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

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


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

Warning

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

Can you write Python code for it?

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


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

query = 'trial_number < 10'
plot_query_results(query)


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

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

# License: BSD (3-clause)

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

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

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

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

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


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

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


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

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


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Accepting a shallower roll-off of the filter in the frequency domain makes
our time-domain response potentially much better. We end up with a more
gradual slope through the transition region, but a much cleaner time
domain signal. Here again for the 1 s filter:
Can you write Python code for it?

h = signal.firwin2(n, freq, gain, nyq=nyq)
plot_filter(h, sfreq, freq, gain, 'Windowed 10 Hz transition (1.0 s)',
            flim=flim, compensate=True)


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
And now an example of a minimum-phase filter:
Can you write Python code for it?

h = mne.filter.create_filter(x, sfreq, l_freq=None, h_freq=f_p,
                             phase='minimum', fir_design='firwin',
                             verbose=True)
x_min = np.convolve(h, x)
transition_band = 0.25 * f_p
f_s = f_p + transition_band
filter_dur = 6.6 / transition_band  # sec
n = int(sfreq * filter_dur)
freq = [0., f_p, f_s, sfreq / 2.]
gain = [1., 1., 0., 0.]
plot_filter(h, sfreq, freq, gain, 'Minimum-phase filter', flim=flim)


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Applying IIR filters
Now let's look at how our shallow and steep Butterworth IIR filters
perform on our Morlet signal from before:
Can you write Python code for it?

axes = plt.subplots(1, 2)[1]
yticks = np.arange(4) / -30.
yticklabels = ['Original', 'Noisy', 'Butterworth-2', 'Butterworth-8']
plot_signal(x_orig, offset=yticks[0])
plot_signal(x, offset=yticks[1])
plot_signal(x_shallow, offset=yticks[2])
plot_signal(x_steep, offset=yticks[3])
axes[0].set(xlim=tlim, title='IIR, Lowpass=%d Hz' % f_p, xticks=tticks,
            ylim=[-0.125, 0.025], yticks=yticks, yticklabels=yticklabels,)
for text in axes[0].get_yticklabels():
    text.set(rotation=45, size=8)
axes[1].set(xlim=flim, ylim=(-60, 10), xlabel='Frequency (Hz)',
            ylabel='Magnitude (dB)')
mne.viz.adjust_axes(axes)
mne.viz.tight_layout()
plt.show()


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Background information on filtering
Here we give some background information on filtering in general,
and how it is done in MNE-Python in particular.
Recommended reading for practical applications of digital
filter design can be found in Parks & Burrus (1987) [1] and
Ifeachor & Jervis (2002) [2], and for filtering in an
M/EEG context we recommend reading Widmann et al. (2015) [7]_.
To see how to use the default filters in MNE-Python on actual data, see
the tut-filter-resample tutorial.
Problem statement
Practical issues with filtering electrophysiological data are covered
in Widmann et al. (2012) [6]_, where they conclude with this statement:
Filtering can result in considerable distortions of the time course
(and amplitude) of a signal as demonstrated by VanRullen (2011) [[3]_].
Thus, filtering should not be used lightly. However, if effects of
filtering are cautiously considered and filter artifacts are minimized,
a valid interpretation of the temporal dynamics of filtered
electrophysiological data is possible and signals missed otherwise
can be detected with filtering.

In other words, filtering can increase signal-to-noise ratio (SNR), but if it
is not used carefully, it can distort data. Here we hope to cover some
filtering basics so users can better understand filtering trade-offs and why
MNE-Python has chosen particular defaults.
Filtering basics
Let's get some of the basic math down. In the frequency domain, digital
filters have a transfer function that is given by:
\begin{align}H(z) &= \frac{b_0 + b_1 z^{-1} + b_2 z^{-2} + \ldots + b_M z^{-M}}
                 {1 + a_1 z^{-1} + a_2 z^{-2} + \ldots + a_N z^{-M}} \
         &= \frac{\sum_{k=0}^Mb_kz^{-k}}{\sum_{k=1}^Na_kz^{-k}}\end{align}
In the time domain, the numerator coefficients $b_k$ and denominator
coefficients $a_k$ can be used to obtain our output data
$y(n)$ in terms of our input data $x(n)$ as:
\begin{align}:label: summations
y(n) &= b_0 x(n) + b_1 x(n-1) + \ldots + b_M x(n-M)
        - a_1 y(n-1) - a_2 y(n - 2) - \ldots - a_N y(n -...
Can you write Python code for it?

import numpy as np
from numpy.fft import fft, fftfreq
from scipy import signal
import matplotlib.pyplot as plt

from mne.time_frequency.tfr import morlet
from mne.viz import plot_filter, plot_ideal_filter

import mne

sfreq = 1000.
f_p = 40.
flim = (1., sfreq / 2.)  # limits for plotting


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Both groups seem to acknowledge that the choices of filtering cutoffs, and
perhaps even the application of baseline correction, depend on the
characteristics of the data being investigated, especially when it comes to:

The frequency content of the underlying evoked activity relative
      to the filtering parameters.
The validity of the assumption of no consistent evoked activity
      in the baseline period.

We thus recommend carefully applying baseline correction and/or high-pass
values based on the characteristics of the data to be analyzed.
Filtering defaults
Defaults in MNE-Python
Most often, filtering in MNE-Python is done at the :class:mne.io.Raw level,
and thus :func:mne.io.Raw.filter is used. This function under the hood
(among other things) calls :func:mne.filter.filter_data to actually
filter the data, which by default applies a zero-phase FIR filter designed
using :func:scipy.signal.firwin. In Widmann et al. (2015) [7]_, they
suggest a specific set of parameters to use for high-pass filtering,
including:
"... providing a transition bandwidth of 25% of the lower passband
edge but, where possible, not lower than 2 Hz and otherwise the
distance from the passband edge to the critical frequency.”

In practice, this means that for each high-pass value l_freq or
low-pass value h_freq below, you would get this corresponding
l_trans_bandwidth or h_trans_bandwidth, respectively,
if the sample rate were 100 Hz (i.e., Nyquist frequency of 50 Hz):
+------------------+-------------------+-------------------+
| l_freq or h_freq | l_trans_bandwidth | h_trans_bandwidth |
+==================+===================+===================+
|             0.01 |              0.01 |               2.0 |
+------------------+-------------------+-------------------+
|              0.1 |               0.1 |               2.0 |
+------------------+-------------------+-------------------+
|              1.0 |               1.0 |               2.0 |
+------------------+-------------------+-------------------+
|              2.0 |  ...
Can you write Python code for it?

# Use the same settings as when calling e.g., `raw.filter()`
fir_coefs = mne.filter.create_filter(
    data=None,  # data is only used for sanity checking, not strictly needed
    sfreq=1000.,  # sfreq of your data in Hz
    l_freq=None,
    h_freq=40.,  # assuming a lowpass of 40 Hz
    method='fir',
    fir_window='hamming',
    fir_design='firwin',
    verbose=True)

# See the printed log for the transition bandwidth and filter length.
# Alternatively, get the filter length through:
filter_length = fir_coefs.shape[0]


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Both the MNE-Python 0.13 and MNE-C filters have excellent frequency
attenuation, but it comes at a cost of potential
ringing (long-lasting ripples) in the time domain. Ringing can occur with
steep filters, especially in signals with frequency content around the
transition band. Our Morlet wavelet signal has power in our transition band,
and the time-domain ringing is thus more pronounced for the steep-slope,
long-duration filter than the shorter, shallower-slope filter:
Can you write Python code for it?

axes = plt.subplots(1, 2)[1]

def plot_signal(x, offset):
    """Plot a signal."""
    t = np.arange(len(x)) / sfreq
    axes[0].plot(t, x + offset)
    axes[0].set(xlabel='Time (s)', xlim=t[[0, -1]])
    X = fft(x)
    freqs = fftfreq(len(x), 1. / sfreq)
    mask = freqs >= 0
    X = X[mask]
    freqs = freqs[mask]
    axes[1].plot(freqs, 20 * np.log10(np.maximum(np.abs(X), 1e-16)))
    axes[1].set(xlim=flim)

yscale = 30
yticklabels = ['Original', 'Noisy', 'FIR-firwin (0.16)', 'FIR-firwin2 (0.14)',
               'FIR-steep (0.13)', 'FIR-steep (MNE-C)', 'Minimum-phase']
yticks = -np.arange(len(yticklabels)) / yscale
plot_signal(x_orig, offset=yticks[0])
plot_signal(x, offset=yticks[1])
plot_signal(x_v16, offset=yticks[2])
plot_signal(x_v14, offset=yticks[3])
plot_signal(x_v13, offset=yticks[4])
plot_signal(x_mne_c, offset=yticks[5])
plot_signal(x_min, offset=yticks[6])
axes[0].set(xlim=tlim, title='FIR, Lowpass=%d Hz' % f_p, xticks=tticks,
            ylim=[-len(yticks) / yscale, 1. / yscale],
            yticks=yticks, yticklabels=yticklabels)
for text in axes[0].get_yticklabels():
    text.set(rotation=45, size=8)
axes[1].set(xlim=flim, ylim=(-60, 10), xlabel='Frequency (Hz)',
            ylabel='Magnitude (dB)')
mne.viz.tight_layout()
plt.show()


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
But if we shorten the filter too much (2 cycles of 10 Hz = 0.2 s),
our effective stop frequency gets pushed out past 60 Hz:
Can you write Python code for it?

n = int(round(sfreq * 0.2)) + 1
h = signal.firwin2(n, freq, gain, nyq=nyq)
plot_filter(h, sfreq, freq, gain, 'Windowed 10 Hz transition (0.2 s)',
            flim=flim, compensate=True)


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Filter it with a different design method fir_design="firwin2", and also
compensate for the constant filter delay. This method does not produce
quite as sharp a transition compared to fir_design="firwin", despite
being twice as long:
Can you write Python code for it?

transition_band = 0.25 * f_p
f_s = f_p + transition_band
freq = [0., f_p, f_s, sfreq / 2.]
gain = [1., 1., 0., 0.]
# This would be equivalent:
# filter_dur = 6.6 / transition_band  # sec
# n = int(sfreq * filter_dur)
# h = signal.firwin2(n, freq, gain, nyq=sfreq / 2.)
h = mne.filter.create_filter(x, sfreq, l_freq=None, h_freq=f_p,
                             fir_design='firwin2', verbose=True)
x_v14 = np.convolve(h, x)[len(h) // 2:]

plot_filter(h, sfreq, freq, gain, 'MNE-Python 0.14 default', flim=flim,
            compensate=True)


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
IIR filters
MNE-Python also offers IIR filtering functionality that is based on the
methods from :mod:scipy.signal. Specifically, we use the general-purpose
functions :func:scipy.signal.iirfilter and :func:scipy.signal.iirdesign,
which provide unified interfaces to IIR filter design.
Designing IIR filters
Let's continue with our design of a 40 Hz low-pass filter and look at
some trade-offs of different IIR filters.
Often the default IIR filter is a Butterworth filter_, which is designed
to have a maximally flat pass-band. Let's look at a few filter orders,
i.e., a few different number of coefficients used and therefore steepness
of the filter:

Note

Notice that the group delay (which is related to the phase) of
          the IIR filters below are not constant. In the FIR case, we can
          design so-called linear-phase filters that have a constant group
          delay, and thus compensate for the delay (making the filter
          non-causal) if necessary. This cannot be done with IIR filters, as
          they have a non-linear phase (non-constant group delay). As the
          filter order increases, the phase distortion near and in the
          transition band worsens. However, if non-causal (forward-backward)
          filtering can be used, e.g. with :func:`scipy.signal.filtfilt`,
          these phase issues can theoretically be mitigated.

Can you write Python code for it?

sos = signal.iirfilter(2, f_p / nyq, btype='low', ftype='butter', output='sos')
plot_filter(dict(sos=sos), sfreq, freq, gain, 'Butterworth order=2', flim=flim,
            compensate=True)
x_shallow = signal.sosfiltfilt(sos, x)
del sos


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
If we want a filter that is only 0.1 seconds long, we should probably use
something more like a 25 Hz transition band (0.2 s = 5 cycles @ 25 Hz):
Can you write Python code for it?

trans_bandwidth = 25
f_s = f_p + trans_bandwidth
freq = [0, f_p, f_s, nyq]
h = signal.firwin2(n, freq, gain, nyq=nyq)
plot_filter(h, sfreq, freq, gain, 'Windowed 50 Hz transition (0.2 s)',
            flim=flim, compensate=True)


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
In response, Maess et al. (2016) [11]_ note that these simulations do not
address cases of pre-stimulus activity that is shared across conditions, as
applying baseline correction will effectively copy the topology outside the
baseline period. We can see this if we give our signal x with some
consistent pre-stimulus activity, which makes everything look bad.

Note

An important thing to keep in mind with these plots is that they
          are for a single simulated sensor. In multi-electrode recordings
          the topology (i.e., spatial pattern) of the pre-stimulus activity
          will leak into the post-stimulus period. This will likely create a
          spatially varying distortion of the time-domain signals, as the
          averaged pre-stimulus spatial pattern gets subtracted from the
          sensor time courses.

Putting some activity in the baseline period:
Can you write Python code for it?

n_pre = (t < 0).sum()
sig_pre = 1 - np.cos(2 * np.pi * np.arange(n_pre) / (0.5 * n_pre))
x[:n_pre] += sig_pre
baseline_plot(x)


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Let's also filter it with the MNE-C default, which is a long-duration
steep-slope FIR filter designed using frequency-domain techniques:
Can you write Python code for it?

h = mne.filter.design_mne_c_filter(sfreq, l_freq=None, h_freq=f_p + 2.5)
x_mne_c = np.convolve(h, x)[len(h) // 2:]

transition_band = 5  # Hz (default in MNE-C)
f_s = f_p + transition_band
freq = [0., f_p, f_s, sfreq / 2.]
gain = [1., 1., 0., 0.]
plot_filter(h, sfreq, freq, gain, 'MNE-C default', flim=flim, compensate=True)


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Let's also filter with the MNE-Python 0.13 default, which is a
long-duration, steep cutoff FIR that gets applied twice:
Can you write Python code for it?

transition_band = 0.5  # Hz
f_s = f_p + transition_band
filter_dur = 10.  # sec
freq = [0., f_p, f_s, sfreq / 2.]
gain = [1., 1., 0., 0.]
# This would be equivalent
# n = int(sfreq * filter_dur)
# h = signal.firwin2(n, freq, gain, nyq=sfreq / 2.)
h = mne.filter.create_filter(x, sfreq, l_freq=None, h_freq=f_p,
                             h_trans_bandwidth=transition_band,
                             filter_length='%ss' % filter_dur,
                             fir_design='firwin2', verbose=True)
x_v13 = np.convolve(np.convolve(h, x)[::-1], h)[::-1][len(h) - 1:-len(h) - 1]
# the effective h is one that is applied to the time-reversed version of itself
h_eff = np.convolve(h, h[::-1])
plot_filter(h_eff, sfreq, freq, gain, 'MNE-Python 0.13 default', flim=flim,
            compensate=True)


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Now we have very sharp frequency suppression, but our filter rings for the
entire 10 seconds. So this naïve method is probably not a good way to build
our low-pass filter.
Fortunately, there are multiple established methods to design FIR filters
based on desired response characteristics. These include:
1. The Remez_ algorithm (:func:`scipy.signal.remez`, `MATLAB firpm`_)
2. Windowed FIR design (:func:`scipy.signal.firwin2`,
   :func:`scipy.signal.firwin`, and `MATLAB fir2`_)
3. Least squares designs (:func:`scipy.signal.firls`, `MATLAB firls`_)
4. Frequency-domain design (construct filter in Fourier
   domain and use an :func:`IFFT <numpy.fft.ifft>` to invert it)

Note

Remez and least squares designs have advantages when there are
          "do not care" regions in our frequency response. However, we want
          well controlled responses in all frequency regions.
          Frequency-domain construction is good when an arbitrary response
          is desired, but generally less clean (due to sampling issues) than
          a windowed approach for more straightforward filter applications.
          Since our filters (low-pass, high-pass, band-pass, band-stop)
          are fairly simple and we require precise control of all frequency
          regions, we will primarily use and explore windowed FIR design.

If we relax our frequency-domain filter requirements a little bit, we can
use these functions to construct a lowpass filter that instead has a
transition band, or a region between the pass frequency $f_p$
and stop frequency $f_s$, e.g.:
Can you write Python code for it?

trans_bandwidth = 10  # 10 Hz transition band
f_s = f_p + trans_bandwidth  # = 50 Hz

freq = [0., f_p, f_s, nyq]
gain = [1., 1., 0., 0.]
ax = plt.subplots(1, figsize=third_height)[1]
title = '%s Hz lowpass with a %s Hz transition' % (f_p, trans_bandwidth)
plot_ideal_filter(freq, gain, ax, title=title, flim=flim)


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Since our lowpass is around 40 Hz with a 10 Hz transition, we can actually
use a shorter filter (5 cycles at 10 Hz = 0.5 s) and still get acceptable
stop-band attenuation:
Can you write Python code for it?

n = int(round(sfreq * 0.5)) + 1
h = signal.firwin2(n, freq, gain, nyq=nyq)
plot_filter(h, sfreq, freq, gain, 'Windowed 10 Hz transition (0.5 s)',
            flim=flim, compensate=True)


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
So far, we have only discussed non-causal filtering, which means that each
sample at each time point $t$ is filtered using samples that come
after ($t + \Delta t$) and before ($t - \Delta t$) the current
time point $t$.
In this sense, each sample is influenced by samples that come both before
and after it. This is useful in many cases, especially because it does not
delay the timing of events.
However, sometimes it can be beneficial to use causal filtering,
whereby each sample $t$ is filtered only using time points that came
after it.
Note that the delay is variable (whereas for linear/zero-phase filters it
is constant) but small in the pass-band. Unlike zero-phase filters, which
require time-shifting backward the output of a linear-phase filtering stage
(and thus becoming non-causal), minimum-phase filters do not require any
compensation to achieve small delays in the pass-band. Note that as an
artifact of the minimum phase filter construction step, the filter does
not end up being as steep as the linear/zero-phase version.
We can construct a minimum-phase filter from our existing linear-phase
filter with the minimum_phase function in :mod:scipy.signal, and note
that the falloff is not as steep:
Can you write Python code for it?

h_min = mne.fixes.minimum_phase(h)
plot_filter(h_min, sfreq, freq, gain, 'Minimum-phase', flim=flim)


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Take for example an ideal low-pass filter, which would give a magnitude
response of 1 in the pass-band (up to frequency $f_p$) and a magnitude
response of 0 in the stop-band (down to frequency $f_s$) such that
$f_p=f_s=40$ Hz here (shown to a lower limit of -60 dB for simplicity):
Can you write Python code for it?

nyq = sfreq / 2.  # the Nyquist frequency is half our sample rate
freq = [0, f_p, f_p, nyq]
gain = [1, 1, 0, 0]

third_height = np.array(plt.rcParams['figure.figsize']) * [1, 1. / 3.]
ax = plt.subplots(1, figsize=third_height)[1]
plot_ideal_filter(freq, gain, ax, title='Ideal %s Hz lowpass' % f_p, flim=flim)


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
There are other types of IIR filters that we can use. For a complete list,
check out the documentation for :func:scipy.signal.iirdesign. Let's
try a Chebychev (type I) filter, which trades off ripple in the pass-band
to get better attenuation in the stop-band:
Can you write Python code for it?

iir_params.update(ftype='cheby1',
                  rp=1.,  # dB of acceptable pass-band ripple
                  )
filt = mne.filter.create_filter(x, sfreq, l_freq=None, h_freq=f_p,
                                method='iir', iir_params=iir_params,
                                verbose=True)
plot_filter(filt, sfreq, freq, gain,
            'Chebychev-1 order=8, ripple=1 dB', flim=flim, compensate=True)


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
This filter hypothetically achieves zero ripple in the frequency domain,
perfect attenuation, and perfect steepness. However, due to the discontinuity
in the frequency response, the filter would require infinite ringing in the
time domain (i.e., infinite order) to be realized. Another way to think of
this is that a rectangular window in the frequency domain is actually a sinc_
function in the time domain, which requires an infinite number of samples
(and thus infinite time) to represent. So although this filter has ideal
frequency suppression, it has poor time-domain characteristics.
Let's try to naïvely make a brick-wall filter of length 0.1 s, and look
at the filter itself in the time domain and the frequency domain:
Can you write Python code for it?

n = int(round(0.1 * sfreq))
n -= n % 2 - 1  # make it odd
t = np.arange(-(n // 2), n // 2 + 1) / sfreq  # center our sinc
h = np.sinc(2 * f_p * t) / (4 * np.pi)
plot_filter(h, sfreq, freq, gain, 'Sinc (0.1 s)', flim=flim, compensate=True)


I am working on the file "0.19/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
This is not so good! Making the filter 10 times longer (1 s) gets us a
slightly better stop-band suppression, but still has a lot of ringing in
the time domain. Note the x-axis is an order of magnitude longer here,
and the filter has a correspondingly much longer group delay (again equal
to half the filter length, or 0.5 seconds):
Can you write Python code for it?

n = int(round(1. * sfreq))
n -= n % 2 - 1  # make it odd
t = np.arange(-(n // 2), n // 2 + 1) / sfreq
h = np.sinc(2 * f_p * t) / (4 * np.pi)
plot_filter(h, sfreq, freq, gain, 'Sinc (1.0 s)', flim=flim, compensate=True)


I am working on the file "0.19/_downloads/804ea48504b27f5f04fd03d517675af5/plot_point_spread.ipynb".
The first task is:
Create source-space data with known signals
Put known signals onto surface vertices using the array of signals and
the label masks (stored in labels[i].values).
Can you write Python code for it?

stc_gen = simulate_stc(fwd['src'], labels, signal, times[0], dt,
                       value_fun=lambda x: x)


I am working on the file "0.19/_downloads/804ea48504b27f5f04fd03d517675af5/plot_point_spread.ipynb".
The first task is:
Load the MEG data
Can you write Python code for it?

fwd = mne.read_forward_solution(fname_fwd)
fwd = mne.convert_forward_solution(fwd, force_fixed=True, surf_ori=True,
                                   use_cps=False)
fwd['info']['bads'] = []
inv_op = read_inverse_operator(fname_inv)

raw = mne.io.read_raw_fif(op.join(data_path, 'MEG', 'sample',
                                  'sample_audvis_raw.fif'))
raw.set_eeg_reference(projection=True)
events = mne.find_events(raw)
event_id = {'Auditory/Left': 1, 'Auditory/Right': 2}
epochs = mne.Epochs(raw, events, event_id, baseline=(None, 0), preload=True)
epochs.info['bads'] = []
evoked = epochs.average()

labels = mne.read_labels_from_annot('sample', subjects_dir=subjects_dir)
label_names = [l.name for l in labels]
n_labels = len(labels)


I am working on the file "0.19/_downloads/804ea48504b27f5f04fd03d517675af5/plot_point_spread.ipynb".
The first task is:
Plot original signals
Note that the original signals are highly concentrated (point) sources.
Can you write Python code for it?

kwargs = dict(subjects_dir=subjects_dir, hemi='split', smoothing_steps=4,
              time_unit='s', initial_time=0.05, size=1200,
              views=['lat', 'med'])
clim = dict(kind='value', pos_lims=[1e-9, 1e-8, 1e-7])
brain_gen = stc_gen.plot(clim=clim, **kwargs)


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


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

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

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


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

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

# to save report
report.save('my_report.html', overwrite=True)


I am working on the file "0.19/_downloads/82590448493c884f52ea0c7ddc5b446b/plot_publication_figure.ipynb".
The first task is:
During interactive plotting, we might see figures like this:
Can you write Python code for it?

evoked.plot()

stc.plot(views='lat', hemi='split', size=(800, 400), subject='sample',
         subjects_dir=subjects_dir, initial_time=max_t)


I am working on the file "0.19/_downloads/82590448493c884f52ea0c7ddc5b446b/plot_publication_figure.ipynb".
The first task is:
Now let's create our custom figure. There are lots of ways to do this step.
Here we'll create the figure and the subplot axes in one step, specifying
overall figure size, number and arrangement of subplots, and the ratio of
subplot heights for each row using :mod:GridSpec keywords
<matplotlib.gridspec>. Other approaches (using
:func:~matplotlib.pyplot.subplot2grid, or adding each axes manually) are
shown commented out, for reference.
Can you write Python code for it?

# figsize unit is inches
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(4.5, 3.),
                         gridspec_kw=dict(height_ratios=[3, 4]))

# alternate way #1: using subplot2grid
# fig = plt.figure(figsize=(4.5, 3.))
# axes = [plt.subplot2grid((7, 1), (0, 0), rowspan=3),
#         plt.subplot2grid((7, 1), (3, 0), rowspan=4)]

# alternate way #2: using figure-relative coordinates
# fig = plt.figure(figsize=(4.5, 3.))
# axes = [fig.add_axes([0.125, 0.58, 0.775, 0.3]),  # left, bot., width, height
#         fig.add_axes([0.125, 0.11, 0.775, 0.4])]

# we'll put the evoked plot in the upper axes, and the brain below
evoked_idx = 0
brain_idx = 1

# plot the evoked in the desired subplot, and add a line at peak activation
evoked.plot(axes=axes[evoked_idx])
peak_line = axes[evoked_idx].axvline(max_t, color='#66CCEE', ls='--')
# custom legend
axes[evoked_idx].legend(
    [axes[evoked_idx].lines[0], peak_line], ['MEG data', 'Peak time'],
    frameon=True, columnspacing=0.1, labelspacing=0.1,
    fontsize=8, fancybox=True, handlelength=1.8)
# remove the "N_ave" annotation
axes[evoked_idx].texts = []
# Remove spines and add grid
axes[evoked_idx].grid(True)
axes[evoked_idx].set_axisbelow(True)
for key in ('top', 'right'):
    axes[evoked_idx].spines[key].set(visible=False)
# Tweak the ticks and limits
axes[evoked_idx].set(
    yticks=np.arange(-200, 201, 100), xticks=np.arange(-0.2, 0.51, 0.1))
axes[evoked_idx].set(
    ylim=[-225, 225], xlim=[-0.2, 0.5])

# now add the brain to the lower axes
axes[brain_idx].imshow(cropped_screenshot)
axes[brain_idx].axis('off')
# add a vertical colorbar with the same properties as the 3D one
divider = make_axes_locatable(axes[brain_idx])
cax = divider.append_axes('right', size='5%', pad=0.2)
cbar = mne.viz.plot_brain_colorbar(cax, clim, colormap, label='Activation (F)')

# tweak margins and spacing
fig.subplots_adjust(
    left=0.15, right=0.9, bottom=0.01, top=0.9, wspace=0.1, hspace=0.5)

# add subplot labels
for ax, label in zip(axes, 'AB'):
    ax.text(0.03,...


I am working on the file "0.19/_downloads/82590448493c884f52ea0c7ddc5b446b/plot_publication_figure.ipynb".
The first task is:
Now let's crop out the white margins and the white gap between hemispheres.
The screenshot has dimensions (h, w, 3), with the last axis being R, G, B
values for each pixel, encoded as integers between 0 and 255. (255,
255, 255) encodes a white pixel, so we'll detect any pixels that differ
from that:
Can you write Python code for it?

nonwhite_pix = (screenshot != 255).any(-1)
nonwhite_row = nonwhite_pix.any(1)
nonwhite_col = nonwhite_pix.any(0)
cropped_screenshot = screenshot[nonwhite_row][:, nonwhite_col]

# before/after results
fig = plt.figure(figsize=(4, 4))
axes = ImageGrid(fig, 111, nrows_ncols=(2, 1), axes_pad=0.5)
for ax, image, title in zip(axes, [screenshot, cropped_screenshot],
                            ['Before', 'After']):
    ax.imshow(image)
    ax.set_title('{} cropping'.format(title))


I am working on the file "0.19/_downloads/82590448493c884f52ea0c7ddc5b446b/plot_publication_figure.ipynb".
The first task is:
Suppose we want a figure with an evoked plot on top, and the brain activation
below, with the brain subplot slightly bigger than the evoked plot. Let's
start by loading some example data <sample-dataset>.
Can you write Python code for it?

data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
fname_stc = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg-eeg-lh.stc')
fname_evoked = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')

evoked = mne.read_evokeds(fname_evoked, 'Left Auditory')
evoked.pick_types(meg='grad').apply_baseline((None, 0.))
max_t = evoked.get_peak()[1]

stc = mne.read_source_estimate(fname_stc)


I am working on the file "0.19/_downloads/82590448493c884f52ea0c7ddc5b446b/plot_publication_figure.ipynb".
The first task is:
To make a publication-ready figure, first we'll re-plot the brain on a white
background, take a screenshot of it, and then crop out the white margins.
While we're at it, let's change the colormap, set custom colormap limits, and
remove the default colorbar (so we can add a smaller, vertical one later):
Can you write Python code for it?

colormap = 'viridis'
clim = dict(kind='value', lims=[4, 8, 12])

# Plot the STC, get the brain image, crop it
brain = stc.plot(views='lat', hemi='split', size=(800, 400), subject='sample',
                 subjects_dir=subjects_dir, initial_time=max_t,
                 background='w', colorbar=False, clim=clim, colormap=colormap)
screenshot = brain.screenshot()
brain.close()


I am working on the file "0.19/_downloads/85b80d223414f32365a9175978a38cb4/plot_limo_data.ipynb".
The first task is:
As it can be seen above, events are coded as Face/A and Face/B.
Information about the phase-coherence of the presented faces is stored in
limo_epochs.metadata, which also contains information about the presented
faces for convenience.
Check epochs metadata
Can you write Python code for it?