I am working on the file "0.22/_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')


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

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


I am working on the file "0.22/_downloads/963786e591fc03946ca0f3b819f12772/plot_xdawn_denoising.ipynb".
The first task is:
Epochs are denoised by calling apply, which by default keeps only the
signal subspace corresponding to the first n_components specified in the
Xdawn constructor above.
Can you write Python code for it?

epochs_denoised = xd.apply(epochs)

# Plot image epoch after Xdawn
plot_epochs_image(epochs_denoised['vis_r'], picks=[230], vmin=-500, vmax=500)


I am working on the file "0.22/_downloads/963786e591fc03946ca0f3b819f12772/plot_xdawn_denoising.ipynb".
The first task is:
XDAWN Denoising
XDAWN filters are trained from epochs, signal is projected in the sources
space and then projected back in the sensor space using only the first two
XDAWN components. The process is similar to an ICA, but is
supervised in order to maximize the signal to signal + noise ratio of the
evoked response.

Warning

As this denoising method exploits the known events to
             maximize SNR of the contrast between conditions it can lead
             to overfitting. To avoid a statistical analysis problem you
             should split epochs used in fit with the ones used in
             apply method.

References
[1] Rivet, B., Souloumiac, A., Attina, V., & Gibert, G. (2009). xDAWN
algorithm to enhance evoked potentials: application to brain-computer
interface. Biomedical Engineering, IEEE Transactions on, 56(8), 2035-2043.
[2] Rivet, B., Cecotti, H., Souloumiac, A., Maby, E., & Mattout, J. (2011,
August). Theoretical analysis of xDAWN algorithm: application to an
efficient sensor selection in a P300 BCI. In Signal Processing Conference,
2011 19th European (pp. 1382-1386). IEEE.
Can you write Python code for it?

# Authors: Alexandre Barachant <alexandre.barachant@gmail.com>
#
# License: BSD (3-clause)

from mne import (io, compute_raw_covariance, read_events, pick_types, Epochs)
from mne.datasets import sample
from mne.preprocessing import Xdawn
from mne.viz import plot_epochs_image

print(__doc__)

data_path = sample.data_path()


I am working on the file "0.22/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
For this visualization, nilearn must be installed.
This visualization is interactive. Click on any of the anatomical slices
to explore the time series. Clicking on any time point will bring up the
corresponding anatomical map.
We could visualize the source estimate on a glass brain. Unlike the previous
visualization, a glass brain does not show us one slice but what we would
see if the brain was transparent like glass, and
:term:maximum intensity projection) is used:
Can you write Python code for it?

stc.plot(src, subject='sample', subjects_dir=subjects_dir, mode='glass_brain')


I am working on the file "0.22/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Note that here we used initial_time=0.1, but we can also browse through
time using time_viewer=True.
In case mayavi is not available, we also offer a matplotlib
backend. Here we use verbose='error' to ignore a warning that not all
vertices were used in plotting.
Can you write Python code for it?

mpl_fig = stc.plot(subjects_dir=subjects_dir, initial_time=initial_time,
                   backend='matplotlib', verbose='error')


I am working on the file "0.22/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
The SourceEstimate object is in fact a surface source estimate. MNE also
supports volume-based source estimates but more on that later.
We can plot the source estimate using the
:func:stc.plot <mne.SourceEstimate.plot> just as in other MNE
objects. Note that for this visualization to work, you must have mayavi
and pysurfer installed on your machine.
Can you write Python code for it?

initial_time = 0.1
brain = stc.plot(subjects_dir=subjects_dir, initial_time=initial_time,
                 clim=dict(kind='value', lims=[3, 6, 9]))


I am working on the file "0.22/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Then, we can load the precomputed inverse operator from a file.
Can you write Python code for it?

fname_inv = data_path + '/MEG/sample/sample_audvis-meg-vol-7-meg-inv.fif'
inv = read_inverse_operator(fname_inv)
src = inv['src']
mri_head_t = inv['mri_head_t']


I am working on the file "0.22/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Then, we read the stc from file
Can you write Python code for it?

stc = mne.read_source_estimate(fname_stc, subject='sample')


I am working on the file "0.22/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
This time, we have a different container
(:class:VolSourceEstimate <mne.VolSourceEstimate>) for the source time
course.
Can you write Python code for it?


I am working on the file "0.22/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
This too comes with a convenient plot method.
Can you write Python code for it?


I am working on the file "0.22/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Vector Source Estimates
If we choose to use pick_ori='vector' in
:func:apply_inverse <mne.minimum_norm.apply_inverse>
Can you write Python code for it?

fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
inv = read_inverse_operator(fname_inv)
stc = apply_inverse(evoked, inv, lambda2, 'dSPM', pick_ori='vector')
brain = stc.plot(subject='sample', subjects_dir=subjects_dir,
                 initial_time=initial_time)


I am working on the file "0.22/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Visualize source time courses (stcs)
This tutorial focuses on visualization of
:term:stcs <source estimates (abbr. stc)>.
Surface Source Estimates
First, we get the paths for the evoked data and the time courses (stcs).
Can you write Python code for it?

import os
import os.path as op

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.datasets import sample
from mne.minimum_norm import apply_inverse, read_inverse_operator
from mne import read_evokeds

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

fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
fname_stc = os.path.join(sample_dir, 'sample_audvis-meg')


I am working on the file "0.22/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
You can also extract label time courses using volumetric atlases. Here we'll
use the built-in aparc.a2009s+aseg.mgz:
Can you write Python code for it?

fname_aseg = op.join(subjects_dir, 'sample', 'mri', 'aparc.a2009s+aseg.mgz')
label_names = mne.get_volume_labels_from_aseg(fname_aseg)
label_tc = stc.extract_label_time_course(fname_aseg, src=src)

lidx, tidx = np.unravel_index(np.argmax(label_tc), label_tc.shape)
fig, ax = plt.subplots(1)
ax.plot(stc.times, label_tc.T, 'k', lw=1., alpha=0.5)
xy = np.array([stc.times[tidx], label_tc[lidx, tidx]])
xytext = xy + [0.01, 1]
ax.annotate(
    label_names[lidx], xy, xytext, arrowprops=dict(arrowstyle='->'), color='r')
ax.set(xlim=stc.times[[0, -1]], xlabel='Time (s)', ylabel='Activation')
for key in ('right', 'top'):
    ax.spines[key].set_visible(False)
fig.tight_layout()


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:

Note

Before applying SSP (or any artifact repair strategy), be sure to observe
    the artifacts in your data to make sure you choose the right repair tool.
    Sometimes the right tool is no tool at all — if the artifacts are small
    enough you may not even need to repair them to get good analysis results.
    See `tut-artifact-overview` for guidance on detecting and
    visualizing various types of artifact.

What is SSP?
Signal-space projection (SSP) :footcite:UusitaloIlmoniemi1997 is a
technique for removing noise from EEG
and MEG signals by :term:projecting <projector> the signal onto a
lower-dimensional subspace. The subspace is chosen by calculating the average
pattern across sensors when the noise is present, treating that pattern as
a "direction" in the sensor space, and constructing the subspace to be
orthogonal to the noise direction (for a detailed walk-through of projection
see tut-projectors-background).
The most common use of SSP is to remove noise from MEG signals when the noise
comes from environmental sources (sources outside the subject's body and the
MEG system, such as the electromagnetic fields from nearby electrical
equipment) and when that noise is stationary (doesn't change much over the
duration of the recording). However, SSP can also be used to remove
biological artifacts such as heartbeat (ECG) and eye movement (EOG)
artifacts. Examples of each of these are given below.
Example: Environmental noise reduction from empty-room recordings
The example data <sample-dataset> was recorded on a Neuromag system,
which stores SSP projectors for environmental noise removal in the system
configuration (so that reasonably clean raw data can be viewed in real-time
during acquisition). For this reason, all the ~mne.io.Raw data in
the example dataset already includes SSP projectors, which are noted in the
output when loading the data:
Can you write Python code for it?

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file)


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Creating the empty-room projectors
We create the SSP vectors using ~mne.compute_proj_raw, and control
the number of projectors with parameters n_grad and n_mag. Once
created, the field pattern of the projectors can be easily visualized with
~mne.viz.plot_projs_topomap. We include the parameter
vlim='joint' so that the colormap is computed jointly for all projectors
of a given channel type; this makes it easier to compare their relative
smoothness. Note that for the function to know the types of channels in a
projector, you must also provide the corresponding ~mne.Info object:
Can you write Python code for it?

empty_room_projs = mne.compute_proj_raw(empty_room_raw, n_grad=3, n_mag=3)
mne.viz.plot_projs_topomap(empty_room_projs, colorbar=True, vlim='joint',
                           info=empty_room_raw.info)


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Just like we did with the heartbeat artifact, we can compute SSP projectors
for the ocular artifact using ~mne.preprocessing.compute_proj_eog,
which again takes a ~mne.io.Raw object as input and returns the
requested number of projectors for magnetometers, gradiometers, and EEG
channels (default is two projectors for each channel type). This time, we'll
pass no_proj parameter (so we get back only the new EOG projectors, not
also the existing projectors in the ~mne.io.Raw object), and we'll
ignore the events array by assigning it to _ (the conventional way of
handling unwanted return elements in Python).
Can you write Python code for it?

eog_projs, _ = compute_proj_eog(raw, n_grad=1, n_mag=1, n_eeg=1, reject=None,
                                no_proj=True)


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Just like with the empty-room and ECG projectors, we can visualize the scalp
distribution:
Can you write Python code for it?


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Just like with the empty-room projectors, we can visualize the scalp
distribution:
Can you write Python code for it?


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Notice that the small peaks in the first to magnetometer channels (MEG
1411 and MEG 1421) that occur at the same time as the large EEG
deflections have also been removed.
Choosing the number of projectors
In the examples above, we used 3 projectors (all magnetometer) to capture
empty room noise, and saw how projectors computed for the gradiometers failed
to capture global patterns (and thus we discarded the gradiometer
projectors). Then we computed 3 projectors (1 for each channel type) to
capture the heartbeat artifact, and 3 more to capture the ocular artifact.
How did we choose these numbers? The short answer is "based on experience" —
knowing how heartbeat artifacts typically manifest across the sensor array
allows us to recognize them when we see them, and recognize when additional
projectors are capturing something else other than a heartbeat artifact (and
thus may be removing brain signal and should be discarded).
Visualizing SSP sensor-space bias via signal reconstruction
.. sidebar:: SSP reconstruction
Internally, the reconstruction is performed by effectively using a
minimum-norm source localization to a spherical source space with the
projections accounted for, and then projecting the source-space data
back out to sensor space.

