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

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


I am working on the file "0.19/_downloads/306dcf0b43a155a02804528d597e4e81/plot_roi_erpimage_by_rt.ipynb".
The first task is:
Create Epochs
Can you write Python code for it?

# define target events:
# 1. find response times: distance between "square" and "rt" events
# 2. extract A. "square" events B. followed by a button press within 700 msec
tmax = .7
sfreq = raw.info["sfreq"]
reference_id, target_id = 2, 1
new_events, rts = define_target_events(events, reference_id, target_id, sfreq,
                                       tmin=0., tmax=tmax, new_id=2)

epochs = mne.Epochs(raw, events=new_events, tmax=tmax + .1,
                    event_id={"square": 2})


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

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

event_id = {"rt": 1, "square": 2}  # must be specified for str events
raw = mne.io.read_raw_eeglab(fname)

mapping = {
    'EEG 000': 'Fpz', 'EEG 001': 'EOG1', 'EEG 002': 'F3', 'EEG 003': 'Fz',
    'EEG 004': 'F4', 'EEG 005': 'EOG2', 'EEG 006': 'FC5', 'EEG 007': 'FC1',
    'EEG 008': 'FC2', 'EEG 009': 'FC6', 'EEG 010': 'T7', 'EEG 011': 'C3',
    'EEG 012': 'C4', 'EEG 013': 'Cz', 'EEG 014': 'T8', 'EEG 015': 'CP5',
    'EEG 016': 'CP1', 'EEG 017': 'CP2', 'EEG 018': 'CP6', 'EEG 019': 'P7',
    'EEG 020': 'P3', 'EEG 021': 'Pz', 'EEG 022': 'P4', 'EEG 023': 'P8',
    'EEG 024': 'PO7', 'EEG 025': 'PO3', 'EEG 026': 'POz', 'EEG 027': 'PO4',
    'EEG 028': 'PO8', 'EEG 029': 'O1', 'EEG 030': 'Oz', 'EEG 031': 'O2'
}
raw.rename_channels(mapping)
raw.set_channel_types({"EOG1": 'eog', "EOG2": 'eog'})
raw.set_montage('standard_1020')

events = mne.events_from_annotations(raw, event_id)[0]


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

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


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

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

src.export_volume(nii_fname, mri_resolution=True)

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


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

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

import mne
from mne import setup_source_space, setup_volume_source_space
from mne.datasets import sample

print(__doc__)

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


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

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


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

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

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

# Combine the source spaces
src = surf + lh_cereb


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


I am working on the file "0.19/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
Here again we can visualize the spatial pattern of the associated field at
various times relative to the peak of the EOG response:
Can you write Python code for it?


I am working on the file "0.19/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
Here we see narrow frequency peaks at 60, 120, 180, and 240 Hz — the power
line frequency of the USA (where the sample data was recorded) and its 2nd,
3rd, and 4th harmonics. Other peaks (around 25 to 30 Hz, and the second
harmonic of those) are probably related to the heartbeat, which is more
easily seen in the time domain using a dedicated heartbeat detection function
as described in the next section.
Heartbeat artifacts (ECG)
~~~~~~~~~~~~~~~~~~~~~~~~~
MNE-Python includes a dedicated function
:func:~mne.preprocessing.find_ecg_events in the :mod:mne.preprocessing
submodule, for detecting heartbeat artifacts from either dedicated ECG
channels or from magnetometers (if no ECG channel is present). Additionally,
the function :func:~mne.preprocessing.create_ecg_epochs will call
:func:~mne.preprocessing.find_ecg_events under the hood, and use the
resulting events array to extract epochs centered around the detected
heartbeat artifacts. Here we create those epochs, then show an image plot of
the detected ECG artifacts along with the average ERF across artifacts. We'll
show all three channel types, even though EEG channels are less strongly
affected by heartbeat artifacts:
Can you write Python code for it?

ecg_epochs = mne.preprocessing.create_ecg_epochs(raw)
ecg_epochs.plot_image(combine='mean')


I am working on the file "0.19/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
Low-frequency drifts
~~~~~~~~~~~~~~~~~~~~
Low-frequency drifts are most readily detected by visual inspection using the
basic :meth:~mne.io.Raw.plot method, though it is helpful to plot a
relatively long time span and to disable channel-wise DC shift correction.
Here we plot 60 seconds and show all the magnetometer channels:
Can you write Python code for it?

mag_channels = mne.pick_types(raw.info, meg='mag')
raw.plot(duration=60, order=mag_channels, n_channels=len(mag_channels),
         remove_dc=False)


I am working on the file "0.19/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
Low-frequency drifts are readily removed by high-pass filtering at a fairly
low cutoff frequency (the wavelength of the drifts seen above is probably
around 20 seconds, so in this case a cutoff of 0.1 Hz would probably suppress
most of the drift).
Power line noise
~~~~~~~~~~~~~~~~
Power line artifacts are easiest to see on plots of the spectrum, so we'll
use :meth:~mne.io.Raw.plot_psd to illustrate.
Can you write Python code for it?

fig = raw.plot_psd(tmax=np.inf, fmax=250, average=True)
# add some arrows at 60 Hz and its harmonics:
for ax in fig.axes[:2]:
    freqs = ax.lines[-1].get_xdata()
    psds = ax.lines[-1].get_ydata()
    for freq in (60, 120, 180, 240):
        idx = np.searchsorted(freqs, freq)
        ax.arrow(x=freqs[idx], y=psds[idx] + 18, dx=0, dy=-12, color='red',
                 width=0.1, head_width=3, length_includes_head=True)


I am working on the file "0.19/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
Overview of artifact detection
This tutorial covers the basics of artifact detection, and introduces the
artifact detection tools available in MNE-Python.
   :depth: 2
We begin as always by importing the necessary Python modules and loading some
example data <sample-dataset>:
Can you write Python code for it?

import os
import numpy as np
import mne

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file)
raw.crop(0, 60).load_data()  # just use a fraction of data for speed here


I am working on the file "0.19/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
The horizontal streaks in the magnetometer image plot reflect the fact that
the heartbeat artifacts are superimposed on low-frequency drifts like the one
we saw in an earlier section. You can also get a quick look at the
ECG-related field pattern across sensors by averaging the ECG epochs together
via the :meth:~mne.Epochs.average method, and then using the
:meth:mne.Evoked.plot_topomap method:
Can you write Python code for it?


I am working on the file "0.19/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
What are artifacts?
^^^^^^^^^^^^^^^^^^^
Artifacts are parts of the recorded signal that arise from sources other than
the source of interest (i.e., neuronal activity in the brain). As such,
artifacts are a form of interference or noise relative to the signal of
interest. There are many possible causes of such interference, for example:

Environmental artifacts

Persistent oscillations centered around the AC power line frequency_
  (typically 50 or 60 Hz)
Brief signal jumps due to building vibration (such as a door slamming)
Electromagnetic field noise from nearby elevators, cell phones, the
  geomagnetic field, etc.

Instrumentation artifacts

Electromagnetic interference from stimulus presentation (such as EEG
  sensors picking up the field generated by unshielded headphones)
Continuous oscillations at specific frequencies used by head position
  indicator (HPI) coils
Random high-amplitude fluctuations (or alternatively, constant zero
  signal) in a single channel due to sensor malfunction (e.g., in surface
  electrodes, poor scalp contact)

Biological artifacts

Periodic QRS_-like signal patterns (especially in magnetometer
  channels) due to electrical activity of the heart
Short step-like deflections (especially in frontal EEG channels) due to
  eye movements
Large transient deflections (especially in frontal EEG channels) due to
  blinking
Brief bursts of high frequency fluctuations across several channels due
  to the muscular activity during swallowing

There are also some cases where signals from within the brain can be
considered artifactual. For example, if a researcher is primarily interested
in the sensory response to a stimulus, but the experimental paradigm involves
a behavioral response (such as button press), the neural activity associated
with the planning and executing the button press could be considered an
artifact relative to signal of interest (i.e., the evoked sensory response).

Note

Artifacts of the same genesis may appear different in...
Can you write Python code for it?

ssp_projectors = raw.info['projs']
raw.del_proj()


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

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

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


I am working on the file "0.19/_downloads/36ac16a286b47b66f1b51a959c65b5b9/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
Create TFR representations for all conditions
Can you write Python code for it?

epochs_power = list()
for condition in [epochs[k] for k in event_id]:
    this_tfr = tfr_morlet(condition, freqs, n_cycles=n_cycles,
                          decim=decim, average=False, zero_mean=zero_mean,
                          return_itc=False)
    this_tfr.apply_baseline(mode='ratio', baseline=(None, 0))
    this_power = this_tfr.data[:, 0, :, :]  # we only have one channel.
    epochs_power.append(this_power)


I am working on the file "0.19/_downloads/36ac16a286b47b66f1b51a959c65b5b9/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
Create new stats image with only significant clusters:
Can you write Python code for it?

good_clusters = np.where(cluster_p_values < .05)[0]
T_obs_plot = np.ma.masked_array(T_obs,
                                np.invert(clusters[np.squeeze(good_clusters)]))

plt.figure()
for f_image, cmap in zip([T_obs, T_obs_plot], [plt.cm.gray, 'RdBu_r']):
    plt.imshow(f_image, cmap=cmap, extent=[times[0], times[-1],
               freqs[0], freqs[-1]], aspect='auto',
               origin='lower')
