I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
EEG processing and Event Related Potentials (ERPs)
This tutorial shows how to perform standard ERP analyses in MNE-Python. Most of
the material here is covered in other tutorials too, but for convenience the
functions and methods most useful for ERP analyses are collected here, with
links to other tutorials where more detailed information is given.
As usual we'll start by importing the modules we need and loading some example
data. Instead of parsing the events from the raw data's :term:stim channel
(like we do in this tutorial <tut-events-vs-annotations>), we'll load
the events from an external events file. Finally, to speed up computations so
our documentation server can handle them, we'll crop the raw data from ~4.5
minutes down to 90 seconds.
Can you write Python code for it?

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

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

sample_data_events_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                       'sample_audvis_filt-0-40_raw-eve.fif')
events = mne.read_events(sample_data_events_file)

raw.crop(tmax=90)  # in seconds; happens in-place
# discard events >90 seconds (not strictly necessary: avoids some warnings)
events = events[events[:, 0] <= raw.last_samp]


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
Global field power (GFP)
Global field power :footcite:Lehmann1980,Lehmann1984,Murray2008 is,
generally speaking, a measure of agreement of the signals picked up by all
sensors across the entire scalp: if all sensors have the same value at a
given time point, the GFP will be zero at that time point; if the signals
differ, the GFP will be non-zero at that time point. GFP
peaks may reflect "interesting" brain activity, warranting further
investigation. Mathematically, the GFP is the population standard
deviation across all sensors, calculated separately for every time point.
You can plot the GFP using evoked.plot(gfp=True) <mne.Evoked.plot>. The GFP
trace will be black if spatial_colors=True and green otherwise. The EEG
reference does not affect the GFP:
Can you write Python code for it?

for evk in (l_aud, l_vis):
    evk.plot(gfp=True, spatial_colors=True, ylim=dict(eeg=[-12, 12]))


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
If you're working with a standard montage like the 10-20 <ten_twenty_>_
system, you can add sensor locations to the data like this:
raw.set_montage('standard_1020').  See tut-sensor-locations for
info on what other standard montages are built-in to MNE-Python.
If you have digitized realistic sensor locations, there are dedicated
functions for loading those digitization files into MNE-Python; see
reading-dig-montages for discussion and dig-formats for a list
of supported formats. Once loaded, the digitized sensor locations can be
added to the data by passing the loaded montage object to
raw.set_montage().
Setting the EEG reference
As mentioned above, this data already has an EEG common average reference
added as a :term:projector. We can view the effect of this on the raw data
by plotting with and without the projector applied:
Can you write Python code for it?

for proj in (False, True):
    fig = raw.plot(n_channels=5, proj=proj, scalings=dict(eeg=50e-6))
    fig.subplots_adjust(top=0.9)  # make room for title
    ref = 'Average' if proj else 'No'
    fig.suptitle(f'{ref} reference', size='xx-large', weight='bold')


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
Mean Amplitude
Another common practice in ERP studies is to define a component (or effect)
as the mean amplitude within a specified time window. One advantage of this
approach is that it is less sensitive to high frequency noise (compared to
peak amplitude measures) because averaging over a time window acts like a
low-pass filter (see discussion in the above section
Peak latency and amplitude_).
When using mean amplitude measures, selecting the time window based on
the effect of interest (e.g., the difference between two conditions) can
inflate the likelihood of finding false positives in your results because
this approach is circular :footcite:LuckGaspelin2017. There are other, and
better, ways to identify a time window to use for extracting mean amplitude
measures. First, you can use a priori time window based on prior research.
A second way is to define a time window from an independent condition or set
of trials not used in the analysis (e.g., a "localizer"). A third approach is
to define a time window using the across-condition grand average. This latter
approach is not circular because the across-condition mean and condition
difference are independent of one another. The issues discussed above also
apply to selecting channels used for analysis.
The following example demonstrates how to pull out the mean amplitude
from the left visual condition (i.e., the l_vis :class:~mne.Evoked
object) using from selected channels and time windows. Stimulating the
left visual field is increases neural activity visual cortex of the
contralateral (i.e., right) hemisphere. We can test this by examining the
amplitude of the ERP for left visual field stimulation over right
(contralateral) and left (ipsilateral) channels. The channels used for this
analysis are eeg54 and eeg57 (left hemisphere), and eeg59 and
eeg55 (right hemisphere). The time window used is .08 (good_tmin)
to .12 s (good_tmax) as it corresponds to when P100 typically occurs. The
P100 is sensitive to left and right visual field stimulation. The...
Can you write Python code for it?

# Select all of the channels and crop to the time window
channels = ['eeg54', 'eeg57', 'eeg55', 'eeg59']
hemisphere = ['left', 'left', 'right', 'right']
l_vis_mean_roi = l_vis.copy().pick(channels).crop(
    tmin=good_tmin, tmax=good_tmax)

# Extract mean amplitude in µV over time
mean_amp_roi = l_vis_mean_roi.data.mean(axis=1) * 1e6

# Store the data in a data frame
mean_amp_roi_df = pd.DataFrame({
    'ch_name': l_vis_mean_roi.ch_names,
    'hemisphere': ['left', 'left', 'right', 'right'],
    'mean_amp': mean_amp_roi
})

# Print the data frame
print(mean_amp_roi_df.groupby('hemisphere').mean())


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
Next we generate a barplot of which channels contributed most to epochs
getting rejected. If one channel is responsible for lots of epoch rejections,
it may be worthwhile to mark that channel as "bad" in the ~mne.io.Raw
object and then re-run epoching (fewer channels w/ more good epochs may be
preferable to keeping all channels but losing many epochs). See
tut-bad-channels for more info.
Can you write Python code for it?


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
Now we can extract epochs from the continuous data. An interactive plot
allows you to click on epochs to mark them as "bad" and drop them from the
analysis (it is not interactive on the documentation website, but will be
when you run epochs.plot() <mne.Epochs.plot> in a Python console).
Can you write Python code for it?

epochs = mne.Epochs(raw, events, event_id=event_dict, tmin=-0.3, tmax=0.7,
                    preload=True)
fig = epochs.plot(events=events)


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
Scalp topographies can also be obtained non-interactively with the
~mne.Evoked.plot_topomap method. Here we display topomaps of the average
field in 50 ms time windows centered at -200 ms, 100 ms, and 400 ms.
Can you write Python code for it?

l_aud.plot_topomap(times=[-0.2, 0.1, 0.4], average=0.05)


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
The file that we loaded has already been partially processed: 3D sensor
locations have been saved as part of the .fif file, the data have been
low-pass filtered at 40 Hz, and a common average reference is set for the
EEG channels, stored as a projector (see section-avg-ref-proj in the
tut-set-eeg-ref tutorial for more info about when you may want to do
this). We'll discuss how to do each of these below.
Since this is a combined EEG+MEG dataset, let's start by restricting the data
to just the EEG and EOG channels. This will cause the other projectors saved
in the file (which apply only to magnetometer channels) to be removed. By
looking at the measurement info we can see that we now have 59 EEG channels
and 1 EOG channel.
Can you write Python code for it?


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
The output shows that channel eeg55 had the maximum positive peak in
the chosen time window from all of the 'eeg' channels searched.
In practice, one might want to pull out the peak for
an a priori region of interest or a single channel depending on the study.
This can be done by combining the :meth:~mne.Evoked.pick
or :meth:~mne.Evoked.pick_channels methods with the
:meth:~mne.Evoked.get_peak method.
Here, let's assume we believe the effects of interest will occur
at eeg59.
Can you write Python code for it?

# Fist, return a copy of l_vis to select the channel from
l_vis_roi = l_vis.copy().pick('eeg59')

# Get the peak and latency measure from the selected channel
ch_roi, lat_roi, amp_roi = l_vis_roi.get_peak(
    tmin=good_tmin, tmax=good_tmax, mode='pos', return_amplitude=True)