Because SSP performs an orthogonal projection, any spatial component in the
data that is not perfectly orthogonal to the SSP spatial direction(s) will
have its overall amplitude reduced by the projection operation. In other
words, SSP typically introduces some amount of amplitude reduction bias in
the sensor space data.
When performing source localization of M/EEG data, these projections are
properly taken into account by being applied not just to the M/EEG data
but also to the forward solution, and hence SSP should not bias the estimated
source amplitudes. However, for sensor space analyses, it can be useful to
visualize the extent to which SSP projection has biased the data. This can be
explored by using proj='reconstruct' in evoked plotting functions, for
example via...
Can you write Python code for it?

evoked = epochs.average()
# Apply the average ref first:
# It's how we typically view EEG data, and here we're really just interested
# in the effect of the EOG+ECG SSPs
evoked.del_proj().set_eeg_reference(projection=True).apply_proj()
evoked.add_proj(ecg_projs).add_proj(eog_projs)
fig, axes = plt.subplots(3, 3, figsize=(8, 6))
for ii in range(3):
    axes[ii, 0].get_shared_y_axes().join(*axes[ii])
for pi, proj in enumerate((False, True, 'reconstruct')):
    evoked.plot(proj=proj, axes=axes[:, pi], spatial_colors=True)
    if pi == 0:
        for ax in axes[:, pi]:
            parts = ax.get_title().split('(')
            ax.set(ylabel=f'{parts[0]} ({ax.get_ylabel()})\n'
                          f'{parts[1].replace(")", "")}')
    axes[0, pi].set(title=f'proj={proj}')
    axes[0, pi].texts = []
plt.setp(axes[1:, :].ravel(), title='')
plt.setp(axes[:, 1:].ravel(), ylabel='')
plt.setp(axes[:-1, :].ravel(), xlabel='')
mne.viz.tight_layout()


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Now we repeat the plot from above (with empty room and ECG projectors) and
compare it to a plot with empty room, ECG, and EOG projectors, to see how
well the ocular artifacts have been repaired:
Can you write Python code for it?

for title in ('Without', 'With'):
    if title == 'With':
        raw.add_proj(eog_projs)
    fig = raw.plot(order=artifact_picks, n_channels=len(artifact_picks))
    fig.subplots_adjust(top=0.9)  # make room for title
    fig.suptitle('{} EOG projectors'.format(title), size='xx-large',
                 weight='bold')


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Plotting the ERP/F using evoked.plot() or evoked.plot_joint() with
and without projectors applied can also be informative, as can plotting with
proj='reconstruct', which can reduce the signal bias introduced by
projections (see tut-artifact-ssp-reconstruction below).
Example: EOG and ECG artifact repair
Visualizing the artifacts
As mentioned in the ICA tutorial <tut-artifact-ica>, an important
first step is visualizing the artifacts you want to repair. Here they are in
the raw data:
Can you write Python code for it?

# pick some channels that clearly show heartbeats and blinks
regexp = r'(MEG [12][45][123]1|EEG 00.)'
artifact_picks = mne.pick_channels_regexp(raw.ch_names, regexp=regexp)
raw.plot(order=artifact_picks, n_channels=len(artifact_picks))


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Repairing ECG artifacts with SSP
MNE-Python provides several functions for detecting and removing heartbeats
from EEG and MEG data. As we saw in tut-artifact-overview,
~mne.preprocessing.create_ecg_epochs can be used to both detect and
extract heartbeat artifacts into an ~mne.Epochs object, which can
be used to visualize how the heartbeat artifacts manifest across the sensors:
Can you write Python code for it?

ecg_evoked = create_ecg_epochs(raw).average()
ecg_evoked.plot_joint()


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Repairing artifacts with SSP
This tutorial covers the basics of signal-space projection (SSP) and shows
how SSP can be used for artifact repair; extended examples illustrate use
of SSP for environmental noise reduction, and for repair of ocular and
heartbeat artifacts.
   :depth: 2
We begin as always by importing the necessary Python modules. To save ourselves
from repeatedly typing mne.preprocessing we'll directly import a handful of
functions from that submodule:
Can you write Python code for it?

import os
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.preprocessing import (create_eog_epochs, create_ecg_epochs,
                               compute_proj_ecg, compute_proj_eog)


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Since no dedicated ECG sensor channel was detected in the
~mne.io.Raw object, by default
~mne.preprocessing.compute_proj_ecg used the magnetometers to
estimate the ECG signal (as stated on the third line of output, above). You
can also supply the ch_name parameter to restrict which channel to use
for ECG artifact detection; this is most useful when you had an ECG sensor
but it is not labeled as such in the ~mne.io.Raw file.
The next few lines of the output describe the filter used to isolate ECG
events. The default settings are usually adequate, but the filter can be
customized via the parameters ecg_l_freq, ecg_h_freq, and
filter_length (see the documentation of
~mne.preprocessing.compute_proj_ecg for details).
.. TODO what are the cases where you might need to customize the ECG filter?
   infants? Heart murmur?
Once the ECG events have been identified,
~mne.preprocessing.compute_proj_ecg will also filter the data
channels before extracting epochs around each heartbeat, using the parameter
values given in l_freq, h_freq, filter_length, filter_method,
and iir_params. Here again, the default parameter values are usually
adequate.
.. TODO should advice for filtering here be the same as advice for filtering
   raw data generally? (e.g., keep high-pass very low to avoid peak shifts?
   what if your raw data is already filtered?)
By default, the filtered epochs will be averaged together
before the projection is computed; this can be controlled with the boolean
average parameter. In general this improves the signal-to-noise (where
"signal" here is our artifact!) ratio because the artifact temporal waveform
is fairly similar across epochs and well time locked to the detected events.
To get a sense of how the heartbeat affects the signal at each sensor, you
can plot the data with and without the ECG projectors:
Can you write Python code for it?

raw.del_proj()
for title, proj in [('Without', empty_room_projs), ('With', ecg_projs)]:
    raw.add_proj(proj, remove_existing=False)
    fig = raw.plot(order=artifact_picks, n_channels=len(artifact_picks))
    fig.subplots_adjust(top=0.9)  # make room for title
    fig.suptitle('{} ECG projectors'.format(title), size='xx-large',
                 weight='bold')


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
The effect is sometimes easier to see on averaged data. Here we use an
interactive feature of mne.Evoked.plot_topomap to turn projectors on
and off to see the effect on the data. Of course, the interactivity won't
work on the tutorial website, but you can download the tutorial and try it
locally:
Can you write Python code for it?

events = mne.find_events(raw, stim_channel='STI 014')
event_id = {'auditory/left': 1}

# NOTE: appropriate rejection criteria are highly data-dependent
reject = dict(mag=4000e-15,     # 4000 fT
              grad=4000e-13,    # 4000 fT/cm
              eeg=150e-6,       # 150 µV
              eog=250e-6)       # 250 µV

# time range where we expect to see the auditory N100: 50-150 ms post-stimulus
times = np.linspace(0.05, 0.15, 5)

epochs = mne.Epochs(raw, events, event_id, proj='delayed', reject=reject)
fig = epochs.average().plot_topomap(times, proj='interactive')


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
The example data <sample-dataset> also includes an "empty room"
recording taken the same day as the recording of the subject. This will
provide a more accurate estimate of environmental noise than the projectors
stored with the system (which are typically generated during annual
maintenance and tuning). Since we have this subject-specific empty-room
recording, we'll create our own projectors from it and discard the
system-provided SSP projectors (saving them first, for later comparison with
the custom ones):
Can you write Python code for it?

system_projs = raw.info['projs']
raw.del_proj()
empty_room_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                               'ernoise_raw.fif')
empty_room_raw = mne.io.read_raw_fif(empty_room_file)


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
The first line of output tells us that
~mne.preprocessing.compute_proj_ecg found three existing projectors
already in the ~mne.io.Raw object, and will include those in the
list of projectors that it returns (appending the new ECG projectors to the
end of the list). If you don't want that, you can change that behavior with
the boolean no_proj parameter. Since we've already run the computation,
we can just as easily separate out the ECG projectors by indexing the list of
projectors:
Can you write Python code for it?


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
To compute SSP projectors for the heartbeat artifact, you can use
~mne.preprocessing.compute_proj_ecg, which takes a
~mne.io.Raw object as input and returns the requested number of
projectors for magnetometers, gradiometers, and EEG channels (default is two
projectors for each channel type).
~mne.preprocessing.compute_proj_ecg also returns an :term:events
array containing the sample numbers corresponding to the peak of the
R wave <https://en.wikipedia.org/wiki/QRS_complex>__ of each detected
heartbeat.
Can you write Python code for it?

projs, events = compute_proj_ecg(raw, n_grad=1, n_mag=1, n_eeg=1, reject=None)


I am working on the file "0.22/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Visualizing how projectors affect the signal
We could visualize the different effects these have on the data by applying
each set of projectors to different copies of the ~mne.io.Raw object
using ~mne.io.Raw.apply_proj. However, the ~mne.io.Raw.plot
method has a proj parameter that allows us to temporarily apply
projectors while plotting, so we can use this to visualize the difference
without needing to copy the data. Because the projectors are so similar, we
need to zoom in pretty close on the data to see any differences:
Can you write Python code for it?

mags = mne.pick_types(raw.info, meg='mag')
for title, projs in [('system', system_projs),
                     ('subject-specific', empty_room_projs[3:])]:
    raw.add_proj(projs, remove_existing=True)
    fig = raw.plot(proj=True, order=mags, duration=1, n_channels=2)
    fig.subplots_adjust(top=0.9)  # make room for title
    fig.suptitle('{} projectors'.format(title), size='xx-large', weight='bold')


