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

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


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

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

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

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


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

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


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

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


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

Warning

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

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

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


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


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

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


I am working on the file "0.20/_downloads/7b1b17f7cd0e886e3d0da4385e8a1630/plot_psf_ctf_vertices.ipynb".
The first task is:
Plot point-spread functions (PSFs) and cross-talk functions (CTFs)
Visualise PSF and CTF at one vertex for sLORETA.
Can you write Python code for it?

# Authors: Olaf Hauk <olaf.hauk@mrc-cbu.cam.ac.uk>
#          Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)

import mne
from mne.datasets import sample
from mne.minimum_norm import (make_inverse_resolution_matrix, get_cross_talk,
                              get_point_spread)

print(__doc__)

data_path = sample.data_path()
subjects_dir = data_path + '/subjects/'
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
fname_cov = data_path + '/MEG/sample/sample_audvis-cov.fif'
fname_evo = data_path + '/MEG/sample/sample_audvis-ave.fif'

# read forward solution
forward = mne.read_forward_solution(fname_fwd)
# forward operator with fixed source orientations
forward = mne.convert_forward_solution(forward, surf_ori=True,
                                       force_fixed=True)

# noise covariance matrix
noise_cov = mne.read_cov(fname_cov)

# evoked data for info
evoked = mne.read_evokeds(fname_evo, 0)

# make inverse operator from forward solution
# free source orientation
inverse_operator = mne.minimum_norm.make_inverse_operator(
    info=evoked.info, forward=forward, noise_cov=noise_cov, loose=0.,
    depth=None)

# regularisation parameter
snr = 3.0
lambda2 = 1.0 / snr ** 2
method = 'MNE'  # can be 'MNE' or 'sLORETA'

# compute resolution matrix for sLORETA
rm_lor = make_inverse_resolution_matrix(forward, inverse_operator,
                                        method='sLORETA', lambda2=lambda2)

# get PSF and CTF for sLORETA at one vertex
sources = [1000]

stc_psf = get_point_spread(rm_lor, forward['src'], sources, norm=True)

stc_ctf = get_cross_talk(rm_lor, forward['src'], sources, norm=True)


I am working on the file "0.20/_downloads/7b1b17f7cd0e886e3d0da4385e8a1630/plot_psf_ctf_vertices.ipynb".
The first task is:
Visualise
Can you write Python code for it?

# Which vertex corresponds to selected source
vertno_lh = forward['src'][0]['vertno']
verttrue = [vertno_lh[sources[0]]]  # just one vertex

# find vertices with maxima in PSF and CTF
vert_max_psf = vertno_lh[stc_psf.data.argmax()]
vert_max_ctf = vertno_lh[stc_ctf.data.argmax()]

brain_psf = stc_psf.plot('sample', 'inflated', 'lh', subjects_dir=subjects_dir,
                         figure=1)
brain_psf.show_view('ventral')
brain_psf.add_text(0.1, 0.9, 'sLORETA PSF', 'title', font_size=16)

# True source location for PSF
brain_psf.add_foci(verttrue, coords_as_verts=True, scale_factor=1., hemi='lh',
                   color='green')

# Maximum of PSF
brain_psf.add_foci(vert_max_psf, coords_as_verts=True, scale_factor=1.,
                   hemi='lh', color='black')

brain_ctf = stc_ctf.plot('sample', 'inflated', 'lh', subjects_dir=subjects_dir,
                         figure=2)
brain_ctf.add_text(0.1, 0.9, 'sLORETA CTF', 'title', font_size=16)
brain_ctf.show_view('ventral')
brain_ctf.add_foci(verttrue, coords_as_verts=True, scale_factor=1., hemi='lh',
                   color='green')

# Maximum of CTF
brain_ctf.add_foci(vert_max_ctf, coords_as_verts=True, scale_factor=1.,
                   hemi='lh', color='black')

print('The green spheres indicate the true source location, and the black '
      'spheres the maximum of the distribution.')


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

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


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

src_fs = mne.read_source_spaces(fname_src_fsaverage)
morph = mne.compute_source_morph(
    inverse_operator['src'], subject_from='sample', subjects_dir=subjects_dir,
    niter_affine=[10, 10, 5], niter_sdr=[10, 10, 5],  # just for speed
    src_to=src_fs, verbose=True)


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

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

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

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


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

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

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

fname_t1_fsaverage = os.path.join(subjects_dir, 'fsaverage', 'mri',
                                  'brain.mgz')
fetch_fsaverage(subjects_dir)  # ensure fsaverage src exists
fname_src_fsaverage = subjects_dir + '/fsaverage/bem/fsaverage-vol-5-src.fif'


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

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

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

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

from sklearn.decomposition import FastICA, PCA

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

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

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

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


I am working on the file "0.20/_downloads/7c31b7bed6ff2a9686e321d607181951/plot_background_ica.ipynb".
The first task is:
Now try to recover the sources
Can you write Python code for it?

# compute ICA
ica = FastICA(n_components=3)
S_ = ica.fit_transform(X)  # Get the estimated sources
A_ = ica.mixing_  # Get estimated mixing matrix

# compute PCA
pca = PCA(n_components=3)
H = pca.fit_transform(X)  # estimate PCA sources

plt.figure(figsize=(9, 6))

models = [X, S, S_, H]
names = ['Observations (mixed signal)',
         'True Sources',
         'ICA estimated sources',
         'PCA estimated sources']
colors = ['red', 'steelblue', 'orange']

for ii, (model, name) in enumerate(zip(models, names), 1):
    plt.subplot(4, 1, ii)
    plt.title(name)
    for sig, color in zip(model.T, colors):
        plt.plot(sig, color=color)

plt.tight_layout()


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

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

import numpy as np
import matplotlib.pyplot as plt

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

print(__doc__)

data_path = sample.data_path()

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

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

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

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

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

# Initialize EMS transformer
ems = EMS()

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

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

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


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

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

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


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

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


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

query = 'trial_number < 10'
plot_query_results(query)


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

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


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

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