plt.xlabel('Time (ms)')
plt.ylabel('Frequency (Hz)')
plt.title("Time-locked response for 'modality by location' (%s)\n"
          " cluster-level corrected (p <= 0.05)" % ch_name)
plt.show()


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

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

import numpy as np
import matplotlib.pyplot as plt

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

print(__doc__)


I am working on the file "0.19/_downloads/36ac16a286b47b66f1b51a959c65b5b9/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
Now using FDR:
Can you write Python code for it?

mask, _ = fdr_correction(pvals[2])
T_obs_plot2 = np.ma.masked_array(T_obs, np.invert(mask))

plt.figure()
for f_image, cmap in zip([T_obs, T_obs_plot2], [plt.cm.gray, 'RdBu_r']):
    plt.imshow(f_image, cmap=cmap, extent=[times[0], times[-1],
               freqs[0], freqs[-1]], aspect='auto',
               origin='lower')

plt.xlabel('Time (ms)')
plt.ylabel('Frequency (Hz)')
plt.title("Time-locked response for 'modality by location' (%s)\n"
          " FDR corrected (p <= 0.05)" % ch_name)
plt.show()


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

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

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


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

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

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

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

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

ch_name = 'MEG 1332'

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


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

epochs.equalize_event_counts(event_id)

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


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

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

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

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


I am working on the file "0.19/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:

Warning

Be careful when concatenating :class:`~mne.io.Raw` objects from different
    recordings, especially when saving: :meth:`~mne.io.Raw.append` only
    preserves the ``info`` attribute of the initial :class:`~mne.io.Raw`
    object (the one outside the :meth:`~mne.io.Raw.append` method call).

Extracting data from Raw objects
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
So far we've been looking at ways to modify a :class:~mne.io.Raw object.
This section shows how to extract the data from a :class:~mne.io.Raw object
into a :class:NumPy array <numpy.ndarray>, for analysis or plotting using
functions outside of MNE-Python. To select portions of the data,
:class:~mne.io.Raw objects can be indexed using square brackets. However,
indexing :class:~mne.io.Raw works differently than indexing a :class:NumPy
array <numpy.ndarray> in two ways:

Along with the requested sample value(s) MNE-Python also returns an array
   of times (in seconds) corresponding to the requested samples. The data
   array and the times array are returned together as elements of a tuple.

The data array will always be 2-dimensional even if you request only a
   single time sample or a single channel.

Extracting data by index
~~~~~~~~~~~~~~~~~~~~~~~~
To illustrate the above two points, let's select a couple seconds of data
from the first channel:
Can you write Python code for it?

sampling_freq = raw.info['sfreq']
start_stop_seconds = np.array([11, 13])
start_sample, stop_sample = (start_stop_seconds * sampling_freq).astype(int)
channel_index = 0
raw_selection = raw[channel_index, start_sample:stop_sample]
print(raw_selection)


I am working on the file "0.19/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:

Note

Most of the fields of ``raw.info`` reflect metadata recorded at
    acquisition time, and should not be changed by the user. There are a few
    exceptions (such as ``raw.info['bads']`` and ``raw.info['projs']``), but
    in most cases there are dedicated MNE-Python functions or methods to
    update the :class:`~mne.Info` object safely (such as
    :meth:`~mne.io.Raw.add_proj` to update ``raw.info['projs']``).

Time, sample number, and sample index
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. sidebar:: Sample numbering in VectorView data
For data from VectorView systems, it is important to distinguish *sample
number* from *sample index*. See :term:`first_samp` for more information.

One method of :class:~mne.io.Raw objects that is frequently useful is
:meth:~mne.io.Raw.time_as_index, which converts a time (in seconds) into
the integer index of the sample occurring closest to that time. The method
can also take a list or array of times, and will return an array of indices.
It is important to remember that there may not be a data sample at exactly
the time requested, so the number of samples between time = 1 second and
time = 2 seconds may be different than the number of samples between
time = 2 and time = 3:
Can you write Python code for it?

print(raw.time_as_index(20))
print(raw.time_as_index([20, 30, 40]), '\n')

print(np.diff(raw.time_as_index([1, 2, 3])))


I am working on the file "0.19/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
As you can see above, :func:~mne.io.read_raw_fif automatically displays
some information about the file it's loading. For example, here it tells us
that there are three "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, and are discussed in a 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:
Can you write Python code for it?


I am working on the file "0.19/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Extracting channels by name
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The :class:~mne.io.Raw object can also be indexed with the names of
channels instead of their index numbers. You can pass a single string to get
just one channel, or a list of strings to select multiple channels. As with
integer indexing, this will return a tuple of (data_array, times_array)
that can be easily plotted. Since we're plotting 2 channels this time, we'll
add a vertical offset to one channel so it's not plotted right on top
of the other one:
Can you write Python code for it?

channel_names = ['MEG_0712', 'MEG_1022']
two_meg_chans = raw[channel_names, start_sample:stop_sample]
y_offset = np.array([5e-11, 0])  # just enough to separate the channel traces
x = two_meg_chans[1]
y = two_meg_chans[0].T + y_offset
lines = plt.plot(x, y)
plt.legend(lines, channel_names)


I am working on the file "0.19/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Extracting channels by type
~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are several ways to select all channels of a given type from a
:class:~mne.io.Raw object. The safest method is to use
:func:mne.pick_types to obtain the integer indices of the channels you
want, then use those indices with the square-bracket indexing method shown
above. The :func:~mne.pick_types function uses the :class:~mne.Info
attribute of the :class:~mne.io.Raw object to determine channel types, and
takes boolean or string parameters to indicate which type(s) to retain. The
meg parameter defaults to True, and all others default to False,
so to get just the EEG channels, we pass eeg=True and meg=False:
Can you write Python code for it?

eeg_channel_indices = mne.pick_types(raw.info, meg=False, eeg=True)
eeg_data, times = raw[eeg_channel_indices]
print(eeg_data.shape)


I am working on the file "0.19/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
If for some reason the channel types in your :class:~mne.io.Raw object are
inaccurate, you can change the type of any channel with the
:meth:~mne.io.Raw.set_channel_types method. The method takes a
:class:dictionary <dict> mapping channel names to types; allowed types are
ecg, eeg, emg, eog, exci, ias, misc, resp, seeg, stim, syst, ecog, hbo,
hbr. A common use case for changing channel type is when using frontal EEG
electrodes as makeshift EOG channels:
Can you write Python code for it?

raw.set_channel_types({'EEG_001': 'eog'})
print(raw.copy().pick_types(meg=False, eog=True).ch_names)


I am working on the file "0.19/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
If you want the array of times, :meth:~mne.io.Raw.get_data has an optional
return_times parameter:
Can you write Python code for it?

data, times = raw.get_data(return_times=True)
print(data.shape)
print(times.shape)


I am working on the file "0.19/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
If you want the channels in a specific order (e.g., for plotting),
:meth:~mne.io.Raw.reorder_channels works just like
:meth:~mne.io.Raw.pick_channels but also reorders the channels; for
example, here we pick the EOG and frontal EEG channels, putting the EOG
first and the EEG in reverse order:
Can you write Python code for it?

channel_names = ['EOG 061', 'EEG 003', 'EEG 002', 'EEG 001']
eog_and_frontal_eeg = raw.copy().reorder_channels(channel_names)
print(eog_and_frontal_eeg.ch_names)


I am working on the file "0.19/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
It is also possible to export the data to a :class:Pandas DataFrame
<pandas.DataFrame> object, and use the saving methods that :mod:Pandas
<pandas> affords. The :class:~mne.io.Raw object's
:meth:~mne.io.Raw.to_data_frame method is similar to
:meth:~mne.io.Raw.get_data in that it has a picks parameter for
restricting which channels are exported, and start and stop
parameters for restricting the time domain. Note that, by default, times will
be converted to milliseconds, rounded to the nearest millisecond, and used as
the DataFrame index; see the scaling_time parameter in the documentation
of :meth:~mne.io.Raw.to_data_frame for more details.
Can you write Python code for it?

sampling_freq = raw.info['sfreq']
start_end_secs = np.array([10, 13])
start_sample, stop_sample = (start_end_secs * sampling_freq).astype(int)
df = raw.to_data_frame(picks=['eeg'], start=start_sample, stop=stop_sample)
# then save using df.to_csv(...), df.to_hdf(...), etc
print(df.head())


I am working on the file "0.19/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Modifying Raw objects
^^^^^^^^^^^^^^^^^^^^^^^^^
.. sidebar:: len(raw)
Although the :class:`~mne.io.Raw` object underlyingly stores data samples
in a :class:`NumPy array <numpy.ndarray>` of shape (n_channels,
n_timepoints), the :class:`~mne.io.Raw` object behaves differently from
:class:`NumPy arrays <numpy.ndarray>` with respect to the :func:`len`
function. ``len(raw)`` will return the number of timepoints (length along
data axis 1), not the number of channels (length along data axis 0).
Hence in this section you'll see ``len(raw.ch_names)`` to get the number
of channels.