I am working on the file "0.22/_downloads/a09c964ce37825f750704113fa863276/plot_mne_inverse_envelope_correlation_volume.ipynb".
The first task is:
Compute the degree and plot it
Can you write Python code for it?

degree = mne.connectivity.degree(corr, 0.15)
stc = mne.VolSourceEstimate(degree, [src[0]['vertno']], 0, 1, 'bst_resting')
brain = stc.plot(
    src, clim=dict(kind='percent', lims=[75, 85, 95]), colormap='gnuplot',
    subjects_dir=subjects_dir, mode='glass_brain')


I am working on the file "0.22/_downloads/a09c964ce37825f750704113fa863276/plot_mne_inverse_envelope_correlation_volume.ipynb".
The first task is:
Compute the forward and inverse
Can you write Python code for it?

# This source space is really far too coarse, but we do this for speed
# considerations here
pos = 15.  # 1.5 cm is very broad, done here for speed!
src = mne.setup_volume_source_space('bst_resting', pos, bem=bem,
                                    subjects_dir=subjects_dir, verbose=True)
fwd = mne.make_forward_solution(epochs.info, trans, src, bem)
data_cov = mne.compute_covariance(epochs)
filters = make_lcmv(epochs.info, fwd, data_cov, 0.05, cov,
                    pick_ori='max-power', weight_norm='nai')
del fwd


I am working on the file "0.22/_downloads/a09c964ce37825f750704113fa863276/plot_mne_inverse_envelope_correlation_volume.ipynb".
The first task is:
Here we do some things in the name of speed, such as crop (which will
hurt SNR) and downsample. Then we compute SSP projectors and apply them.
Can you write Python code for it?

raw = mne.io.read_raw_ctf(raw_fname, verbose='error')
raw.crop(0, crop_to).pick_types(meg=True, eeg=False).load_data().resample(80)
raw.apply_gradient_compensation(3)
projs_ecg, _ = compute_proj_ecg(raw, n_grad=1, n_mag=2)
projs_eog, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='MLT31-4407')
raw.info['projs'] += projs_ecg
raw.info['projs'] += projs_eog
raw.apply_proj()
cov = mne.compute_raw_covariance(raw)  # compute before band-pass of interest


I am working on the file "0.22/_downloads/a1ab4842a5aa341564b4fa0a6bf60065/plot_dipole_orientations.ipynb".
The first task is:
Discarding dipole orientation information
Often, further analysis of the data does not need information about the
orientation of the dipoles, but rather their magnitudes. The pick_ori
parameter of the :func:mne.minimum_norm.apply_inverse function allows you
to specify whether to return the full vector solution ('vector') or
rather the magnitude of the vectors (None, the default) or only the
activity in the direction perpendicular to the cortex ('normal').
Can you write Python code for it?

# Only retain vector magnitudes
stc = apply_inverse(left_auditory, inv, pick_ori=None)

# Visualize it at the moment of peak activity
_, time_max = stc.get_peak(hemi='lh')
brain = stc.plot(surface='white', subjects_dir=subjects_dir,
                 initial_time=time_max, time_unit='s', size=(600, 400))


I am working on the file "0.22/_downloads/a1ab4842a5aa341564b4fa0a6bf60065/plot_dipole_orientations.ipynb".
The first task is:
Fixed dipole orientations
While the source space defines the position of the dipoles, the inverse
operator defines the possible orientations of them. One of the options is to
assign a fixed orientation. Since the neural currents from which MEG and EEG
signals originate flows mostly perpendicular to the cortex [1]_, restricting
the orientation of the dipoles accordingly places a useful restriction on the
source estimate.
By specifying fixed=True when calling
:func:mne.minimum_norm.make_inverse_operator, the dipole orientations are
fixed to be orthogonal to the surface of the cortex, pointing outwards. Let's
visualize this:
Can you write Python code for it?

fig = mne.viz.create_3d_figure(size=(600, 400))

# Plot the cortex
mne.viz.plot_alignment(
    subject=subject, subjects_dir=subjects_dir, trans=trans,
    surfaces='white', coord_frame='head', fig=fig)

# Show the dipoles as arrows pointing along the surface normal
mne.viz.plot_dipole_locations(
    dipoles=dipoles, trans=trans, mode='arrow', subject=subject,
    subjects_dir=subjects_dir, coord_frame='head', scale=7e-4, fig=fig)

mne.viz.set_3d_view(figure=fig, azimuth=180, distance=0.1)


I am working on the file "0.22/_downloads/a1ab4842a5aa341564b4fa0a6bf60065/plot_dipole_orientations.ipynb".
The first task is:
Limiting orientations, but not fixing them
Often, the best results will be obtained by allowing the dipoles to have
somewhat free orientation, but not stray too far from a orientation that is
perpendicular to the cortex. The loose parameter of the
:func:mne.minimum_norm.make_inverse_operator allows you to specify a value
between 0 (fixed) and 1 (unrestricted or "free") to indicate the amount the
orientation is allowed to deviate from the surface normal.
Can you write Python code for it?

# Set loose to 0.2, the default value
inv = make_inverse_operator(left_auditory.info, fwd, noise_cov, fixed=False,
                            loose=0.2)
stc = apply_inverse(left_auditory, inv, pick_ori='vector')

# Visualize it at the moment of peak activity.
_, time_max = stc.magnitude().get_peak(hemi='lh')
brain_loose = stc.plot(subjects_dir=subjects_dir, initial_time=time_max,
                       time_unit='s', size=(600, 400), overlay_alpha=0)


I am working on the file "0.22/_downloads/a1ab4842a5aa341564b4fa0a6bf60065/plot_dipole_orientations.ipynb".
The first task is:
When computing the source estimate, the activity at each of the three dipoles
is collapsed into the XYZ components of a single vector, which leads to the
following source estimate for the sample data:
Can you write Python code for it?

# Make an inverse operator with loose dipole orientations
inv = make_inverse_operator(left_auditory.info, fwd, noise_cov, fixed=False,
                            loose=1.0)

# Compute the source estimate, indicate that we want a vector solution
stc = apply_inverse(left_auditory, inv, pick_ori='vector')

# Visualize it at the moment of peak activity.
_, time_max = stc.magnitude().get_peak(hemi='lh')
brain_mag = stc.plot(subjects_dir=subjects_dir, initial_time=time_max,
                     time_unit='s', size=(600, 400), overlay_alpha=0)


I am working on the file "0.22/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
Configuring MNE-Python
This tutorial covers how to configure MNE-Python to suit your local system and
your analysis preferences.
   :depth: 1
We begin by importing the necessary Python modules:
Can you write Python code for it?


I am working on the file "0.22/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
Getting and setting configuration variables
Configuration variables are read and written using the functions
:func:mne.get_config and :func:mne.set_config. To read a specific
configuration variable, pass its name to :func:~mne.get_config as the
key parameter (key is the first parameter so you can pass it unnamed
if you want):
Can you write Python code for it?


I am working on the file "0.22/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
However it is not a good idea to directly edit files in the :file:.mne
directory; use the getting and setting functions described in the
previous section <config-get-set>.
If for some reason you want to load the configuration from a different
location, you can pass the home_dir parameter to
:func:~mne.get_config_path, specifying the parent directory of the
:file:.mne directory where the configuration file you wish to load is
stored.
Using environment variables
For compatibility with :doc:MNE-C <../../install/mne_c>, MNE-Python
also reads and writes environment variables_ to specify configuration. This
is done with the same functions that read and write the JSON configuration,
and is controlled with the parameters use_env and set_env. By
default, :func:~mne.get_config will check :data:os.environ before
checking the MNE-Python JSON file; to check only the JSON file use
use_env=False. To demonstrate, here's an environment variable that is not
specific to MNE-Python (and thus is not in the JSON config file):
Can you write Python code for it?

# make sure it's not in the JSON file (no error means our assertion held):
assert mne.get_config('PATH', use_env=False) is None
# but it *is* in the environment:
print(mne.get_config('PATH'))


I am working on the file "0.22/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
Let's delete that config variable we just created. To unset a config
variable, use :func:~mne.set_config with value=None. Since we're still
dealing with an unrecognized key (as far as MNE-Python is concerned) we'll
still get a warning, but the key will be unset:
Can you write Python code for it?

mne.set_config('MNEE_USE_CUUDAA', None)
assert 'MNEE_USE_CUUDAA' not in mne.get_config('')


I am working on the file "0.22/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
No messages were generated, because none of the messages were of severity
"warning" or worse. Next, we'll load the same file with log level info
(the default level):
Can you write Python code for it?

raw = mne.io.read_raw_kit(kit_data_path, verbose='info')


I am working on the file "0.22/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
The logging levels that can be set as config variables are debug,
info, warning, error, and critical. Around 90% of the log
messages in MNE-Python are info messages, so for most users the choice is
between info (tell me what is happening) and warning (tell me only if
something worrisome happens). The debug logging level is intended for
MNE-Python developers.
In an earlier section <config-get-set> we saw how
:func:mne.set_config is used to change the logging level for the current
Python session and all future sessions. To change the logging level only for
the current Python session, you can use :func:mne.set_log_level instead.
The :func:~mne.set_log_level function takes the same five string options
that are used for the MNE_LOGGING_LEVEL config variable; additionally, it
can accept :class:int or :class:bool values that are equivalent to those
strings. The equivalencies are given in this table:
+----------+---------+---------+
| String   | Integer | Boolean |
+==========+=========+=========+
| DEBUG    | 10      |         |
+----------+---------+---------+
| INFO     | 20      | True    |
+----------+---------+---------+
| WARNING  | 30      | False   |
+----------+---------+---------+
| ERROR    | 40      |         |
+----------+---------+---------+
| CRITICAL | 50      |         |
+----------+---------+---------+
With many MNE-Python functions it is possible to change the logging level
temporarily for just that function call, by using the verbose parameter.
To illustrate this, we'll load some sample data with different logging levels
set. First, with log level warning:
Can you write Python code for it?

kit_data_path = os.path.join(os.path.abspath(os.path.dirname(mne.__file__)),
                             'io', 'kit', 'tests', 'data', 'test.sqd')
raw = mne.io.read_raw_kit(kit_data_path, verbose='warning')