I am working on the file "0.20/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Applying FIR filters
Now lets look at some practical effects of these filters by applying
them to some data.
Let's construct a Gaussian-windowed sinusoid (i.e., Morlet imaginary part)
plus noise (random and line). Note that the original clean signal contains
frequency content in both the pass band and transition bands of our
low-pass filter.
Can you write Python code for it?

dur = 10.
center = 2.
morlet_freq = f_p
tlim = [center - 0.2, center + 0.2]
tticks = [tlim[0], center, tlim[1]]
flim = [20, 70]

x = np.zeros(int(sfreq * dur) + 1)
blip = morlet(sfreq, [morlet_freq], n_cycles=7)[0].imag / 20.
n_onset = int(center * sfreq) - len(blip) // 2
x[n_onset:n_onset + len(blip)] += blip
x_orig = x.copy()

rng = np.random.RandomState(0)
x += rng.randn(len(x)) / 1000.
x += np.sin(2. * np.pi * 60. * np.arange(len(x)) / sfreq) / 2000.


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

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


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

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

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

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

import mne

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


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

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

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

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

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

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


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

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

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

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


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

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

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


I am working on the file "0.20/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
If we can live with even more ripple, we can get it slightly steeper,
but the impulse response begins to ring substantially longer (note the
different x-axis scale):
Can you write Python code for it?

iir_params['rp'] = 6.
filt = mne.filter.create_filter(x, sfreq, l_freq=None, h_freq=f_p,
                                method='iir', iir_params=iir_params,
                                verbose=True)
plot_filter(filt, sfreq, freq, gain,
            'Chebychev-1 order=8, ripple=6 dB', flim=flim,
            compensate=True)


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

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

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


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

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


I am working on the file "0.20/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Let's make the stop-band tighter still with a longer filter (10 s),
with a resulting larger x-axis:
Can you write Python code for it?

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


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

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


I am working on the file "0.20/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Some pitfalls of filtering
Multiple recent papers have noted potential risks of drawing
errant inferences due to misapplication of filters.
Low-pass problems
Filters in general, especially those that are non-causal (zero-phase), can
make activity appear to occur earlier or later than it truly did. As
mentioned in VanRullen (2011) [3], investigations of commonly (at the time)
used low-pass filters created artifacts when they were applied to simulated
data. However, such deleterious effects were minimal in many real-world
examples in Rousselet (2012) [5].
Perhaps more revealing, it was noted in Widmann & Schröger (2012) [6] that
the problematic low-pass filters from VanRullen (2011) [3]:

Used a least-squares design (like :func:scipy.signal.firls) that
      included "do-not-care" transition regions, which can lead to
      uncontrolled behavior.
Had a filter length that was independent of the transition bandwidth,
      which can cause excessive ringing and signal distortion.

High-pass problems
When it comes to high-pass filtering, using corner frequencies above 0.1 Hz
were found in Acunzo et al. (2012) [4]_ to:
"... generate a systematic bias easily leading to misinterpretations of
   neural activity.”
In a related paper, Widmann et al. (2015) [7] also came to suggest a
0.1 Hz highpass. More evidence followed in Tanner et al. (2015) [8] of
such distortions. Using data from language ERP studies of semantic and
syntactic processing (i.e., N400 and P600), using a high-pass above 0.3 Hz
caused significant effects to be introduced implausibly early when compared
to the unfiltered data. From this, the authors suggested the optimal
high-pass value for language processing to be 0.1 Hz.
We can recreate a problematic simulation from Tanner et al. (2015) [8]_:
"The simulated component is a single-cycle cosine wave with an amplitude
   of 5µV [sic], onset of 500 ms poststimulus, and duration of 800 ms. The
   simulated component was embedded in 20 s of zero values to avoid
   filtering edge effects... Distortions [were]...
Can you write Python code for it?

x = np.zeros(int(2 * sfreq))
t = np.arange(0, len(x)) / sfreq - 0.2
onset = np.where(t >= 0.5)[0][0]
cos_t = np.arange(0, int(sfreq * 0.8)) / sfreq
sig = 2.5 - 2.5 * np.cos(2 * np.pi * (1. / 0.8) * cos_t)
x[onset:onset + len(sig)] = sig

iir_lp_30 = signal.iirfilter(2, 30. / sfreq, btype='lowpass')
iir_hp_p1 = signal.iirfilter(2, 0.1 / sfreq, btype='highpass')
iir_lp_2 = signal.iirfilter(2, 2. / sfreq, btype='lowpass')
iir_hp_2 = signal.iirfilter(2, 2. / sfreq, btype='highpass')
x_lp_30 = signal.filtfilt(iir_lp_30[0], iir_lp_30[1], x, padlen=0)
x_hp_p1 = signal.filtfilt(iir_hp_p1[0], iir_hp_p1[1], x, padlen=0)
x_lp_2 = signal.filtfilt(iir_lp_2[0], iir_lp_2[1], x, padlen=0)
x_hp_2 = signal.filtfilt(iir_hp_2[0], iir_hp_2[1], x, padlen=0)

xlim = t[[0, -1]]
ylim = [-2, 6]
xlabel = 'Time (sec)'
ylabel = r'Amplitude ($\mu$V)'
tticks = [0, 0.5, 1.3, t[-1]]
axes = plt.subplots(2, 2)[1].ravel()
for ax, x_f, title in zip(axes, [x_lp_2, x_lp_30, x_hp_2, x_hp_p1],
                          ['LP$_2$', 'LP$_{30}$', 'HP$_2$', 'LP$_{0.1}$']):
    ax.plot(t, x, color='0.5')
    ax.plot(t, x_f, color='k', linestyle='--')
    ax.set(ylim=ylim, xlim=xlim, xticks=tticks,
           title=title, xlabel=xlabel, ylabel=ylabel)
mne.viz.adjust_axes(axes)
mne.viz.tight_layout()
plt.show()


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

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

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


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

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


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

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


I am working on the file "0.20/_downloads/804ea48504b27f5f04fd03d517675af5/plot_point_spread.ipynb".
The first task is:
Corrupt known signal with point spread
The aim of this tutorial is to demonstrate how to put a known signal at a
desired location(s) in a :class:mne.SourceEstimate and then corrupt the
signal with point-spread by applying a forward and inverse solution.
Can you write Python code for it?

import os.path as op

import numpy as np