:class:~mne.io.Raw objects have a number of methods that modify the
:class:~mne.io.Raw instance in-place and return a reference to the modified
instance. This can be useful for method chaining_
(e.g., raw.crop(...).filter(...).pick_channels(...).plot())
but it also poses a problem during interactive analysis: if you modify your
:class:~mne.io.Raw object for an exploratory plot or analysis (say, by
dropping some channels), you will then need to re-load the data (and repeat
any earlier processing steps) to undo the channel-dropping and try something
else. For that reason, the examples in this section frequently use the
:meth:~mne.io.Raw.copy method before the other methods being demonstrated,
so that the original :class:~mne.io.Raw object is still available in the
variable raw for use in later examples.
Selecting, dropping, and reordering channels
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Altering the channels of a :class:~mne.io.Raw object can be done in several
ways. As a first example, we'll use the :meth:~mne.io.Raw.pick_types method
to restrict the :class:~mne.io.Raw object to just the EEG and EOG channels:
Can you write Python code for it?

eeg_and_eog = raw.copy().pick_types(meg=False, eeg=True, eog=True)
print(len(raw.ch_names), '→', len(eeg_and_eog.ch_names))


I am working on the file "0.19/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Remember that sample times don't always align exactly with requested tmin
or tmax values (due to sampling), which is why the max values of the
cropped files don't exactly match the requested tmax (see
time-as-index for further details).
If you need to select discontinuous spans of a :class:~mne.io.Raw object —
or combine two or more separate :class:~mne.io.Raw objects — you can use
the :meth:~mne.io.Raw.append method:
Can you write Python code for it?

raw_selection1 = raw.copy().crop(tmin=30, tmax=30.1)     # 0.1 seconds
raw_selection2 = raw.copy().crop(tmin=40, tmax=41.1)     # 1.1 seconds
raw_selection3 = raw.copy().crop(tmin=50, tmax=51.3)     # 1.3 seconds
raw_selection1.append([raw_selection2, raw_selection3])  # 2.5 seconds total
print(raw_selection1.times.min(), raw_selection1.times.max())


I am working on the file "0.19/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Similar to the :meth:~mne.io.Raw.pick_types method, there is also the
:meth:~mne.io.Raw.pick_channels method to pick channels by name, and a
corresponding :meth:~mne.io.Raw.drop_channels method to remove channels by
name:
Can you write Python code for it?

raw_temp = raw.copy()
print('Number of channels in raw_temp:')
print(len(raw_temp.ch_names), end=' → drop two → ')
raw_temp.drop_channels(['EEG 037', 'EEG 059'])
print(len(raw_temp.ch_names), end=' → pick three → ')
raw_temp.pick_channels(['MEG 1811', 'EEG 017', 'EOG 061'])
print(len(raw_temp.ch_names))


I am working on the file "0.19/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Some of the parameters of :func:mne.pick_types accept string arguments as
well as booleans. For example, the meg parameter can take values
'mag', 'grad', 'planar1', or 'planar2' to select only
magnetometers, all gradiometers, or a specific type of gradiometer. See the
docstring of :meth:mne.pick_types for full details.
The Raw.get_data() method
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you only want the data (not the corresponding array of times),
:class:~mne.io.Raw objects have a :meth:~mne.io.Raw.get_data method. Used
with no parameters specified, it will extract all data from all channels, in
a (n_channels, n_timepoints) :class:NumPy array <numpy.ndarray>:
Can you write Python code for it?


data = raw.get_data()
np.save(file='my_data.npy', arr=data)


I am working on the file "0.19/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
This next example replaces spaces in the channel names with underscores,
using a Python dict comprehension_:
Can you write Python code for it?

print(raw.ch_names[-3:])
channel_renaming_dict = {name: name.replace(' ', '_') for name in raw.ch_names}
raw.rename_channels(channel_renaming_dict)
print(raw.ch_names[-3:])


I am working on the file "0.19/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
You can see that it contains 2 arrays. This combination of data and times
makes it easy to plot selections of raw data (although note that we're
transposing the data array so that each channel is a column instead of a row,
to match what matplotlib expects when plotting 2-dimensional y against
1-dimensional x):
Can you write Python code for it?

x = raw_selection[1]
y = raw_selection[0].T
plt.plot(x, y)


I am working on the file "0.19/_downloads/382a5de26ca055fa17a698d47e9b2d5f/plot_epoching_and_averaging.ipynb".
The first task is:

Note

It is also possible to add metadata to Epochs objects, allowing for
  more complex selections on subsets of Epochs. See
  `tut-epochs-metadata` for more information.

Finally, let's plot the evoked responses.
Can you write Python code for it?


I am working on the file "0.19/_downloads/382a5de26ca055fa17a698d47e9b2d5f/plot_epoching_and_averaging.ipynb".
The first task is:
In this tutorial we are only interested in triggers 1, 2, 3 and 4. These
triggers correspond to auditory and visual stimuli. The event_id here
can be an int, a list of ints or a dict. With dicts it is possible to assign
these ids to distinct categories. When using ints or lists this information
is lost. First we shall define some parameters to feed to the
:class:mne.Epochs constructor. The values tmin and tmax refer to
offsets in relation to the events. Here we make epochs that collect the data
from 200 ms before to 500 ms after the event.
Can you write Python code for it?

tmin, tmax = -0.2, 0.5
event_id = {'Auditory/Left': 1, 'Auditory/Right': 2,
            'Visual/Left': 3, 'Visual/Right': 4}


I am working on the file "0.19/_downloads/382a5de26ca055fa17a698d47e9b2d5f/plot_epoching_and_averaging.ipynb".
The first task is:
Notice channel STI 014 at the bottom. It is the trigger channel that
was used for combining all the events to a single channel. We can see that it
has several pulses of different amplitude throughout the recording. These
pulses correspond to different stimuli presented to the subject during the
acquisition. The pulses have values of 1, 2, 3, 4, 5 and 32. These are the
events we are going to align the epochs to. To create an event list from raw
data, we simply call a function dedicated just for that. Since the event list
is simply a numpy array, you can also manually create one. If you create one
from an outside source (like a separate file of events), pay special
attention in aligning the events correctly with the raw data.
Can you write Python code for it?

events = mne.find_events(raw)
print('Found %s events, first five:' % len(events))
print(events[:5])

# Plot the events to get an idea of the paradigm
# Specify colors and an event_id dictionary for the legend.
event_id = {'Auditory/Left': 1, 'Auditory/Right': 2,
            'Visual/Left': 3, 'Visual/Right': 4,
            'smiley': 5, 'button': 32}
color = {1: 'green', 2: 'yellow', 3: 'red', 4: 'c', 5: 'black', 32: 'blue'}

mne.viz.plot_events(events, raw.info['sfreq'], raw.first_samp, color=color,
                    event_id=event_id)


I am working on the file "0.19/_downloads/382a5de26ca055fa17a698d47e9b2d5f/plot_epoching_and_averaging.ipynb".
The first task is:
Notice we have used forward slashes ('/') to separate the factors of the
conditions of the experiment. We can use these 'tags' to select for example
all left trials (both visual left and auditory right) ...
Can you write Python code for it?

epochs_left = epochs['Left']

# ... or to select a very specific subset. This is the same as above:
evoked_left_again = epochs['Left/Auditory'].average(picks=picks)


I am working on the file "0.19/_downloads/382a5de26ca055fa17a698d47e9b2d5f/plot_epoching_and_averaging.ipynb".
The first task is:
To get the evoked response you can simply do epochs.average(). It
includes only the data channels by default. For the sake of example, we use
picks to include the EOG channels as well. Notice that we cannot use the
same picks as before as the indices are different. 'Why are they different?'
you might ask. They're different because picks is simply a list of
channel indices and as the epochs were constructed, also a new info structure
is created where the channel indices run from 0 to epochs.info['nchan'].
See tut-info-class for more information.
Can you write Python code for it?

picks = mne.pick_types(epochs.info, meg=True, eog=True)
evoked_left = epochs['Auditory/Left'].average(picks=picks)
evoked_right = epochs['Auditory/Right'].average(picks=picks)


I am working on the file "0.19/_downloads/38f243960dd98f9910f9b981f0b54dd0/plot_fdr_stats_evoked.ipynb".
The first task is:
Compute statistic
Can you write Python code for it?

T, pval = stats.ttest_1samp(X, 0)
alpha = 0.05

n_samples, n_tests = X.shape
threshold_uncorrected = stats.t.ppf(1.0 - alpha, n_samples - 1)

reject_bonferroni, pval_bonferroni = bonferroni_correction(pval, alpha=alpha)
threshold_bonferroni = stats.t.ppf(1.0 - alpha / n_tests, n_samples - 1)

reject_fdr, pval_fdr = fdr_correction(pval, alpha=alpha, method='indep')
threshold_fdr = np.min(np.abs(T)[reject_fdr])


I am working on the file "0.19/_downloads/38f243960dd98f9910f9b981f0b54dd0/plot_fdr_stats_evoked.ipynb".
The first task is:
FDR correction on T-test on sensor data
One tests if the evoked response significantly deviates from 0.
Multiple comparison problem is addressed with
False Discovery Rate (FDR) correction.
Can you write Python code for it?

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

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

import mne
from mne import io
from mne.datasets import sample
from mne.stats import bonferroni_correction, fdr_correction

print(__doc__)


I am working on the file "0.19/_downloads/38f243960dd98f9910f9b981f0b54dd0/plot_fdr_stats_evoked.ipynb".
The first task is:
Plot
Can you write Python code for it?