I am working on the file "0.22/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
The second convenience mode will return a :class:tuple of all the keys that
MNE-Python recognizes and uses, regardless of whether they've been set on
your system. This is done by passing an empty string '' as the key:
Can you write Python code for it?


I am working on the file "0.22/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
There are also two convenience modes of :func:~mne.get_config. The first
will return a :class:dict containing all config variables (and their
values) that have been set on your system; this is done by passing
key=None (which is the default, so it can be omitted):
Can you write Python code for it?

print(mne.get_config())  # same as mne.get_config(key=None)


I am working on the file "0.22/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
This time, we got a few messages about extracting information from the file,
converting that information into the MNE-Python :class:~mne.Info format,
etc. Finally, if we request debug-level information, we get even more
detail:
Can you write Python code for it?

raw = mne.io.read_raw_kit(kit_data_path, verbose='debug')


I am working on the file "0.22/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:

Note

We could also have loaded the events from file, using
    :func:`mne.read_events`::

        sample_data_events_file = os.path.join(sample_data_folder,
                                               'MEG', 'sample',
                                               'sample_audvis_raw-eve.fif')
        events_from_file = mne.read_events(sample_data_events_file)

    See `tut-section-events-io` for more details.

The :class:~mne.io.Raw object and the events array are the bare minimum
needed to create an :class:~mne.Epochs object, which we create with the
:class:mne.Epochs class constructor. However, you will almost surely want
to change some of the other default parameters. Here we'll change tmin
and tmax (the time relative to each event at which to start and end each
epoch). Note also that the :class:~mne.Epochs constructor accepts
parameters reject and flat for rejecting individual epochs based on
signal amplitude. See the tut-reject-epochs-section section for
examples.
Can you write Python code for it?

epochs = mne.Epochs(raw, events, tmin=-0.3, tmax=0.7)


I am working on the file "0.22/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
Changing channel name and type
You can change the name or type of a channel using
:meth:~mne.Epochs.rename_channels or :meth:~mne.Epochs.set_channel_types.
Both methods take :class:dictionaries <dict> where the keys are existing
channel names, and the values are the new name (or type) for that channel.
Existing channels that are not in the dictionary will be unchanged.
Can you write Python code for it?

epochs.rename_channels({'EOG 061': 'BlinkChannel'})

epochs.set_channel_types({'EEG 060': 'ecg'})
print(list(zip(epochs.ch_names, epochs.get_channel_types()))[-4:])

# let's set them back to the correct values before moving on
epochs.rename_channels({'BlinkChannel': 'EOG 061'})
epochs.set_channel_types({'EEG 060': 'eeg'})


I am working on the file "0.22/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
However, if no match is found, an error is returned:
Can you write Python code for it?

try:
    print(epochs[['top', 'bottom']])
except KeyError:
    print('Tag-based selection with no matches raises a KeyError!')


I am working on the file "0.22/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
However, if you wanted to expand the time domain of an :class:~mne.Epochs
object, you would need to go back to the :class:~mne.io.Raw data and
recreate the :class:~mne.Epochs with different values for tmin and/or
tmax.
It is also possible to change the "zero point" that defines the time values
in an :class:~mne.Epochs object, with the :meth:~mne.Epochs.shift_time
method. :meth:~mne.Epochs.shift_time allows shifting times relative to the
current values, or specifying a fixed time to set as the new time value of
the first sample (deriving the new time values of subsequent samples based on
the :class:~mne.Epochs object's sampling frequency).
Can you write Python code for it?

# shift times so that first sample of each epoch is at time zero
later_epochs = epochs.copy().shift_time(tshift=0., relative=False)
print(later_epochs.times[:3])

# shift times by a relative amount
later_epochs.shift_time(tshift=-7, relative=True)
print(later_epochs.times[:3])

del shorter_epochs, later_epochs


I am working on the file "0.22/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
If you want to iterate over :class:~mne.Epochs objects, you can use an
integer index as the iterator:
Can you write Python code for it?

for index in range(3):
    print(type(epochs[index]))


I am working on the file "0.22/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
In almost all cases this will not require changing anything about your code.
However, if you need to do type checking on epochs objects, you can test
against the base class that these classes are derived from:
Can you write Python code for it?

print(all([isinstance(epochs, mne.BaseEpochs),
           isinstance(epochs_from_file, mne.BaseEpochs)]))


I am working on the file "0.22/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
Iterating over Epochs
Iterating over an :class:~mne.Epochs object will yield :class:arrays
<numpy.ndarray> rather than single-trial :class:~mne.Epochs objects:
Can you write Python code for it?

for epoch in epochs[:3]:
    print(type(epoch))


I am working on the file "0.22/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
Note that although time shifting respects the sampling frequency (the spacing
between samples), it does not enforce the assumption that there is a sample
occurring at exactly time=0.
Extracting data in other forms
The :meth:~mne.Epochs.get_data method returns the epoched data as a
:class:NumPy array <numpy.ndarray>, of shape (n_epochs, n_channels,
n_times); an optional picks parameter selects a subset of channels by
index, name, or type:
Can you write Python code for it?

eog_data = epochs.get_data(picks='EOG 061')
meg_data = epochs.get_data(picks=['mag', 'grad'])
channel_4_6_8 = epochs.get_data(picks=slice(4, 9, 2))

for name, arr in dict(EOG=eog_data, MEG=meg_data, Slice=channel_4_6_8).items():
    print('{} contains {} channels'.format(name, arr.shape[1]))


I am working on the file "0.22/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
Notice that the Event IDs are in quotes; since we didn't provide an event
dictionary, the :class:mne.Epochs constructor created one automatically and
used the string representation of the integer Event IDs as the dictionary
keys. This is more clear when viewing the event_id attribute:
Can you write Python code for it?


I am working on the file "0.22/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
Notice that the individual epochs are sequentially numbered along the bottom
axis; the event ID associated with the epoch is marked on the top axis;
epochs are separated by vertical dashed lines; and a vertical solid green
line marks time=0 for each epoch (i.e., in this case, the stimulus onset
time for each trial). Epoch plots are interactive (similar to
:meth:raw.plot() <mne.io.Raw.plot>) and have many of the same interactive
controls as :class:~mne.io.Raw plots. Horizontal and vertical scrollbars
allow browsing through epochs or channels (respectively), and pressing
:kbd:? when the plot is focused will show a help screen with all the
available controls. See tut-visualize-epochs for more details (as well
as other ways of visualizing epoched data).
Subselecting epochs
Now that we have our :class:~mne.Epochs object with our descriptive event
labels added, we can subselect epochs easily using square brackets. For
example, we can load all the "catch trials" where the stimulus was a face:
Can you write Python code for it?


I am working on the file "0.22/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
See the tut-epochs-dataframe tutorial for many more examples of the
:meth:~mne.Epochs.to_data_frame method.
Loading and saving Epochs objects to disk
:class:~mne.Epochs objects can be loaded and saved in the .fif format
just like :class:~mne.io.Raw objects, using the :func:mne.read_epochs
function and the :meth:~mne.Epochs.save method. Functions are also
available for loading data that was epoched outside of MNE-Python, such as
:func:mne.read_epochs_eeglab and :func:mne.read_epochs_kit.
Can you write Python code for it?

epochs.save('saved-audiovisual-epo.fif', overwrite=True)
epochs_from_file = mne.read_epochs('saved-audiovisual-epo.fif', preload=False)


I am working on the file "0.22/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
Selecting epochs by index
:class:~mne.Epochs objects can also be indexed with integers, :term:slices
<slice>, or lists of integers. This method of selection ignores event
labels, so if you want the first 10 epochs of a particular type, you can
select the type first, then use integers or slices:
Can you write Python code for it?

print(epochs[:10])    # epochs 0-9
print(epochs[1:8:2])  # epochs 1, 3, 5, 7

print(epochs['buttonpress'][:4])            # first 4 "buttonpress" epochs
print(epochs['buttonpress'][[0, 1, 2, 3]])  # same as previous line


I am working on the file "0.22/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
This time let's pass preload=True and provide an event dictionary; our
provided dictionary will get stored as the event_id attribute and will
make referencing events and pooling across event types easier:
Can you write Python code for it?

event_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
              'visual/right': 4, 'face': 5, 'buttonpress': 32}
epochs = mne.Epochs(raw, events, tmin=-0.3, tmax=0.7, event_id=event_dict,
                    preload=True)
print(epochs.event_id)
del raw  # we're done with raw, free up some memory


I am working on the file "0.22/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
We can also pool across conditions easily, thanks to how MNE-Python handles
the / character in epoch labels (using what is sometimes called
"tag-based indexing"):
Can you write Python code for it?

# pool across left + right
print(epochs['auditory'])
assert len(epochs['auditory']) == (len(epochs['auditory/left']) +
                                   len(epochs['auditory/right']))
# pool across auditory + visual
print(epochs['left'])
assert len(epochs['left']) == (len(epochs['auditory/left']) +
                               len(epochs['visual/left']))


I am working on the file "0.22/_downloads/ab8b138d73a5774a0442141d84ed9689/plot_10_epochs_overview.ipynb".
The first task is:
You can also pool conditions by passing multiple tags as a list. Note that
MNE-Python will not complain if you ask for tags not present in the object,
as long as it can find some match: the below example is parsed as
(inclusive) 'right' or 'bottom', and you can see from the output
that it selects only auditory/right and visual/right.
Can you write Python code for it?


I am working on the file "0.22/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
Brainstorm CTF phantom dataset tutorial
Here we compute the evoked from raw for the Brainstorm CTF phantom
tutorial dataset. For comparison, see [1]_ and:
https://neuroimage.usc.edu/brainstorm/Tutorials/PhantomCtf

References
.. [1] Tadel F, Baillet S, Mosher JC, Pantazis D, Leahy RM.
       Brainstorm: A User-Friendly Application for MEG/EEG Analysis.
       Computational Intelligence and Neuroscience, vol. 2011, Article ID
       879716, 13 pages, 2011. doi:10.1155/2011/879716
Can you write Python code for it?

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

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

import mne
from mne import fit_dipole
from mne.datasets.brainstorm import bst_phantom_ctf
from mne.io import read_raw_ctf