import mne
from mne.datasets import sample

from mne.minimum_norm import read_inverse_operator, apply_inverse
from mne.simulation import simulate_stc, simulate_evoked


I am working on the file "0.20/_downloads/804ea48504b27f5f04fd03d517675af5/plot_point_spread.ipynb".
The first task is:
Find the center vertices in source space of each label
We want the known signal in each label to only be active at the center. We
create a mask for each label that is 1 at the center vertex and 0 at all
other vertices in the label. This mask is then used when simulating
source-space data.
Can you write Python code for it?

hemi_to_ind = {'lh': 0, 'rh': 1}
for i, label in enumerate(labels):
    # The `center_of_mass` function needs labels to have values.
    labels[i].values.fill(1.)

    # Restrict the eligible vertices to be those on the surface under
    # consideration and within the label.
    surf_vertices = fwd['src'][hemi_to_ind[label.hemi]]['vertno']
    restrict_verts = np.intersect1d(surf_vertices, label.vertices)
    com = labels[i].center_of_mass(subject='sample',
                                   subjects_dir=subjects_dir,
                                   restrict_vertices=restrict_verts,
                                   surf='white')

    # Convert the center of vertex index from surface vertex list to Label's
    # vertex list.
    cent_idx = np.where(label.vertices == com)[0][0]

    # Create a mask with 1 at center vertex and zeros elsewhere.
    labels[i].values.fill(0.)
    labels[i].values[cent_idx] = 1.


I am working on the file "0.20/_downloads/804ea48504b27f5f04fd03d517675af5/plot_point_spread.ipynb".
The first task is:
First, we set some parameters.
Can you write Python code for it?

seed = 42

# parameters for inverse method
method = 'sLORETA'
snr = 3.
lambda2 = 1.0 / snr ** 2

# signal simulation parameters
# do not add extra noise to the known signals
nave = np.inf
T = 100
times = np.linspace(0, 1, T)
dt = times[1] - times[0]

# Paths to MEG data
data_path = sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
fname_fwd = op.join(data_path, 'MEG', 'sample',
                    'sample_audvis-meg-oct-6-fwd.fif')
fname_inv = op.join(data_path, 'MEG', 'sample',
                    'sample_audvis-meg-oct-6-meg-fixed-inv.fif')

fname_evoked = op.join(data_path, 'MEG', 'sample',
                       'sample_audvis-ave.fif')


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

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


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

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

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

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


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

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


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


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

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

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


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

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

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


I am working on the file "0.20/_downloads/82590448493c884f52ea0c7ddc5b446b/plot_publication_figure.ipynb".
The first task is:
A lot of figure settings can be adjusted after the figure is created, but
many can also be adjusted in advance by updating the
:data:~matplotlib.rcParams dictionary. This is especially useful when your
script generates several figures that you want to all have the same style:
Can you write Python code for it?

# Tweak the figure style
plt.rcParams.update({
    'ytick.labelsize': 'small',
    'xtick.labelsize': 'small',
    'axes.labelsize': 'small',
    'axes.titlesize': 'medium',
    'grid.color': '0.75',
    'grid.linestyle': ':',
})


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

evoked.plot()

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


I am working on the file "0.20/_downloads/82590448493c884f52ea0c7ddc5b446b/plot_publication_figure.ipynb".
The first task is:
Make figures more publication ready
In this example, we take some MNE plots and make some changes to make
a figure closer to publication-ready.
Can you write Python code for it?

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

import os.path as op

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable, ImageGrid

import mne


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

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

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

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

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

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

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

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

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


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

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

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


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

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

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

stc = mne.read_source_estimate(fname_stc)


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

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

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


I am working on the file "0.20/_downloads/85b80d223414f32365a9175978a38cb4/plot_limo_data.ipynb".
The first task is:
As shown above, there are some considerable differences between the
activation patterns evoked by stimuli with low vs. high phase-coherence at
the chosen electrodes.
Prepare data for linear regression analysis
Before we test the significance of these differences using linear
regression, we'll interpolate missing channels that were
dropped during preprocessing of the data.
Furthermore, we'll drop the EOG channels (marked by the "EXG" prefix)
present in the data:
Can you write Python code for it?

limo_epochs.interpolate_bads(reset_bads=True)
limo_epochs.drop_channels(['EXG1', 'EXG2', 'EXG3', 'EXG4'])


I am working on the file "0.20/_downloads/85b80d223414f32365a9175978a38cb4/plot_limo_data.ipynb".
The first task is:
Conversely, there appears to be no (or very small) systematic effects when
comparing Face A and Face B stimuli. This is largely consistent with the
difference wave approach presented above.
Can you write Python code for it?

ts_args = dict(xlim=(-0.25, 0.5))

reg['face a - face b'].beta.plot_joint(ts_args=ts_args,
                                       title='Effect of Face A vs. Face B',
                                       times=[0.23])


I am working on the file "0.20/_downloads/85b80d223414f32365a9175978a38cb4/plot_limo_data.ipynb".
The first task is:
Define predictor variables and design matrix
To run the regression analysis,
we need to create a design matrix containing information about the
variables (i.e., predictors) we want to use for prediction of brain
activity patterns. For this purpose, we'll use the information we have in
limo_epochs.metadata: phase-coherence and Face A vs. Face B.
Can you write Python code for it?

# name of predictors + intercept
predictor_vars = ['face a - face b', 'phase-coherence', 'intercept']

# create design matrix
design = limo_epochs.metadata[['phase-coherence', 'face']].copy()
design['face a - face b'] = np.where(design['face'] == 'A', 1, -1)
design['intercept'] = 1
design = design[predictor_vars]


I am working on the file "0.20/_downloads/85b80d223414f32365a9175978a38cb4/plot_limo_data.ipynb".
The first task is:
Extract regression coefficients
The results are stored within the object reg,
which is a dictionary of evoked objects containing
multiple inferential measures for each predictor in the design matrix.
Can you write Python code for it?

print('predictors are:', list(reg))
print('fields are:', [field for field in getattr(reg['intercept'], '_fields')])