times = 1e3 * epochs.times

plt.close('all')
plt.plot(times, T, 'k', label='T-stat')
xmin, xmax = plt.xlim()
plt.hlines(threshold_uncorrected, xmin, xmax, linestyle='--', colors='k',
           label='p=0.05 (uncorrected)', linewidth=2)
plt.hlines(threshold_bonferroni, xmin, xmax, linestyle='--', colors='r',
           label='p=0.05 (Bonferroni)', linewidth=2)
plt.hlines(threshold_fdr, xmin, xmax, linestyle='--', colors='b',
           label='p=0.05 (FDR)', linewidth=2)
plt.legend()
plt.xlabel("Time (ms)")
plt.ylabel("T-stat")
plt.show()


I am working on the file "0.19/_downloads/38f243960dd98f9910f9b981f0b54dd0/plot_fdr_stats_evoked.ipynb".
The first task is:
Read epochs for the channel of interest
Can you write Python code for it?

picks = mne.pick_types(raw.info, meg=False, eog=True, include=include,
                       exclude='bads')
event_id = 1
reject = dict(grad=4000e-13, eog=150e-6)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject)
X = epochs.get_data()  # as 3D matrix
X = X[:, 0, :]  # take only one channel to get a 2D array


I am working on the file "0.19/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:

Note

The ``@`` symbol indicates matrix multiplication on NumPy arrays, and was
    introduced in Python 3.5 / NumPy 1.10. The notation ``plot(*point)`` uses
    Python `argument expansion`_ to "unpack" the elements of ``point`` into
    separate positional arguments to the function. In other words,
    ``plot(*point)`` expands to ``plot(3, 2, 5)``.

Notice that we used matrix multiplication to compute the projection of our
point $(3, 2, 5)$onto the $x, y$ plane:
\begin{align}\left[
      \begin{matrix} 1 & 0 & 0 \ 0 & 1 & 0 \ 0 & 0 & 0 \end{matrix}
    \right]
    \left[ \begin{matrix} 3 \ 2 \ 5 \end{matrix} \right] =
    \left[ \begin{matrix} 3 \ 2 \ 0 \end{matrix} \right]\end{align}
...and that applying the projection again to the result just gives back the
result again:
\begin{align}\left[
      \begin{matrix} 1 & 0 & 0 \ 0 & 1 & 0 \ 0 & 0 & 0 \end{matrix}
    \right]
    \left[ \begin{matrix} 3 \ 2 \ 0 \end{matrix} \right] =
    \left[ \begin{matrix} 3 \ 2 \ 0 \end{matrix} \right]\end{align}
From an information perspective, this projection has taken the point
$x, y, z$ and removed the information about how far in the $z$
direction our point was located; all we know now is its position in the
$x, y$ plane. Moreover, applying our projection matrix to any point
in $x, y, z$ space will reduce it to a corresponding point on the
$x, y$ plane. The term for this is a subspace: the projection matrix
projects points in the original space into a subspace of lower dimension
than the original. The reason our subspace is the $x,y$ plane (instead
of, say, the $y,z$ plane) is a direct result of the particular values
in our projection matrix.
Example: projection as noise reduction
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Another way to describe this "loss of information" or "projection into a
subspace" is to say that projection reduces the rank (or "degrees of
freedom") of the measurement — here, from 3 dimensions down to 2. On the
other hand, if you know that measurement...
Can you write Python code for it?

trigger_effect = np.array([[3, -1, 1]]).T


I am working on the file "0.19/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
Additional ways of visualizing projectors are covered in the tutorial
tut-artifact-ssp.
Loading and saving projectors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SSP can be used for other types of signal cleaning besides just reduction of
environmental noise. You probably noticed two large deflections in the
magnetometer signals in the previous plot that were not removed by the
empty-room projectors — those are artifacts of the subject's heartbeat. SSP
can be used to remove those artifacts as well. The sample data includes
projectors for heartbeat noise reduction that were saved in a separate file
from the raw data, which can be loaded with the :func:mne.read_proj
function:
Can you write Python code for it?

ecg_proj_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                             'sample_audvis_ecg-proj.fif')
ecg_projs = mne.read_proj(ecg_proj_file)
print(ecg_projs)


I am working on the file "0.19/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
Just as before, the projection matrix will map any point in $x, y, z$
space onto that plane, and once a point has been projected onto that plane,
applying the projection again will have no effect. For that reason, it should
be clear that although the projected points vary in all three $x$,
$y$, and $z$ directions, the set of projected points have only
two effective dimensions (i.e., they are constrained to a plane).
.. sidebar:: Terminology
In MNE-Python, the matrix used to project a raw signal into a subspace is
usually called a :term:`projector <projector>` or a *projection
operator* — these terms are interchangeable with the term *projection
matrix* used above.

Projections of EEG or MEG signals work in very much the same way: the point
$x, y, z$ corresponds to the value of each sensor at a single time
point, and the projection matrix varies depending on what aspects of the
signal (i.e., what kind of noise) you are trying to project out. The only
real difference is that instead of a single 3-dimensional point $(x, y,
z)$ you're dealing with a time series of $N$-dimensional "points" (one
at each sampling time), where $N$ is usually in the tens or hundreds
(depending on how many sensors your EEG/MEG system has). Fortunately, because
projection is a matrix operation, it can be done very quickly even on signals
with hundreds of dimensions and tens of thousands of time points.
Signal-space projection (SSP)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
We mentioned above that the projection matrix will vary depending on what
kind of noise you are trying to project away. Signal-space projection (SSP)
[1]_ is a way of estimating what that projection matrix should be, by
comparing measurements with and without the signal of interest. For example,
you can take additional "empty room" measurements that record activity at the
sensors when no subject is present. By looking at the spatial pattern of
activity across MEG sensors in an empty room measurement, you can create one
or more $N$-dimensional vector(s) giving the...
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_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file)
raw.crop(tmax=60).load_data()


I am working on the file "0.19/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
Knowing that, we can compute a plane that is orthogonal to the effect of the
trigger (using the fact that a plane through the origin has equation
$Ax + By + Cz = 0$ given a normal vector $(A, B, C)$), and
project our real measurements onto that plane.
Can you write Python code for it?

# compute the plane orthogonal to trigger_effect
x, y = np.meshgrid(np.linspace(-1, 5, 61), np.linspace(-1, 5, 61))
A, B, C = trigger_effect
z = (-A * x - B * y) / C
# cut off the plane below z=0 (just to make the plot nicer)
mask = np.where(z >= 0)
x = x[mask]
y = y[mask]
z = z[mask]


I am working on the file "0.19/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
The :class:~mne.io.Raw, :class:~mne.Epochs, and :class:~mne.Evoked
objects all have a boolean :attr:~mne.io.Raw.proj attribute that indicates
whether there are any unapplied / inactive projectors stored in the object.
In other words, the :attr:~mne.io.Raw.proj attribute is True if at
least one :term:projector is present and all of them are active. In
addition, each individual projector also has a boolean active field:
Can you write Python code for it?


I am working on the file "0.19/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
There is a corresponding :func:mne.write_proj function that can be used to
save projectors to disk in .fif format:
.. code-block:: python3
mne.write_proj('heartbeat-proj.fif', ecg_projs)

Note

By convention, MNE-Python expects projectors to be saved with a filename
    ending in ``-proj.fif`` (or ``-proj.fif.gz``), and will issue a warning
    if you forgo this recommendation.

Adding and removing projectors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Above, when we printed the ecg_projs list that we loaded from a file, it
showed two projectors for gradiometers (the first two, marked "planar"), two
for magnetometers (the middle two, marked "axial"), and two for EEG sensors
(the last two, marked "eeg"). We can add them to the :class:~mne.io.Raw
object using the :meth:~mne.io.Raw.add_proj method:
Can you write Python code for it?


I am working on the file "0.19/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
To remove projectors, there is a corresponding method
:meth:~mne.io.Raw.del_proj that will remove projectors based on their index
within the raw.info['projs'] list. For the special case of replacing the
existing projectors with new ones, use
raw.add_proj(ecg_projs, remove_existing=True).
To see how the ECG projectors affect the measured signal, we can once again
plot the data with and without the projectors applied (though remember that
the :meth:~mne.io.Raw.plot method only temporarily applies the projectors
for visualization, and does not permanently change the underlying data).
We'll compare the mags variable we created above, which had only the
empty room SSP projectors, to the data with both empty room and ECG
projectors:
Can you write Python code for it?

mags_ecg = raw.copy().crop(tmax=2).pick_types(meg='mag')
for data, title in zip([mags, mags_ecg], ['Without', 'With']):
    fig = data.plot(butterfly=True, proj=True)
    fig.subplots_adjust(top=0.9)
    fig.suptitle('{} ECG projector'.format(title), size='xx-large',
                 weight='bold')


I am working on the file "0.19/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
raw.info['projs'] is an ordinary Python :class:list of
:class:~mne.Projection objects, so you can access individual projectors by
indexing into it. The :class:~mne.Projection object itself is similar to a
Python :class:dict, so you can use its .keys() method to see what
fields it contains (normally you don't need to access its properties
directly, but you can if necessary):
Can you write Python code for it?

first_projector = raw.info['projs'][0]
print(first_projector)
print(first_projector.keys())