print(__doc__)


I am working on the file "0.22/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
But here we can get slightly better noise suppression, lower localization
bias, and a better dipole goodness of fit with spatio-temporal (tSSS)
Maxwell filtering:
Can you write Python code for it?

raw.apply_gradient_compensation(0)  # must un-do software compensation first
mf_kwargs = dict(origin=(0., 0., 0.), st_duration=10.)
raw = mne.preprocessing.maxwell_filter(raw, **mf_kwargs)
raw.plot()


I am working on the file "0.22/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
Compare the actual position with the estimated one.
Can you write Python code for it?

expected_pos = np.array([18., 0., 49.])
diff = np.sqrt(np.sum((dip.pos[0] * 1000 - expected_pos) ** 2))
print('Actual pos:     %s mm' % np.array_str(expected_pos, precision=1))
print('Estimated pos:  %s mm' % np.array_str(dip.pos[0] * 1000, precision=1))
print('Difference:     %0.1f mm' % diff)
print('Amplitude:      %0.1f nAm' % (1e9 * dip.amplitude[0]))
print('GOF:            %0.1f %%' % dip.gof[0])


I am working on the file "0.22/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
Let's create some events using this signal by thresholding the sinusoid.
Can you write Python code for it?

events = np.where(np.diff(sinusoid > 0.5) > 0)[1] + raw.first_samp
events = np.vstack((events, np.zeros_like(events), np.ones_like(events))).T


I am working on the file "0.22/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
Let's use a sphere head geometry model <eeg_sphere_model>
and let's see the coordinate alignment and the sphere location.
Can you write Python code for it?

sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=None)

mne.viz.plot_alignment(raw.info, subject='sample',
                       meg='helmet', bem=sphere, dig=True,
                       surfaces=['brain'])
del raw, epochs


I am working on the file "0.22/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
Our choice of tmin and tmax should capture exactly one cycle, so
we can make the unusual choice of baselining using the entire epoch
when creating our evoked data. We also then crop to a single time point
(@t=0) because this is a peak in our signal.
Can you write Python code for it?

tmin = -0.5 / dip_freq
tmax = -tmin
epochs = mne.Epochs(raw, events, event_id=1, tmin=tmin, tmax=tmax,
                    baseline=(None, None))
evoked = epochs.average()
evoked.plot(time_unit='s')
evoked.crop(0., 0.)


I am working on the file "0.22/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
The data were collected with a CTF system at 2400 Hz.
Can you write Python code for it?

data_path = bst_phantom_ctf.data_path(verbose=True)

# Switch to these to use the higher-SNR data:
# raw_path = op.join(data_path, 'phantom_200uA_20150709_01.ds')
# dip_freq = 7.
raw_path = op.join(data_path, 'phantom_20uA_20150603_03.ds')
dip_freq = 23.
erm_path = op.join(data_path, 'emptyroom_20150709_01.ds')
raw = read_raw_ctf(raw_path, preload=True)


I am working on the file "0.22/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
The sinusoidal signal is generated on channel HDAC006, so we can use
that to obtain precise timing.
Can you write Python code for it?

sinusoid, times = raw[raw.ch_names.index('HDAC006-4408')]
plt.figure()
plt.plot(times[times < 1.], sinusoid.T[times < 1.])


I am working on the file "0.22/_downloads/ad29ebf74c7706fc10eea18e56a6fec7/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
To do a dipole fit, let's use the covariance provided by the empty room
recording.
Can you write Python code for it?

raw_erm = read_raw_ctf(erm_path).apply_gradient_compensation(0)
raw_erm = mne.preprocessing.maxwell_filter(raw_erm, coord_frame='meg',
                                           **mf_kwargs)
cov = mne.compute_raw_covariance(raw_erm)
del raw_erm

dip, residual = fit_dipole(evoked, cov, sphere, verbose=True)


I am working on the file "0.22/_downloads/ad79868fcd6af353ce922b8a3a2fc362/plot_30_info.ipynb".
The first task is:
:func:~mne.pick_channels_regexp can be especially useful for channels named
according to the 10-20 <ten-twenty_>_ system (e.g., to select all channels
ending in "z" to get the midline, or all channels beginning with "O" to get
the occipital channels). Note that :func:~mne.pick_channels_regexp uses the
Python standard module :mod:re to perform regular expression matching; see
the documentation of the :mod:re module for implementation details.

Warning

Both :func:`~mne.pick_channels` and :func:`~mne.pick_channels_regexp`
   operate on lists of channel names, so they are unaware of which channels
   (if any) have been marked as "bad" in ``info['bads']``. Use caution to
   avoid accidentally selecting bad channels.

Obtaining channel type information
Sometimes it can be useful to know channel type based on its index in the
data array. For this case, use :func:mne.channel_type, which takes
an :class:~mne.Info object and a single integer channel index:
Can you write Python code for it?


I am working on the file "0.22/_downloads/ad79868fcd6af353ce922b8a3a2fc362/plot_30_info.ipynb".
The first task is:
:func:~mne.pick_types works differently, since channel type cannot always
be reliably determined from channel name alone. Consequently,
:func:~mne.pick_types needs an :class:~mne.Info object instead of just a
list of channel names, and has boolean keyword arguments for each channel
type. Default behavior is to pick only MEG channels (and MEG reference
channels if present) and exclude any channels already marked as "bad" in the
bads field of the :class:~mne.Info object. Therefore, to get all and
only the EEG channel indices (including the "bad" EEG channels) we must
pass meg=False and exclude=[]:
Can you write Python code for it?

print(mne.pick_types(info, meg=False, eeg=True, exclude=[]))


I am working on the file "0.22/_downloads/ad79868fcd6af353ce922b8a3a2fc362/plot_30_info.ipynb".
The first task is:
As seen in the introductory tutorial <tut-overview>, when a
:class:~mne.io.Raw object is loaded, an :class:~mne.Info object is
created automatically, and stored in the raw.info attribute:
Can you write Python code for it?


I am working on the file "0.22/_downloads/ad79868fcd6af353ce922b8a3a2fc362/plot_30_info.ipynb".
The first task is:
As you can see, the :class:~mne.Info object keeps track of a lot of
information about:

the recording system (gantry angle, HPI details, sensor digitizations,
  channel names, ...)
the experiment (project name and ID, subject information, recording date,
  experimenter name or ID, ...)
the data (sampling frequency, applied filter frequencies, bad channels,
  projectors, ...)

The complete list of fields is given in :class:the API documentation
<mne.Info>.
Querying the Info object
The fields in a :class:~mne.Info object act like Python :class:dictionary
<dict> keys, using square brackets and strings to access the contents of a
field:
Can you write Python code for it?

print(info.keys())
print()  # insert a blank line
print(info['ch_names'])


I am working on the file "0.22/_downloads/ad79868fcd6af353ce922b8a3a2fc362/plot_30_info.ipynb".
The first task is:
Dropping channels from an Info object
If you want to modify an :class:~mne.Info object by eliminating some of the
channels in it, you can use the :func:mne.pick_info function to pick the
channels you want to keep and omit the rest:
Can you write Python code for it?

print(info['nchan'])
eeg_indices = mne.pick_types(info, meg=False, eeg=True)
print(mne.pick_info(info, eeg_indices)['nchan'])


I am working on the file "0.22/_downloads/ad79868fcd6af353ce922b8a3a2fc362/plot_30_info.ipynb".
The first task is:
However, it is not strictly necessary to load the :class:~mne.io.Raw object
in order to view or edit the :class:~mne.Info object; you can extract all
the relevant information into a stand-alone :class:~mne.Info object using
:func:mne.io.read_info:
Can you write Python code for it?

info = mne.io.read_info(sample_data_raw_file)
print(info)


I am working on the file "0.22/_downloads/ad79868fcd6af353ce922b8a3a2fc362/plot_30_info.ipynb".
The first task is:
The Info data structure
This tutorial describes the :class:mne.Info data structure, which keeps track
of various recording details, and is attached to :class:~mne.io.Raw,
:class:~mne.Epochs, and :class:~mne.Evoked objects.
   :depth: 2
We'll begin by loading the Python modules we need, and loading the same
example data <sample-dataset> we used in the introductory tutorial
<tut-overview>:
Can you write Python code for it?

import os
import mne

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


I am working on the file "0.22/_downloads/ad79868fcd6af353ce922b8a3a2fc362/plot_30_info.ipynb".
The first task is:
To obtain several channel types at once, you could embed
:func:~mne.channel_type in a :term:list comprehension, or use the
:meth:~mne.io.Raw.get_channel_types method of a :class:~mne.io.Raw,
:class:~mne.Epochs, or :class:~mne.Evoked instance:
Can you write Python code for it?

picks = (25, 76, 77, 319)
print([mne.channel_type(info, x) for x in picks])
print(raw.get_channel_types(picks=picks))


I am working on the file "0.22/_downloads/ae8fb158e1a8fbcc6dff5d3e55a698dc/plot_30_filtering_resampling.ipynb".
The first task is:
A half-period of this slow drift appears to last around 10 seconds, so a full
period would be 20 seconds, i.e., $\frac{1}{20} \mathrm{Hz}$. To be
sure those components are excluded, we want our highpass to be higher than
that, so let's try $\frac{1}{10} \mathrm{Hz}$ and $\frac{1}{5}
\mathrm{Hz}$ filters to see which works best:
Can you write Python code for it?

for cutoff in (0.1, 0.2):
    raw_highpass = raw.copy().filter(l_freq=cutoff, h_freq=None)
    fig = raw_highpass.plot(duration=60, order=mag_channels, proj=False,
                            n_channels=len(mag_channels), remove_dc=False)
    fig.subplots_adjust(top=0.9)
    fig.suptitle('High-pass filtered at {} Hz'.format(cutoff), size='xx-large',
                 weight='bold')