I am working on the file "0.20/_downloads/85b80d223414f32365a9175978a38cb4/plot_limo_data.ipynb".
The first task is:
Note that the result of the loading process is an
:class:mne.EpochsArray containing the data ready to interface
with MNE-Python.
Can you write Python code for it?


I am working on the file "0.20/_downloads/85b80d223414f32365a9175978a38cb4/plot_limo_data.ipynb".
The first task is:
Now let's take a closer look at the information in the epochs
metadata.
Can you write Python code for it?

# We want include all columns in the summary table
epochs_summary = limo_epochs.metadata.describe(include='all').round(3)
print(epochs_summary)


I am working on the file "0.20/_downloads/85b80d223414f32365a9175978a38cb4/plot_limo_data.ipynb".
The first task is:
Now we can set up the linear model to be used in the analysis using
MNE-Python's func:~mne.stats.linear_regression function.
Can you write Python code for it?

reg = linear_regression(limo_epochs,
                        design_matrix=design,
                        names=predictor_vars)


I am working on the file "0.20/_downloads/85b80d223414f32365a9175978a38cb4/plot_limo_data.ipynb".
The first task is:
Single trial linear regression analysis with the LIMO dataset
Here we explore the structure of the data contained in the
LIMO dataset.
This example replicates and extends some of the main analysis
and tools integrated in LIMO MEEG, a MATLAB toolbox originally designed
to interface with EEGLAB_.
In summary, the example:

Fetches epoched data files for a single subject of the LIMO dataset [1]_.
  If the LIMO files are not found on disk, the
  fetcher :func:mne.datasets.limo.load_data() will automatically download
  the files from a remote repository.

During import, information about the data (i.e., sampling rate, number of
  epochs per condition, number and name of EEG channels per subject, etc.) is
  extracted from the LIMO :file:.mat files stored on disk and added to the
  epochs structure as metadata.

Fits linear models on the single subject's data and visualizes inferential
  measures to evaluate the significance of the estimated effects.

References
.. [1] Guillaume, Rousselet. (2016). LIMO EEG Dataset, [dataset].
       University of Edinburgh, Centre for Clinical Brain Sciences.
       https://doi.org/10.7488/ds/1556.
.. [2] Rousselet, G. A., Gaspar, C. M., Pernet, C. R., Husk, J. S.,
       Bennett, P. J., & Sekuler, A. B. (2010). Healthy aging delays scalp EEG
       sensitivity to noise in a face discrimination task.
       Frontiers in psychology, 1, 19. https://doi.org/10.3389/fpsyg.2010.00019
.. [3] Rousselet, G. A., Pernet, C. R., Bennett, P. J., & Sekuler, A. B.
       (2008). Parametric study of EEG sensitivity to phase noise during face
       processing. BMC neuroscience, 9(1), 98.
       https://doi.org/10.1186/1471-2202-9-98
Can you write Python code for it?

# Authors: Jose C. Garcia Alanis <alanis.jcg@gmail.com>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

from mne.datasets.limo import load_data
from mne.stats import linear_regression
from mne.viz import plot_events, plot_compare_evokeds
from mne import combine_evoked

print(__doc__)

# subject to use
subj = 1


I am working on the file "0.20/_downloads/85b80d223414f32365a9175978a38cb4/plot_limo_data.ipynb".
The first task is:
We can also compute the difference wave contrasting Face A and Face B.
Although, looking at the evoked responses above, we shouldn't expect great
differences among these face-stimuli.
Can you write Python code for it?

# Face A minus Face B
difference_wave = combine_evoked([limo_epochs['Face/A'].average(),
                                  -limo_epochs['Face/B'].average()],
                                 weights='equal')

# plot difference wave
difference_wave.plot_joint(times=[0.15], title='Difference Face A - Face B')


I am working on the file "0.20/_downloads/85b80d223414f32365a9175978a38cb4/plot_limo_data.ipynb".
The first task is:
We do see a difference between Face A and B, but it is pretty small.
Visualize effect of stimulus phase-coherence
Since phase-coherence
determined whether a face stimulus could be easily identified,
one could expect that faces with high phase-coherence should evoke stronger
activation patterns along occipital electrodes.
Can you write Python code for it?

phase_coh = limo_epochs.metadata['phase-coherence']
# get levels of phase coherence
levels = sorted(phase_coh.unique())
# create labels for levels of phase coherence (i.e., 0 - 85%)
labels = ["{0:.2f}".format(i) for i in np.arange(0., 0.90, 0.05)]

# create dict of evokeds for each level of phase-coherence
evokeds = {label: limo_epochs[phase_coh == level].average()
           for level, label in zip(levels, labels)}

# pick channel to plot
electrodes = ['C22', 'B11']
# create figures
for electrode in electrodes:
    fig, ax = plt.subplots(figsize=(8, 4))
    plot_compare_evokeds(evokeds,
                         axes=ax,
                         ylim=dict(eeg=(-20, 15)),
                         picks=electrode,
                         cmap=("Phase coherence", "magma"))


I am working on the file "0.20/_downloads/85e12f42707b248635bc0c477c2ffc2f/plot_mne_solutions.ipynb".
The first task is:
And finally eLORETA:
Can you write Python code for it?

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


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


I am working on the file "0.20/_downloads/85e12f42707b248635bc0c477c2ffc2f/plot_mne_solutions.ipynb".
The first task is:
Fixed orientation
First let's create a fixed-orientation inverse, with the default weighting.
Can you write Python code for it?

inv = make_inverse_operator(evoked.info, fwd, cov, loose=0., depth=0.8,
                            verbose=True)


I am working on the file "0.20/_downloads/8763e6c899a8b9971980be1308b5f693/plot_dics.ipynb".
The first task is:
DICS for power mapping
In this tutorial, we'll simulate two signals originating from two
locations on the cortex. These signals will be sinusoids, so we'll be looking
at oscillatory activity (as opposed to evoked activity).
We'll use dynamic imaging of coherent sources (DICS) [1]_ to map out
spectral power along the cortex. Let's see if we can find our two simulated
sources.
Can you write Python code for it?

# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
#
# License: BSD (3-clause)