I am working on the file "0.19/_downloads/4395f5fd5291fa48208a82dab72d1893/plot_sensor_regression.ipynb".
The first task is:
Analysing continuous features with binning and regression in sensor space
Predict single trial activity from a continuous variable.
A single-trial regression is performed in each sensor and timepoint
individually, resulting in an :class:mne.Evoked object which contains the
regression coefficient (beta value) for each combination of sensor and
timepoint. This example shows the regression coefficient; the t and p values
are also calculated automatically.
Here, we repeat a few of the analyses from [1]_. This can be easily performed
by accessing the metadata object, which contains word-level information about
various psycholinguistically relevant features of the words for which we have
EEG activity.
For the general methodology, see e.g. [2]_.
References
.. [1] Dufau, S., Grainger, J., Midgley, KJ., Holcomb, PJ. A thousand
   words are worth a picture: Snapshots of printed-word processing in an
   event-related potential megastudy. Psychological Science, 2015
.. [2] Hauk et al. The time course of visual word recognition as revealed by
   linear regression analysis of ERP data. Neuroimage, 2006
Can you write Python code for it?

# Authors: Tal Linzen <linzen@nyu.edu>
#          Denis A. Engemann <denis.engemann@gmail.com>
#          Jona Sassenhagen <jona.sassenhagen@gmail.com>
#
# License: BSD (3-clause)

import pandas as pd
import mne
from mne.stats import linear_regression, fdr_correction
from mne.viz import plot_compare_evokeds
from mne.datasets import kiloword

# Load the data
path = kiloword.data_path() + '/kword_metadata-epo.fif'
epochs = mne.read_epochs(path)
print(epochs.metadata.head())


I am working on the file "0.19/_downloads/4395f5fd5291fa48208a82dab72d1893/plot_sensor_regression.ipynb".
The first task is:
Because the linear_regression function also estimates p values, we can --
after applying FDR correction for multiple comparisons -- also visualise the
statistical significance of the regression of word concreteness.
The :func:mne.viz.plot_evoked_image function takes a mask parameter.
If we supply it with a boolean mask of the positions where we can reject
the null hypothesis, points that are not significant will be shown
transparently, and if desired, in a different colour palette and surrounded
by dark contour lines.
Can you write Python code for it?

reject_H0, fdr_pvals = fdr_correction(res["Concreteness"].p_val.data)
evoked = res["Concreteness"].beta
evoked.plot_image(mask=reject_H0, time_unit='s')


I am working on the file "0.19/_downloads/43b08af05181aa9ee6947cbe626ed9cc/plot_object_evoked.ipynb".
The first task is:
Here for convenience we read the evoked dataset from a file.
Can you write Python code for it?

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


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


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

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


I am working on the file "0.19/_downloads/43b08af05181aa9ee6947cbe626ed9cc/plot_object_evoked.ipynb".
The first task is:
The :class:Evoked <mne.Evoked> data structure: evoked/averaged data
The :class:Evoked <mne.Evoked> data structure is mainly used for storing
averaged data over trials. In MNE the evoked objects are usually created by
averaging epochs data with :func:mne.Epochs.average.
Can you write Python code for it?

import os.path as op

import matplotlib.pyplot as plt
import mne


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

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


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

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


I am working on the file "0.19/_downloads/460fe4a441caf01fe3a0ace1c9325a0d/plot_tf_lcmv.ipynb".
The first task is:
Time-frequency beamforming based on LCMV
Can you write Python code for it?

# Setting frequency bins as in Dalal et al. 2008 (high gamma was subdivided)
freq_bins = [(4, 12), (12, 30), (30, 55), (65, 299)]  # Hz
win_lengths = [0.3, 0.2, 0.15, 0.1]  # s

# Setting the time step
tstep = 0.05

# Setting the whitened data covariance regularization parameter
data_reg = 0.001

# Subtract evoked response prior to computation?
subtract_evoked = False

# Calculating covariance from empty room noise. To use baseline data as noise
# substitute raw for raw_noise, epochs.events for epochs_noise.events, tmin for
# desired baseline length, and 0 for tmax_plot.
# Note, if using baseline data, the averaged evoked response in the baseline
# period should be flat.
noise_covs = []
for (l_freq, h_freq) in freq_bins:
    raw_band = raw_noise.copy()
    raw_band.filter(l_freq, h_freq, n_jobs=1, fir_design='firwin')
    epochs_band = mne.Epochs(raw_band, epochs_noise.events, event_id,
                             tmin=tmin_plot, tmax=tmax_plot, baseline=None,
                             proj=True)

    noise_cov = compute_covariance(epochs_band, method='shrunk', rank=None)
    noise_covs.append(noise_cov)
    del raw_band  # to save memory

# Computing LCMV solutions for time-frequency windows in a label in source
# space for faster computation, use label=None for full solution
stcs = tf_lcmv(epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths,
               freq_bins=freq_bins, subtract_evoked=subtract_evoked,
               reg=data_reg, label=label, rank=None)

# Plotting source spectrogram for source with maximum activity.
# Note that tmin and tmax are set to display a time range that is smaller than
# the one for which beamforming estimates were calculated. This ensures that
# all time bins shown are a result of smoothing across an identical number of
# time windows.
plot_source_spectrogram(stcs, freq_bins, tmin=tmin_plot, tmax=tmax_plot,
                        source_index=None, colorbar=True)


I am working on the file "0.19/_downloads/4a27e3735cff9a10082eb2938ef41c34/plot_sensor_permutation_test.ipynb".
The first task is:
Permutation T-test on sensor data
One tests if the signal significantly deviates from 0
during a fixed time window of interest. Here computation
is performed on MNE sample dataset between 40 and 60 ms.
Can you write Python code for it?

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

import numpy as np

import mne
from mne import io
from mne.stats import permutation_t_test
from mne.datasets import sample

print(__doc__)


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

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

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

# pick MEG Gradiometers
picks = mne.pick_types(raw.info, meg='grad', eeg=False, stim=False, eog=True,
                       exclude='bads')
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6))
data = epochs.get_data()
times = epochs.times

temporal_mask = np.logical_and(0.04 <= times, times <= 0.06)
data = np.mean(data[:, :, temporal_mask], axis=2)

n_permutations = 50000
T0, p_values, H0 = permutation_t_test(data, n_permutations, n_jobs=1)

significant_sensors = picks[p_values <= 0.05]
significant_sensors_names = [raw.ch_names[k] for k in significant_sensors]

print("Number of significant sensors : %d" % len(significant_sensors))
print("Sensors names : %s" % significant_sensors_names)


I am working on the file "0.19/_downloads/4a39dd4a31cad8a0e098b02526b9c3d3/plot_covariance_whitening_dspm.ipynb".
The first task is:
Estimate covariances
Can you write Python code for it?

samples_epochs = 5, 15,
method = 'empirical', 'shrunk'
colors = 'steelblue', 'red'

evokeds = list()
stcs = list()
methods_ordered = list()
for n_train in samples_epochs:
    # estimate covs based on a subset of samples
    # make sure we have the same number of conditions.
    events_ = np.concatenate([events[events[:, 2] == id_][:n_train]
                              for id_ in [event_ids[k] for k in conditions]])
    events_ = events_[np.argsort(events_[:, 0])]
    epochs_train = mne.Epochs(raw, events_, event_ids, tmin, tmax, picks=picks,
                              baseline=baseline, preload=True, reject=reject,
                              decim=8)
    epochs_train.equalize_event_counts(event_ids)
    assert len(epochs_train) == 2 * n_train

    # We know some of these have too few samples, so suppress warning
    # with verbose='error'
    noise_covs = compute_covariance(
        epochs_train, method=method, tmin=None, tmax=0,  # baseline only
        return_estimators=True, rank=None, verbose='error')  # returns list
    # prepare contrast
    evokeds = [epochs_train[k].average() for k in conditions]
    del epochs_train, events_
    # do contrast

    # We skip empirical rank estimation that we introduced in response to
    # the findings in reference [1] to use the naive code path that
    # triggered the behavior described in [1]. The expected true rank is
    # 274 for this dataset. Please do not do this with your data but
    # rely on the default rank estimator that helps regularizing the
    # covariance.
    stcs.append(list())
    methods_ordered.append(list())
    for cov in noise_covs:
        inverse_operator = make_inverse_operator(evokeds[0].info, forward,
                                                 cov, loose=0.2, depth=0.8)
        assert len(inverse_operator['sing']) == 274  # sanity check
        stc_a, stc_b = (apply_inverse(e, inverse_operator, lambda2, "dSPM",
                                      pick_ori=None) for e in evokeds)
        stc = stc_a - stc_b
       ...


I am working on the file "0.19/_downloads/4a39dd4a31cad8a0e098b02526b9c3d3/plot_covariance_whitening_dspm.ipynb".
The first task is:
Get data
Can you write Python code for it?

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

raw_fname = data_path + '/MEG/spm/SPM_CTF_MEG_example_faces%d_3D.ds'

raw = io.read_raw_ctf(raw_fname % 1)  # Take first run
# To save time and memory for this demo, we'll just use the first
# 2.5 minutes (all we need to get 30 total events) and heavily
# resample 480->60 Hz (usually you wouldn't do either of these!)
raw = raw.crop(0, 150.).load_data()

picks = mne.pick_types(raw.info, meg=True, exclude='bads')
raw.filter(None, 20.)