# Print output
print('** PEAK MEASURES FOR ONE CHANNEL FROM A GOOD TIME WINDOW **')
print_peak_measures(ch_roi, good_tmin, good_tmax, lat_roi, amp_roi)


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
The tut-event-arrays tutorial discusses event arrays in more detail.
Integer event codes are mapped to more descriptive text using a Python
:class:dictionary <dict> usually called event_id. This mapping is
determined by your experiment code (i.e., it reflects which event codes you
chose to use to represent different experimental events or conditions). For
the sample-dataset data has the following mapping:
Can you write Python code for it?

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


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
These ~mne.Evoked objects have their own interactive plotting method
(though again, it won't be interactive on the documentation website):
click-dragging a span of time will generate a scalp field topography for that
time span. Here we also demonstrate built-in color-coding the channel traces
by location:
Can you write Python code for it?

fig1 = l_aud.plot()
fig2 = l_vis.plot(spatial_colors=True)


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
To plot the GFP by itself you can pass gfp='only' (this makes it easier
to read off the GFP data values, because the scale is aligned):
Can you write Python code for it?


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
We can also compare conditions by subtracting one ~mne.Evoked object from
another using the mne.combine_evoked function (this function also allows
pooling of epochs without subtraction).
Can you write Python code for it?

aud_minus_vis = mne.combine_evoked([l_aud, l_vis], weights=[1, -1])
aud_minus_vis.plot_joint()


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
We can select the auditory conditions (left and right together) by passing:
Can you write Python code for it?


I am working on the file "0.24/_downloads/299b3deaa8eb66e88d34f06090d06628/evoked_ers_source_power.ipynb".
The first task is:
Compute covariances
ERS activity starts at 0.5 seconds after stimulus onset. Because these
data have been processed by MaxFilter directly (rather than MNE-Python's
version), we have to be careful to compute the rank with a more conservative
threshold in order to get the correct data rank (64). Once this is used in
combination with an advanced covariance estimator like "shrunk", the rank
will be correctly preserved.
Can you write Python code for it?

rank = mne.compute_rank(epochs, tol=1e-6, tol_kind='relative')
active_win = (0.5, 1.5)
baseline_win = (-1, 0)
baseline_cov = compute_covariance(epochs, tmin=baseline_win[0],
                                  tmax=baseline_win[1], method='shrunk',
                                  rank=rank, verbose=True)
active_cov = compute_covariance(epochs, tmin=active_win[0], tmax=active_win[1],
                                method='shrunk', rank=rank, verbose=True)

# Weighted averaging is already in the addition of covariance objects.
common_cov = baseline_cov + active_cov
mne.viz.plot_cov(baseline_cov, epochs.info)


I am working on the file "0.24/_downloads/299b3deaa8eb66e88d34f06090d06628/evoked_ers_source_power.ipynb".
The first task is:
Plot source estimates
DICS:
Can you write Python code for it?

brain_dics = stc_dics.plot(
    hemi='rh', subjects_dir=subjects_dir, subject=subject,
    time_label='DICS source power in the 12-30 Hz frequency band')


I am working on the file "0.24/_downloads/299b3deaa8eb66e88d34f06090d06628/evoked_ers_source_power.ipynb".
The first task is:
dSPM:
Can you write Python code for it?

brain_dspm = stc_dspm.plot(
    hemi='rh', subjects_dir=subjects_dir, subject=subject,
    time_label='dSPM source power in the 12-30 Hz frequency band')


I am working on the file "0.24/_downloads/2d3a2ce4cdcb2dad9804801c80816516/parcellation.ipynb".
The first task is:
Plot a cortical parcellation
In this example, we download the HCP-MMP1.0 parcellation
:footcite:GlasserEtAl2016 and show it on fsaverage.
We will also download the customized 448-label aparc
parcellation from :footcite:KhanEtAl2018.

Note

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

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

Can you write Python code for it?

# Author: Eric Larson <larson.eric.d@gmail.com>
#         Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD-3-Clause

import mne
Brain = mne.viz.get_brain_class()

subjects_dir = mne.datasets.sample.data_path() + '/subjects'
mne.datasets.fetch_hcp_mmp_parcellation(subjects_dir=subjects_dir,
                                        verbose=True)

mne.datasets.fetch_aparc_sub_parcellation(subjects_dir=subjects_dir,
                                          verbose=True)

labels = mne.read_labels_from_annot(
    'fsaverage', 'HCPMMP1', 'lh', subjects_dir=subjects_dir)

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


I am working on the file "0.24/_downloads/2d3a2ce4cdcb2dad9804801c80816516/parcellation.ipynb".
The first task is:
We can add another custom parcellation
Can you write Python code for it?

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


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

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


I am working on the file "0.24/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Adding a ~mne.Forward solution
Forward solutions ("leadfields") can be added by passing a ~mne.Forward
object or the path to a forward solution stored on disk to
meth:mne.Report.add_forward.
Can you write Python code for it?

fwd_path = sample_dir / 'sample_audvis-meg-oct-6-fwd.fif'

report = mne.Report(title='Forward solution example')
report.add_forward(forward=fwd_path, title='Forward solution')
report.save('report_forward_sol.html', overwrite=True)


I am working on the file "0.24/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Adding a ~mne.SourceEstimate
An inverse solution (also called source estimate or source time course, STC)
can be added via :meth:mne.Report.add_stc. The
method expects an ~mne.SourceEstimate, the corresponding FreeSurfer subject
name and subjects directory, and a title. By default, it will produce
snapshots at 51 equally-spaced time points (or fewer, if the data contains
fewer time points). We can adjust this via the n_time_points parameter.
Can you write Python code for it?

stc_path = sample_dir / 'sample_audvis-meg'

report = mne.Report(title='Source estimate example')
report.add_stc(
    stc=stc_path, subject='sample', subjects_dir=subjects_dir,
    title='Source estimate', n_time_points=2  # few for speed
)
report.save('report_inverse_sol.html', overwrite=True)


I am working on the file "0.24/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Adding an ~mne.minimum_norm.InverseOperator
An inverse operator can be added via :meth:mne.Report.add_inverse_operator.
The method expects an ~mne.minimum_norm.InverseOperator object or a path to
one stored on disk, and a title.
Can you write Python code for it?

inverse_op_path = sample_dir / 'sample_audvis-meg-oct-6-meg-inv.fif'

report = mne.Report(title='Inverse operator example')
report.add_inverse_operator(
    inverse_operator=inverse_op_path, title='Inverse operator'
)
report.save('report_inverse_op.html', overwrite=True)


I am working on the file "0.24/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Adding coregistration
The head -> mri transformation (obtained by "coregistration") can be
visualized via :meth:mne.Report.add_trans. The method expects the
transformation either as a ~mne.transforms.Transform object or as a path to
a trans.fif file, the FreeSurfer subject name and subjects directory, and
a title.
Can you write Python code for it?

trans_path = sample_dir / 'sample_audvis_raw-trans.fif'

report = mne.Report(title='Coregistration example')
report.add_trans(
    trans=trans_path, info=raw_path, subject='sample',
    subjects_dir=subjects_dir, title='Coregistration'
)
report.save('report_coregistration.html', overwrite=True)


I am working on the file "0.24/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Adding custom figures
Custom Matplotlib figures can be added via :meth:~mne.Report.add_figure.
Required parameters are the figure and a title. Optionally, may add a caption
to appear below the figure. You can also specify the image format of the
image file that will be generated from the figure, so it can be embedded in
the HTML report.
Can you write Python code for it?

x = np.linspace(start=0, stop=10, num=100)
y = x**2

fig, ax = plt.subplots()
ax.plot(x, y, ls='--', lw=2, color='blue', label='my function')
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.legend()

report = mne.Report(title='Figure example')
report.add_figure(
    fig=fig, title='A custom figure',
    caption='A blue dashed line reaches up into the sky …',
    image_format='PNG'
)
report.save('report_custom_figure.html', overwrite=True)


I am working on the file "0.24/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Adding image files
Existing images (e.g., photos, screenshots, sketches etc.) can be added
to the report via :meth:mne.Report.add_image. Supported image formats
include JPEG, PNG, GIF, and SVG (and possibly others). Like with Matplotlib
figures, you can specify a caption to appear below the image.
Can you write Python code for it?

report = mne.Report(title='Image example')
report.add_image(
    image=mne_logo_path, title='MNE',
    caption='Powered by 🧠 🧠 🧠 around the world!'
)
report.save('report_custom_image.html', overwrite=True)


I am working on the file "0.24/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Adding ~mne.Covariance
(Noise) covariance objects can be added via
:meth:mne.Report.add_covariance. The method accepts ~mne.Covariance
objects and the path to a file on disk. It also expects us to pass an
~mne.Info object or the path to a file to read the measurement info from,
as well as a title.
Can you write Python code for it?

cov_path = sample_dir / 'sample_audvis-cov.fif'

report = mne.Report(title='Covariance example')
report.add_covariance(cov=cov_path, info=raw_path, title='Covariance')
report.save('report_cov.html', overwrite=True)


I am working on the file "0.24/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Adding ~mne.Evoked
Evoked data can be added via :meth:mne.Report.add_evokeds. By default, the
Evoked.comment attribute of each evoked will be used as a title. We can
specify custom titles via the titles parameter. Again, this method
also accepts the path to an evoked file stored on disk; in the following
example, however, we load the evokeds manually first, since we only want to
add a subset of them to the report. The evokeds are not baseline-corrected,
so we apply baseline correction, too. Lastly, by providing an (optional)
noise covariance, we can add plots evokeds that were "whitened" using this
covariance matrix.
By default, this method will produce snapshots at 21 equally-spaced time
points (or fewer, if the data contains fewer time points). We can adjust this
via the n_time_points parameter.
Can you write Python code for it?

evoked_path = sample_dir / 'sample_audvis-ave.fif'
cov_path = sample_dir / 'sample_audvis-cov.fif'

evokeds = mne.read_evokeds(evoked_path, baseline=(None, 0))
evokeds_subset = evokeds[:2]  # The first two
for evoked in evokeds_subset:
    evoked.pick('eeg')  # just for speed of plotting

report = mne.Report(title='Evoked example')
report.add_evokeds(
    evokeds=evokeds_subset,
    titles=['evoked 1',  # Manually specify titles
            'evoked 2'],
    noise_cov=cov_path,
    n_time_points=5
)
report.save('report_evoked.html', overwrite=True)


I am working on the file "0.24/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Adding ~mne.Projection vectors
~mne.Projection vectors can be added via
:meth:mne.Report.add_projs. The method requires an ~mne.Info object
(or the path to one) and a title. Projectors found in the ~mne.Info will
be visualized. You may also supply a list of ~mne.Projection objects or
a path to projectors stored on disk. In this case, the channel information
is read from the ~mne.Info, but projectors potentially included will be
ignored; instead, only the explicitly passed projectors will be plotted.
Can you write Python code for it?

ecg_proj_path = sample_dir / 'sample_audvis_ecg-proj.fif'
eog_proj_path = sample_dir / 'sample_audvis_eog-proj.fif'

report = mne.Report(title='Projectors example')
report.add_projs(info=raw_path, title='Projs from info')
report.add_projs(info=raw_path, projs=ecg_proj_path,
                 title='ECG projs from path')
report.add_projs(info=raw_path, projs=eog_proj_path,
                 title='EOG projs from path')
report.save('report_projs.html', overwrite=True)


I am working on the file "0.24/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Getting started with :class:mne.Report
mne.Report is a way to create interactive HTML summaries of your data. These
reports can show many different visualizations of one or multiple subject's
data. A common use case is creating diagnostic summaries to check data quality
at different stages in the processing pipeline. The report can show things like
plots of data before and after each preprocessing step, epoch rejection
statistics, MRI slices with overlaid BEM shells, all the way up to plots of
estimated cortical activity.
Compared to a Jupyter notebook, mne.Report is easier to deploy (the HTML
pages it generates are self-contained and do not require a running Python
environment) but less flexible (you can't change code and re-run something
directly within the browser). This tutorial covers the basics of building a
~mne.Report. As usual, we'll start by importing the modules and data we need:
Can you write Python code for it?

from pathlib import Path
import tempfile
import numpy as np
import scipy.ndimage
import matplotlib.pyplot as plt
import mne

data_path = Path(mne.datasets.sample.data_path(verbose=False))
sample_dir = data_path / 'MEG' / 'sample'
subjects_dir = data_path / 'subjects'


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

pattern = 'sample_audvis-cov.fif'
info_fname = sample_dir / 'sample_audvis-ave.fif'
report = mne.Report(title='parse_folder example 5', info_fname=info_fname)
report.parse_folder(
    data_path, pattern=pattern, render_bem=False, n_time_points_evokeds=5
)
report.save('report_parse_folder_cov.html', overwrite=True)


I am working on the file "0.24/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Now let's look at how :class:~mne.Report handles :class:~mne.Evoked
data (we will skip the MRIs to save computation time).
The MNE sample dataset we're using in this example has not been
baseline-corrected; so let's apply baseline correction this now for the
report!
To request baseline correction, pass a baseline argument to
~mne.Report, which should be a tuple with the starting and ending time of
the baseline period. For more details, see the documentation on
~mne.Evoked.apply_baseline. Here, we will apply baseline correction for a
baseline period from the beginning of the time interval to time point zero.
Lastly, we want to render the "whitened" evoked data, too. Whitening
requires us to specify the path to a covariance matrix file via the
cov_fname parameter of ~mne.Report.
Now, let's put all of this together! Here we use a temporary directory
for speed so we can render a single Evoked instance, using just EEG
channels.
Can you write Python code for it?

baseline = (None, 0)
cov_fname = sample_dir / 'sample_audvis-cov.fif'
pattern = 'sample_audvis-no-filter-ave.fif'
evoked = mne.read_evokeds(sample_dir / pattern)[0]
report = mne.Report(
    title='parse_folder example 4', baseline=baseline, cov_fname=cov_fname
)
with tempfile.TemporaryDirectory() as path:
    evoked.save(Path(path) / pattern)
    report.parse_folder(
        path, pattern=pattern, render_bem=False, n_time_points_evokeds=5
    )
report.save('report_parse_folder_evoked.html', overwrite=True)


I am working on the file "0.24/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
The saved report can be read back and modified or amended. This allows the
possibility to e.g. run multiple scripts in a processing pipeline, where each
script adds new content to an existing report.
Can you write Python code for it?

report_from_disk = mne.open_report('report_partial.hdf5')
report_from_disk.add_image(image=mne_logo_path, title='MNE 2')
report_from_disk.save('report_partial.hdf5', overwrite=True)


I am working on the file "0.24/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
To make this even easier, :class:mne.Report can be used as a
context manager (note the with statement)`):
Can you write Python code for it?

with mne.open_report('report_partial.hdf5') as report:
    report.add_image(image=mne_logo_path, title='MNE 3')
    report.save('report_final.html', overwrite=True)


I am working on the file "0.24/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
With the context manager, the updated report is also automatically saved
back to :file:report.h5 upon leaving the block.
Adding an entire folder of files
We also provide a way to add an entire folder of files to the report at
once, without having to invoke the individual add_* methods outlined
above for each file. This approach, while convenient, provides less
flexibility with respect to content ordering, tags, titles, etc.
For our first example, we'll generate a barebones report for all the
:file:.fif files containing raw data in the sample dataset, by passing the
pattern *raw.fif to :meth:~mne.Report.parse_folder. We'll omit the
subject and subjects_dir parameters from the :class:~mne.Report
constructor, but we'll also pass render_bem=False to the
:meth:~mne.Report.parse_folder method — otherwise we would get a warning
about not being able to render MRI and trans files without knowing the
subject. To save some processing time in this tutorial, we're also going to
disable rendering of the butterfly plots for the ~mne.io.Raw data by
passing raw_butterfly=False.
Which files are included depends on both the pattern parameter passed to
:meth:~mne.Report.parse_folder and also the subject and
subjects_dir parameters provided to the :class:~mne.Report constructor.
Can you write Python code for it?

report = mne.Report(title='parse_folder example')
report.parse_folder(
    data_path=data_path, pattern='*raw.fif', render_bem=False,
    raw_butterfly=False
)
report.save('report_parse_folder_basic.html', overwrite=True)


I am working on the file "0.24/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Working with tags
Each add_* method accepts a keyword parameter tags, which can be
used to pass one or more tags to associate with the respective content
elements. By default, each add_* method adds a tag describing the data
type, e.g., evoked or source-estimate. When viewing the HTML report,
the Filter by tags dropdown menu can be used to interactively show or
hide content with specific tags. This allows you e.g. to only view
evoked or participant-001 data, should you have added those tags.
Visible tags will appear with blue, and hidden tags with gray background
color.
To toggle the visibility of all tags, use the respective checkbox in the
Filter by tags dropdown menu, or press :kbd:T.
Can you write Python code for it?

report = mne.Report(title='Tags example')
report.add_image(
    image=mne_logo_path,
    title='MNE Logo',
    tags=('image', 'mne', 'logo', 'open-source')
)
report.save('report_tags.html', overwrite=True)


I am working on the file "0.24/_downloads/2dd868e4ea307404d807080fb341eb26/evoked_topomap.ipynb".
The first task is:
Animating the topomap
Instead of using a still image we can plot magnetometer data as an animation,
which animates properly only in matplotlib interactive mode.
Can you write Python code for it?

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


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


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

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

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

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

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


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

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


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

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


I am working on the file "0.24/_downloads/2dd868e4ea307404d807080fb341eb26/evoked_topomap.ipynb".
The first task is:
Or by manually picking the channels to highlight at different times:
Can you write Python code for it?

times = (0.09, 0.1, 0.11)
_times = ((np.abs(evoked.times - t)).argmin() for t in times)
significant_channels = [
    ('MEG 0231', 'MEG 1611', 'MEG 1621', 'MEG 1631', 'MEG 1811'),
    ('MEG 2411', 'MEG 2421'),
    ('MEG 1621')]
_channels = [np.in1d(evoked.ch_names, ch) for ch in significant_channels]

mask = np.zeros(evoked.data.shape, dtype='bool')
for _chs, _time in zip(_channels, _times):
    mask[_chs, _time] = True

evoked.plot_topomap(times, ch_type='mag', time_unit='s', mask=mask,
                    mask_params=dict(markersize=10, markerfacecolor='y'))


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

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


I am working on the file "0.24/_downloads/2dd868e4ea307404d807080fb341eb26/evoked_topomap.ipynb".
The first task is:
We can also highlight specific channels by adding a mask, to e.g. mark
channels exceeding a threshold at a given time:
Can you write Python code for it?

# Define a threshold and create the mask
mask = evoked.data > 1e-13

# Select times and plot
times = (0.09, 0.1, 0.11)
evoked.plot_topomap(times, ch_type='mag', time_unit='s', mask=mask,
                    mask_params=dict(markersize=10, markerfacecolor='y'))


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

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


I am working on the file "0.24/_downloads/2dd868e4ea307404d807080fb341eb26/evoked_topomap.ipynb".
The first task is:
sphinx_gallery_thumbnail_number = 5
Can you write Python code for it?

import numpy as np
import matplotlib.pyplot as plt

from mne.datasets import sample
from mne import read_evokeds

print(__doc__)

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

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


I am working on the file "0.24/_downloads/31239620dd9631320a99b07ac4a81074/interpolate_bad_channels.ipynb".
The first task is:
Compute interpolation (also works with Raw and Epochs objects)
Can you write Python code for it?

evoked_interp = evoked.copy().interpolate_bads(reset_bads=False)
evoked_interp.plot(exclude=[], picks=('grad', 'eeg'))


I am working on the file "0.24/_downloads/33d5dd5786fed13908838e94d55ac785/90_compute_covariance.ipynb".
The first task is:
Note that this method also attenuates any activity in your
source estimates that resemble the baseline, if you like it or not.
Can you write Python code for it?

noise_cov_baseline = mne.compute_covariance(epochs, tmax=0)


I am working on the file "0.24/_downloads/33d5dd5786fed13908838e94d55ac785/90_compute_covariance.ipynb".
The first task is:
The definition of noise depends on the paradigm. In MEG it is quite common
to use empty room measurements for the estimation of sensor noise. However if
you are dealing with evoked responses, you might want to also consider
resting state brain activity as noise.
First we compute the noise using empty room recording. Note that you can also
use only a part of the recording with tmin and tmax arguments. That can be
useful if you use resting state as a noise baseline. Here we use the whole
empty room recording to compute the noise covariance (tmax=None is the
same as the end of the recording, see :func:mne.compute_raw_covariance).
Keep in mind that you want to match your empty room dataset to your
actual MEG data, processing-wise. Ensure that filters
are all the same and if you use ICA, apply it to your empty-room and subject
data equivalently. In this case we did not filter the data and
we don't use ICA. However, we do have bad channels and projections in
the MEG data, and, hence, we want to make sure they get stored in the
covariance object.
Can you write Python code for it?

raw_empty_room.info['bads'] = [
    bb for bb in raw.info['bads'] if 'EEG' not in bb]
raw_empty_room.add_proj(
    [pp.copy() for pp in raw.info['projs'] if 'EEG' not in pp['desc']])

noise_cov = mne.compute_raw_covariance(
    raw_empty_room, tmin=0, tmax=None)


I am working on the file "0.24/_downloads/33d5dd5786fed13908838e94d55ac785/90_compute_covariance.ipynb".
The first task is:
This procedure evaluates the noise covariance quantitatively by how well it
whitens the data using the
negative log-likelihood of unseen data. The final result can also be visually
inspected.
Under the assumption that the baseline does not contain a systematic signal
(time-locked to the event of interest), the whitened baseline signal should
be follow a multivariate Gaussian distribution, i.e.,
whitened baseline signals should be between -1.96 and 1.96 at a given time
sample.
Based on the same reasoning, the expected value for the :term:global field
power (GFP) <GFP> is 1 (calculation of the GFP should take into account the
true degrees of freedom, e.g. ddof=3 with 2 active SSP vectors):
Can you write Python code for it?

evoked = epochs.average()
evoked.plot_white(noise_cov_reg, time_unit='s')


I am working on the file "0.24/_downloads/3bb9354e99617f5fdf32e50748fc566d/15_inplace.ipynb".
The first task is:
Channel picking
Another group of methods where data is modified in-place are the
channel-picking methods. For example:
Can you write Python code for it?

print(f'original data had {original_raw.info["nchan"]} channels.')
original_raw.pick('eeg')  # selects only the EEG channels
print(f'after picking, it has {original_raw.info["nchan"]} channels.')


I am working on the file "0.24/_downloads/3bb9354e99617f5fdf32e50748fc566d/15_inplace.ipynb".
The first task is:
Modifying data in-place
Many of MNE-Python's data objects (~mne.io.Raw, ~mne.Epochs, ~mne.Evoked,
etc) have methods that modify the data in-place (either optionally or
obligatorily). This can be advantageous when working with large datasets
because it reduces the amount of computer memory needed to perform the
computations. However, it can lead to unexpected results if you're not aware
that it's happening. This tutorial provides a few examples of in-place
processing, and how and when to avoid it.
As usual we'll start by importing the modules we need and
loading some example data <sample-dataset>:
Can you write Python code for it?

import os
import mne

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
# the preload flag loads the data into memory now
raw = mne.io.read_raw_fif(sample_data_raw_file, preload=True)
raw.crop(tmax=10.)  # raw.crop() always happens in-place


I am working on the file "0.24/_downloads/3bb9354e99617f5fdf32e50748fc566d/15_inplace.ipynb".
The first task is:
Note also that when picking only EEG channels, projectors that affected only
the magnetometers were dropped, since there are no longer any magnetometer
channels.
The copy parameter
Above we saw an example of using the ~mne.io.Raw.copy method to facilitate
comparing data before and after processing. This is not needed when using
certain MNE-Python functions, because they have a function parameter
where you can specify copy=True (return a modified copy of the data) or
copy=False (operate in-place). For example, mne.set_eeg_reference is
one such function; notice that here we plot original_raw after the
rereferencing has been done, but original_raw is unaffected because
we specified copy=True:
Can you write Python code for it?

rereferenced_raw, ref_data = mne.set_eeg_reference(original_raw, ['EEG 003'],
                                                   copy=True)
original_raw.plot()
rereferenced_raw.plot()


I am working on the file "0.24/_downloads/3bb9354e99617f5fdf32e50748fc566d/15_inplace.ipynb".
The first task is:
Signal processing
Most MNE-Python data objects have built-in methods for filtering, including
high-, low-, and band-pass filters (~mne.io.Raw.filter), band-stop filters
(~mne.io.Raw.notch_filter),
Hilbert transforms (~mne.io.Raw.apply_hilbert),
and even arbitrary or user-defined functions (~mne.io.Raw.apply_function).
These typically always modify data in-place, so if we want to preserve
the unprocessed data for comparison, we must first make a copy of it. For
example:
Can you write Python code for it?

original_raw = raw.copy()
raw.apply_hilbert()
print(f'original data type was {original_raw.get_data().dtype}, after '
      f'apply_hilbert the data type changed to {raw.get_data().dtype}.')


I am working on the file "0.24/_downloads/3d564af6b3f1e758cf01cd38abefd45f/50_epochs_to_data_frame.ipynb".
The first task is:
Converting an Epochs object to a DataFrame
Once we have our :class:~mne.Epochs object, converting it to a
:class:~pandas.DataFrame is simple: just call :meth:epochs.to_data_frame()
<mne.Epochs.to_data_frame>. Each channel's data will be a column of the new
:class:~pandas.DataFrame, alongside three additional columns of event name,
epoch number, and sample time. Here we'll just show the first few rows and
columns:
Can you write Python code for it?

df = epochs.to_data_frame()
df.iloc[:5, :10]


I am working on the file "0.24/_downloads/3d564af6b3f1e758cf01cd38abefd45f/50_epochs_to_data_frame.ipynb".
The first task is:
Exporting Epochs to Pandas DataFrames
This tutorial shows how to export the data in :class:~mne.Epochs objects to a
:class:Pandas DataFrame <pandas.DataFrame>, and applies a typical Pandas
:doc:split-apply-combine <pandas:user_guide/groupby> workflow to examine the
latencies of the response maxima across epochs and conditions.
We'll use the sample-dataset dataset, but load a version of the raw file
that has already been filtered and downsampled, and has an average reference
applied to its EEG channels. As usual we'll start by importing the modules we
need and loading the data:
Can you write Python code for it?

import os
import seaborn as sns
import mne

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


I am working on the file "0.24/_downloads/3d564af6b3f1e758cf01cd38abefd45f/50_epochs_to_data_frame.ipynb".
The first task is:
Generating the :class:~pandas.DataFrame in long format can be helpful when
using other Python modules for subsequent analysis or plotting. For example,
here we'll take data from the "auditory/left" condition, pick a couple MEG
channels, and use :func:seaborn.lineplot to automatically plot the mean and
confidence band for each channel, with confidence computed across the epochs
in the chosen condition:
Can you write Python code for it?

channels = ['MEG 1332', 'MEG 1342']
data = long_df.loc['auditory/left'].query('channel in @channels')
# convert channel column (CategoryDtype → string; for a nicer-looking legend)
data['channel'] = data['channel'].astype(str)
sns.lineplot(x='time', y='value', hue='channel', data=data)


I am working on the file "0.24/_downloads/3d564af6b3f1e758cf01cd38abefd45f/50_epochs_to_data_frame.ipynb".
The first task is:
Next we'll load a list of events from file, map them to condition names with
an event dictionary, set some signal rejection thresholds (cf.
tut-reject-epochs-section), and segment the continuous data into
epochs:
Can you write Python code for it?

sample_data_events_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                       'sample_audvis_filt-0-40_raw-eve.fif')
events = mne.read_events(sample_data_events_file)

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

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

tmin, tmax = (-0.2, 0.5)  # epoch from 200 ms before event to 500 ms after it
baseline = (None, 0)      # baseline period from start of epoch to time=0

epochs = mne.Epochs(raw, events, event_dict, tmin, tmax, proj=True,
                    baseline=baseline, reject=reject_criteria, preload=True)
del raw


I am working on the file "0.24/_downloads/3d564af6b3f1e758cf01cd38abefd45f/50_epochs_to_data_frame.ipynb".
The first task is:
Notice that the time values are no longer integers, and the channel values
have changed by several orders of magnitude compared to the earlier
DataFrame.
Setting the index
It is also possible to move one or more of the indicator columns (event name,
epoch number, and sample time) into the index <pandas:indexing>, by
passing a string or list of strings as the index parameter. We'll also
demonstrate here the effect of time_format='timedelta', yielding
:class:~pandas.Timedelta values in the "time" column.
Can you write Python code for it?

df = epochs.to_data_frame(index=['condition', 'epoch'],
                          time_format='timedelta')
df.iloc[:5, :10]


I am working on the file "0.24/_downloads/3d564af6b3f1e758cf01cd38abefd45f/50_epochs_to_data_frame.ipynb".
The first task is:
Scaling time and channel values
By default, time values are converted from seconds to milliseconds and
then rounded to the nearest integer; if you don't want this, you can pass
time_format=None to keep time as a :class:float value in seconds, or
convert it to a :class:~pandas.Timedelta value via
time_format='timedelta'.
Note also that, by default, channel measurement values are scaled so that EEG
data are converted to µV, magnetometer data are converted to fT, and
gradiometer data are converted to fT/cm. These scalings can be customized
through the scalings parameter, or suppressed by passing
scalings=dict(eeg=1, mag=1, grad=1).
Can you write Python code for it?

df = epochs.to_data_frame(time_format=None,
                          scalings=dict(eeg=1, mag=1, grad=1))
df.iloc[:5, :10]


I am working on the file "0.24/_downloads/3d564af6b3f1e758cf01cd38abefd45f/50_epochs_to_data_frame.ipynb".
The first task is:
We can also now use all the power of Pandas for grouping and transforming our
data. Here, we find the latency of peak activation of 2 gradiometers (one
near auditory cortex and one near visual cortex), and plot the distribution
of the timing of the peak in each channel as a :func:~seaborn.violinplot:
Can you write Python code for it?

df = epochs.to_data_frame(time_format=None)
peak_latency = (df.filter(regex=r'condition|epoch|MEG 1332|MEG 2123')
                .groupby(['condition', 'epoch'])
                .aggregate(lambda x: df['time'].iloc[x.idxmax()])
                .reset_index()
                .melt(id_vars=['condition', 'epoch'],
                      var_name='channel',
                      value_name='latency of peak')
                )

ax = sns.violinplot(x='channel', y='latency of peak', hue='condition',
                    data=peak_latency, palette='deep', saturation=1)


I am working on the file "0.24/_downloads/3d564af6b3f1e758cf01cd38abefd45f/50_epochs_to_data_frame.ipynb".
The first task is:
Wide- versus long-format DataFrames
Another parameter, long_format, determines whether each channel's data
is in a separate column of the :class:~pandas.DataFrame
(long_format=False), or whether the measured values are pivoted into a
single 'value' column with an extra indicator column for the channel name
(long_format=True). Passing long_format=True will also create an
extra column ch_type indicating the channel type.
Can you write Python code for it?

long_df = epochs.to_data_frame(time_format=None, index='condition',
                               long_format=True)
long_df.head()


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

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

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

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

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

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

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


I am working on the file "0.24/_downloads/48e14d460d6470997b890b156746a671/30_strf.ipynb".
The first task is:
Load audio data
We'll read in the audio data from :footcite:CrosseEtAl2016 in order to
simulate a response.
In addition, we'll downsample the data along the time dimension in order to
speed up computation. Note that depending on the input values, this may
not be desired. For example if your input stimulus varies more quickly than
1/2 the sampling rate to which we are downsampling.
Can you write Python code for it?

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


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

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


I am working on the file "0.24/_downloads/48e14d460d6470997b890b156746a671/30_strf.ipynb".
The first task is:
Spectro-temporal receptive field (STRF) estimation on continuous data
This demonstrates how an encoding model can be fit with multiple continuous
inputs. In this case, we simulate the model behind a spectro-temporal receptive
field (or STRF). First, we create a linear filter that maps patterns in
spectro-temporal space onto an output, representing neural activity. We fit
a receptive field model that attempts to recover the original linear filter
that was used to create this data.
Can you write Python code for it?

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

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.decoding import ReceptiveField, TimeDelayingRidge

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


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

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

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

ix_best_alpha_lap = np.argmax(scores_lap)


I am working on the file "0.24/_downloads/499a81f33500445fc2e1eac0be346d47/temporal_whitening.ipynb".
The first task is:
Plot the different time series and PSDs
Can you write Python code for it?

plt.close('all')
plt.figure()
plt.plot(d[:100], label='signal')
plt.plot(d_[:100], label='regenerated signal')
plt.legend()

plt.figure()
plt.psd(d, Fs=raw.info['sfreq'], NFFT=2048)
plt.psd(innovation, Fs=raw.info['sfreq'], NFFT=2048)
plt.psd(d_, Fs=raw.info['sfreq'], NFFT=2048, linestyle='--')
plt.legend(('Signal', 'Innovation', 'Regenerated signal'))
plt.show()


I am working on the file "0.24/_downloads/499a81f33500445fc2e1eac0be346d47/temporal_whitening.ipynb".
The first task is:
Temporal whitening with AR model
Here we fit an AR model to the data and use it
to temporally whiten the signals.
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 signal
import matplotlib.pyplot as plt

import mne
from mne.time_frequency import fit_iir_model_raw
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
proj_fname = data_path + '/MEG/sample/sample_audvis_ecg-proj.fif'

raw = mne.io.read_raw_fif(raw_fname)
proj = mne.read_proj(proj_fname)
raw.add_proj(proj)
raw.info['bads'] = ['MEG 2443', 'EEG 053']  # mark bad channels

# Set up pick list: Gradiometers - bad channels
picks = mne.pick_types(raw.info, meg='grad', exclude='bads')

order = 5  # define model order
picks = picks[:1]

# Estimate AR models on raw data
b, a = fit_iir_model_raw(raw, order=order, picks=picks, tmin=60, tmax=180)
d, times = raw[0, 10000:20000]  # look at one channel from now on
d = d.ravel()  # make flat vector
innovation = signal.convolve(d, a, 'valid')
d_ = signal.lfilter(b, a, innovation)  # regenerate the signal
d_ = np.r_[d_[0] * np.ones(order), d_]  # dummy samples to keep signal length


I am working on the file "0.24/_downloads/4a4a8e5bd5ae7cafea93a04d8c0a0d00/psf_ctf_vertices_lcmv.ipynb".
The first task is:
Compute LCMV filters with different data covariance matrices
Can you write Python code for it?

# compute LCMV beamformer filters for pre-stimulus interval
filters_pre = make_lcmv(info, forward, cov_pre, reg=0.05,
                        noise_cov=noise_cov,
                        pick_ori=None, rank=None,
                        weight_norm=None,
                        reduce_rank=False,
                        verbose=False)

# compute LCMV beamformer filters for post-stimulus interval
filters_post = make_lcmv(info, forward, cov_post, reg=0.05,
                         noise_cov=noise_cov,
                         pick_ori=None, rank=None,
                         weight_norm=None,
                         reduce_rank=False,
                         verbose=False)


I am working on the file "0.24/_downloads/4a4a8e5bd5ae7cafea93a04d8c0a0d00/psf_ctf_vertices_lcmv.ipynb".
The first task is:
Compute resolution matrices for the two LCMV beamformers
Can you write Python code for it?

# compute cross-talk functions (CTFs) for one target vertex
sources = [3000]
verttrue = [forward['src'][0]['vertno'][sources[0]]]  # pick one vertex
rm_pre = make_lcmv_resolution_matrix(filters_pre, forward, info)
stc_pre = get_cross_talk(rm_pre, forward['src'], sources, norm=True)
del rm_pre

rm_post = make_lcmv_resolution_matrix(filters_post, forward, info)
stc_post = get_cross_talk(rm_post, forward['src'], sources, norm=True)
del rm_post


I am working on the file "0.24/_downloads/4a4a8e5bd5ae7cafea93a04d8c0a0d00/psf_ctf_vertices_lcmv.ipynb".
The first task is:
Visualize
Pre:
Can you write Python code for it?

brain_pre = stc_pre.plot('sample', 'inflated', 'lh', subjects_dir=subjects_dir,
                         figure=1, clim=dict(kind='value', lims=(0, .2, .4)))

brain_pre.add_text(0.1, 0.9, 'LCMV beamformer with pre-stimulus\ndata '
                   'covariance matrix', 'title', font_size=16)

# mark true source location for CTFs
brain_pre.add_foci(verttrue, coords_as_verts=True, scale_factor=1., hemi='lh',
                   color='green')


I am working on the file "0.24/_downloads/4d3b714a9291625bb4b01d7f9c7c3a16/compute_source_psd_epochs.ipynb".
The first task is:
Compute Power Spectral Density of inverse solution from single epochs
Compute PSD of dSPM inverse solution on single trial epochs restricted
to a brain label. The PSD is computed using a multi-taper method with
Discrete Prolate Spheroidal Sequence (DPSS) windows.
Can you write Python code for it?

# Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#
# License: BSD-3-Clause

import matplotlib.pyplot as plt

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

print(__doc__)

data_path = sample.data_path()
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_raw = data_path + '/MEG/sample/sample_audvis_raw.fif'
fname_event = data_path + '/MEG/sample/sample_audvis_raw-eve.fif'
label_name = 'Aud-lh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name
subjects_dir = data_path + '/subjects'

event_id, tmin, tmax = 1, -0.2, 0.5
snr = 1.0  # use smaller SNR for raw data
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

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

# Set up pick list
include = []
raw.info['bads'] += ['EEG 053']  # bads + 1 more

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

# define frequencies of interest
fmin, fmax = 0., 70.
bandwidth = 4.  # bandwidth of the windows in Hz


I am working on the file "0.24/_downloads/4d3b714a9291625bb4b01d7f9c7c3a16/compute_source_psd_epochs.ipynb".
The first task is:
Compute source space PSD in label
..note:: By using "return_generator=True" stcs will be a generator object
         instead of a list. This allows us so to iterate without having to
         keep everything in memory.
Can you write Python code for it?

n_epochs_use = 10
stcs = compute_source_psd_epochs(epochs[:n_epochs_use], inverse_operator,
                                 lambda2=lambda2,
                                 method=method, fmin=fmin, fmax=fmax,
                                 bandwidth=bandwidth, label=label,
                                 return_generator=True, verbose=True)

# compute average PSD over the first 10 epochs
psd_avg = 0.
for i, stc in enumerate(stcs):
    psd_avg += stc.data
psd_avg /= n_epochs_use
freqs = stc.times  # the frequencies are stored here
stc.data = psd_avg  # overwrite the last epoch's data with the average


I am working on the file "0.24/_downloads/4d3b714a9291625bb4b01d7f9c7c3a16/compute_source_psd_epochs.ipynb".
The first task is:
Visualize the 10 Hz PSD:
Can you write Python code for it?

brain = stc.plot(initial_time=10., hemi='lh', views='lat',  # 10 HZ
                 clim=dict(kind='value', lims=(20, 40, 60)),
                 smoothing_steps=3, subjects_dir=subjects_dir)
brain.add_label(label, borders=True, color='k')


I am working on the file "0.24/_downloads/511c644e95ae48be8cf394cec24a1865/80_brainstorm_phantom_elekta.ipynb".
The first task is:
Brainstorm Elekta phantom dataset tutorial
Here we compute the evoked from raw for the Brainstorm Elekta phantom
tutorial dataset. For comparison, see :footcite:TadelEtAl2011 and
the original Brainstorm tutorial
<https://neuroimage.usc.edu/brainstorm/Tutorials/PhantomElekta>__.
Can you write Python code for it?

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

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

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

print(__doc__)


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

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


I am working on the file "0.24/_downloads/511c644e95ae48be8cf394cec24a1865/80_brainstorm_phantom_elekta.ipynb".
The first task is:
Do a quick visualization of how much variance we explained, putting the
data and residuals on the same scale (here the "time points" are the
32 dipole peak values that we fit):
Can you write Python code for it?

fig, axes = plt.subplots(2, 1)
evoked.plot(axes=axes)
for ax in axes:
    for text in list(ax.texts):
        text.remove()
    for line in ax.lines:
        line.set_color('#98df81')
residual.plot(axes=axes)


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

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

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


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

actual_amp = np.ones(len(dip))  # misc amp to create Dipole instance
actual_gof = np.ones(len(dip))  # misc GOF to create Dipole instance
dip_true = \
    mne.Dipole(dip.times, actual_pos, actual_amp, actual_ori, actual_gof)

fig = mne.viz.plot_alignment(
    evoked.info, trans, subject, bem=sphere, surfaces={'head-dense': 0.2},
    coord_frame='head', meg='helmet', show_axes=True,
    subjects_dir=subjects_dir)

# Plot the position and the orientation of the actual dipole
fig = mne.viz.plot_dipole_locations(dipoles=dip_true, mode='arrow',
                                    subject=subject, color=(0., 0., 0.),
                                    fig=fig)

# Plot the position and the orientation of the estimated dipole
fig = mne.viz.plot_dipole_locations(dipoles=dip, mode='arrow', subject=subject,
                                    color=(0.2, 1., 0.5), fig=fig)

mne.viz.set_3d_view(figure=fig, azimuth=70, elevation=80, distance=0.5)


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

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

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

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

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

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

fig.tight_layout()
plt.show()


I am working on the file "0.24/_downloads/511c644e95ae48be8cf394cec24a1865/80_brainstorm_phantom_elekta.ipynb".
The first task is:
Now we epoch our data, average it, and look at the first dipole response.
The first peak appears around 3 ms. Because we low-passed at 40 Hz,
we can also decimate our data to save memory.
Can you write Python code for it?

tmin, tmax = -0.1, 0.1
bmax = -0.05  # Avoid capture filter ringing into baseline
event_id = list(range(1, 33))
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, baseline=(None, bmax),
                    preload=False)
epochs['1'].average().plot(time_unit='s')


I am working on the file "0.24/_downloads/51cca4c9f4bd40623cb6bfa890e2eb4b/20_erp_stats.ipynb".
The first task is:
Absent specific hypotheses, we can also conduct an exploratory
mass-univariate analysis at all sensors and time points. This requires
correcting for multiple tests.
MNE offers various methods for this; amongst them, cluster-based permutation
methods allow deriving power from the spatio-temoral correlation structure
of the data. Here, we use TFCE.
Can you write Python code for it?

# Calculate adjacency matrix between sensors from their locations
adjacency, _ = find_ch_adjacency(epochs.info, "eeg")

# Extract data: transpose because the cluster test requires channels to be last
# In this case, inference is done over items. In the same manner, we could
# also conduct the test over, e.g., subjects.
X = [long_words.get_data().transpose(0, 2, 1),
     short_words.get_data().transpose(0, 2, 1)]
tfce = dict(start=.4, step=.4)  # ideally start and step would be smaller

# Calculate statistical thresholds
t_obs, clusters, cluster_pv, h0 = spatio_temporal_cluster_test(
    X, tfce, adjacency=adjacency,
    n_permutations=100)  # a more standard number would be 1000+
significant_points = cluster_pv.reshape(t_obs.shape).T < .05
print(str(significant_points.sum()) + " points selected by TFCE ...")


I am working on the file "0.24/_downloads/51cca4c9f4bd40623cb6bfa890e2eb4b/20_erp_stats.ipynb".
The first task is:
Visualising statistical significance thresholds on EEG data
MNE-Python provides a range of tools for statistical hypothesis testing
and the visualisation of the results. Here, we show a few options for
exploratory and confirmatory tests - e.g., targeted t-tests, cluster-based
permutation approaches (here with Threshold-Free Cluster Enhancement);
and how to visualise the results.
The underlying data comes from :footcite:DufauEtAl2015; we contrast long vs.
short words. TFCE is described in :footcite:SmithNichols2009.
Can you write Python code for it?

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

import mne
from mne.channels import find_ch_adjacency, make_1020_channel_selections
from mne.stats import spatio_temporal_cluster_test

np.random.seed(0)

# Load the data
path = mne.datasets.kiloword.data_path() + '/kword_metadata-epo.fif'
epochs = mne.read_epochs(path)
# These data are quite smooth, so to speed up processing we'll (unsafely!) just
# decimate them
epochs.decimate(4, verbose='error')
name = "NumberOfLetters"

# Split up the data by the median length in letters via the attached metadata
median_value = str(epochs.metadata[name].median())
long_words = epochs[name + " > " + median_value]
short_words = epochs[name + " < " + median_value]


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

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


I am working on the file "0.24/_downloads/524b9a6067f1a7bd3b66aa385465b921/20_source_alignment.ipynb".
The first task is:
Defining the head↔MRI trans using the GUI
You can try creating the head↔MRI transform yourself using
:func:mne.gui.coregistration.

First you must load the digitization data from the raw file
  (Head Shape Source). The MRI data is already loaded if you provide the
  subject and subjects_dir. Toggle Always Show Head Points to see
  the digitization points.
To set the landmarks, toggle Edit radio button in MRI Fiducials.
Set the landmarks by clicking the radio button (LPA, Nasion, RPA) and then
  clicking the corresponding point in the image.
After doing this for all the landmarks, toggle Lock radio button. You
  can omit outlier points, so that they don't interfere with the finetuning.

.. note:: You can save the fiducials to a file and pass
            mri_fiducials=True to plot them in
            :func:mne.viz.plot_alignment. The fiducials are saved to the
            subject's bem folder by default.
* Click Fit Head Shape. This will align the digitization points to the
  head surface. Sometimes the fitting algorithm doesn't find the correct
  alignment immediately. You can try first fitting using LPA/RPA or fiducials
  and then align according to the digitization. You can also finetune
  manually with the controls on the right side of the panel.
* Click Save As... (lower right corner of the panel), set the filename
  and read it with :func:mne.read_trans.
For more information, see step by step instructions
in these slides
<https://www.slideshare.net/mne-python/mnepython-coregistration>_.
Uncomment the following line to align the data yourself.
Can you write Python code for it?


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

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

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

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

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


I am working on the file "0.24/_downloads/548b4fc45f1ed79527138879cd79d3c8/muscle_detection.ipynb".
The first task is:
Annotate muscle artifacts
Muscle contractions produce high frequency activity that can mask brain signal
of interest. Muscle artifacts can be produced when clenching the jaw,
swallowing, or twitching a cranial muscle. Muscle artifacts are most
noticeable in the range of 110-140 Hz.
This example uses :func:~mne.preprocessing.annotate_muscle_zscore to annotate
segments where muscle activity is likely present. This is done by band-pass
filtering the data in the 110-140 Hz range. Then, the envelope is taken using
the hilbert analytical signal to only consider the absolute amplitude and not
the phase of the high frequency signal. The envelope is z-scored and summed
across channels and divided by the square root of the number of channels.
Because muscle artifacts last several hundred milliseconds, a low-pass filter
is applied on the averaged z-scores at 4 Hz, to remove transient peaks.
Segments above a set threshold are annotated as BAD_muscle. In addition,
the min_length_good parameter determines the cutoff for whether short
spans of "good data" in between muscle artifacts are included in the
surrounding "BAD" annotation.
Can you write Python code for it?

# Authors: Adonay Nunes <adonay.s.nunes@gmail.com>
#          Luke Bloy <luke.bloy@gmail.com>
# License: BSD-3-Clause

import os.path as op
import matplotlib.pyplot as plt
import numpy as np
from mne.datasets.brainstorm import bst_auditory
from mne.io import read_raw_ctf
from mne.preprocessing import annotate_muscle_zscore

# Load data
data_path = bst_auditory.data_path()
raw_fname = op.join(data_path, 'MEG', 'bst_auditory', 'S01_AEF_20131218_01.ds')

raw = read_raw_ctf(raw_fname, preload=False)

raw.crop(130, 160).load_data()  # just use a fraction of data for speed here
raw.resample(300, npad="auto")


I am working on the file "0.24/_downloads/548b4fc45f1ed79527138879cd79d3c8/muscle_detection.ipynb".
The first task is:
Notch filter the data:

Note

If line noise is present, you should perform notch-filtering *before*
    detecting muscle artifacts. See `tut-section-line-noise` for an
    example.

Can you write Python code for it?

raw.notch_filter([50, 100])

# The threshold is data dependent, check the optimal threshold by plotting
# ``scores_muscle``.
threshold_muscle = 5  # z-score
# Choose one channel type, if there are axial gradiometers and magnetometers,
# select magnetometers as they are more sensitive to muscle activity.
annot_muscle, scores_muscle = annotate_muscle_zscore(
    raw, ch_type="mag", threshold=threshold_muscle, min_length_good=0.2,
    filter_freq=[110, 140])


I am working on the file "0.24/_downloads/548b4fc45f1ed79527138879cd79d3c8/muscle_detection.ipynb".
The first task is:
View the annotations
Can you write Python code for it?

order = np.arange(144, 164)
raw.set_annotations(annot_muscle)
raw.plot(start=5, duration=20, order=order)


I am working on the file "0.24/_downloads/568aae18ec92d284aff29cfb5f3c11e7/resolution_metrics.ipynb".
The first task is:
And dSPM:
Can you write Python code for it?

brain_sd_dspm = sd_dspm_psf.plot('sample', 'inflated', 'lh',
                                 subjects_dir=subjects_dir, figure=5,
                                 clim=dict(kind='value', lims=(0, 2, 4)))
brain_sd_dspm.add_text(0.1, 0.9, 'SD dSPM', 'title', font_size=16)


brain_ple_dspm = ple_dspm_psf.plot('sample', 'inflated', 'lh',
                                   subjects_dir=subjects_dir, figure=2,
                                   clim=dict(kind='value', lims=(0, 2, 4)))
brain_ple_dspm.add_text(0.1, 0.9, 'PLE dSPM', 'title', font_size=16)


I am working on the file "0.24/_downloads/568aae18ec92d284aff29cfb5f3c11e7/resolution_metrics.ipynb".
The first task is:
MNE
Compute resolution matrices, peak localisation error (PLE) for point spread
functions (PSFs), spatial deviation (SD) for PSFs:
Can you write Python code for it?

rm_mne = make_inverse_resolution_matrix(forward, inverse_operator,
                                        method='MNE', lambda2=lambda2)
ple_mne_psf = resolution_metrics(rm_mne, inverse_operator['src'],
                                 function='psf', metric='peak_err')
sd_mne_psf = resolution_metrics(rm_mne, inverse_operator['src'],
                                function='psf', metric='sd_ext')
del rm_mne


I am working on the file "0.24/_downloads/568aae18ec92d284aff29cfb5f3c11e7/resolution_metrics.ipynb".
The first task is:
Subtract the two distributions and plot this difference:
Can you write Python code for it?

diff_sd = sd_mne_psf - sd_dspm_psf

brain_sd_diff = diff_sd.plot('sample', 'inflated', 'lh',
                             subjects_dir=subjects_dir, figure=6,
                             clim=dict(kind='value', pos_lims=(0., 1., 2.)))
brain_sd_diff.add_text(0.1, 0.9, 'SD MNE-dSPM', 'title', font_size=16)


I am working on the file "0.24/_downloads/568aae18ec92d284aff29cfb5f3c11e7/resolution_metrics.ipynb".
The first task is:
Visualize results
Visualise peak localisation error (PLE) across the whole cortex for MNE PSF:
Can you write Python code for it?

brain_ple_mne = ple_mne_psf.plot('sample', 'inflated', 'lh',
                                 subjects_dir=subjects_dir, figure=1,
                                 clim=dict(kind='value', lims=(0, 2, 4)))
brain_ple_mne.add_text(0.1, 0.9, 'PLE MNE', 'title', font_size=16)


I am working on the file "0.24/_downloads/5ac2a3ff8baa6aba4bf6dd1d047703e2/spm_faces_dataset_sgskip.ipynb".
The first task is:
Compute forward model
Can you write Python code for it?

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(contrast.info, trans_fname, src, bem)


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

snr = 3.0
lambda2 = 1.0 / snr ** 2
method = 'dSPM'

inverse_operator = make_inverse_operator(contrast.info, forward, noise_cov,
                                         loose=0.2, depth=0.8)

# Compute inverse solution on contrast
stc = apply_inverse(contrast, inverse_operator, lambda2, method, pick_ori=None)
# stc.save('spm_%s_dSPM_inverse' % contrast.comment)

# Plot contrast in 3D with mne.viz.Brain if available
brain = stc.plot(hemi='both', subjects_dir=subjects_dir, initial_time=0.170,
                 views=['ven'], clim={'kind': 'value', 'lims': [3., 6., 9.]})
# brain.save_image('dSPM_map.png')


I am working on the file "0.24/_downloads/5ac2a3ff8baa6aba4bf6dd1d047703e2/spm_faces_dataset_sgskip.ipynb".
The first task is:
Load and filter data, set up epochs
Can you write Python code for it?

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

raw = io.read_raw_ctf(raw_fname % 1, preload=True)  # Take first run
# Here to save memory and time we'll downsample heavily -- this is not
# advised for real data as it can effectively jitter events!
raw.resample(120., npad='auto')

picks = mne.pick_types(raw.info, meg=True, exclude='bads')
raw.filter(1, 30, method='fir', fir_design='firwin')

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

# plot the events to get an idea of the paradigm
mne.viz.plot_events(events, raw.info['sfreq'])

event_ids = {"faces": 1, "scrambled": 2}

tmin, tmax = -0.2, 0.6
baseline = None  # no baseline as high-pass is applied
reject = dict(mag=5e-12)

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

# Fit ICA, find and remove major artifacts
ica = ICA(n_components=0.95, max_iter='auto', random_state=0)
ica.fit(raw, decim=1, reject=reject)

# compute correlation scores, get bad indices sorted by score
eog_epochs = create_eog_epochs(raw, ch_name='MRT31-2908', reject=reject)
eog_inds, eog_scores = ica.find_bads_eog(eog_epochs, ch_name='MRT31-2908')
ica.plot_scores(eog_scores, eog_inds)  # see scores the selection is based on
ica.plot_components(eog_inds)  # view topographic sensitivity of components
ica.exclude += eog_inds[:1]  # we saw the 2nd ECG component looked too dipolar
ica.plot_overlay(eog_epochs.average())  # inspect artifact removal
ica.apply(epochs)  # clean data, default in place

evoked = [epochs[k].average() for k in event_ids]

contrast = combine_evoked(evoked, weights=[-1, 1])  # Faces - scrambled

evoked.append(contrast)

for e in evoked:
    e.plot(ylim=dict(mag=[-400, 400]))

plt.show()

# estimate noise covarariance
noise_cov = mne.compute_covariance(epochs, tmax=0, method='shrunk',
                                   rank=None)


I am working on the file "0.24/_downloads/5b9edf9c05aec2b9bb1f128f174ca0f3/40_cluster_1samp_time_freq.ipynb".
The first task is:
Compute statistic
Can you write Python code for it?

threshold = 3.
n_permutations = 50  # Warning: 50 is way too small for real-world analysis.
T_obs, clusters, cluster_p_values, H0 = \
    permutation_cluster_1samp_test(epochs_power, n_permutations=n_permutations,
                                   threshold=threshold, tail=0,
                                   adjacency=adjacency,
                                   out_type='mask', verbose=True)


I am working on the file "0.24/_downloads/5b9edf9c05aec2b9bb1f128f174ca0f3/40_cluster_1samp_time_freq.ipynb".
The first task is:
Define adjacency for statistics
To compute a cluster-corrected value, we need a suitable definition
for the adjacency/adjacency of our values. So we first compute the
sensor adjacency, then combine that with a grid/lattice adjacency
assumption for the time-frequency plane:
Can you write Python code for it?

sensor_adjacency, ch_names = mne.channels.find_ch_adjacency(
    tfr_epochs.info, 'grad')
# Subselect the channels we are actually using
use_idx = [ch_names.index(ch_name.replace(' ', ''))
           for ch_name in tfr_epochs.ch_names]
sensor_adjacency = sensor_adjacency[use_idx][:, use_idx]
assert sensor_adjacency.shape == \
    (len(tfr_epochs.ch_names), len(tfr_epochs.ch_names))
assert epochs_power.data.shape == (
    len(epochs), len(tfr_epochs.ch_names),
    len(tfr_epochs.freqs), len(tfr_epochs.times))
adjacency = mne.stats.combine_adjacency(
    sensor_adjacency, len(tfr_epochs.freqs), len(tfr_epochs.times))

# our adjacency is square with each dim matching the data size
assert adjacency.shape[0] == adjacency.shape[1] == \
    len(tfr_epochs.ch_names) * len(tfr_epochs.freqs) * len(tfr_epochs.times)


I am working on the file "0.24/_downloads/5b9edf9c05aec2b9bb1f128f174ca0f3/40_cluster_1samp_time_freq.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'
tmin, tmax, event_id = -0.3, 0.6, 1

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

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

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

# Load condition 1
event_id = 1
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), preload=True,
                    reject=dict(grad=4000e-13, eog=150e-6))
# just use right temporal sensors for speed
epochs.pick_channels(mne.read_vectorview_selection('Right-temporal'))
evoked = epochs.average()

# Factor to down-sample the temporal dimension of the TFR computed by
# tfr_morlet. Decimation occurs after frequency decomposition and can
# be used to reduce memory usage (and possibly computational time of downstream
# operations such as nonparametric statistics) if you don't need high
# spectrotemporal resolution.
decim = 5
freqs = np.arange(8, 40, 2)  # define frequencies of interest
sfreq = raw.info['sfreq']  # sampling in Hz
tfr_epochs = tfr_morlet(epochs, freqs, n_cycles=4., decim=decim,
                        average=False, return_itc=False, n_jobs=1)

# Baseline power
tfr_epochs.apply_baseline(mode='logratio', baseline=(-.100, 0))

# Crop in time to keep only what is between 0 and 400 ms
evoked.crop(-0.1, 0.4)
tfr_epochs.crop(-0.1, 0.4)

epochs_power = tfr_epochs.data


I am working on the file "0.24/_downloads/5b9edf9c05aec2b9bb1f128f174ca0f3/40_cluster_1samp_time_freq.ipynb".
The first task is:
View time-frequency plots
Can you write Python code for it?

evoked_data = evoked.data
times = 1e3 * evoked.times

plt.figure()
plt.subplots_adjust(0.12, 0.08, 0.96, 0.94, 0.2, 0.43)

# Create new stats image with only significant clusters
T_obs_plot = np.nan * np.ones_like(T_obs)
for c, p_val in zip(clusters, cluster_p_values):
    if p_val <= 0.05:
        T_obs_plot[c] = T_obs[c]

# Just plot one channel's data
ch_idx, f_idx, t_idx = np.unravel_index(
    np.nanargmax(np.abs(T_obs_plot)), epochs_power.shape[1:])
# ch_idx = tfr_epochs.ch_names.index('MEG 1332')  # to show a specific one

vmax = np.max(np.abs(T_obs))
vmin = -vmax
plt.subplot(2, 1, 1)
plt.imshow(T_obs[ch_idx], cmap=plt.cm.gray,
           extent=[times[0], times[-1], freqs[0], freqs[-1]],
           aspect='auto', origin='lower', vmin=vmin, vmax=vmax)
plt.imshow(T_obs_plot[ch_idx], cmap=plt.cm.RdBu_r,
           extent=[times[0], times[-1], freqs[0], freqs[-1]],
           aspect='auto', origin='lower', vmin=vmin, vmax=vmax)
plt.colorbar()
plt.xlabel('Time (ms)')
plt.ylabel('Frequency (Hz)')
plt.title(f'Induced power ({tfr_epochs.ch_names[ch_idx]})')

ax2 = plt.subplot(2, 1, 2)
evoked.plot(axes=[ax2], time_unit='s')
plt.show()


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

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

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

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

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


I am working on the file "0.24/_downloads/5bedf835c134d956a9b527dc8c5f488c/20_rejecting_bad_data.ipynb".
The first task is:
Alternatively, if rejection thresholds were not originally given to the
:class:~mne.Epochs constructor, they can be passed to
:meth:~mne.Epochs.drop_bad later instead; this can also be a way of
imposing progressively more stringent rejection criteria:
Can you write Python code for it?

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

epochs.drop_bad(reject=stronger_reject_criteria)
print(epochs.drop_log)


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

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


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

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

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


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


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

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


I am working on the file "0.24/_downloads/5bedf835c134d956a9b527dc8c5f488c/20_rejecting_bad_data.ipynb".
The first task is:
Now detect break periods. We can control how far the break annotations shall
expand toward both ends of each break.
Can you write Python code for it?

break_annots = mne.preprocessing.annotate_break(
    raw=raw,
    min_break_duration=20,  # consider segments of at least 20 s duration
    t_start_after_previous=5,  # start annotation 5 s after end of previous one
    t_stop_before_next=2  # stop annotation 2 s before beginning of next one
)

raw.set_annotations(raw.annotations + break_annots)  # add to existing
raw.plot()


I am working on the file "0.24/_downloads/5bedf835c134d956a9b527dc8c5f488c/20_rejecting_bad_data.ipynb".
The first task is:
Now we can confirm that the annotations are centered on the EOG events. Since
blinks are usually easiest to see in the EEG channels, we'll only plot EEG
here:
Can you write Python code for it?

eeg_picks = mne.pick_types(raw.info, meg=False, eeg=True)
raw.plot(events=eog_events, order=eeg_picks)