I am working on the file "0.20/_downloads/8763e6c899a8b9971980be1308b5f693/plot_dics.ipynb".
The first task is:
Data simulation
The following function generates a timeseries that contains an oscillator,
whose frequency fluctuates a little over time, but stays close to 10 Hz.
We'll use this function to generate our two signals.
Can you write Python code for it?

sfreq = 50.  # Sampling frequency of the generated signal
n_samp = int(round(10. * sfreq))
times = np.arange(n_samp) / sfreq  # 10 seconds of signal
n_times = len(times)

def coh_signal_gen():
    """Generate an oscillating signal.

    Returns
    -------
    signal : ndarray
        The generated signal.
    """
    t_rand = 0.001  # Variation in the instantaneous frequency of the signal
    std = 0.1  # Std-dev of the random fluctuations added to the signal
    base_freq = 10.  # Base frequency of the oscillators in Hertz
    n_times = len(times)

    # Generate an oscillator with varying frequency and phase lag.
    signal = np.sin(2.0 * np.pi *
                    (base_freq * np.arange(n_times) / sfreq +
                     np.cumsum(t_rand * rand.randn(n_times))))

    # Add some random fluctuations to the signal.
    signal += std * rand.randn(n_times)

    # Scale the signal to be in the right order of magnitude (~100 nAm)
    # for MEG data.
    signal *= 100e-9

    return signal


I am working on the file "0.20/_downloads/8763e6c899a8b9971980be1308b5f693/plot_dics.ipynb".
The first task is:
Setup
We first import the required packages to run this tutorial and define a list
of filenames for various things we'll be using.
Can you write Python code for it?

import os.path as op
import numpy as np
from scipy.signal import welch, coherence, unit_impulse
from matplotlib import pyplot as plt

import mne
from mne.simulation import simulate_raw, add_noise
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
from mne.time_frequency import csd_morlet
from mne.beamformer import make_dics, apply_dics_csd

# We use the MEG and MRI setup from the MNE-sample dataset
data_path = sample.data_path(download=False)
subjects_dir = op.join(data_path, 'subjects')

# Filenames for various files we'll be using
meg_path = op.join(data_path, 'MEG', 'sample')
raw_fname = op.join(meg_path, 'sample_audvis_raw.fif')
fwd_fname = op.join(meg_path, 'sample_audvis-meg-eeg-oct-6-fwd.fif')
cov_fname = op.join(meg_path, 'sample_audvis-cov.fif')
fwd = mne.read_forward_solution(fwd_fname)

# Seed for the random number generator
rand = np.random.RandomState(42)


I am working on the file "0.20/_downloads/8763e6c899a8b9971980be1308b5f693/plot_dics.ipynb".
The first task is:
We will now compute the cortical power map at 10 Hz. using a DICS beamformer.
A beamformer will construct for each vertex a spatial filter that aims to
pass activity originating from the vertex, while dampening activity from
other sources as much as possible.
The :func:mne.beamformer.make_dics function has many switches that offer
precise control
over the way the filter weights are computed. Currently, there is no clear
consensus regarding the best approach. This is why we will demonstrate two
approaches here:

The approach as described in [2]_, which first normalizes the forward
    solution and computes a vector beamformer.
The scalar beamforming approach based on [3]_, which uses weight
    normalization instead of normalizing the forward solution.
Can you write Python code for it?

# Estimate the cross-spectral density (CSD) matrix on the trial containing the
# signal.
csd_signal = csd_morlet(epochs['signal'], frequencies=[10])

# Compute the spatial filters for each vertex, using two approaches.
filters_approach1 = make_dics(
    info, fwd, csd_signal, reg=0.05, pick_ori='max-power', normalize_fwd=True,
    inversion='single', weight_norm=None)
print(filters_approach1)

filters_approach2 = make_dics(
    info, fwd, csd_signal, reg=0.1, pick_ori='max-power', normalize_fwd=False,
    inversion='matrix', weight_norm='unit-noise-gain')
print(filters_approach2)

# You can save these to disk with:
# filters_approach1.save('filters_1-dics.h5')

# Compute the DICS power map by applying the spatial filters to the CSD matrix.
power_approach1, f = apply_dics_csd(csd_signal, filters_approach1)
power_approach2, f = apply_dics_csd(csd_signal, filters_approach2)

# Plot the DICS power maps for both approaches.
for approach, power in enumerate([power_approach1, power_approach2], 1):
    title = 'DICS power map, approach %d' % approach
    brain = power.plot('sample', subjects_dir=subjects_dir, hemi='both',
                       figure=approach + 1, size=600, time_label=title,
                       title=title)

    # Indicate the true locations of the source activity on the plot.
    brain.add_foci(vertices[0][0], coords_as_verts=True, hemi='lh')
    brain.add_foci(vertices[1][0], coords_as_verts=True, hemi='rh')

    # Rotate the view and add a title.
    brain.show_view(view={'azimuth': 0, 'elevation': 0, 'distance': 550,
                    'focalpoint': [0, 0, 0]})


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

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

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


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


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

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

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

t0 = 0.07  # peak of the response

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

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


I am working on the file "0.20/_downloads/8ea66c2199216e6ce0647e90bf50c6c1/plot_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.20/_downloads/8ea66c2199216e6ce0647e90bf50c6c1/plot_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.20/_downloads/8ea66c2199216e6ce0647e90bf50c6c1/plot_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.20/_downloads/8ea66c2199216e6ce0647e90bf50c6c1/plot_compute_source_psd_epochs.ipynb".
The first task is:
Visualize the entire spectrum:
Can you write Python code for it?

fig, ax = plt.subplots()
ax.plot(freqs, psd_avg.mean(axis=0))
ax.set_xlabel('Freq (Hz)')
ax.set_xlim(stc.times[[0, -1]])
ax.set_ylabel('Power Spectral Density')


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:

Note

:meth:`~mne.preprocessing.ICA.plot_components` (which plots the scalp
    field topographies for each component) has an optional ``inst`` parameter
    that takes an instance of :class:`~mne.io.Raw` or :class:`~mne.Epochs`.
    Passing ``inst`` makes the scalp topographies interactive: clicking one
    will bring up a diagnostic :meth:`~mne.preprocessing.ICA.plot_properties`
    window (see below) for that component.