events = mne.find_events(raw, stim_channel='UPPT001')

event_ids = {"faces": 1, "scrambled": 2}
tmin, tmax = -0.2, 0.5
baseline = (None, 0)
reject = dict(mag=3e-12)

# Make forward
trans = data_path + '/MEG/spm/SPM_CTF_MEG_example_faces1_3D_raw-trans.fif'
src = data_path + '/subjects/spm/bem/spm-oct-6-src.fif'
bem = data_path + '/subjects/spm/bem/spm-5120-5120-5120-bem-sol.fif'
forward = mne.make_forward_solution(raw.info, trans, src, bem)
del src

# inverse parameters
conditions = 'faces', 'scrambled'
snr = 3.0
lambda2 = 1.0 / snr ** 2
clim = dict(kind='value', lims=[0, 2.5, 5])


I am working on the file "0.19/_downloads/4e37370a8ca815e788684add8304ce44/plot_ssp_projs_sensitivity_map.ipynb".
The first task is:
Show sensitivity map
Can you write Python code for it?

plt.hist(ssp_ecg_map.data.ravel())
plt.show()

args = dict(clim=dict(kind='value', lims=(0.2, 0.6, 1.)), smoothing_steps=7,
            hemi='rh', subjects_dir=subjects_dir)
ssp_ecg_map.plot(subject='sample', time_label='ECG SSP sensitivity', **args)


I am working on the file "0.19/_downloads/5052c5720946ade7aa05ff53ac81bd6d/plot_epochs_to_data_frame.ipynb".
The first task is:
Export DataFrame
Can you write Python code for it?

# The following parameters will scale the channels and times plotting
# friendly. The info columns 'epoch' and 'time' will be used as hierarchical
# index whereas the condition is treated as categorial data. Note that
# this is optional. By passing None you could also print out all nesting
# factors in a long table style commonly used for analyzing repeated measure
# designs.

index, scaling_time, scalings = ['epoch', 'time'], 1e3, dict(grad=1e13)

df = epochs.to_data_frame(picks=None, scalings=scalings,
                          scaling_time=scaling_time, index=index)

# Create MEG channel selector and drop EOG channel.
meg_chs = [c for c in df.columns if 'MEG' in c]

df.pop('EOG 061')  # this works just like with a list.


I am working on the file "0.19/_downloads/5052c5720946ade7aa05ff53ac81bd6d/plot_epochs_to_data_frame.ipynb".
The first task is:
Export epochs to Pandas DataFrame
In this example the pandas exporter will be used to produce a DataFrame
object. After exploring some basic features a split-apply-combine
work flow will be conducted to examine the latencies of the response
maxima across epochs and conditions.

Note

Equivalent methods are available for raw and evoked data objects.

More information and additional introductory materials can be found at the
pandas doc sites: http://pandas.pydata.org/pandas-docs/stable/
Short Pandas Primer
Pandas Data Frames
~~~~~~~~~~~~~~~~~~
A data frame can be thought of as a combination of matrix, list and dict:
It knows about linear algebra and element-wise operations but is size mutable
and allows for labeled access to its data. In addition, the pandas data frame
class provides many useful methods for restructuring, reshaping and visualizing
data. As most methods return data frame instances, operations can be chained
with ease; this allows to write efficient one-liners. Technically a DataFrame
can be seen as a high-level container for numpy arrays and hence switching
back and forth between numpy arrays and DataFrames is very easy.
Taken together, these features qualify data frames for inter operation with
databases and for interactive data exploration / analysis.
Additionally, pandas interfaces with the R statistical computing language that
covers a huge amount of statistical functionality.
Export Options
~~~~~~~~~~~~~~
The pandas exporter comes with a few options worth being commented.
Pandas DataFrame objects use a so called hierarchical index. This can be
thought of as an array of unique tuples, in our case, representing the higher
dimensional MEG data in a 2D data table. The column names are the channel names
from the epoch object. The channels can be accessed like entries of a
dictionary::
>>> df['MEG 2333']

Epochs and time slices can be accessed with the .loc method::
>>> epochs_df.loc[(1, 2), 'MEG 2333']

However, it is also...
Can you write Python code for it?

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

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

print(__doc__)

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

# These data already have an average EEG ref applied
raw = mne.io.read_raw_fif(raw_fname)

# For simplicity we will only consider the first 10 epochs
events = mne.read_events(event_fname)[:10]

# Add a bad channel
raw.info['bads'] += ['MEG 2443']
picks = mne.pick_types(raw.info, meg='grad', eeg=True, eog=True,
                       stim=False, exclude='bads')

tmin, tmax = -0.2, 0.5
baseline = (None, 0)
reject = dict(grad=4000e-13, eog=150e-6)

event_id = dict(auditory_l=1, auditory_r=2, visual_l=3, visual_r=4)

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


I am working on the file "0.19/_downloads/5405ec123125b53ac343bbc1ba002342/plot_stats_spatio_temporal_cluster_sensors.ipynb".
The first task is:
Find the FieldTrip neighbor definition to setup sensor connectivity
Can you write Python code for it?

connectivity, ch_names = find_ch_connectivity(epochs.info, ch_type='mag')

print(type(connectivity))  # it's a sparse matrix!

plt.imshow(connectivity.toarray(), cmap='gray', origin='lower',
           interpolation='nearest')
plt.xlabel('{} Magnetometers'.format(len(ch_names)))
plt.ylabel('{} Magnetometers'.format(len(ch_names)))
plt.title('Between-sensor adjacency')


I am working on the file "0.19/_downloads/5405ec123125b53ac343bbc1ba002342/plot_stats_spatio_temporal_cluster_sensors.ipynb".
The first task is:
Read epochs for the channel of interest
Can you write Python code for it?

picks = mne.pick_types(raw.info, meg='mag', eog=True)

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

epochs.drop_channels(['EOG 061'])
epochs.equalize_event_counts(event_id)

X = [epochs[k].get_data() for k in event_id]  # as 3D matrix
X = [np.transpose(x, (0, 2, 1)) for x in X]  # transpose for clustering


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

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
event_id = {'Aud/L': 1, 'Aud/R': 2, 'Vis/L': 3, 'Vis/R': 4}
tmin = -0.2
tmax = 0.5

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


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

print('Computing connectivity.')
connectivity = mne.spatial_src_connectivity(src)

#    Note that X needs to be a multi-dimensional array of shape
#    samples (subjects) x time x space, so we permute dimensions
X = np.transpose(X, [2, 1, 0])

#    Now let's actually do the clustering. This can take a long time...
#    Here we set the threshold quite high to reduce computation.
p_threshold = 0.001
t_threshold = -stats.distributions.t.ppf(p_threshold / 2., n_subjects - 1)
print('Clustering.')
T_obs, clusters, cluster_p_values, H0 = clu = \
    spatio_temporal_cluster_1samp_test(X, connectivity=connectivity, n_jobs=1,
                                       threshold=t_threshold, buffer_size=None,
                                       verbose=True)
#    Now select the clusters that are sig. at p < 0.05 (note that this value
#    is multiple-comparisons corrected).
good_cluster_inds = np.where(cluster_p_values < 0.05)[0]


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

# Read the source space we are morphing to
src = mne.read_source_spaces(src_fname)
fsave_vertices = [s['vertno'] for s in src]
morph_mat = mne.compute_source_morph(
    src=inverse_operator['src'], subject_to='fsaverage',
    spacing=fsave_vertices, subjects_dir=subjects_dir).morph_mat

n_vertices_fsave = morph_mat.shape[0]

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


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

raw.info['bads'] += ['MEG 2443']
picks = mne.pick_types(raw.info, meg=True, eog=True, exclude='bads')
event_id = 1  # L auditory
reject = dict(grad=1000e-13, mag=4000e-15, eog=150e-6)
epochs1 = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                     baseline=(None, 0), reject=reject, preload=True)

event_id = 3  # L visual
epochs2 = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                     baseline=(None, 0), reject=reject, preload=True)

#    Equalize trial counts to eliminate bias (which would otherwise be
#    introduced by the abs() performed below)
equalize_epoch_counts([epochs1, epochs2])


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

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

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

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


I am working on the file "0.19/_downloads/581c1c0ba541022ae5f26cefb5b0685e/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Transform to common cortical space
Normally you would read in estimates across several subjects and morph
them to the same cortical space (e.g. fsaverage). For example purposes,
we will simulate this by just having each "subject" have the same
response (just noisy in source space) here.

Note

Note that for 7 subjects with a two-sided statistical test, the minimum
    significance under a permutation test is only p = 1/(2 ** 6) = 0.015,
    which is large.

Can you write Python code for it?

n_vertices_sample, n_times = condition1.data.shape
n_subjects = 7
print('Simulating data for %d subjects.' % n_subjects)

#    Let's make sure our results replicate, so set the seed.
np.random.seed(0)
X = randn(n_vertices_sample, n_times, n_subjects, 2) * 10
X[:, :, :, 0] += condition1.data[:, :, np.newaxis]
X[:, :, :, 1] += condition2.data[:, :, np.newaxis]


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

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

#    Let's average and compute inverse, resampling to speed things up
evoked1 = epochs1.average()
evoked1.resample(50, npad='auto')
condition1 = apply_inverse(evoked1, inverse_operator, lambda2, method)
evoked2 = epochs2.average()
evoked2.resample(50, npad='auto')
condition2 = apply_inverse(evoked2, inverse_operator, lambda2, method)