I am working on the file "0.22/_downloads/ae8fb158e1a8fbcc6dff5d3e55a698dc/plot_30_filtering_resampling.ipynb".
The first task is:
Background on filtering
A filter removes or attenuates parts of a signal. Usually, filters act on
specific frequency ranges of a signal — for example, suppressing all
frequency components above or below a certain cutoff value. There are many
ways of designing digital filters; see disc-filtering for a longer
discussion of the various approaches to filtering physiological signals in
MNE-Python.
Repairing artifacts by filtering
Artifacts that are restricted to a narrow frequency range can sometimes
be repaired by filtering the data. Two examples of frequency-restricted
artifacts are slow drifts and power line noise. Here we illustrate how each
of these can be repaired by filtering.
Slow drifts
Low-frequency drifts in raw data can usually be spotted by plotting a fairly
long span of data with the :meth:~mne.io.Raw.plot method, though it is
helpful to disable channel-wise DC shift correction to make slow drifts
more readily visible. Here we plot 60 seconds, showing all the magnetometer
channels:
Can you write Python code for it?

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


I am working on the file "0.22/_downloads/ae8fb158e1a8fbcc6dff5d3e55a698dc/plot_30_filtering_resampling.ipynb".
The first task is:
Because resampling involves filtering, there are some pitfalls to resampling
at different points in the analysis stream:

Performing resampling on :class:~mne.io.Raw data (before epoching) will
  negatively affect the temporal precision of Event arrays, by causing
  jitter_ in the event timing. This reduced temporal precision will
  propagate to subsequent epoching operations.

Performing resampling after epoching can introduce edge artifacts on
  every epoch, whereas filtering the :class:~mne.io.Raw object will only
  introduce artifacts at the start and end of the recording (which is often
  far enough from the first and last epochs to have no affect on the
  analysis).

The following section suggests best practices to mitigate both of these
issues.
Best practices
To avoid the reduction in temporal precision of events that comes with
resampling a :class:~mne.io.Raw object, and also avoid the edge artifacts
that come with filtering an :class:~mne.Epochs or :class:~mne.Evoked
object, the best practice is to:

low-pass filter the :class:~mne.io.Raw data at or below
   $\frac{1}{3}$ of the desired sample rate, then

decimate the data after epoching, by either passing the decim
   parameter to the :class:~mne.Epochs constructor, or using the
   :meth:~mne.Epochs.decimate method after the :class:~mne.Epochs have
   been created.

Warning