In the plots above it's fairly obvious which ICs are capturing our EOG and
ECG artifacts, but there are additional ways visualize them anyway just to
be sure. First, we can plot an overlay of the original signal against the
reconstructed signal with the artifactual ICs excluded, using
:meth:~mne.preprocessing.ICA.plot_overlay:
Can you write Python code for it?

# blinks
ica.plot_overlay(raw, exclude=[0], picks='eeg')
# heartbeats
ica.plot_overlay(raw, exclude=[1], picks='mag')


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
As a final note, it is possible to extract ICs numerically using the
:meth:~mne.preprocessing.ICA.get_components method of
:class:~mne.preprocessing.ICA objects. This will return a :class:NumPy
array <numpy.ndarray> that can be passed to
:func:~mne.preprocessing.corrmap instead of the :class:tuple of
(subject_index, component_index) we passed before, and will yield the
same result:
Can you write Python code for it?

template_eog_component = icas[0].get_components()[:, eog_inds[0]]
corrmap(icas, template=template_eog_component, threshold=0.9)
print(template_eog_component)


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Filtering to remove slow drifts
Before we run the ICA, an important step is filtering the data to remove
low-frequency drifts, which can negatively affect the quality of the ICA fit.
The slow drifts are problematic because they reduce the independence of the
assumed-to-be-independent sources (e.g., during a slow upward drift, the
neural, heartbeat, blink, and other muscular sources will all tend to have
higher values), making it harder for the algorithm to find an accurate
solution. A high-pass filter with 1 Hz cutoff frequency is recommended.
However, because filtering is a linear operation, the ICA solution found from
the filtered signal can be applied to the unfiltered signal (see [2]_ for
more information), so we'll keep a copy of the unfiltered
:class:~mne.io.Raw object around so we can apply the ICA solution to it
later.
Can you write Python code for it?

filt_raw = raw.copy()
filt_raw.load_data().filter(l_freq=1., h_freq=None)


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Fitting and plotting the ICA solution
.. sidebar:: Ignoring the time domain
The ICA algorithms implemented in MNE-Python find patterns across
channels, but ignore the time domain. This means you can compute ICA on
discontinuous :class:`~mne.Epochs` or :class:`~mne.Evoked` objects (not
just continuous :class:`~mne.io.Raw` objects), or only use every Nth
sample by passing the ``decim`` parameter to ``ICA.fit()``.

Now we're ready to set up and fit the ICA. Since we know (from observing our
raw data) that the EOG and ECG artifacts are fairly strong, we would expect
those artifacts to be captured in the first few dimensions of the PCA
decomposition that happens before the ICA. Therefore, we probably don't need
a huge number of components to do a good job of isolating our artifacts
(though it is usually preferable to include more components for a more
accurate solution). As a first guess, we'll run ICA with n_components=15
(use only the first 15 PCA components to compute the ICA decomposition) — a
very small number given that our data has over 300 channels, but with the
advantage that it will run quickly and we will able to tell easily whether it
worked or not (because we already know what the EOG / ECG artifacts should
look like).
ICA fitting is not deterministic (e.g., the components may get a sign
flip on different runs, or may not always be returned in the same order), so
we'll also specify a random seed_ so that we get identical results each
time this tutorial is built by our web servers.
Can you write Python code for it?

ica = ICA(n_components=15, random_state=97)
ica.fit(filt_raw)


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Here we can pretty clearly see that the first component (ICA000) captures
the EOG signal quite well, and the second component (ICA001) looks a lot
like a heartbeat <qrs_> (for more info on visually identifying Independent
Components, this EEGLAB tutorial is a good resource). We can also
visualize the scalp field distribution of each component using
:meth:~mne.preprocessing.ICA.plot_components. These are interpolated based
on the values in the ICA unmixing matrix:
Can you write Python code for it?


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
In the remaining sections, we'll look at different ways of choosing which ICs
to exclude prior to reconstructing the sensor signals.
Selecting ICA components manually
Once we're certain which components we want to exclude, we can specify that
manually by setting the ica.exclude attribute. Similar to marking bad
channels, merely setting ica.exclude doesn't do anything immediately (it
just adds the excluded ICs to a list that will get used later when it's
needed). Once the exclusions have been set, ICA methods like
:meth:~mne.preprocessing.ICA.plot_overlay will exclude those component(s)
even if no exclude parameter is passed, and the list of excluded
components will be preserved when using :meth:mne.preprocessing.ICA.save
and :func:mne.preprocessing.read_ica.
Can you write Python code for it?

ica.exclude = [0, 1]  # indices chosen based on various plots above


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Note that above we used :meth:~mne.preprocessing.ICA.plot_sources on both
the original :class:~mne.io.Raw instance and also on an
:class:~mne.Evoked instance of the extracted EOG artifacts. This can be
another way to confirm that :meth:~mne.preprocessing.ICA.find_bads_eog has
identified the correct components.
Using a simulated channel to select ICA components
If you don't have an EOG channel,
:meth:~mne.preprocessing.ICA.find_bads_eog has a ch_name parameter that
you can use as a proxy for EOG. You can use a single channel, or create a
bipolar reference from frontal EEG sensors and use that as virtual EOG
channel. This carries a risk however: you must hope that the frontal EEG
channels only reflect EOG and not brain dynamics in the prefrontal cortex (or
you must not care about those prefrontal signals).
For ECG, it is easier: :meth:~mne.preprocessing.ICA.find_bads_ecg can use
cross-channel averaging of magnetometer or gradiometer channels to construct
a virtual ECG channel, so if you have MEG channels it is usually not
necessary to pass a specific channel name.
:meth:~mne.preprocessing.ICA.find_bads_ecg also has two options for its
method parameter: 'ctps' (cross-trial phase statistics [3]_) and
'correlation' (Pearson correlation between data and ECG channel).
Can you write Python code for it?

ica.exclude = []
# find which ICs match the ECG pattern
ecg_indices, ecg_scores = ica.find_bads_ecg(raw, method='correlation')
ica.exclude = ecg_indices

# barplot of ICA component "ECG match" scores
ica.plot_scores(ecg_scores)

# plot diagnostics
ica.plot_properties(raw, picks=ecg_indices)