#    Let's only deal with t > 0, cropping to reduce multiple comparisons
condition1.crop(0, None)
condition2.crop(0, None)
tmin = condition1.tmin
tstep = condition1.tstep


I am working on the file "0.19/_downloads/581c1c0ba541022ae5f26cefb5b0685e/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Visualize the clusters
Can you write Python code for it?

print('Visualizing clusters.')

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

#    Let's actually plot the first "time point" in the SourceEstimate, which
#    shows all the clusters, weighted by duration
subjects_dir = op.join(data_path, 'subjects')
# blue blobs are for condition A < condition B, red for A > B
brain = stc_all_cluster_vis.plot(
    hemi='both', views='lateral', subjects_dir=subjects_dir,
    time_label='Duration significant (ms)', size=(800, 800),
    smoothing_steps=5, clim=dict(kind='value', pos_lims=[0, 1, 40]))
# brain.save_image('clusters.png')


I am working on the file "0.19/_downloads/5896a1084085b2a4929647fc8cbaf675/plot_movement_compensation.ipynb".
The first task is:
First, take the average of stationary data (bilateral auditory patterns).
Can you write Python code for it?

evoked_stat = mne.Epochs(raw_stat, events, 1, -0.2, 0.8).average()
evoked_stat.plot_topomap(title='Stationary', **topo_kwargs)


I am working on the file "0.19/_downloads/5896a1084085b2a4929647fc8cbaf675/plot_movement_compensation.ipynb".
The first task is:
Maxwell filter data with movement compensation
Demonstrate movement compensation on simulated data. The simulated data
contains bilateral activation of auditory cortices, repeated over 14
different head rotations (head center held fixed). See the following for
details:
https://github.com/mne-tools/mne-misc-data/blob/master/movement/simulate.py
Can you write Python code for it?

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

from os import path as op

import mne
from mne.preprocessing import maxwell_filter

print(__doc__)

data_path = op.join(mne.datasets.misc.data_path(verbose=True), 'movement')

head_pos = mne.chpi.read_head_pos(op.join(data_path, 'simulated_quats.pos'))
raw = mne.io.read_raw_fif(op.join(data_path, 'simulated_movement_raw.fif'))
raw_stat = mne.io.read_raw_fif(op.join(data_path,
                                       'simulated_stationary_raw.fif'))


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

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

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


I am working on the file "0.19/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
.. sidebar:: Computing sensor locations
If you are interested in how standard ("idealized") EEG sensor positions
are computed on a spherical head model, the `eeg_positions`_ repository
provides code and documentation to this end.

As you may be able to tell from the filenames shown above, the included
montage files are all for EEG systems. These are idealized sensor positions
based on a spherical head model. Montage files for MEG systems are not
provided because the 3D coordinates of MEG sensors are included in the raw
recordings from MEG systems, and are automatically stored in the info
attribute of the :class:~mne.io.Raw file upon loading. In contrast, layout
files are included for MEG systems (to facilitate easy plotting of MEG
sensor location diagrams).
You may also have noticed that the file formats and filename extensions of
layout and montage files vary considerably. This reflects different
manufacturers' conventions; to simplify this, the montage and layout loading
functions in MNE-Python take the filename without its extension so you
don't have to keep track of which file format is used by which manufacturer.
Examples of this can be seen in the following sections.
If you have digitized the locations of EEG sensors on the scalp during your
recording session (e.g., with a Polhemus Fastrak digitizer), these can be
loaded in MNE-Python as :class:~mne.channels.DigMontage objects; see
reading-dig-montages (below).
Working with layout files
~~~~~~~~~~~~~~~~~~~~~~~~~
To load a layout file, use the :func:mne.channels.read_layout
function, and provide the filename without its file extension. You can then
visualize the layout using its :meth:~mne.channels.Layout.plot method, or
(equivalently) by passing it to :func:mne.viz.plot_layout:
Can you write Python code for it?

biosemi_layout = mne.channels.read_layout('biosemi')
biosemi_layout.plot()  # same result as: mne.viz.plot_layout(biosemi_layout)


I am working on the file "0.19/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
About montages and layouts
^^^^^^^^^^^^^^^^^^^^^^^^^^
MNE-Python comes pre-loaded with information about the sensor positions of
many MEG and EEG systems. This information is stored in layout files and
montages. :class:Layouts <mne.channels.Layout> give sensor positions in 2
dimensions (defined by x, y, width, and height values for
each sensor), and are primarily used for illustrative purposes (i.e., making
diagrams of approximate sensor positions in top-down diagrams of the head).
In contrast, :class:montages <mne.channels.DigMontage> contain sensor
positions in 3D (x, y, z, in meters). Many layout and montage
files are included during MNE-Python installation, and are stored in your
mne-python directory, in the :file:mne/channels/data/layouts and
:file:mne/channels/data/montages folders, respectively:
Can you write Python code for it?

data_dir = os.path.join(os.path.dirname(mne.__file__), 'channels', 'data')
for subfolder in ['layouts', 'montages']:
    print('\nBUILT-IN {} FILES'.format(subfolder[:-1].upper()))
    print('======================')
    print(sorted(os.listdir(os.path.join(data_dir, subfolder))))


I am working on the file "0.19/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
If you're working with a :class:~mne.io.Raw object that already has sensor
positions incorporated, you can create a :class:~mne.channels.Layout object
with either the :func:mne.channels.make_eeg_layout function or
(equivalently) the :func:mne.channels.find_layout function.
Can you write Python code for it?

layout_from_raw = mne.channels.make_eeg_layout(raw.info)
# same result as: mne.channels.find_layout(raw.info, ch_type='eeg')
layout_from_raw.plot()