The recommendation for setting the low-pass corner frequency at
   $\frac{1}{3}$ of the desired sample rate is a fairly safe rule of
   thumb based on the default settings in :meth:`raw.filter()
   <mne.io.Raw.filter>` (which are different from the filter settings used
   inside the :meth:`raw.resample() <mne.io.Raw.resample>` method). If you
   use a customized lowpass filter (specifically, if your transition
   bandwidth is wider than 0.5× the lowpass cutoff), downsampling to 3× the
   lowpass cutoff may still not be enough to avoid `aliasing`_, and
   MNE-Python will not warn you about it (because the :class:`raw.info
  ...
Can you write Python code for it?

current_sfreq = raw.info['sfreq']
desired_sfreq = 90  # Hz
decim = np.round(current_sfreq / desired_sfreq).astype(int)
obtained_sfreq = current_sfreq / decim
lowpass_freq = obtained_sfreq / 3.

raw_filtered = raw.copy().filter(l_freq=None, h_freq=lowpass_freq)
events = mne.find_events(raw_filtered)
epochs = mne.Epochs(raw_filtered, events, decim=decim)

print('desired sampling frequency was {} Hz; decim factor of {} yielded an '
      'actual sampling frequency of {} Hz.'
      .format(desired_sfreq, decim, epochs.info['sfreq']))


I am working on the file "0.22/_downloads/ae8fb158e1a8fbcc6dff5d3e55a698dc/plot_30_filtering_resampling.ipynb".
The first task is:
Filtering and resampling data
This tutorial covers filtering and resampling, and gives examples of how
filtering can be used for artifact repair.
   :depth: 2
We begin as always by importing the necessary Python modules and loading some
example data <sample-dataset>. We'll also crop the data to 60 seconds
(to save memory on the documentation server):
Can you write Python code for it?

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

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file)
raw.crop(0, 60).load_data()  # use just 60 seconds of data, to save memory


I am working on the file "0.22/_downloads/ae8fb158e1a8fbcc6dff5d3e55a698dc/plot_30_filtering_resampling.ipynb".
The first task is:
Looks like 0.1 Hz was not quite high enough to fully remove the slow drifts.
Notice that the text output summarizes the relevant characteristics of the
filter that was created. If you want to visualize the filter, you can pass
the same arguments used in the call to :meth:raw.filter()
<mne.io.Raw.filter> above to the function :func:mne.filter.create_filter
to get the filter parameters, and then pass the filter parameters to
:func:mne.viz.plot_filter. :func:~mne.filter.create_filter also requires
parameters data (a :class:NumPy array <numpy.ndarray>) and sfreq
(the sampling frequency of the data), so we'll extract those from our
:class:~mne.io.Raw object:
Can you write Python code for it?

filter_params = mne.filter.create_filter(raw.get_data(), raw.info['sfreq'],
                                         l_freq=0.2, h_freq=None)


I am working on the file "0.22/_downloads/b3ffeb2f03415702b6ce2358ca876d49/plot_35_artifact_correction_regression.ipynb".
The first task is:
Compute and apply EOG regression
Next we'll compare the ~mne.Evoked data (average across epochs) before and
after we regress out the EOG signal. We do this by first estimating the
regression coefficients on epoch data with the evoked response subtracted
out. As long as the EOG artifacts are in the epochs, then the algorithm
should be able to estimate regression coefficients. The EOG artifacts do not
need to be time-locked to the stimulus/epoch event timing of the epochs.
Can you write Python code for it?

# do regression
_, betas = mne.preprocessing.regress_artifact(epochs.copy().subtract_evoked())


I am working on the file "0.22/_downloads/b3ffeb2f03415702b6ce2358ca876d49/plot_35_artifact_correction_regression.ipynb".
The first task is:
For this dataset and example we'll use just event type 1 (only the
"standard" trials) for simplicity. Event timing is adjusted by comparing the
trigger times on detected sound onsets on channel UADC001-4408.
Can you write Python code for it?

events = mne.find_events(raw, stim_channel='UPPT001')
sound_data = raw[raw.ch_names.index('UADC001-4408')][0][0]
onsets = np.where(np.abs(sound_data) > 2. * np.std(sound_data))[0]
min_diff = int(0.5 * raw.info['sfreq'])
diffs = np.concatenate([[min_diff + 1], np.diff(onsets)])
onsets = onsets[diffs > min_diff]
assert len(onsets) == len(events)
events[:, 0] = onsets
epochs = mne.Epochs(raw, events, event_id=1, decim=decim, preload=True)


I am working on the file "0.22/_downloads/b3ffeb2f03415702b6ce2358ca876d49/plot_35_artifact_correction_regression.ipynb".
The first task is:
Repairing artifacts with regression
This tutorial covers removal of artifacts using regression as in Gratton et al.
(1983) :footcite:GrattonEtAl1983.
   :depth: 2
Generally speaking, artifacts that result in time waveforms on the sensors
that are accurately reflected by some reference signal can be removed by
regression. Blink artifacts captured by bipolar EOG channels serve as a good
example of this, so we will demonstrate this here.
Although ECG signals are well captured by bipolar ECG electrodes,
regression-based removal of ECG artifacts usually does not work very well.
This is likely because the heart acts like a rotating dipole, and
therefore the ECG channel time waveform recorded from the ECG electrode sites
does not reflect the same temporal dynamics that manifest at each MEG channel
(obtained by sampling some component of the related magnetic vector field).
Other approaches like ICA <tut-artifact-ica> or
SSP <tut-artifact-ssp> will likely work better for ECG.
Prepare the data
We begin as always by importing the necessary Python modules and loading some
data. In this case we use data from Brainstorm <tut-brainstorm-auditory>
because it has some clear, large blink artifacts. We then crop it to 60
seconds, set some channel information, then process the auditory evoked data.
Note that there are other corrections that are useful for this dataset that we
will not apply here (see tut-brainstorm-auditory for more information).
Can you write Python code for it?

import os.path as op
import numpy as np
import mne

data_path = mne.datasets.brainstorm.bst_auditory.data_path()
raw_fname = op.join(data_path, 'MEG', 'bst_auditory', 'S01_AEF_20131218_01.ds')
raw = mne.io.read_raw_ctf(raw_fname).crop(0, 60)
raw.set_channel_types({'HEOG': 'eog', 'VEOG': 'eog', 'ECG': 'ecg'})
raw.pick_types(meg=True, stim=True, misc=True,
               eog=True, ecg=True, ref_meg=False).load_data()
raw.info['bads'] = ['MLO52-4408', 'MRT51-4408', 'MLO42-4408', 'MLO43-4408']
raw.filter(None, 40)
decim = 12  # 2400 -> 200 Hz sample rate for epochs


I am working on the file "0.22/_downloads/b3ffeb2f03415702b6ce2358ca876d49/plot_35_artifact_correction_regression.ipynb".
The first task is:
The effect is subtle in these evoked data, but you can see that a bump toward
the end of the window has had its amplitude decreased.
Visualize the effect on EOG epochs
The effect is clearer if we create epochs around (autodetected) blink events,
and plot the average blink artifact before and after the regression based on
the same regression coefficients we computed earlier. If the resulting
blink evoked data are reduced to near zero, it helps validate
that the regression efficiently removes blink artifacts.
Can you write Python code for it?

# extract epochs around each blink
evo_kwargs['ylim'].update(mag=[-4000, 3000], eog=[-600, 100])
eog_epochs = mne.preprocessing.create_eog_epochs(raw, decim=decim)
eog_epochs.apply_baseline((None, None))

# regress, using the `betas` we already found above
eog_epochs_clean, _ = mne.preprocessing.regress_artifact(eog_epochs,
                                                         betas=betas)

# plot original blink epochs
fig = eog_epochs.average(picks=plot_picks).plot(**evo_kwargs)
fig.suptitle('EOG epochs')
mne.viz.tight_layout()

# plot regressed blink epochs
fig = eog_epochs_clean.average(picks=plot_picks).plot(**evo_kwargs)
fig.suptitle('EOG epochs, EOG regressed')
mne.viz.tight_layout()


I am working on the file "0.22/_downloads/b3ffeb2f03415702b6ce2358ca876d49/plot_35_artifact_correction_regression.ipynb".
The first task is:
Visualize the effect on auditory epochs
Now we can plot the auditory evoked response before and after regression:
Can you write Python code for it?

# get ready to plot
plot_picks = ['meg', 'eog']
evo_kwargs = dict(picks=plot_picks, spatial_colors=True,
                  verbose='error')  # ignore warnings about spatial colors

evo_kwargs['ylim'] = dict(mag=[-350, 300], eog=[-35, 5])
# plot original data (averaged across epochs)
fig = epochs.average(picks=plot_picks).plot(**evo_kwargs)
fig.suptitle('Auditory epochs')
mne.viz.tight_layout()

# plot regressed data
fig = epochs_clean.average(picks=plot_picks).plot(**evo_kwargs)
fig.suptitle('Auditory epochs, EOG regressed')
mne.viz.tight_layout()

# clean up
del epochs, epochs_clean


I am working on the file "0.22/_downloads/b3ffeb2f03415702b6ce2358ca876d49/plot_35_artifact_correction_regression.ipynb".
The first task is:
Visualize the effect on raw data
We can also apply the regression directly to the raw data. To do this
following the Gratton method requires first computing the regression weights
from epoched data with the evoked response subtracted out (as we did
above). It is possible to instead compute regression weights directly from
the raw data, but this could bias the evoked response more than computing
the weights from data with the evoked response removed.
Can you write Python code for it?

# get ready to plot
order = np.concatenate([  # plotting order: EOG+ECG first, then MEG
    mne.pick_types(raw.info, meg=False, eog=True, ecg=True),
    mne.pick_types(raw.info, meg=True)])
raw_kwargs = dict(events=eog_epochs.events, order=order, start=20, duration=5,
                  n_channels=40)

# plot original data
raw.plot(**raw_kwargs)

# regress (using betas computed above) & plot
raw_clean, _ = mne.preprocessing.regress_artifact(raw, betas=betas)
raw_clean.plot(**raw_kwargs)


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

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


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

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

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


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

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

fig = mne.viz.plot_alignment(evoked.info, bem=sphere, surfaces='inner_skull',
                             coord_frame='head', meg='helmet', show_axes=True)

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

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

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


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

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

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

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

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

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

fig.tight_layout()
plt.show()


I am working on the file "0.22/_downloads/ba93e79a900327aac9ad4c8f17e818c8/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
The data have strong line frequency (60 Hz and harmonics) and cHPI coil
noise (five peaks around 300 Hz). Here we plot only out to 60 seconds
to save memory:
Can you write Python code for it?


I am working on the file "0.22/_downloads/ba93e79a900327aac9ad4c8f17e818c8/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
The data were collected with an Elekta Neuromag VectorView system at 1000 Hz
and low-pass filtered at 330 Hz. Here the medium-amplitude (200 nAm) data
are read to construct instances of :class:mne.io.Raw.
Can you write Python code for it?

data_path = bst_phantom_elekta.data_path(verbose=True)
subject = 'sample'

raw_fname = op.join(data_path, 'kojak_all_200nAm_pp_no_chpi_no_ms_raw.fif')
raw = read_raw_fif(raw_fname)


I am working on the file "0.22/_downloads/bb8e52a46ac1372ec146fb9c9983f326/plot_15_handling_bad_channels.ipynb".
The first task is:
.. sidebar:: Blocking execution
If you want to build an interactive bad-channel-marking step into an
analysis script, be sure to include the parameter ``block=True`` in your
call to ``raw.plot()`` or ``epochs.plot()``. This will pause the script
while the plot is open, giving you time to mark bad channels before
subsequent analysis or plotting steps are executed. This can be
especially helpful if your script loops over multiple subjects.

You can also interactively toggle whether a channel is marked "bad" in the
plot windows of raw.plot() or epochs.plot() by clicking on the
channel name along the vertical axis (in raw.plot() windows you can also
do this by clicking the channel's trace in the plot area). The bads field
gets updated immediately each time you toggle a channel, and will retain its
modified state after the plot window is closed.
The list of bad channels in the :class:mne.Info object's bads field is
automatically taken into account in dozens of functions and methods across
the MNE-Python codebase. This is done consistently with a parameter
exclude='bads' in the function or method signature. Typically this
exclude parameter also accepts a list of channel names or indices, so if
you want to include the bad channels you can do so by passing
exclude=[] (or some other list of channels to exclude). For example:
Can you write Python code for it?

# default is exclude='bads':
good_eeg = mne.pick_types(raw.info, meg=False, eeg=True)
all_eeg = mne.pick_types(raw.info, meg=False, eeg=True, exclude=[])
print(np.setdiff1d(all_eeg, good_eeg))
print(np.array(raw.ch_names)[np.setdiff1d(all_eeg, good_eeg)])


I am working on the file "0.22/_downloads/bb8e52a46ac1372ec146fb9c9983f326/plot_15_handling_bad_channels.ipynb".
The first task is:
By default, :meth:~mne.io.Raw.interpolate_bads will clear out
raw.info['bads'] after interpolation, so that the interpolated channels
are no longer excluded from subsequent computations. Here, for illustration
purposes, we'll prevent that by specifying reset_bads=False so that when
we plot the data before and after interpolation, the affected channels will
still plot in red:
Can you write Python code for it?

eeg_data = raw.copy().pick_types(meg=False, eeg=True, exclude=[])
eeg_data_interp = eeg_data.copy().interpolate_bads(reset_bads=False)

for title, data in zip(['orig.', 'interp.'], [eeg_data, eeg_data_interp]):
    fig = data.plot(butterfly=True, color='#00000022', bad_color='r')
    fig.subplots_adjust(top=0.9)
    fig.suptitle(title, size='xx-large', weight='bold')


I am working on the file "0.22/_downloads/bb8e52a46ac1372ec146fb9c9983f326/plot_15_handling_bad_channels.ipynb".
The first task is:
Interpolating bad channels
This tutorial covers manual marking of bad channels and reconstructing bad
channels based on good signals at other sensors.
   :depth: 2
As usual we'll start by importing the modules we need, and loading some example
data:
Can you write Python code for it?

import os
from copy import deepcopy
import numpy as np
import mne

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)


I am working on the file "0.22/_downloads/bb8e52a46ac1372ec146fb9c9983f326/plot_15_handling_bad_channels.ipynb".
The first task is:
Note that we used the exclude=[] trick in the call to
:meth:~mne.io.Raw.pick_types to make sure the bad channels were not
automatically dropped from the selection. Here is the corresponding example
with the interpolated gradiometer channel; since there are more channels
we'll use a more transparent gray color this time:
Can you write Python code for it?

grad_data = raw.copy().pick_types(meg='grad', exclude=[])
grad_data_interp = grad_data.copy().interpolate_bads(reset_bads=False)

for data in (grad_data, grad_data_interp):
    data.plot(butterfly=True, color='#00000009', bad_color='r')


I am working on the file "0.22/_downloads/bb8e52a46ac1372ec146fb9c9983f326/plot_15_handling_bad_channels.ipynb".
The first task is:
Notice first of all that the channels marked as "bad" are plotted in a light
gray color in a layer behind the other channels, to make it easy to
distinguish them from "good" channels. The plots make it clear that EEG
053 is not picking up scalp potentials at all, and MEG 2443 looks like
it's got a lot more internal noise than its neighbors — its signal is a few
orders of magnitude greater than the other MEG channels, making it a clear
candidate for exclusion.
If you want to change which channels are marked as bad, you can edit
raw.info['bads'] directly; it's an ordinary Python :class:list so the
usual list methods will work:
Can you write Python code for it?

original_bads = deepcopy(raw.info['bads'])
raw.info['bads'].append('EEG 050')               # add a single channel
raw.info['bads'].extend(['EEG 051', 'EEG 052'])  # add a list of channels
bad_chan = raw.info['bads'].pop(-1)  # remove the last entry in the list
raw.info['bads'] = original_bads     # change the whole list at once


I am working on the file "0.22/_downloads/bb8e52a46ac1372ec146fb9c9983f326/plot_15_handling_bad_channels.ipynb".
The first task is:
The bad EEG channel is not so obvious, but the bad gradiometer is easy to
see.
Remember, marking bad channels should be done as early as possible in the
analysis pipeline. When bad channels are marked in a :class:~mne.io.Raw
object, the markings will be automatically transferred through the chain of
derived object types: including :class:~mne.Epochs and :class:~mne.Evoked
objects, but also :class:noise covariance <mne.Covariance> objects,
:class:forward solution computations <mne.Forward>, :class:inverse
operators <mne.minimum_norm.InverseOperator>, etc. If you don't notice the
badness until later stages of your analysis pipeline, you'll probably need to
go back and re-run the pipeline, so it's a good investment of time to
carefully explore the data for bad channels early on.
Why mark bad channels at all?
Many analysis computations can be strongly affected by the presence of bad
channels. For example, a malfunctioning channel with completely flat signal
will have zero channel variance, which will cause noise estimates to be
unrealistically low. This low noise estimate will lead to a strong channel
weight in the estimate of cortical current, and because the channel is flat,
the magnitude of cortical current estimates will shrink dramatically.
Conversely, very noisy channels can also cause problems. For example, they
can lead to too many epochs being discarded based on signal amplitude
rejection thresholds, which in turn can lead to less robust estimation of the
noise covariance across sensors. Noisy channels can also interfere with
:term:SSP <projector> computations, because the projectors will be
spatially biased in the direction of the noisy channel, which can cause
adjacent good channels to be suppressed. ICA is corrupted by noisy channels
for similar reasons. On the other hand, when performing machine learning
analyses, bad channels may have limited, if any impact (i.e., bad channels
will be uninformative and therefore ignored / deweighted by the algorithm).
Interpolating bad...
Can you write Python code for it?


I am working on the file "0.22/_downloads/bb8e52a46ac1372ec146fb9c9983f326/plot_15_handling_bad_channels.ipynb".
The first task is:
We can do the same thing for the bad MEG channel (MEG 2443). Since we
know that Neuromag systems (like the one used to record the example data) use
the last digit of the MEG channel number to indicate sensor type, here our
regular expression_ will pick all the channels that start with 2 and end
with 3:
Can you write Python code for it?

picks = mne.pick_channels_regexp(raw.ch_names, regexp='MEG 2..3')
raw.plot(order=picks, n_channels=len(picks))


I am working on the file "0.22/_downloads/bb8e52a46ac1372ec146fb9c9983f326/plot_15_handling_bad_channels.ipynb".
The first task is:
When to look for bad channels
You can start looking for bad channels during the experiment session when the
data is being acquired. If you notice any flat or excessively noisy channels,
you can note them in your experiment log or protocol sheet. If your system
computes online averages, these can be a good way to spot bad channels as
well. After the data has been collected, you can do a more thorough check for
bad channels by browsing the raw data using :meth:mne.io.Raw.plot, with any
projectors or ICA applied. Finally, you can compute offline averages (again
with projectors, ICA, and EEG referencing disabled) to look for channels with
unusual properties. Here's an example of ERP/F plots where the bad channels
were not properly marked:
Can you write Python code for it?

raw2 = raw.copy()
raw2.info['bads'] = []
events = mne.find_events(raw2, stim_channel='STI 014')
epochs = mne.Epochs(raw2, events=events)['2'].average().plot()


I am working on the file "0.22/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
If you prefer untransformed power estimates, you can pass dB=False. It is
also possible to normalize the power estimates by dividing by the total power
across all frequencies, by passing normalize=True. See the docstring of
~mne.Epochs.plot_psd_topomap for details.
Plotting Epochs as an image map
A convenient way to visualize many epochs simultaneously is to plot them as
an image map, with each row of pixels in the image representing a single
epoch, the horizontal axis representing time, and each pixel's color
representing the signal value at that time sample for that epoch. Of course,
this requires either a separate image map for each channel, or some way of
combining information across channels. The latter is possible using the
~mne.Epochs.plot_image method; the former can be achieved with the
~mne.Epochs.plot_image method (one channel at a time) or with the
~mne.Epochs.plot_topo_image method (all sensors at once).
By default, the image map generated by ~mne.Epochs.plot_image will be
accompanied by a scalebar indicating the range of the colormap, and a time
series showing the average signal across epochs and a bootstrapped 95%
confidence band around the mean. ~mne.Epochs.plot_image is a highly
customizable method with many parameters, including customization of the
auxiliary colorbar and averaged time series subplots. See the docstrings of
~mne.Epochs.plot_image and mne.viz.plot_compare_evokeds (which is
used to plot the average time series) for full details. Here we'll show the
mean across magnetometers for all epochs with an auditory stimulus:
Can you write Python code for it?


I am working on the file "0.22/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
It is also possible to plot spectral estimates across sensors as a scalp
topography, using ~mne.Epochs.plot_psd_topomap. The default parameters will
plot five frequency bands (δ, θ, α, β, γ), will compute power based on
magnetometer channels, and will plot the power estimates in decibels:
Can you write Python code for it?


I am working on the file "0.22/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
Just like ~mne.Epochs.plot_projs_topomap,
~mne.Epochs.plot_psd_topomap has a vlim='joint' option for fixing
the colorbar limits jointly across all subplots, to give a better sense of
the relative magnitude in each band. You can change which channel type is
used  via the ch_type parameter, and if you want to view different
frequency bands than the defaults, the bands parameter takes a list of
tuples, with each tuple containing either a single frequency and a subplot
title, or lower/upper frequency limits and a subplot title:
Can you write Python code for it?

bands = [(10, '10 Hz'), (15, '15 Hz'), (20, '20 Hz'), (10, 20, '10-20 Hz')]
epochs['visual/right'].plot_psd_topomap(bands=bands, vlim='joint',
                                        ch_type='grad')


I am working on the file "0.22/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
Plotting projectors from an Epochs object
In the plot above we can see heartbeat artifacts in the magnetometer
channels, so before we continue let's load ECG projectors from disk and apply
them to the data:
Can you write Python code for it?

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


I am working on the file "0.22/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
Plotting sensor locations
Just like ~mne.io.Raw objects, ~mne.Epochs objects
keep track of sensor locations, which can be visualized with the
~mne.Epochs.plot_sensors method:
Can you write Python code for it?

epochs.plot_sensors(kind='3d', ch_type='all')
epochs.plot_sensors(kind='topomap', ch_type='all')


I am working on the file "0.22/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
Plotting the power spectrum of Epochs
Again, just like ~mne.io.Raw objects, ~mne.Epochs objects
have a ~mne.Epochs.plot_psd method for plotting the spectral
density_ of the data.
Can you write Python code for it?


I am working on the file "0.22/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
To plot an image map for all sensors, use
~mne.Epochs.plot_topo_image, which is optimized for plotting a large
number of image maps simultaneously, and (in interactive sessions) allows you
to click on each small image map to pop open a separate figure with the
full-sized image plot (as if you had called ~mne.Epochs.plot_image on
just that sensor). At the small scale shown in this tutorial it's hard to see
much useful detail in these plots; it's often best when plotting
interactively to maximize the topo image plots to fullscreen. The default is
a figure with black background, so here we specify a white background and
black foreground text. By default ~mne.Epochs.plot_topo_image will
show magnetometers and gradiometers on the same plot (and hence not show a
colorbar, since the sensors are on different scales) so we'll also pass a
~mne.channels.Layout restricting each plot to one channel type.
First, however, we'll also drop any epochs that have unusually high signal
levels, because they can cause the colormap limits to be too extreme and
therefore mask smaller signal fluctuations of interest.
Can you write Python code for it?

reject_criteria = dict(mag=3000e-15,     # 3000 fT
                       grad=3000e-13,    # 3000 fT/cm
                       eeg=150e-6)       # 150 µV
epochs.drop_bad(reject=reject_criteria)

for ch_type, title in dict(mag='Magnetometers', grad='Gradiometers').items():
    layout = mne.channels.find_layout(epochs.info, ch_type=ch_type)
    epochs['auditory/left'].plot_topo_image(layout=layout, fig_facecolor='w',
                                            font_color='k', title=title)


I am working on the file "0.22/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
To plot image maps for all EEG sensors, pass an EEG layout as the layout
parameter of ~mne.Epochs.plot_topo_image. Note also here the use of
the sigma parameter, which smooths each image map along the vertical
dimension (across epochs) which can make it easier to see patterns across the
small image maps (by smearing noisy epochs onto their neighbors, while
reinforcing parts of the image where adjacent epochs are similar). However,
sigma can also disguise epochs that have persistent extreme values and
maybe should have been excluded, so it should be used with caution.
Can you write Python code for it?

layout = mne.channels.find_layout(epochs.info, ch_type='eeg')
epochs['auditory/left'].plot_topo_image(layout=layout, fig_facecolor='w',
                                        font_color='k', sigma=1)


I am working on the file "0.22/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
To plot image maps for individual sensors or a small group of sensors, use
the picks parameter. Passing combine=None (the default) will yield
separate plots for each sensor in picks; passing combine='gfp' will
plot the global field power (useful for combining sensors that respond with
opposite polarity).
Can you write Python code for it?

epochs['auditory'].plot_image(picks=['MEG 0242', 'MEG 0243'])
epochs['auditory'].plot_image(picks=['MEG 0242', 'MEG 0243'], combine='gfp')


I am working on the file "0.22/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
To see all sensors at once, we can use butterfly mode and group by selection:
Can you write Python code for it?

epochs['face'].plot(events=catch_trials_and_buttonpresses, event_id=event_dict,
                    event_color=dict(button='red', face='blue'),
                    group_by='selection', butterfly=True)


I am working on the file "0.22/_downloads/bc5044f9d3ef1d29067dd6b7d83ceed2/plot_20_visualize_epochs.ipynb".
The first task is:
Visualizing epoched data
This tutorial shows how to plot epoched data as time series, how to plot the
spectral density of epoched data, how to plot epochs as an imagemap, and how to
plot the sensor locations and projectors stored in ~mne.Epochs
objects.
   :depth: 2
We'll start by importing the modules we need, loading the continuous (raw)
sample data, and cropping it to save memory:
Can you write Python code for it?

import os
import mne

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False).crop(tmax=120)


I am working on the file "0.22/_downloads/c569084177bc9cce4e0419ab10cfd45d/plot_dipole_fit.ipynb".
The first task is:
Let's localize the N100m (using MEG only)
Can you write Python code for it?

evoked = mne.read_evokeds(fname_ave, condition='Right Auditory',
                          baseline=(None, 0))
evoked.pick_types(meg=True, eeg=False)
evoked_full = evoked.copy()
evoked.crop(0.07, 0.08)

# Fit a dipole
dip = mne.fit_dipole(evoked, fname_cov, fname_bem, fname_trans)[0]

# Plot the result in 3D brain with the MRI image.
dip.plot_locations(fname_trans, 'sample', subjects_dir, mode='orthoview')


I am working on the file "0.22/_downloads/c6e78cc597e84b2937af26abbd068794/plot_ica_comparison.ipynb".
The first task is:
Compare the different ICA algorithms in MNE
Different ICA algorithms are fit to raw MEG data, and the corresponding maps
are displayed.
Can you write Python code for it?

# Authors: Pierre Ablin <pierreablin@gmail.com>
#
# License: BSD (3-clause)

from time import time

import mne
from mne.preprocessing import ICA
from mne.datasets import sample

print(__doc__)


I am working on the file "0.22/_downloads/c6e78cc597e84b2937af26abbd068794/plot_ica_comparison.ipynb".
The first task is:
Define a function that runs ICA on the raw MEG data and plots the components
Can you write Python code for it?

def run_ica(method, fit_params=None):
    ica = ICA(n_components=20, method=method, fit_params=fit_params,
              random_state=0)
    t0 = time()
    ica.fit(raw, picks=picks, reject=reject)
    fit_time = time() - t0
    title = ('ICA decomposition using %s (took %.1fs)' % (method, fit_time))
    ica.plot_components(title=title)


I am working on the file "0.22/_downloads/c6e78cc597e84b2937af26abbd068794/plot_ica_comparison.ipynb".
The first task is:
FastICA
Can you write Python code for it?