# plot ICs applied to raw data, with ECG matches highlighted
ica.plot_sources(raw)

# plot ICs applied to the averaged ECG epochs, with ECG matches highlighted
ica.plot_sources(ecg_evoked)


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Notice that subject 1 does seem to have an IC that looks like it reflects
blink artifacts (component ICA000). Notice also that subject 3 appears to
have two components that are reflecting ocular artifacts (ICA000 and
ICA002), but only one was caught by :func:~mne.preprocessing.corrmap.
Let's try setting the threshold manually:
Can you write Python code for it?

corrmap(icas, template=(0, eog_inds[0]), threshold=0.9)


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Notice that the first subject has 3 different labels for the IC at index 0:
"eog/0/Fpz", "eog", and "blink". The first two were added by
:meth:~mne.preprocessing.ICA.find_bads_eog; the "blink" label was added by
the last call to :func:~mne.preprocessing.corrmap. Notice also that each
subject has at least one IC index labelled "blink", and subject 3 has two
components (0 and 2) labelled "blink" (consistent with the plot of IC sources
above). The labels_ attribute of :class:~mne.preprocessing.ICA objects
can also be manually edited to annotate the ICs with custom labels. They also
come in handy when plotting:
Can you write Python code for it?

icas[3].plot_components(picks=icas[3].labels_['blink'])
icas[3].exclude = icas[3].labels_['blink']
icas[3].plot_sources(raws[3])


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Now let's run :func:~mne.preprocessing.corrmap:
Can you write Python code for it?

# use the first subject as template; use Fpz as proxy for EOG
raw = raws[0]
ica = icas[0]
eog_inds, eog_scores = ica.find_bads_eog(raw, ch_name='Fpz')
corrmap(icas, template=(0, eog_inds[0]))


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Now that the exclusions have been set, we can reconstruct the sensor signals
with artifacts removed using the :meth:~mne.preprocessing.ICA.apply method
(remember, we're applying the ICA solution from the filtered data to the
original unfiltered signal). Plotting the original raw data alongside the
reconstructed data shows that the heartbeat and blink artifacts are repaired.
Can you write Python code for it?

# ica.apply() changes the Raw object in-place, so let's make a copy first:
reconst_raw = raw.copy()
ica.apply(reconst_raw)

raw.plot(order=artifact_picks, n_channels=len(artifact_picks))
reconst_raw.plot(order=artifact_picks, n_channels=len(artifact_picks))
del reconst_raw


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Now we get the message At least 1 IC detected for each subject (which is
good). At this point we'll re-run :func:~mne.preprocessing.corrmap with
parameters label=blink, show=False to label the ICs from each subject
that capture the blink artifacts (without plotting them again).
Can you write Python code for it?

corrmap(icas, template=(0, eog_inds[0]), threshold=0.9, label='blink',
        plot=False)
print([ica.labels_ for ica in icas])


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Now we'll do the same for the heartbeat artifacts, using
:func:~mne.preprocessing.create_ecg_epochs:
Can you write Python code for it?

ecg_evoked = create_ecg_epochs(raw).average()
ecg_evoked.apply_baseline(baseline=(None, -0.2))
ecg_evoked.plot_joint()


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Selecting ICA components using template matching
When dealing with multiple subjects, it is also possible to manually select
an IC for exclusion on one subject, and then use that component as a
template for selecting which ICs to exclude from other subjects' data,
using :func:mne.preprocessing.corrmap [4]_. The idea behind
:func:~mne.preprocessing.corrmap is that the artifact patterns are similar
enough across subjects that corresponding ICs can be identified by
correlating the ICs from each ICA solution with a common template, and
picking the ICs with the highest correlation strength.
:func:~mne.preprocessing.corrmap takes a list of ICA solutions, and a
template parameter that specifies which ICA object and which component
within it to use as a template.
Since our sample dataset only contains data from one subject, we'll use a
different dataset with multiple subjects: the EEGBCI dataset [5] [6]. The
dataset has 109 subjects, we'll just download one run (a left/right hand
movement task) from each of the first 4 subjects:
Can you write Python code for it?


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Some optional parameters that we could have passed to the
:meth:~mne.preprocessing.ICA.fit method include decim (to use only
every Nth sample in computing the ICs, which can yield a considerable
speed-up) and reject (for providing a rejection dictionary for maximum
acceptable peak-to-peak amplitudes for each channel type, just like we used
when creating epoched data in the tut-overview tutorial).
Now we can examine the ICs to see what they captured.
:meth:~mne.preprocessing.ICA.plot_sources will show the time series of the
ICs. Note that in our call to :meth:~mne.preprocessing.ICA.plot_sources we
can use the original, unfiltered :class:~mne.io.Raw object:
Can you write Python code for it?


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
The first figure shows the template map, while the second figure shows all
the maps that were considered a "match" for the template (including the
template itself). There were only three matches from the four subjects;
notice the output message No maps selected for subject(s) 1, consider a
more liberal threshold.  By default the threshold is set automatically by
trying several values; here it may have chosen a threshold that is too high.
Let's take a look at the ICA sources for each subject:
Can you write Python code for it?

for index, (ica, raw) in enumerate(zip(icas, raws)):
    fig = ica.plot_sources(raw)
    fig.suptitle('Subject {}'.format(index))


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
The last of these plots is especially useful: it shows us that the heartbeat
artifact is coming through on two ICs, and we've only caught one of them.
In fact, if we look closely at the output of
:meth:~mne.preprocessing.ICA.plot_sources (online, you can right-click →
"view image" to zoom in), it looks like ICA014 has a weak periodic
component that is in-phase with ICA001. It might be worthwhile to re-run
the ICA with more components to see if that second heartbeat artifact
resolves out a little better:
Can you write Python code for it?

# refit the ICA with 30 components this time
new_ica = ICA(n_components=30, random_state=97)
new_ica.fit(filt_raw)

# find which ICs match the ECG pattern
ecg_indices, ecg_scores = new_ica.find_bads_ecg(raw, method='correlation')
new_ica.exclude = ecg_indices

# barplot of ICA component "ECG match" scores
new_ica.plot_scores(ecg_scores)

# plot diagnostics
new_ica.plot_properties(raw, picks=ecg_indices)