I am working on the file "0.19/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
Reading sensor digitization files
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
It's probably evident from the 2D topomap above that there is some
irregularity in the EEG sensor positions in the sample dataset
<sample-dataset> — this is because the sensor positions in that dataset are
digitizations of the sensor positions on an actual subject's head. Depending
on what system was used to scan the positions one can use different
reading functions (:func:mne.channels.read_dig_captrack for
a CapTrak Brain Products system, :func:mne.channels.read_dig_egi
for an EGI system, :func:mne.channels.read_dig_polhemus_isotrak for
Polhemus ISOTRAK, :func:mne.channels.read_dig_fif to read from
a .fif file or :func:mne.channels.read_dig_hpts to read MNE .hpts
files. The read :class:montage <mne.channels.DigMontage> can then be added
to :class:~mne.io.Raw objects with the :meth:~mne.io.Raw.set_montage
method; in the sample data this was done prior to saving the
:class:~mne.io.Raw object to disk, so the sensor positions are already
incorporated into the info attribute of the :class:~mne.io.Raw object.
See the documentation of the reading functions and
:meth:~mne.io.Raw.set_montage for further details. Once loaded,
locations can be plotted with :meth:~mne.channels.DigMontage.plot and
saved with :meth:~mne.channels.DigMontage.save, like when working
with a standard montage.
The possibilities to read in digitized montage files are summarized
in dig-formats.

Note

When setting a montage with :meth:`~mne.io.Raw.set_montage`
    the measurement info is updated at two places (the `chs`
    and `dig` entries are updated). See `tut-info-class`.
    `dig` will potentially contain more than channel locations,
    such HPI, head shape points or fiducials 3D coordinates.

Rendering sensor position with mayavi
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
It is also possible to render an image of a MEG sensor helmet in 3D, using
mayavi instead of matplotlib, by calling the...
Can you write Python code for it?

fig = mne.viz.plot_alignment(raw.info, trans=None, dig=False, eeg=False,
                             surfaces=[], meg=['helmet', 'sensors'],
                             coord_frame='meg')
mne.viz.set_3d_view(fig, azimuth=50, elevation=90, distance=0.5)


I am working on the file "0.19/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
Similar functionality is also available with the
:meth:~mne.io.Raw.plot_sensors method of :class:~mne.io.Raw objects,
again with the option to plot in either 2D or 3D.
:meth:~mne.io.Raw.plot_sensors also allows channel selection by type, can
color-code channels in various ways (by default, channels listed in
raw.info['bads'] will be plotted in red), and allows drawing into an
existing matplotlib axes object (so the channel positions can easily be
made as a subplot in a multi-panel figure):
Can you write Python code for it?

fig = plt.figure()
ax2d = fig.add_subplot(121)
ax3d = fig.add_subplot(122, projection='3d')
raw.plot_sensors(ch_type='eeg', axes=ax2d)
raw.plot_sensors(ch_type='eeg', axes=ax3d, kind='3d')
ax3d.view_init(azim=70, elev=15)


I am working on the file "0.19/_downloads/59a29cf7eb53c7ab95857dfb2e3b31ba/plot_40_sensor_locations.ipynb".
The first task is:
Similar to the picks argument for selecting channels from
:class:~mne.io.Raw objects, the :meth:~mne.channels.Layout.plot method of
:class:~mne.channels.Layout objects also has a picks argument. However,
because layouts only contain information about sensor name and location (not
sensor type), the :meth:~mne.channels.Layout.plot method only allows
picking channels by index (not by name or by type). Here we find the indices
we want using :func:numpy.where; selection by name or type is possible via
:func:mne.pick_channels or :func:mne.pick_types.
Can you write Python code for it?

midline = np.where([name.endswith('z') for name in biosemi_layout.names])[0]
biosemi_layout.plot(picks=midline)


I am working on the file "0.19/_downloads/59aa8e259e776a361531f7d21fa2f1ec/plot_compute_raw_data_spectrum.ipynb".
The first task is:
Alternative functions for PSDs
There are also several functions in MNE that create a PSD using a Raw
object. These are in the :mod:mne.time_frequency module and begin with
psd_*. For example, we'll use a multitaper method to compute the PSD
below.
Can you write Python code for it?

f, ax = plt.subplots()
psds, freqs = psd_multitaper(raw, low_bias=True, tmin=tmin, tmax=tmax,
                             fmin=fmin, fmax=fmax, proj=True, picks=picks,
                             n_jobs=1)
psds = 10 * np.log10(psds)
psds_mean = psds.mean(0)
psds_std = psds.std(0)

ax.plot(freqs, psds_mean, color='k')
ax.fill_between(freqs, psds_mean - psds_std, psds_mean + psds_std,
                color='k', alpha=.5)
ax.set(title='Multitaper PSD', xlabel='Frequency',
       ylabel='Power Spectral Density (dB)')
plt.show()


I am working on the file "0.19/_downloads/59aa8e259e776a361531f7d21fa2f1ec/plot_compute_raw_data_spectrum.ipynb".
The first task is:
Load data
We'll load a sample MEG dataset, along with SSP projections that will
allow us to reduce EOG and ECG artifacts. For more information about
reducing artifacts, see the preprocessing section in documentation.
Can you write Python code for it?

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
proj_fname = data_path + '/MEG/sample/sample_audvis_eog-proj.fif'

tmin, tmax = 0, 60  # use the first 60s of data

# Setup for reading the raw data (to save memory, crop before loading)
raw = io.read_raw_fif(raw_fname).crop(tmin, tmax).load_data()
raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more

# Add SSP projection vectors to reduce EOG and ECG artifacts
projs = read_proj(proj_fname)
raw.add_proj(projs, remove_existing=True)

fmin, fmax = 2, 300  # look at frequencies between 2 and 300Hz
n_fft = 2048  # the FFT size (n_fft). Ideally a power of 2


I am working on the file "0.19/_downloads/59aa8e259e776a361531f7d21fa2f1ec/plot_compute_raw_data_spectrum.ipynb".
The first task is:
Plot a cleaned PSD
Next we'll focus the visualization on a subset of channels.
This can be useful for identifying particularly noisy channels or
investigating how the power spectrum changes across channels.
We'll visualize how this PSD changes after applying some standard
filtering techniques. We'll first apply the SSP projections, which is
accomplished with the proj=True kwarg. We'll then perform a notch filter
to remove particular frequency bands.
Can you write Python code for it?

# Pick MEG magnetometers in the Left-temporal region
selection = read_selection('Left-temporal')
picks = mne.pick_types(raw.info, meg='mag', eeg=False, eog=False,
                       stim=False, exclude='bads', selection=selection)

# Let's just look at the first few channels for demonstration purposes
picks = picks[:4]

plt.figure()
ax = plt.axes()
raw.plot_psd(tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, n_fft=n_fft,
             n_jobs=1, proj=False, ax=ax, color=(0, 0, 1),  picks=picks,
             show=False, average=True)

raw.plot_psd(tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, n_fft=n_fft,
             n_jobs=1, proj=True, ax=ax, color=(0, 1, 0), picks=picks,
             show=False, average=True)

# And now do the same with SSP + notch filtering
# Pick all channels for notch since the SSP projection mixes channels together
raw.notch_filter(np.arange(60, 241, 60), n_jobs=1, fir_design='firwin')
raw.plot_psd(tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, n_fft=n_fft,
             n_jobs=1, proj=True, ax=ax, color=(1, 0, 0), picks=picks,
             show=False, average=True)

ax.set_title('Four left-temporal magnetometers')
plt.legend(ax.lines[::3], ['Without SSP', 'With SSP', 'SSP + Notch'])


I am working on the file "0.19/_downloads/5a3a8c2664be35abac537a97ac994e3e/plot_modifying_data_inplace.ipynb".
The first task is:
In addition, there are functions for applying the Hilbert transform, which is
useful to calculate phase / amplitude of your signal.
Can you write Python code for it?

# Filter signal with a fairly steep filter, then take hilbert transform

raw_band = raw.copy()
raw_band.filter(12, 18, l_trans_bandwidth=2., h_trans_bandwidth=2.,
                fir_design='firwin')
raw_hilb = raw_band.copy()
hilb_picks = mne.pick_types(raw_band.info, meg=False, eeg=True)
raw_hilb.apply_hilbert(hilb_picks)
print(raw_hilb[0][0].dtype)


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

data_path = op.join(mne.datasets.sample.data_path(), 'MEG',
                    'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(data_path, preload=True)
raw = raw.crop(0, 10)
print(raw)


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

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


I am working on the file "0.19/_downloads/5a3a8c2664be35abac537a97ac994e3e/plot_modifying_data_inplace.ipynb".
The first task is:
Signal processing
Most MNE objects have in-built methods for filtering:
Can you write Python code for it?

filt_bands = [(1, 3), (3, 10), (10, 20), (20, 60)]
_, (ax, ax2) = plt.subplots(2, 1, figsize=(15, 10))
data, times = raw[0]
_ = ax.plot(data[0])
for fmin, fmax in filt_bands:
    raw_filt = raw.copy()
    raw_filt.filter(fmin, fmax, fir_design='firwin')
    _ = ax2.plot(raw_filt[0][0][0])
ax2.legend(filt_bands)
ax.set_title('Raw data')
ax2.set_title('Band-pass filtered data')


I am working on the file "0.19/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
Event dictionaries like this one are used when extracting epochs from
continuous data, and the resulting :class:~mne.Epochs object allows pooling
by requesting partial trial descriptors. For example, if we wanted to pool
all auditory trials, instead of merging Event IDs 1 and 2 using the
:func:~mne.merge_events function, we can make use of the fact that the keys
of event_dict contain multiple trial descriptors separated by /
characters: requesting 'auditory' trials will select all epochs with
Event IDs 1 and 2; requesting 'left' trials will select all epochs with
Event IDs 1 and 3. An example of this is shown in a later tutorial.
.. TODO replace above sentence when the relevant tut is ready:
   An example of this is shown later, in the epoch-pooling section of
   the epochs-intro-tutorial tutorial.
Plotting events
^^^^^^^^^^^^^^^
Another use of event dictionaries is when plotting events, which can serve as
a useful check that your event signals were properly sent to the STIM
channel(s) and that MNE-Python has successfully found them. The function
:func:mne.viz.plot_events will plot each event versus its sample number
(or, if you provide the sampling frequency, it will plot them versus time in
seconds). It can also account for the offset between sample number and sample
index in Neuromag systems, with the first_samp parameter. If an event
dictionary is provided, it will be used to generate a legend:
Can you write Python code for it?

fig = mne.viz.plot_events(events, sfreq=raw.info['sfreq'],
                          first_samp=raw.first_samp, event_id=event_dict)
fig.subplots_adjust(right=0.7)  # make room for legend


I am working on the file "0.19/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
If some of those events are not of interest, you can easily subselect events
using :func:mne.pick_events, which has parameters include and
exclude. For example, in the sample data Event ID 32 corresponds to a
subject button press, which could be excluded as:
Can you write Python code for it?

events_no_button = mne.pick_events(events, exclude=32)


I am working on the file "0.19/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
It is also possible to combine two Event IDs using :func:mne.merge_events;
the following example will combine Event IDs 1, 2 and 3 into a single event
labelled 1:
Can you write Python code for it?

merged_events = mne.merge_events(events, [1, 2, 3], 1)
print(np.unique(merged_events[:, -1]))


I am working on the file "0.19/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
Making equally-spaced Events arrays
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
For some experiments (such as those intending to analyze resting-state
activity) there may not be any experimental events included in the raw
recording. In such cases, an Events array of equally-spaced events can be
generated using :func:mne.make_fixed_length_events:
Can you write Python code for it?

new_events = mne.make_fixed_length_events(raw, start=5, stop=50, duration=2.)


I am working on the file "0.19/_downloads/5c1cfe3ed46585b58c66f76ec83c96c6/plot_20_event_arrays.ipynb".
The first task is:
Note, however, that merging events is not necessary if you simply want to
pool trial types for analysis; the next section describes how MNE-Python uses
event dictionaries to map integer Event IDs to more descriptive label
strings.
Mapping Event IDs to trial descriptors
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
So far in this tutorial we've only been dealing with integer Event IDs, which
were assigned based on DC voltage pulse magnitude (which is ultimately
determined by the experimenter's choices about what signals to send to the
STIM channels). Keeping track of which Event ID corresponds to which
experimental condition can be cumbersome, and it is often desirable to pool
experimental conditions during analysis. You may recall that the mapping of
integer Event IDs to meaningful descriptions for the sample dataset
<sample-dataset> is given in this table
<sample-data-event-dict-table> in the introductory tutorial
<tut-overview>. Here we simply reproduce that mapping as an
event dictionary:
Can you write Python code for it?

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