# plot ICs applied to raw data, with ECG matches highlighted
new_ica.plot_sources(raw)

# plot ICs applied to the averaged ECG epochs, with ECG matches highlighted
new_ica.plot_sources(ecg_evoked)


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Using an EOG channel to select ICA components
It may have seemed easy to review the plots and manually select which ICs to
exclude, but when processing dozens or hundreds of subjects this can become
a tedious, rate-limiting step in the analysis pipeline. One alternative is to
use dedicated EOG or ECG sensors as a "pattern" to check the ICs against, and
automatically mark for exclusion any ICs that match the EOG/ECG pattern. Here
we'll use :meth:~mne.preprocessing.ICA.find_bads_eog to automatically find
the ICs that best match the EOG signal, then use
:meth:~mne.preprocessing.ICA.plot_scores along with our other plotting
functions to see which ICs it picked. We'll start by resetting
ica.exclude back to an empty list:
Can you write Python code for it?

ica.exclude = []
# find which ICs match the EOG pattern
eog_indices, eog_scores = ica.find_bads_eog(raw)
ica.exclude = eog_indices

# barplot of ICA component "EOG match" scores
ica.plot_scores(eog_scores)

# plot diagnostics
ica.plot_properties(raw, picks=eog_indices)

# plot ICs applied to raw data, with EOG matches highlighted
ica.plot_sources(raw)

# plot ICs applied to the averaged EOG epochs, with EOG matches highlighted
ica.plot_sources(eog_evoked)


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
We can also plot some diagnostics of each IC using
:meth:~mne.preprocessing.ICA.plot_properties:
Can you write Python code for it?


I am working on the file "0.20/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
We can get a summary of how the ocular artifact manifests across each channel
type using :func:~mne.preprocessing.create_eog_epochs like we did in the
tut-artifact-overview tutorial:
Can you write Python code for it?

eog_evoked = create_eog_epochs(raw).average()
eog_evoked.apply_baseline(baseline=(None, -0.2))
eog_evoked.plot_joint()


I am working on the file "0.20/_downloads/90c71f0d36d740bc290fd9fa30bddd8c/plot_compute_covariance.ipynb".
The first task is:
Computing a covariance matrix
Many methods in MNE, including source estimation and some classification
algorithms, require covariance estimations from the recordings.
In this tutorial we cover the basics of sensor covariance computations and
construct a noise covariance matrix that can be used when computing the
minimum-norm inverse solution. For more information, see
minimum_norm_estimates.
Can you write Python code for it?

import os.path as op

import mne
from mne.datasets import sample


I am working on the file "0.20/_downloads/90c71f0d36d740bc290fd9fa30bddd8c/plot_compute_covariance.ipynb".
The first task is:
How should I regularize the covariance matrix?
The estimated covariance can be numerically
unstable and tends to induce correlations between estimated source amplitudes
and the number of samples available. The MNE manual therefore suggests to
regularize the noise covariance matrix (see
cov_regularization_math), especially if only few samples are
available. Unfortunately it is not easy to tell the effective number of
samples, hence, to choose the appropriate regularization.
In MNE-Python, regularization is done using advanced regularization methods
described in [1]_. For this the 'auto' option can be used. With this
option cross-validation will be used to learn the optimal regularization:
Can you write Python code for it?

noise_cov_reg = mne.compute_covariance(epochs, tmax=0., method='auto',
                                       rank=None)


I am working on the file "0.20/_downloads/90c71f0d36d740bc290fd9fa30bddd8c/plot_compute_covariance.ipynb".
The first task is:
Now that you have the covariance matrix in an MNE-Python object you can
save it to a file with :func:mne.write_cov. Later you can read it back
using :func:mne.read_cov.
You can also use the pre-stimulus baseline to estimate the noise covariance.
First we have to construct the epochs. When computing the covariance, you
should use baseline correction when constructing the epochs. Otherwise the
covariance matrix will be inaccurate. In MNE this is done by default, but
just to be sure, we define it here manually.
Can you write Python code for it?

events = mne.find_events(raw)
epochs = mne.Epochs(raw, events, event_id=1, tmin=-0.2, tmax=0.5,
                    baseline=(-0.2, 0.0), decim=3,  # we'll decimate for speed
                    verbose='error')  # and ignore the warning about aliasing


I am working on the file "0.20/_downloads/90c71f0d36d740bc290fd9fa30bddd8c/plot_compute_covariance.ipynb".
The first task is:
Plot the covariance matrices
Try setting proj to False to see the effect. Notice that the projectors in
epochs are already applied, so proj parameter has no effect.
Can you write Python code for it?

noise_cov.plot(raw_empty_room.info, proj=True)
noise_cov_baseline.plot(epochs.info, proj=True)


I am working on the file "0.20/_downloads/90c71f0d36d740bc290fd9fa30bddd8c/plot_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.20/_downloads/90c71f0d36d740bc290fd9fa30bddd8c/plot_compute_covariance.ipynb".
The first task is:
This plot displays both, the whitened evoked signals for each channels and
the whitened :term:GFP. The numbers in the GFP panel represent the
estimated rank of the data, which amounts to the effective degrees of freedom
by which the squared sum across sensors is divided when computing the
whitened :term:GFP. The whitened :term:GFP also helps detecting spurious
late evoked components which can be the consequence of over- or
under-regularization.
Note that if data have been processed using signal space separation
(SSS) [2],
gradiometers and magnetometers will be displayed jointly because both are
reconstructed from the same SSS basis vectors with the same numerical rank.
This also implies that both sensor types are not any longer statistically
independent.
These methods for evaluation can be used to assess model violations.
Additional
introductory materials can be found here <https://goo.gl/ElWrxe>.
For expert use cases or debugging the alternative estimators can also be
compared (see
sphx_glr_auto_examples_visualization_plot_evoked_whitening.py) and
sphx_glr_auto_examples_inverse_plot_covariance_whitening_dspm.py):
Can you write Python code for it?

noise_covs = mne.compute_covariance(
    epochs, tmax=0., method=('empirical', 'shrunk'), return_estimators=True,
    rank=None)
evoked.plot_white(noise_covs, time_unit='s')