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


I am working on the file "0.22/_downloads/cc11b719732b6d62ff79ced562e2d134/plot_otp.ipynb".
The first task is:
Plot sensor denoising using oversampled temporal projection
This demonstrates denoising using the OTP algorithm [1]_ on data with
with sensor artifacts (flux jumps) and random noise.
Can you write Python code for it?

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

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

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

print(__doc__)


I am working on the file "0.22/_downloads/cc11b719732b6d62ff79ced562e2d134/plot_otp.ipynb".
The first task is:
Plot the phantom data, lowpassed to get rid of high-frequency artifacts.
We also crop to a single 10-second segment for speed.
Notice that there are two large flux jumps on channel 1522 that could
spread to other channels when performing subsequent spatial operations
(e.g., Maxwell filtering, SSP, or ICA).
Can you write Python code for it?

dipole_number = 1
data_path = bst_phantom_elekta.data_path()
raw = read_raw_fif(
    op.join(data_path, 'kojak_all_200nAm_pp_no_chpi_no_ms_raw.fif'))
raw.crop(40., 50.).load_data()
order = list(range(160, 170))
raw.copy().filter(0., 40.).plot(order=order, n_channels=10)


I am working on the file "0.22/_downloads/cc11b719732b6d62ff79ced562e2d134/plot_otp.ipynb".
The first task is:
We can also look at the effect on single-trial phantom localization.
See the tut-brainstorm-elekta-phantom
for more information. Here we use a version that does single-trial
localization across the 17 trials are in our 10-second window:
Can you write Python code for it?

def compute_bias(raw):
    events = find_events(raw, 'STI201', verbose=False)
    events = events[1:]  # first one has an artifact
    tmin, tmax = -0.2, 0.1
    epochs = mne.Epochs(raw, events, dipole_number, tmin, tmax,
                        baseline=(None, -0.01), preload=True, verbose=False)
    sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=None,
                                   verbose=False)
    cov = mne.compute_covariance(epochs, tmax=0, method='oas',
                                 rank=None, verbose=False)
    idx = epochs.time_as_index(0.036)[0]
    data = epochs.get_data()[:, :, idx].T
    evoked = mne.EvokedArray(data, epochs.info, tmin=0.)
    dip = fit_dipole(evoked, cov, sphere, n_jobs=1, verbose=False)[0]
    actual_pos = mne.dipole.get_phantom_dipoles()[0][dipole_number - 1]
    misses = 1000 * np.linalg.norm(dip.pos - actual_pos, axis=-1)
    return misses

bias = compute_bias(raw)
print('Raw bias: %0.1fmm (worst: %0.1fmm)'
      % (np.mean(bias), np.max(bias)))
bias_clean = compute_bias(raw_clean)
print('OTP bias: %0.1fmm (worst: %0.1fmm)'
      % (np.mean(bias_clean), np.max(bias_clean),))


I am working on the file "0.22/_downloads/cef7da557456c738c3f4db863a633b34/plot_decoding_spoc_CMC.ipynb".
The first task is:
Plot the contributions to the detected components (i.e., the forward model)
Can you write Python code for it?


I am working on the file "0.22/_downloads/d0650bb5ca9f8c789ed4763f3c3f895e/plot_linear_model_patterns.ipynb".
The first task is:
Decoding in sensor space using a LogisticRegression classifier
Can you write Python code for it?

clf = LogisticRegression(solver='lbfgs')
scaler = StandardScaler()

# create a linear model with LogisticRegression
model = LinearModel(clf)

# fit the classifier on MEG data
X = scaler.fit_transform(meg_data)
model.fit(X, labels)

# Extract and plot spatial filters and spatial patterns
for name, coef in (('patterns', model.patterns_), ('filters', model.filters_)):
    # We fitted the linear model onto Z-scored data. To make the filters
    # interpretable, we must reverse this normalization step
    coef = scaler.inverse_transform([coef])[0]

    # The data was vectorized to fit a single model across all time points and
    # all channels. We thus reshape it:
    coef = coef.reshape(len(meg_epochs.ch_names), -1)

    # Plot
    evoked = EvokedArray(coef, meg_epochs.info, tmin=epochs.tmin)
    evoked.plot_topomap(title='MEG %s' % name, time_unit='s')


I am working on the file "0.22/_downloads/d0650bb5ca9f8c789ed4763f3c3f895e/plot_linear_model_patterns.ipynb".
The first task is:
Let's do the same on EEG data using a scikit-learn pipeline
Can you write Python code for it?

X = epochs.pick_types(meg=False, eeg=True)
y = epochs.events[:, 2]

# Define a unique pipeline to sequentially:
clf = make_pipeline(
    Vectorizer(),                       # 1) vectorize across time and channels
    StandardScaler(),                   # 2) normalize features across trials
    LinearModel(
        LogisticRegression(solver='lbfgs')))  # 3) fits a logistic regression
clf.fit(X, y)

# Extract and plot patterns and filters
for name in ('patterns_', 'filters_'):
    # The `inverse_transform` parameter will call this method on any estimator
    # contained in the pipeline, in reverse order.
    coef = get_coef(clf, name, inverse_transform=True)
    evoked = EvokedArray(coef, epochs.info, tmin=epochs.tmin)
    evoked.plot_topomap(title='EEG %s' % name[:-1], time_unit='s')


I am working on the file "0.22/_downloads/d0650bb5ca9f8c789ed4763f3c3f895e/plot_linear_model_patterns.ipynb".
The first task is:
Linear classifier on sensor data with plot patterns and filters
Here decoding, a.k.a MVPA or supervised machine learning, is applied to M/EEG
data in sensor space. Fit a linear classifier with the LinearModel object
providing topographical patterns which are more neurophysiologically
interpretable :footcite:HaufeEtAl2014 than the classifier filters (weight
vectors). The patterns explain how the MEG and EEG data were generated from
the discriminant neural sources which are extracted by the filters.
Note patterns/filters in MEG data are more similar than EEG data
because the noise is less spatially correlated in MEG than EEG.
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#          Romain Trachel <trachelr@gmail.com>
#          Jean-Remi King <jeanremi.king@gmail.com>
#
# License: BSD (3-clause)

import mne
from mne import io, EvokedArray
from mne.datasets import sample
from mne.decoding import Vectorizer, get_coef

from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline

# import a linear classifier from mne.decoding
from mne.decoding import LinearModel

print(__doc__)

data_path = sample.data_path()
sample_path = data_path + '/MEG/sample'


I am working on the file "0.22/_downloads/d0650bb5ca9f8c789ed4763f3c3f895e/plot_linear_model_patterns.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

raw_fname = sample_path + '/sample_audvis_filt-0-40_raw.fif'
event_fname = sample_path + '/sample_audvis_filt-0-40_raw-eve.fif'
tmin, tmax = -0.1, 0.4
event_id = dict(aud_l=1, vis_l=3)

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

# Read epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    decim=2, baseline=None, preload=True)
del raw

labels = epochs.events[:, -1]

# get MEG and EEG data
meg_epochs = epochs.copy().pick_types(meg=True, eeg=False)
meg_data = meg_epochs.get_data().reshape(len(labels), -1)


I am working on the file "0.22/_downloads/d5dd378a96a427683b4c918f7cdf9064/plot_ssd_spatial_filters.ipynb".
The first task is:
Compute Sepctro-Spatial Decomposition (SSD) spatial filters
In this example, we will compute spatial filters for retaining
oscillatory brain activity and down-weighting 1/f background signals
as proposed by :footcite:NikulinEtAl2011.
The idea is to learn spatial filters that separate oscillatory dynamics
from surrounding non-oscillatory noise based on the covariance in the
frequency band of interest and the noise covariance based on surrounding
frequencies.
Can you write Python code for it?

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

import matplotlib.pyplot as plt
import mne
from mne import Epochs
from mne.datasets.fieldtrip_cmc import data_path
from mne.decoding import SSD


I am working on the file "0.22/_downloads/d5dd378a96a427683b4c918f7cdf9064/plot_ssd_spatial_filters.ipynb".
The first task is:
Define parameters
Can you write Python code for it?

fname = data_path() + '/SubjectCMC.ds'

# Prepare data
raw = mne.io.read_raw_ctf(fname)
raw.crop(50., 110.).load_data()  # crop for memory purposes
raw.resample(sfreq=250)

raw.pick_types(meg=True, eeg=False, ref_meg=False)

freqs_sig = 9, 12
freqs_noise = 8, 13

ssd = SSD(info=raw.info,
          reg='oas',
          sort_by_spectral_ratio=False,  # False for purpose of example.
          filt_params_signal=dict(l_freq=freqs_sig[0], h_freq=freqs_sig[1],
                                  l_trans_bandwidth=1, h_trans_bandwidth=1),
          filt_params_noise=dict(l_freq=freqs_noise[0], h_freq=freqs_noise[1],
                                 l_trans_bandwidth=1, h_trans_bandwidth=1))
ssd.fit(X=raw.get_data())


I am working on the file "0.22/_downloads/d5dd378a96a427683b4c918f7cdf9064/plot_ssd_spatial_filters.ipynb".
The first task is:
Epoched data
Although we suggest to use this method before epoching, there might be some
situations in which data can only be treated by chunks.
Can you write Python code for it?

# Build epochs as sliding windows over the continuous raw file.
events = mne.make_fixed_length_events(raw, id=1, duration=5.0, overlap=0.0)

# Epoch length is 5 seconds.
epochs = Epochs(raw, events, tmin=0., tmax=5,
                baseline=None, preload=True)

ssd_epochs = SSD(info=epochs.info,
                 reg='oas',
                 filt_params_signal=dict(l_freq=freqs_sig[0],
                                         h_freq=freqs_sig[1],
                                         l_trans_bandwidth=1,
                                         h_trans_bandwidth=1),
                 filt_params_noise=dict(l_freq=freqs_noise[0],
                                        h_freq=freqs_noise[1],
                                        l_trans_bandwidth=1,
                                        h_trans_bandwidth=1))
ssd_epochs.fit(X=epochs.get_data())

# Plot topographies.
pattern_epochs = mne.EvokedArray(data=ssd_epochs.patterns_[:4].T,
                                 info=ssd_epochs.info)
pattern_epochs.plot_topomap(units=dict(mag='A.U.'), time_format='')


I am working on the file "0.22/_downloads/d9e2f27df3a137317d331d3be6f3814d/plot_dics_source_power.ipynb".
The first task is:
Applying DICS spatial filters separately to the CSD computed using the
baseline and the CSD computed during the ERS activity.
Can you write Python code for it?

baseline_source_power, freqs = apply_dics_csd(csd_baseline, filters)
beta_source_power, freqs = apply_dics_csd(csd_ers, filters)


I am working on the file "0.22/_downloads/d9e2f27df3a137317d331d3be6f3814d/plot_dics_source_power.ipynb".
The first task is:
Computing DICS spatial filters using the CSD that was computed on the entire
timecourse.
Can you write Python code for it?

fwd = mne.read_forward_solution(fname_fwd)
filters = make_dics(info, fwd, csd, noise_csd=csd_baseline,
                    pick_ori='max-power', reduce_rank=True)
del fwd


I am working on the file "0.22/_downloads/d9e2f27df3a137317d331d3be6f3814d/plot_dics_source_power.ipynb".
The first task is:
Visualizing source power during ERS activity relative to the baseline power.
Can you write Python code for it?

stc = beta_source_power / baseline_source_power
message = 'DICS source power in the 12-30 Hz frequency band'
brain = stc.plot(hemi='both', views='axial', subjects_dir=subjects_dir,
                 subject=subject, time_label=message)


I am working on the file "0.22/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
Finally let's compute the inverse and apply it:
Can you write Python code for it?

inv = mne.minimum_norm.make_inverse_operator(
    evoked.info, fwd, cov, verbose=True)
stc = mne.minimum_norm.apply_inverse(evoked, inv)
brain = stc.plot(subjects_dir=subjects_dir, initial_time=0.1)


I am working on the file "0.22/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
Getting our MRI voxel EEG locations to head (and MRI surface RAS) coords
Let's load our :class:~mne.channels.DigMontage using
:func:mne.channels.read_custom_montage, making note of the fact that
we stored our locations in Freesurfer surface RAS (MRI) coordinates.
.. collapse:: |question| What if my electrodes are in MRI voxels?
    :class: info
If you have voxel coordinates in MRI voxels, you can transform these to
FreeSurfer surface RAS (called "mri" in MNE) coordinates using the
transformations that FreeSurfer computes during reconstruction.
``nibabel`` calls this transformation the ``vox2ras_tkr`` transform
and operates in millimeters, so we can load it, convert it to meters,
and then apply it::

    >>> pos_vox = ...  # loaded from a file somehow
    >>> img = nibabel.load(fname_T1)
    >>> vox2mri_t = img.header.get_vox2ras_tkr()  # voxel -> mri trans
    >>> pos_mri = mne.transforms.apply_trans(vox2mri_t, pos_vox)
    >>> pos_mri /= 1000.  # mm -> m

You can also verify that these are correct (or manually convert voxels
to MRI coords) by looking at the points in Freeview or tkmedit.
Can you write Python code for it?

dig_montage = read_custom_montage(fname_mon, head_size=None, coord_frame='mri')
dig_montage.plot()


I am working on the file "0.22/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
Let's apply this digitization to our dataset, and in the process
automatically convert our locations to the head coordinate frame, as
shown by :meth:~mne.io.Raw.plot_sensors.
Can you write Python code for it?

raw = mne.io.read_raw_fif(fname_raw)
raw.pick_types(meg=False, eeg=True, stim=True, exclude=()).load_data()
raw.set_montage(dig_montage)
raw.plot_sensors(show_names=True)


I am working on the file "0.22/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
Now we can actually compute the forward:
Can you write Python code for it?

fwd = mne.make_forward_solution(
    evoked.info, trans=trans, src=fname_src, bem=fname_bem, verbose=True)


I am working on the file "0.22/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
Now we can do standard sensor-space operations like make joint plots of
evoked data.
Can you write Python code for it?

raw.set_eeg_reference(projection=True)
events = mne.find_events(raw)
epochs = mne.Epochs(raw, events)
cov = mne.compute_covariance(epochs, tmax=0.)
evoked = epochs['1'].average()  # trigger 1 in auditory/left
evoked.plot_joint()


I am working on the file "0.22/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
Prerequisites
For this we will assume that you have:

raw EEG data
your subject's MRI reconstrcted using FreeSurfer
an appropriate boundary element model (BEM)
an appropriate source space (src)
your EEG electrodes in Freesurfer surface RAS coordinates, stored
  in one of the formats :func:mne.channels.read_custom_montage supports

Let's set the paths to these files for the sample dataset, including
a modified sample MRI showing the electrode locations plus a .elc
file corresponding to the points in MRI coords (these were synthesized
<https://gist.github.com/larsoner/0ac6fad57e31cb2d9caa77350a9ff366>__,
and thus are stored as part of the misc dataset).
Can you write Python code for it?

data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
fname_raw = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
bem_dir = op.join(subjects_dir, 'sample', 'bem')
fname_bem = op.join(bem_dir, 'sample-5120-5120-5120-bem-sol.fif')
fname_src = op.join(bem_dir, 'sample-oct-6-src.fif')

misc_path = mne.datasets.misc.data_path()
fname_T1_electrodes = op.join(misc_path, 'sample_eeg_mri', 'T1_electrodes.mgz')
fname_mon = op.join(misc_path, 'sample_eeg_mri', 'sample_mri_montage.elc')


I am working on the file "0.22/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
Visualizing the MRI
Let's take our MRI-with-eeg-locations and adjust the affine to put the data
in MNI space, and plot using :func:nilearn.plotting.plot_glass_brain,
which does a maximum intensity projection (easy to see the fake electrodes).
This plotting function requires data to be in MNI space.
Because img.affine gives the voxel-to-world (RAS) mapping, if we apply a
RAS-to-MNI transform to it, it becomes the voxel-to-MNI transformation we
need. Thus we create a "new" MRI image in MNI coordinates and plot it as:
Can you write Python code for it?

img = nibabel.load(fname_T1_electrodes)  # original subject MRI w/EEG
ras_mni_t = mne.transforms.read_ras_mni_t('sample', subjects_dir)  # from FS
mni_affine = np.dot(ras_mni_t['trans'], img.affine)  # vox->ras->MNI
img_mni = nibabel.Nifti1Image(img.dataobj, mni_affine)  # now in MNI coords!
plot_glass_brain(img_mni, cmap='hot_black_bone', threshold=0., black_bg=True,
                 resampling_interpolation='nearest', colorbar=True)


I am working on the file "0.22/_downloads/ddc69c7d64f56b270d77306da97dbe20/plot_eeg_mri_coords.ipynb".
The first task is:
We can then get our transformation from the MRI coordinate frame (where our
points are defined) to the head coordinate frame from the object.
Can you write Python code for it?

trans = compute_native_head_t(dig_montage)
print(trans)  # should be mri->head, as the "native" space here is MRI


I am working on the file "0.22/_downloads/defd59f40a19378fba659a70b6f1ec76/plot_sensors_decoding.ipynb".
The first task is:
Decoding (MVPA)
:depth: 3
.. include:: ../../links.inc
Design philosophy
Decoding (a.k.a. MVPA) in MNE largely follows the machine
learning API of the scikit-learn package.
Each estimator implements fit, transform, fit_transform, and
(optionally) inverse_transform methods. For more details on this design,
visit scikit-learn_. For additional theoretical insights into the decoding
framework in MNE :footcite:KingEtAl2018.
For ease of comprehension, we will denote instantiations of the class using
the same name as the class but in small caps instead of camel cases.
Let's start by loading data for a simple two-class problem:
Can you write Python code for it?

import numpy as np
import matplotlib.pyplot as plt

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

import mne
from mne.datasets import sample
from mne.decoding import (SlidingEstimator, GeneralizingEstimator, Scaler,
                          cross_val_multiscore, LinearModel, get_coef,
                          Vectorizer, CSP)

data_path = sample.data_path()

subjects_dir = data_path + '/subjects'
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
tmin, tmax = -0.200, 0.500
event_id = {'Auditory/Left': 1, 'Visual/Left': 3}  # just use two
raw = mne.io.read_raw_fif(raw_fname, preload=True)

# The subsequent decoding analyses only capture evoked responses, so we can
# low-pass the MEG data. Usually a value more like 40 Hz would be used,
# but here low-pass at 20 so we can more heavily decimate, and allow
# the examlpe to run faster. The 2 Hz high-pass helps improve CSP.
raw.filter(2, 20)
events = mne.find_events(raw, 'STI 014')

# Set up pick list: EEG + MEG - bad channels (modify to your needs)
raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more

# Read epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    picks=('grad', 'eog'), baseline=(None, 0.), preload=True,
                    reject=dict(grad=4000e-13, eog=150e-6), decim=10)
epochs.pick_types(meg=True, exclude='bads')  # remove stim and EOG
del raw

X = epochs.get_data()  # MEG signals: n_epochs, n_meg_channels, n_times
y = epochs.events[:, 2]  # target: auditory left vs visual left


I am working on the file "0.22/_downloads/defd59f40a19378fba659a70b6f1ec76/plot_sensors_decoding.ipynb".
The first task is:
PSDEstimator
The :class:mne.decoding.PSDEstimator
computes the power spectral density (PSD) using the multitaper
method. It takes a 3D array as input, converts it into 2D and computes the
PSD.
FilterEstimator
The :class:mne.decoding.FilterEstimator filters the 3D epochs data.
Spatial filters
Just like temporal filters, spatial filters provide weights to modify the
data along the sensor dimension. They are popular in the BCI community
because of their simplicity and ability to distinguish spatially-separated
neural activity.
Common spatial pattern
:class:mne.decoding.CSP is a technique to analyze multichannel data based
on recordings from two classes :footcite:Koles1991 (see also
https://en.wikipedia.org/wiki/Common_spatial_pattern).
Let $X \in R^{C\times T}$ be a segment of data with
$C$ channels and $T$ time points. The data at a single time point
is denoted by $x(t)$ such that $X=[x(t), x(t+1), ..., x(t+T-1)]$.
Common spatial pattern (CSP) finds a decomposition that projects the signal
in the original sensor space to CSP space using the following transformation:
\begin{align}x_{CSP}(t) = W^{T}x(t)
   :label: csp\end{align}
where each column of $W \in R^{C\times C}$ is a spatial filter and each
row of $x_{CSP}$ is a CSP component. The matrix $W$ is also
called the de-mixing matrix in other contexts. Let
$\Sigma^{+} \in R^{C\times C}$ and $\Sigma^{-} \in R^{C\times C}$
be the estimates of the covariance matrices of the two conditions.
CSP analysis is given by the simultaneous diagonalization of the two
covariance matrices
\begin{align}W^{T}\Sigma^{+}W = \lambda^{+}
   :label: diagonalize_p\end{align}
\begin{align}W^{T}\Sigma^{-}W = \lambda^{-}
   :label: diagonalize_n\end{align}
where $\lambda^{C}$ is a diagonal matrix whose entries are the
eigenvalues of the following generalized eigenvalue problem
\begin{align}\Sigma^{+}w = \lambda \Sigma^{-}w
   :label: eigen_problem\end{align}
Large entries in the diagonal matrix corresponds to a spatial filter which
gives high variance in one class but low variance in...
Can you write Python code for it?

csp = CSP(n_components=3, norm_trace=False)
clf_csp = make_pipeline(csp, LinearModel(LogisticRegression(solver='lbfgs')))
scores = cross_val_multiscore(clf_csp, X, y, cv=5, n_jobs=1)
print('CSP: %0.1f%%' % (100 * scores.mean(),))


I am working on the file "0.22/_downloads/defd59f40a19378fba659a70b6f1ec76/plot_sensors_decoding.ipynb".
The first task is:
Plot the full (generalization) matrix:
Can you write Python code for it?

fig, ax = plt.subplots(1, 1)
im = ax.imshow(scores, interpolation='lanczos', origin='lower', cmap='RdBu_r',
               extent=epochs.times[[0, -1, 0, -1]], vmin=0., vmax=1.)
ax.set_xlabel('Testing Time (s)')
ax.set_ylabel('Training Time (s)')
ax.set_title('Temporal generalization')
ax.axvline(0, color='k')
ax.axhline(0, color='k')
plt.colorbar(im, ax=ax)


I am working on the file "0.22/_downloads/defd59f40a19378fba659a70b6f1ec76/plot_sensors_decoding.ipynb".
The first task is:
Projecting sensor-space patterns to source space
If you use a linear classifier (or regressor) for your data, you can also
project these to source space. For example, using our evoked_time_gen
from before:
Can you write Python code for it?

cov = mne.compute_covariance(epochs, tmax=0.)
del epochs
fwd = mne.read_forward_solution(
    data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif')
inv = mne.minimum_norm.make_inverse_operator(
    evoked_time_gen.info, fwd, cov, loose=0.)
stc = mne.minimum_norm.apply_inverse(evoked_time_gen, inv, 1. / 9., 'dSPM')
del fwd, inv


I am working on the file "0.22/_downloads/defd59f40a19378fba659a70b6f1ec76/plot_sensors_decoding.ipynb".
The first task is:
Source power comodulation (SPoC)
Source Power Comodulation (:class:mne.decoding.SPoC)
:footcite:DahneEtAl2014 identifies the composition of
orthogonal spatial filters that maximally correlate with a continuous target.
SPoC can be seen as an extension of the CSP where the target is driven by a
continuous variable rather than a discrete variable. Typical applications
include extraction of motor patterns using EMG power or audio patterns using
sound envelope.
.. topic:: Examples
* `sphx_glr_auto_examples_decoding_plot_decoding_spoc_CMC.py`

xDAWN
:class:mne.preprocessing.Xdawn is a spatial filtering method designed to
improve the signal to signal + noise ratio (SSNR) of the ERP responses
:footcite:RivetEtAl2009. Xdawn was originally
designed for P300 evoked potential by enhancing the target response with
respect to the non-target response. The implementation in MNE-Python is a
generalization to any type of ERP.
.. topic:: Examples
* `sphx_glr_auto_examples_preprocessing_plot_xdawn_denoising.py`
* `sphx_glr_auto_examples_decoding_plot_decoding_xdawn_eeg.py`

Effect-matched spatial filtering
The result of :class:mne.decoding.EMS is a spatial filter at each time
point and a corresponding time course :footcite:SchurgerEtAl2013.
Intuitively, the result gives the similarity between the filter at
each time point and the data vector (sensors) at that time point.
.. topic:: Examples
* `sphx_glr_auto_examples_decoding_plot_ems_filtering.py`

Patterns vs. filters
When interpreting the components of the CSP (or spatial filters in general),
it is often more intuitive to think about how $x(t)$ is composed of
the different CSP components $x_{CSP}(t)$. In other words, we can
rewrite Equation :eq:csp as follows:
\begin{align}x(t) = (W^{-1})^{T}x_{CSP}(t)
   :label: patterns\end{align}
The columns of the matrix $(W^{-1})^T$ are called spatial patterns.
This is also called the mixing matrix. The example
sphx_glr_auto_examples_decoding_plot_linear_model_patterns.py
discusses the difference between patterns and filters.
These can be...
Can you write Python code for it?

# Fit CSP on full data and plot
csp.fit(X, y)
csp.plot_patterns(epochs.info)
csp.plot_filters(epochs.info, scalings=1e-9)


I am working on the file "0.22/_downloads/defd59f40a19378fba659a70b6f1ec76/plot_sensors_decoding.ipynb".
The first task is:
Temporal generalization
Temporal generalization is an extension of the decoding over time approach.
It consists in evaluating whether the model estimated at a particular
time instant accurately predicts any other time instant. It is analogous to
transferring a trained model to a distinct learning problem, where the
problems correspond to decoding the patterns of brain activity recorded at
distinct time instants.
The object to for Temporal generalization is
:class:mne.decoding.GeneralizingEstimator. It expects as input $X$
and $y$ (similarly to :class:~mne.decoding.SlidingEstimator) but
generates predictions from each model for all time instants. The class
:class:~mne.decoding.GeneralizingEstimator is generic and will treat the
last dimension as the one to be used for generalization testing. For
convenience, here, we refer to it as different tasks. If $X$
corresponds to epochs data then the last dimension is time.
This runs the analysis used in :footcite:KingEtAl2014 and further detailed
in :footcite:KingDehaene2014:
Can you write Python code for it?

# define the Temporal generalization object
time_gen = GeneralizingEstimator(clf, n_jobs=1, scoring='roc_auc',
                                 verbose=True)

scores = cross_val_multiscore(time_gen, X, y, cv=5, n_jobs=1)

# Mean scores across cross-validation splits
scores = np.mean(scores, axis=0)

# Plot the diagonal (it's exactly the same as the time-by-time decoding above)
fig, ax = plt.subplots()
ax.plot(epochs.times, np.diag(scores), label='score')
ax.axhline(.5, color='k', linestyle='--', label='chance')
ax.set_xlabel('Times')
ax.set_ylabel('AUC')
ax.legend()
ax.axvline(.0, color='k', linestyle='-')
ax.set_title('Decoding MEG sensors over time')


I am working on the file "0.22/_downloads/defd59f40a19378fba659a70b6f1ec76/plot_sensors_decoding.ipynb".
The first task is:
Transformation classes
Scaler
The :class:mne.decoding.Scaler will standardize the data based on channel
scales. In the simplest modes scalings=None or scalings=dict(...),
each data channel type (e.g., mag, grad, eeg) is treated separately and
scaled by a constant. This is the approach used by e.g.,
:func:mne.compute_covariance to standardize channel scales.
If scalings='mean' or scalings='median', each channel is scaled using
empirical measures. Each channel is scaled independently by the mean and
standand deviation, or median and interquartile range, respectively, across
all epochs and time points during :class:~mne.decoding.Scaler.fit
(during training). The :meth:~mne.decoding.Scaler.transform method is
called to transform data (training or test set) by scaling all time points
and epochs on a channel-by-channel basis. To perform both the fit and
transform operations in a single call, the
:meth:~mne.decoding.Scaler.fit_transform method may be used. To invert the
transform, :meth:~mne.decoding.Scaler.inverse_transform can be used. For
scalings='median', scikit-learn_ version 0.17+ is required.

Note

Using this class is different from directly applying
          :class:`sklearn.preprocessing.StandardScaler` or
          :class:`sklearn.preprocessing.RobustScaler` offered by
          scikit-learn_. These scale each *classification feature*, e.g.
          each time point for each channel, with mean and standard
          deviation computed across epochs, whereas
          :class:`mne.decoding.Scaler` scales each *channel* using mean and
          standard deviation computed across all of its time points
          and epochs.

Vectorizer
Scikit-learn API provides functionality to chain transformers and estimators
by using :class:sklearn.pipeline.Pipeline. We can construct decoding
pipelines and perform cross-validation and grid-search. However scikit-learn
transformers and estimators generally expect 2D data
(n_samples * n_features), whereas MNE transformers...
Can you write Python code for it?

# Uses all MEG sensors and time points as separate classification
# features, so the resulting filters used are spatio-temporal
clf = make_pipeline(Scaler(epochs.info),
                    Vectorizer(),
                    LogisticRegression(solver='lbfgs'))

scores = cross_val_multiscore(clf, X, y, cv=5, n_jobs=1)

# Mean scores across cross-validation splits
score = np.mean(scores, axis=0)
print('Spatio-temporal: %0.1f%%' % (100 * score,))


I am working on the file "0.22/_downloads/dfd4175ec1a2c7f21de3596573c74301/plot_multidict_reweighted_tfmxne.ipynb".
The first task is:
Compute iterative reweighted TF-MxNE with multiscale time-frequency dictionary
The iterative reweighted TF-MxNE solver is a distributed inverse method
based on the TF-MxNE solver, which promotes focal (sparse) sources
:footcite:StrohmeierEtAl2015. The benefit of this approach is that:

it is spatio-temporal without assuming stationarity (sources properties
    can vary over time),
activations are localized in space, time and frequency in one step,
the solver uses non-convex penalties in the TF domain, which results in a
    solution less biased towards zero than when simple TF-MxNE is used,
using a multiscale dictionary allows to capture short transient
    activations along with slower brain waves :footcite:BekhtiEtAl2016.
Can you write Python code for it?

# Author: Mathurin Massias <mathurin.massias@gmail.com>
#         Yousra Bekhti <yousra.bekhti@gmail.com>
#         Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#         Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)

import os.path as op

import mne
from mne.datasets import somato
from mne.inverse_sparse import tf_mixed_norm, make_stc_from_dipoles
from mne.viz import plot_sparse_source_estimates

print(__doc__)


I am working on the file "0.22/_downloads/dfd4175ec1a2c7f21de3596573c74301/plot_multidict_reweighted_tfmxne.ipynb".
The first task is:
Show the evoked response and the residual for gradiometers
Can you write Python code for it?

ylim = dict(grad=[-300, 300])
evoked.pick_types(meg='grad')
evoked.plot(titles=dict(grad='Evoked Response: Gradiometers'), ylim=ylim,
            proj=True)

residual.pick_types(meg='grad')
residual.plot(titles=dict(grad='Residuals: Gradiometers'), ylim=ylim,
              proj=True)


I am working on the file "0.22/_downloads/e6b765a72099a336669c021aac76fd0a/plot_sleep.ipynb".
The first task is:
Create Epochs from the data based on the events found in the annotations
Can you write Python code for it?

tmax = 30. - 1. / raw_train.info['sfreq']  # tmax in included

epochs_train = mne.Epochs(raw=raw_train, events=events_train,
                          event_id=event_id, tmin=0., tmax=tmax, baseline=None)

print(epochs_train)


I am working on the file "0.22/_downloads/e6b765a72099a336669c021aac76fd0a/plot_sleep.ipynb".
The first task is:
Extract 30s events from annotations
The Sleep Physionet dataset is annotated using
8 labels <physionet_labels_>_:
Wake (W), Stage 1, Stage 2, Stage 3, Stage 4 corresponding to the range from
light sleep to deep sleep, REM sleep (R) where REM is the abbreviation for
Rapid Eye Movement sleep, movement (M), and Stage (?) for any none scored
segment.
We will work only with 5 stages: Wake (W), Stage 1, Stage 2, Stage 3/4, and
REM sleep (R). To do so, we use the event_id parameter in
:func:mne.events_from_annotations to select which events are we
interested in and we associate an event identifier to each of them.
Moreover, the recordings contain long awake (W) regions before and after each
night. To limit the impact of class imbalance, we trim each recording by only
keeping 30 minutes of wake time before the first occurrence and 30 minutes
after the last occurrence of sleep stages.
Can you write Python code for it?

annotation_desc_2_event_id = {'Sleep stage W': 1,
                              'Sleep stage 1': 2,
                              'Sleep stage 2': 3,
                              'Sleep stage 3': 4,
                              'Sleep stage 4': 4,
                              'Sleep stage R': 5}

# keep last 30-min wake events before sleep and first 30-min wake events after
# sleep and redefine annotations on raw data
annot_train.crop(annot_train[1]['onset'] - 30 * 60,
                 annot_train[-2]['onset'] + 30 * 60)
raw_train.set_annotations(annot_train, emit_warning=False)

events_train, _ = mne.events_from_annotations(
    raw_train, event_id=annotation_desc_2_event_id, chunk_duration=30.)

# create a new event_id that unifies stages 3 and 4
event_id = {'Sleep stage W': 1,
            'Sleep stage 1': 2,
            'Sleep stage 2': 3,
            'Sleep stage 3/4': 4,
            'Sleep stage R': 5}

# plot events
fig = mne.viz.plot_events(events_train, event_id=event_id,
                          sfreq=raw_train.info['sfreq'],
                          first_samp=events_train[0, 0])

# keep the color-code for further plotting
stage_colors = plt.rcParams['axes.prop_cycle'].by_key()['color']


I am working on the file "0.22/_downloads/e6b765a72099a336669c021aac76fd0a/plot_sleep.ipynb".
The first task is:
In short, yes. We can predict Bob's sleeping stages based on Alice's data.
Further analysis of the data
We can check the confusion matrix or the classification report.
Can you write Python code for it?

print(confusion_matrix(y_test, y_pred))

print(classification_report(y_test, y_pred, target_names=event_id.keys()))


I am working on the file "0.22/_downloads/e6b765a72099a336669c021aac76fd0a/plot_sleep.ipynb".
The first task is:
Sleep stage classification from polysomnography (PSG) data

Note

This code is taken from the analysis code used in [3]_. If you reuse
          this code please consider citing this work.

This tutorial explains how to perform a toy polysomnography analysis that
answers the following question:
.. important:: Given two subjects from the Sleep Physionet dataset [1] [2],
               namely Alice and Bob, how well can we predict the sleep
               stages of Bob from Alice's data?
This problem is tackled as supervised multiclass classification task. The aim
is to predict the sleep stage from 5 possible stages for each chunk of 30
seconds of data.
   :depth: 2
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#          Stanislas Chambon <stan.chambon@gmail.com>
#          Joan Massich <mailsik@gmail.com>
#
# License: BSD Style.

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.datasets.sleep_physionet.age import fetch_data
from mne.time_frequency import psd_welch

from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer


I am working on the file "0.22/_downloads/e6e21719275dd1fe5b070e9c49c33bc5/plot_forward.ipynb".
The first task is:
Compute Source Space
The source space defines the position and orientation of the candidate source
locations. There are two types of source spaces:

surface-based source space when the candidates are confined to a
  surface.

volumetric or discrete source space when the candidates are discrete,
  arbitrarily located source points bounded by the surface.

Surface-based source space is computed using
:func:mne.setup_source_space, while volumetric source space is computed
using :func:mne.setup_volume_source_space.
We will now compute a surface-based source space with an 'oct4'
resolution. See setting_up_source_space for details on source space
definition and spacing parameter.

Warning

``'oct4'`` is used here just for speed, for real analyses the recommended
    spacing is ``'oct6'``.

Can you write Python code for it?

src = mne.setup_source_space(subject, spacing='oct4', add_dist='patch',
                             subjects_dir=subjects_dir)
print(src)


I am working on the file "0.22/_downloads/e6e21719275dd1fe5b070e9c49c33bc5/plot_forward.ipynb".
The first task is:
Compute forward solution
We can now compute the forward solution.
To reduce computation we'll just compute a single layer BEM (just inner
skull) that can then be used for MEG (not EEG).
We specify if we want a one-layer or a three-layer BEM using the
conductivity parameter.
The BEM solution requires a BEM model which describes the geometry
of the head the conductivities of the different tissues.
Can you write Python code for it?

conductivity = (0.3,)  # for single layer
# conductivity = (0.3, 0.006, 0.3)  # for three layers
model = mne.make_bem_model(subject='sample', ico=4,
                           conductivity=conductivity,
                           subjects_dir=subjects_dir)
bem = mne.make_bem_solution(model)


I am working on the file "0.22/_downloads/e6e21719275dd1fe5b070e9c49c33bc5/plot_forward.ipynb".
The first task is:
Head model and forward computation
The aim of this tutorial is to be a getting started for forward computation.
For more extensive details and presentation of the general
concepts for forward modeling, see ch_forward.
Can you write Python code for it?

import os.path as op
import mne
from mne.datasets import sample
data_path = sample.data_path()

# the raw file containing the channel location + types
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
# The paths to Freesurfer reconstructions
subjects_dir = data_path + '/subjects'
subject = 'sample'


I am working on the file "0.22/_downloads/e6e21719275dd1fe5b070e9c49c33bc5/plot_forward.ipynb".
The first task is:
Note that the :term:BEM does not involve any use of the trans file. The BEM
only depends on the head geometry and conductivities.
It is therefore independent from the MEG data and the head position.
Let's now compute the forward operator, commonly referred to as the
gain or leadfield matrix.
See :func:mne.make_forward_solution for details on the meaning of each
parameter.
Can you write Python code for it?

fwd = mne.make_forward_solution(raw_fname, trans=trans, src=src, bem=bem,
                                meg=True, eeg=False, mindist=5.0, n_jobs=1,
                                verbose=True)
print(fwd)


I am working on the file "0.22/_downloads/e6e21719275dd1fe5b070e9c49c33bc5/plot_forward.ipynb".
The first task is:
The surface based source space src contains two parts, one for the left
hemisphere (258 locations) and one for the right hemisphere (258
locations). Sources can be visualized on top of the BEM surfaces in purple.
Can you write Python code for it?

mne.viz.plot_bem(subject=subject, subjects_dir=subjects_dir,
                 brain_surfaces='white', src=src, orientation='coronal')


I am working on the file "0.22/_downloads/e6e21719275dd1fe5b070e9c49c33bc5/plot_forward.ipynb".
The first task is:
To compute a volume based source space defined with a grid of candidate
dipoles inside a sphere of radius 90mm centered at (0.0, 0.0, 40.0) mm
you can use the following code.
Obviously here, the sphere is not perfect. It is not restricted to the
brain and it can miss some parts of the cortex.
Can you write Python code for it?

sphere = (0.0, 0.0, 0.04, 0.09)
vol_src = mne.setup_volume_source_space(subject, subjects_dir=subjects_dir,
                                        sphere=sphere, sphere_units='m')
print(vol_src)

mne.viz.plot_bem(subject=subject, subjects_dir=subjects_dir,
                 brain_surfaces='white', src=vol_src, orientation='coronal')


I am working on the file "0.22/_downloads/e6e21719275dd1fe5b070e9c49c33bc5/plot_forward.ipynb".
The first task is:
To compute a volume based source space defined with a grid of candidate
dipoles inside the brain (requires the :term:BEM surfaces) you can use the
following.
Can you write Python code for it?

surface = op.join(subjects_dir, subject, 'bem', 'inner_skull.surf')
vol_src = mne.setup_volume_source_space(subject, subjects_dir=subjects_dir,
                                        surface=surface)
print(vol_src)

mne.viz.plot_bem(subject=subject, subjects_dir=subjects_dir,
                 brain_surfaces='white', src=vol_src, orientation='coronal')


I am working on the file "0.22/_downloads/e6e21719275dd1fe5b070e9c49c33bc5/plot_forward.ipynb".
The first task is:
We can explore the content of fwd to access the numpy array that contains
the gain matrix.
Can you write Python code for it?

leadfield = fwd['sol']['data']
print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape)


I am working on the file "0.22/_downloads/e6f2b45ae501bec73cddc70f08093041/plot_40_visualize_raw.ipynb".
The first task is:
Built-in plotting methods for Raw objects
This tutorial shows how to plot continuous data as a time series, how to plot
the spectral density of continuous data, and how to plot the sensor locations
and projectors stored in ~mne.io.Raw objects.
   :depth: 2
As usual we'll start by importing the modules we need, loading some
example data <sample-dataset>, and cropping the ~mne.io.Raw
object to just 60 seconds before loading it into RAM 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)
raw.crop(tmax=60).load_data()


I am working on the file "0.22/_downloads/e6f2b45ae501bec73cddc70f08093041/plot_40_visualize_raw.ipynb".
The first task is:
If the data have been filtered, vertical dashed lines will automatically
indicate filter boundaries. The spectrum for each channel type is drawn in
its own subplot; here we've passed the average=True parameter to get a
summary for each channel type, but it is also possible to plot each channel
individually, with options for how the spectrum should be computed,
color-coding the channels by location, and more. For example, here is a plot
of just a few sensors (specified with the picks parameter), color-coded
by spatial location (via the spatial_colors parameter, see the
documentation of ~mne.io.Raw.plot_psd for full details):
Can you write Python code for it?

midline = ['EEG 002', 'EEG 012', 'EEG 030', 'EEG 048', 'EEG 058', 'EEG 060']
raw.plot_psd(picks=midline)


I am working on the file "0.22/_downloads/e6f2b45ae501bec73cddc70f08093041/plot_40_visualize_raw.ipynb".
The first task is:
Plotting projectors from Raw objects
As seen in the output of mne.io.read_raw_fif above, there are
:term:projectors <projector> included in the example ~mne.io.Raw
file (representing environmental noise in the signal, so it can later be
"projected out" during preprocessing). You can visualize these projectors
using the ~mne.io.Raw.plot_projs_topomap method. By default it will
show one figure per channel type for which projectors are present, and each
figure will have one subplot per projector. The three projectors in this file
were only computed for magnetometers, so one figure with three subplots is
generated. More details on working with and plotting projectors are given in
tut-projectors-background and tut-artifact-ssp.
Can you write Python code for it?


I am working on the file "0.22/_downloads/e6f2b45ae501bec73cddc70f08093041/plot_40_visualize_raw.ipynb".
The first task is:
We've seen in a previous tutorial <tut-raw-class> how to plot data
from a ~mne.io.Raw object using :doc:matplotlib <matplotlib:index>,
but ~mne.io.Raw objects also have several built-in plotting methods:

~mne.io.Raw.plot
~mne.io.Raw.plot_psd
~mne.io.Raw.plot_psd_topo
~mne.io.Raw.plot_sensors
~mne.io.Raw.plot_projs_topomap

The first three are discussed here in detail; the last two are shown briefly
and covered in-depth in other tutorials.
Interactive data browsing with Raw.plot()
The ~mne.io.Raw.plot method of ~mne.io.Raw objects provides
a versatile interface for exploring continuous data. For interactive viewing
and data quality checking, it can be called with no additional parameters:
Can you write Python code for it?


I am working on the file "0.22/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
And we also view the HbR activity for the two conditions.
Can you write Python code for it?

epochs['Tapping/Left'].average(picks='hbr').plot_topomap(
    times=times, **topomap_args)
epochs['Tapping/Right'].average(picks='hbr').plot_topomap(
    times=times, **topomap_args)


I am working on the file "0.22/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
At this stage it is appropriate to inspect your data
(for instructions on how to use the interactive data visualisation tool
see tut-visualize-raw)
to ensure that channels with poor scalp coupling have been removed.
If your data contains lots of artifacts you may decide to apply
artifact reduction techniques as described in ex-fnirs-artifacts.
Converting from optical density to haemoglobin
Next we convert the optical density data to haemoglobin concentration using
the modified Beer-Lambert law.
Can you write Python code for it?

raw_haemo = mne.preprocessing.nirs.beer_lambert_law(raw_od)
raw_haemo.plot(n_channels=len(raw_haemo.ch_names),
               duration=500, show_scrollbars=False)


I am working on the file "0.22/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
Compare tapping of left and right hands
Finally we generate topo maps for the left and right conditions to view
the location of activity. First we visualise the HbO activity.
Can you write Python code for it?

times = np.arange(4.0, 11.0, 1.0)
epochs['Tapping/Left'].average(picks='hbo').plot_topomap(
    times=times, **topomap_args)
epochs['Tapping/Right'].average(picks='hbo').plot_topomap(
    times=times, **topomap_args)


I am working on the file "0.22/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
Evaluating the quality of the data
At this stage we can quantify the quality of the coupling
between the scalp and the optodes using the scalp coupling index. This
method looks for the presence of a prominent synchronous signal in the
frequency range of cardiac signals across both photodetected signals.
In this example the data is clean and the coupling is good for all
channels, so we will not mark any channels as bad based on the scalp
coupling index.
Can you write Python code for it?

sci = mne.preprocessing.nirs.scalp_coupling_index(raw_od)
fig, ax = plt.subplots()
ax.hist(sci)
ax.set(xlabel='Scalp Coupling Index', ylabel='Count', xlim=[0, 1])


I am working on the file "0.22/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
Extract epochs
Now that the signal has been converted to relative haemoglobin concentration,
and the unwanted heart rate component has been removed, we can extract epochs
related to each of the experimental conditions.
First we extract the events of interest and visualise them to ensure they are
correct.
Can you write Python code for it?

events, _ = mne.events_from_annotations(raw_haemo, event_id={'1.0': 1,
                                                             '2.0': 2,
                                                             '3.0': 3})
event_dict = {'Control': 1, 'Tapping/Left': 2, 'Tapping/Right': 3}
fig = mne.viz.plot_events(events, event_id=event_dict,
                          sfreq=raw_haemo.info['sfreq'])
fig.subplots_adjust(right=0.7)  # make room for the legend


I am working on the file "0.22/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
Lastly, we can also look at the individual waveforms to see what is
driving the topographic plot above.
Can you write Python code for it?

fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(6, 4))
mne.viz.plot_evoked_topo(epochs['Left'].average(picks='hbo'), color='b',
                         axes=axes, legend=False)
mne.viz.plot_evoked_topo(epochs['Right'].average(picks='hbo'), color='r',
                         axes=axes, legend=False)

# Tidy the legend.
leg_lines = [line for line in axes.lines if line.get_c() == 'b'][:1]
leg_lines.append([line for line in axes.lines if line.get_c() == 'r'][0])
fig.legend(leg_lines, ['Left', 'Right'], loc='lower right')


I am working on the file "0.22/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
Next we define the range of our epochs, the rejection criteria,
baseline correction, and extract the epochs. We visualise the log of which
epochs were dropped.
Can you write Python code for it?

reject_criteria = dict(hbo=80e-6)
tmin, tmax = -5, 15

epochs = mne.Epochs(raw_haemo, events, event_id=event_dict,
                    tmin=tmin, tmax=tmax,
                    reject=reject_criteria, reject_by_annotation=True,
                    proj=True, baseline=(None, 0), preload=True,
                    detrend=None, verbose=True)
epochs.plot_drop_log()


I am working on the file "0.22/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
Plot standard fNIRS response image
Next we generate the most common visualisation of fNIRS data: plotting
both the HbO and HbR on the same figure to illustrate the relation between
the two signals.
Can you write Python code for it?

evoked_dict = {'Tapping/HbO': epochs['Tapping'].average(picks='hbo'),
               'Tapping/HbR': epochs['Tapping'].average(picks='hbr'),
               'Control/HbO': epochs['Control'].average(picks='hbo'),
               'Control/HbR': epochs['Control'].average(picks='hbr')}

# Rename channels until the encoding of frequency in ch_name is fixed
for condition in evoked_dict:
    evoked_dict[condition].rename_channels(lambda x: x[:-4])

color_dict = dict(HbO='#AA3377', HbR='b')
styles_dict = dict(Control=dict(linestyle='dashed'))

mne.viz.plot_compare_evokeds(evoked_dict, combine="mean", ci=0.95,
                             colors=color_dict, styles=styles_dict)


I am working on the file "0.22/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
Preprocessing functional near-infrared spectroscopy (fNIRS) data
This tutorial covers how to convert functional near-infrared spectroscopy
(fNIRS) data from raw measurements to relative oxyhaemoglobin (HbO) and
deoxyhaemoglobin (HbR) concentration.
   :depth: 2
Here we will work with the fNIRS motor data <fnirs-motor-dataset>.
Can you write Python code for it?

import os
import numpy as np
import matplotlib.pyplot as plt
from itertools import compress

import mne

fnirs_data_folder = mne.datasets.fnirs_motor.data_path()
fnirs_cw_amplitude_dir = os.path.join(fnirs_data_folder, 'Participant-1')
raw_intensity = mne.io.read_raw_nirx(fnirs_cw_amplitude_dir, verbose=True)
raw_intensity.load_data()


I am working on the file "0.22/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
View consistency of responses across channels
Similarly we can view how consistent the response is across the optode
pairs that we selected. All the channels in this data are located over the
motor cortex, and all channels show a similar pattern in the data.
Can you write Python code for it?

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(15, 6))
clims = dict(hbo=[-20, 20], hbr=[-20, 20])
epochs['Control'].average().plot_image(axes=axes[:, 0], clim=clims)
epochs['Tapping'].average().plot_image(axes=axes[:, 1], clim=clims)
for column, condition in enumerate(['Control', 'Tapping']):
    for ax in axes[:, column]:
        ax.set_title('{}: {}'.format(condition, ax.get_title()))


I am working on the file "0.22/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
View consistency of responses across trials
Now we can view the haemodynamic response for our tapping condition.
We visualise the response for both the oxy- and deoxyhaemoglobin, and
observe the expected peak in HbO at around 6 seconds consistently across
trials, and the consistent dip in HbR that is slightly delayed relative to
the HbO peak.
Can you write Python code for it?

epochs['Tapping'].plot_image(combine='mean', vmin=-30, vmax=30,
                             ts_args=dict(ylim=dict(hbo=[-15, 15],
                                                    hbr=[-15, 15])))


I am working on the file "0.22/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
View location of sensors over brain surface
Here we validate that the location of sources-detector pairs and channels
are in the expected locations. Source-detector pairs are shown as lines
between the optodes, channels (the mid point of source-detector pairs) are
optionally shown as orange dots. Source are optionally shown as red dots and
detectors as black.
Can you write Python code for it?

subjects_dir = mne.datasets.sample.data_path() + '/subjects'

fig = mne.viz.create_3d_figure(size=(800, 600), bgcolor='white')
fig = mne.viz.plot_alignment(raw_intensity.info, show_axes=True,
                             subject='fsaverage', coord_frame='mri',
                             trans='fsaverage', surfaces=['brain'],
                             fnirs=['channels', 'pairs',
                                    'sources', 'detectors'],
                             subjects_dir=subjects_dir, fig=fig)
mne.viz.set_3d_view(figure=fig, azimuth=20, elevation=60, distance=0.4,
                    focalpoint=(0., -0.01, 0.02))


I am working on the file "0.22/_downloads/ecc61038e0082bd1c13f6a49dd4cd752/plot_70_fnirs_processing.ipynb".
The first task is:
View topographic representation of activity
Next we view how the topographic activity changes throughout the response.
Can you write Python code for it?

times = np.arange(-3.5, 13.2, 3.0)
topomap_args = dict(extrapolate='local')
epochs['Tapping'].average(picks='hbo').plot_joint(
    times=times, topomap_args=topomap_args)


I am working on the file "0.22/_downloads/ee17e3e8df43ce4f0119faeeeccc374f/plot_sensors_time_frequency.ipynb".
The first task is:
Alternatively, you can also create PSDs from Epochs objects with functions
that start with psd_ such as
:func:mne.time_frequency.psd_multitaper and
:func:mne.time_frequency.psd_welch.
Can you write Python code for it?

f, ax = plt.subplots()
psds, freqs = psd_multitaper(epochs, fmin=2, fmax=40, n_jobs=1)
psds = 10. * np.log10(psds)
psds_mean = psds.mean(0).mean(0)
psds_std = psds.mean(0).std(0)

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


I am working on the file "0.22/_downloads/ee17e3e8df43ce4f0119faeeeccc374f/plot_sensors_time_frequency.ipynb".
The first task is:
Frequency analysis
We start by exploring the frequence content of our epochs.
Let's first check out all channel types by averaging across epochs.
Can you write Python code for it?

epochs.plot_psd(fmin=2., fmax=40., average=True, spatial_colors=False)


I am working on the file "0.22/_downloads/ee17e3e8df43ce4f0119faeeeccc374f/plot_sensors_time_frequency.ipynb".
The first task is:
Inspect ITC
Can you write Python code for it?

itc.plot_topo(title='Inter-Trial coherence', vmin=0., vmax=1., cmap='Reds')


I am working on the file "0.22/_downloads/ee17e3e8df43ce4f0119faeeeccc374f/plot_sensors_time_frequency.ipynb".
The first task is:
Notably, :func:mne.time_frequency.psd_welch supports the keyword argument
average, which specifies how to estimate the PSD based on the individual
windowed segments. The default is average='mean', which simply calculates
the arithmetic mean across segments. Specifying average='median', in
contrast, returns the PSD based on the median of the segments (corrected for
bias relative to the mean), which is a more robust measure.
Can you write Python code for it?

# Estimate PSDs based on "mean" and "median" averaging for comparison.
kwargs = dict(fmin=2, fmax=40, n_jobs=1)
psds_welch_mean, freqs_mean = psd_welch(epochs, average='mean', **kwargs)
psds_welch_median, freqs_median = psd_welch(epochs, average='median', **kwargs)

# Convert power to dB scale.
psds_welch_mean = 10 * np.log10(psds_welch_mean)
psds_welch_median = 10 * np.log10(psds_welch_median)

# We will only plot the PSD for a single sensor in the first epoch.
ch_name = 'MEG 0122'
ch_idx = epochs.info['ch_names'].index(ch_name)
epo_idx = 0

_, ax = plt.subplots()
ax.plot(freqs_mean, psds_welch_mean[epo_idx, ch_idx, :], color='k',
        ls='-', label='mean of segments')
ax.plot(freqs_median, psds_welch_median[epo_idx, ch_idx, :], color='k',
        ls='--', label='median of segments')

ax.set(title='Welch PSD ({}, Epoch {})'.format(ch_name, epo_idx),
       xlabel='Frequency (Hz)', ylabel='Power Spectral Density (dB)')
ax.legend(loc='upper right')
plt.show()


I am working on the file "0.22/_downloads/ee17e3e8df43ce4f0119faeeeccc374f/plot_sensors_time_frequency.ipynb".
The first task is:
Now let's take a look at the spatial distributions of the PSD.
Can you write Python code for it?


I am working on the file "0.22/_downloads/ee17e3e8df43ce4f0119faeeeccc374f/plot_sensors_time_frequency.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

data_path = somato.data_path()
subject = '01'
task = 'somato'
raw_fname = op.join(data_path, 'sub-{}'.format(subject), 'meg',
                    'sub-{}_task-{}_meg.fif'.format(subject, task))

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

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

# Construct Epochs
event_id, tmin, tmax = 1, -1., 3.
baseline = (None, 0)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=baseline, reject=dict(grad=4000e-13, eog=350e-6),
                    preload=True)

epochs.resample(200., npad='auto')  # resample to reduce computation time


I am working on the file "0.22/_downloads/ee17e3e8df43ce4f0119faeeeccc374f/plot_sensors_time_frequency.ipynb".
The first task is:
Time-frequency analysis: power and inter-trial coherence
We now compute time-frequency representations (TFRs) from our Epochs.
We'll look at power and inter-trial coherence (ITC).
To this we'll use the function :func:mne.time_frequency.tfr_morlet
but you can also use :func:mne.time_frequency.tfr_multitaper
or :func:mne.time_frequency.tfr_stockwell.
Can you write Python code for it?

# define frequencies of interest (log-spaced)
freqs = np.logspace(*np.log10([6, 35]), num=8)
n_cycles = freqs / 2.  # different number of cycle per frequency
power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True,
                        return_itc=True, decim=3, n_jobs=1)


I am working on the file "0.22/_downloads/eea7e38645d4176f944e2f8d02a34fde/plot_run_ica.ipynb".
The first task is:
Compute ICA components on epochs
ICA is fit to MEG raw data.
We assume that the non-stationary EOG artifacts have already been removed.
The sources matching the ECG are automatically found and displayed.

Note

This example does quite a bit of processing, so even on a
          fast machine it can take about a minute to complete.

Can you write Python code for it?

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

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

print(__doc__)


I am working on the file "0.22/_downloads/eea7e38645d4176f944e2f8d02a34fde/plot_run_ica.ipynb".
The first task is:
Fit ICA model using the FastICA algorithm, detect and plot components
explaining ECG artifacts.
Can you write Python code for it?

ica = ICA(n_components=0.95, method='fastica').fit(epochs)

ecg_epochs = create_ecg_epochs(raw, tmin=-.5, tmax=.5)
ecg_inds, scores = ica.find_bads_ecg(ecg_epochs, threshold='auto')

ica.plot_components(ecg_inds)


I am working on the file "0.22/_downloads/eea7e38645d4176f944e2f8d02a34fde/plot_run_ica.ipynb".
The first task is:
Plot properties of ECG components:
Can you write Python code for it?


I am working on the file "0.22/_downloads/ef89d1f7daeb4e357098461753c3af0f/plot_source_alignment.ipynb".
The first task is:
.. raw:: html
<style>
   .pink {color:DarkSalmon; font-weight:bold}
   .blue {color:DeepSkyBlue; font-weight:bold}
   .gray {color:Gray; font-weight:bold}
   .magenta {color:Magenta; font-weight:bold}
   .purple {color:Indigo; font-weight:bold}
   .green {color:LimeGreen; font-weight:bold}
   .red {color:Red; font-weight:bold}
   </style>

.. role:: pink
.. role:: blue
.. role:: gray
.. role:: magenta
.. role:: purple
.. role:: green
.. role:: red
Understanding coordinate frames
For M/EEG source imaging, there are three coordinate frames must be
brought into alignment using two 3D transformation matrices <wiki_xform_>_
that define how to rotate and translate points in one coordinate frame
to their equivalent locations in another. The three main coordinate frames
are:

:blue:"meg": the coordinate frame for the physical locations of MEG
  sensors
:gray:"mri": the coordinate frame for MRI images, and scalp/skull/brain
  surfaces derived from the MRI images
:pink:"head": the coordinate frame for digitized sensor locations and
  scalp landmarks ("fiducials")

Each of these are described in more detail in the next section.
A good way to start visualizing these coordinate frames is to use the
mne.viz.plot_alignment function, which is used for creating or inspecting
the transformations that bring these coordinate frames into alignment, and
displaying the resulting alignment of EEG sensors, MEG sensors, brain
sources, and conductor models. If you provide subjects_dir and
subject parameters, the function automatically loads the subject's
Freesurfer MRI surfaces. Important for our purposes, passing
show_axes=True to ~mne.viz.plot_alignment will draw the origin of each
coordinate frame in a different color, with axes indicated by different sized
arrows:

shortest arrow: (R)ight / X
medium arrow: forward / (A)nterior / Y
longest arrow: up / (S)uperior / Z

Note that all three coordinate systems are RAS coordinate frames and
hence are also right-handed_ coordinate systems. Finally, note that the
coord_frame parameter...
Can you write Python code for it?

fig = mne.viz.plot_alignment(raw.info, trans=trans, subject='sample',
                             subjects_dir=subjects_dir, surfaces='head-dense',
                             show_axes=True, dig=True, eeg=[], meg='sensors',
                             coord_frame='meg', mri_fiducials='estimated')
mne.viz.set_3d_view(fig, 45, 90, distance=0.6, focalpoint=(0., 0., 0.))
print('Distance from head origin to MEG origin: %0.1f mm'
      % (1000 * np.linalg.norm(raw.info['dev_head_t']['trans'][:3, 3])))
print('Distance from head origin to MRI origin: %0.1f mm'
      % (1000 * np.linalg.norm(trans['trans'][:3, 3])))
dists = mne.dig_mri_distances(raw.info, trans, 'sample',
                              subjects_dir=subjects_dir)
print('Distance from %s digitized points to head surface: %0.1f mm'
      % (len(dists), 1000 * np.mean(dists)))


I am working on the file "0.22/_downloads/ef89d1f7daeb4e357098461753c3af0f/plot_source_alignment.ipynb".
The first task is:
A good example
Here is the same plot, this time with the trans properly defined
(using a precomputed transformation matrix).
Can you write Python code for it?

mne.viz.plot_alignment(raw.info, trans=trans, subject='sample',
                       src=src, subjects_dir=subjects_dir, dig=True,
                       surfaces=['head-dense', 'white'], coord_frame='meg')


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

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


I am working on the file "0.22/_downloads/ef89d1f7daeb4e357098461753c3af0f/plot_source_alignment.ipynb".
The first task is:
Coordinate frame definitions

Neuromag/Elekta/MEGIN head coordinate frame ("head", :pink:pink axes)
     The head coordinate frame is defined through the coordinates of
     anatomical landmarks on the subject's head: usually the Nasion (NAS),
     and the left and right preauricular points (LPA and RPA).
     Different MEG manufacturers may have different definitions of the head
     coordinate frame. A good overview can be seen in the
     FieldTrip FAQ on coordinate systems.
For Neuromag/Elekta/MEGIN, the head coordinate frame is defined by the
 intersection of

the line between the LPA (:red:red sphere) and RPA
    (:purple:purple sphere), and
the line perpendicular to this LPA-RPA line one that goes through
    the Nasion (:green:green sphere).

The axes are oriented as X origin→RPA, Y origin→NAS,
 Z origin→upward (orthogonal to X and Y).
.. note:: The required 3D coordinates for defining the head coordinate
           frame (NAS, LPA, RPA) are measured at a stage separate from
           the MEG data recording. There exist numerous devices to
           perform such measurements, usually called "digitizers". For
           example, see the devices by the company Polhemus_.

MEG device coordinate frame ("meg", :blue:blue axes)
     The MEG device coordinate frame is defined by the respective MEG
     manufacturers. All MEG data is acquired with respect to this coordinate
     frame. To account for the anatomy and position of the subject's head, we
     use so-called head position indicator (HPI) coils. The HPI coils are
     placed at known locations on the scalp of the subject and emit
     high-frequency magnetic fields used to coregister the head coordinate
     frame with the device coordinate frame.
From the Neuromag/Elekta/MEGIN user manual:
 The origin of the device coordinate system is located at the center
 of the posterior spherical section of the helmet with X axis going
 from left to right and Y axis pointing front. The Z axis is, again
 normal to the plane with positive direction up.

.....
Can you write Python code for it?

mne.viz.plot_alignment(raw.info, trans=None, subject='sample', src=src,
                       subjects_dir=subjects_dir, dig=True,
                       surfaces=['head-dense', 'white'], coord_frame='meg')


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

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

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


I am working on the file "0.22/_downloads/ef89d1f7daeb4e357098461753c3af0f/plot_source_alignment.ipynb".
The first task is:
Now that we've transformed all the points, let's plot them. We'll use the
same colors used by ~mne.viz.plot_alignment and use :green:green for the
"mri_voxel" coordinate frame:
Can you write Python code for it?

def add_head(renderer, points, color, opacity=0.95):
    renderer.mesh(*points.T, triangles=seghead_tri, color=color,
                  opacity=opacity)

renderer = mne.viz.backends.renderer.create_3d_figure(
    size=(600, 600), bgcolor='w', scene=False)
add_head(renderer, seghead_rr, 'gray')
add_head(renderer, scalp_pts_in_meg_coord, 'blue')
add_head(renderer, scalp_pts_in_head_coord, 'pink')
add_head(renderer, scalp_points_in_vox, 'green')
mne.viz.set_3d_view(figure=renderer.figure, distance=800,
                    focalpoint=(0., 30., 30.), elevation=105, azimuth=180)
renderer.show()


I am working on the file "0.22/_downloads/ef89d1f7daeb4e357098461753c3af0f/plot_source_alignment.ipynb".
The first task is:
Source alignment and coordinate frames
This tutorial shows how to visually assess the spatial alignment of MEG sensor
locations, digitized scalp landmark and sensor locations, and MRI volumes. This
alignment process is crucial for computing the forward solution, as is
understanding the different coordinate frames involved in this process.
   :depth: 2
Let's start out by loading some data.
Can you write Python code for it?

import os.path as op

import numpy as np
import nibabel as nib
from scipy import linalg

import mne
from mne.io.constants import FIFF

data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
trans_fname = op.join(data_path, 'MEG', 'sample',
                      'sample_audvis_raw-trans.fif')
raw = mne.io.read_raw_fif(raw_fname)
trans = mne.read_trans(trans_fname)
src = mne.read_source_spaces(op.join(subjects_dir, 'sample', 'bem',
                                     'sample-oct-6-src.fif'))

# Load the T1 file and change the header information to the correct units
t1w = nib.load(op.join(data_path, 'subjects', 'sample', 'mri', 'T1.mgz'))
t1w = nib.Nifti1Image(t1w.dataobj, t1w.affine)
t1w.header['xyzt_units'] = np.array(10, dtype='uint8')
t1_mgh = nib.MGHImage(t1w.dataobj, t1w.affine)


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

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

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

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

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


I am working on the file "0.22/_downloads/f01121873dbae065a1740e6c0c20d1d5/plot_eeg_no_mri.ipynb".
The first task is:
EEG forward operator with a template MRI
This tutorial explains how to compute the forward operator from EEG data
using the standard template MRI subject fsaverage.
.. caution:: Source reconstruction without an individual T1 MRI from the
             subject will be less accurate. Do not over interpret
             activity locations which can be off by multiple centimeters.
   :depth: 2
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#          Joan Massich <mailsik@gmail.com>
#
# License: BSD Style.

import os.path as op

import mne
from mne.datasets import eegbci
from mne.datasets import fetch_fsaverage

# Download fsaverage files
fs_dir = fetch_fsaverage(verbose=True)
subjects_dir = op.dirname(fs_dir)

# The files live in:
subject = 'fsaverage'
trans = 'fsaverage'  # MNE has a built-in fsaverage transformation
src = op.join(fs_dir, 'bem', 'fsaverage-ico-5-src.fif')
bem = op.join(fs_dir, 'bem', 'fsaverage-5120-5120-5120-bem-sol.fif')


I am working on the file "0.22/_downloads/f01121873dbae065a1740e6c0c20d1d5/plot_eeg_no_mri.ipynb".
The first task is:
Load the data
We use here EEG data from the BCI dataset.

Note

See `plot_montage` to view all the standard EEG montages
          available in MNE-Python.

Can you write Python code for it?

raw_fname, = eegbci.load_data(subject=1, runs=[6])
raw = mne.io.read_raw_edf(raw_fname, preload=True)

# Clean channel names to be able to use a standard 1005 montage
new_names = dict(
    (ch_name,
     ch_name.rstrip('.').upper().replace('Z', 'z').replace('FP', 'Fp'))
    for ch_name in raw.ch_names)
raw.rename_channels(new_names)

# Read and set the EEG electrode locations
montage = mne.channels.make_standard_montage('standard_1005')
raw.set_montage(montage)
raw.set_eeg_reference(projection=True)  # needed for inverse modeling

# Check that the locations of EEG electrodes is correct with respect to MRI
mne.viz.plot_alignment(
    raw.info, src=src, eeg=['original', 'projected'], trans=trans,
    show_axes=True, mri_fiducials=True, dig='fiducials')


I am working on the file "0.22/_downloads/f01121873dbae065a1740e6c0c20d1d5/plot_eeg_no_mri.ipynb".
The first task is:
Setup source space and compute forward
Can you write Python code for it?

fwd = mne.make_forward_solution(raw.info, trans=trans, src=src,
                                bem=bem, eeg=True, mindist=5.0, n_jobs=1)
print(fwd)

# Use fwd to compute the sensitivity map for illustration purposes
eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed')
brain = eeg_map.plot(time_label='EEG sensitivity', subjects_dir=subjects_dir,
                     clim=dict(lims=[5, 50, 100]))


I am working on the file "0.22/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Compute MNE inverse solution on evoked data with a mixed source space
Create a mixed source space and compute an MNE inverse solution on an
evoked dataset.
Can you write Python code for it?

# Author: Annalisa Pascarella <a.pascarella@iac.cnr.it>
#
# License: BSD (3-clause)

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

from nilearn import plotting

import mne
from mne.minimum_norm import make_inverse_operator, apply_inverse

# Set dir
data_path = mne.datasets.sample.data_path()
subject = 'sample'
data_dir = op.join(data_path, 'MEG', subject)
subjects_dir = op.join(data_path, 'subjects')
bem_dir = op.join(subjects_dir, subject, 'bem')

# Set file names
fname_mixed_src = op.join(bem_dir, '%s-oct-6-mixed-src.fif' % subject)
fname_aseg = op.join(subjects_dir, subject, 'mri', 'aseg.mgz')

fname_model = op.join(bem_dir, '%s-5120-bem.fif' % subject)
fname_bem = op.join(bem_dir, '%s-5120-bem-sol.fif' % subject)

fname_evoked = data_dir + '/sample_audvis-ave.fif'
fname_trans = data_dir + '/sample_audvis_raw-trans.fif'
fname_fwd = data_dir + '/sample_audvis-meg-oct-6-mixed-fwd.fif'
fname_cov = data_dir + '/sample_audvis-shrunk-cov.fif'


I am working on the file "0.22/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Compute inverse solution
Can you write Python code for it?

snr = 3.0            # use smaller SNR for raw data
inv_method = 'dSPM'  # sLORETA, MNE, dSPM
parc = 'aparc'       # the parcellation to use, e.g., 'aparc' 'aparc.a2009s'
loose = dict(surface=0.2, volume=1.)

lambda2 = 1.0 / snr ** 2

inverse_operator = make_inverse_operator(
    evoked.info, fwd, noise_cov, depth=None, loose=loose, verbose=True)
del fwd

stc = apply_inverse(evoked, inverse_operator, lambda2, inv_method,
                    pick_ori=None)
src = inverse_operator['src']


I am working on the file "0.22/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Get a surface-based source space, here with few source points for speed
in this demonstration, in general you should use oct6 spacing!
Can you write Python code for it?

src = mne.setup_source_space(subject, spacing='oct5',
                             add_dist=False, subjects_dir=subjects_dir)


I am working on the file "0.22/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Now we create a mixed src space by adding the volume regions specified in the
list labels_vol. First, read the aseg file and the source space bounds
using the inner skull surface (here using 10mm spacing to save time,
we recommend something smaller like 5.0 in actual analyses):
Can you write Python code for it?

vol_src = mne.setup_volume_source_space(
    subject, mri=fname_aseg, pos=10.0, bem=fname_model,
    volume_label=labels_vol, subjects_dir=subjects_dir,
    add_interpolator=False,  # just for speed, usually this should be True
    verbose=True)

# Generate the mixed source space
src += vol_src
print(f"The source space contains {len(src)} spaces and "
      f"{sum(s['nuse'] for s in src)} vertices")


I am working on the file "0.22/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Plot the mixed source estimate
Can you write Python code for it?

initial_time = 0.1
stc_vec = apply_inverse(evoked, inverse_operator, lambda2, inv_method,
                        pick_ori='vector')
brain = stc_vec.plot(
    hemi='both', src=inverse_operator['src'], views='coronal',
    initial_time=initial_time, subjects_dir=subjects_dir)


I am working on the file "0.22/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Plot the volume
Can you write Python code for it?

fig = stc.volume().plot(initial_time=initial_time, src=src,
                        subjects_dir=subjects_dir)


I am working on the file "0.22/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Process labels
Average the source estimates within each label of the cortical parcellation
and each sub structure contained in the src space
Can you write Python code for it?

# Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi
labels_parc = mne.read_labels_from_annot(
    subject, parc=parc, subjects_dir=subjects_dir)

label_ts = mne.extract_label_time_course(
    [stc], labels_parc, src, mode='mean', allow_empty=True)

# plot the times series of 2 labels
fig, axes = plt.subplots(1)
axes.plot(1e3 * stc.times, label_ts[0][0, :], 'k', label='bankssts-lh')
axes.plot(1e3 * stc.times, label_ts[0][-1, :].T, 'r', label='Brain-stem')
axes.set(xlabel='Time (ms)', ylabel='MNE current (nAm)')
axes.legend()
mne.viz.tight_layout()


I am working on the file "0.22/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
Set up our source space
List substructures we are interested in. We select only the
sub structures we want to include in the source space:
Can you write Python code for it?

labels_vol = ['Left-Amygdala',
              'Left-Thalamus-Proper',
              'Left-Cerebellum-Cortex',
              'Brain-Stem',
              'Right-Amygdala',
              'Right-Thalamus-Proper',
              'Right-Cerebellum-Cortex']


I am working on the file "0.22/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
View the source space
Can you write Python code for it?


I am working on the file "0.22/_downloads/f094864c4eeae2b4353a90789dd18b2b/plot_mixed_source_space_inverse.ipynb".
The first task is:
We could write the mixed source space with::

write_source_spaces(fname_mixed_src, src, overwrite=True)

We can also export source positions to nifti file and visualize it again:
Can you write Python code for it?

nii_fname = op.join(bem_dir, '%s-mixed-src.nii' % subject)
src.export_volume(nii_fname, mri_resolution=True, overwrite=True)
plotting.plot_img(nii_fname, cmap='nipy_spectral')


I am working on the file "0.22/_downloads/f4e0fde886a45c1a46537066c93815f1/plot_parcellation.ipynb".
The first task is:
Plot a cortical parcellation
In this example, we download the HCP-MMP1.0 parcellation [1] and show it
on fsaverage.
We will also download the customized 448-label aparc parcellation from [2]

Note

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

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

References
.. [1] Glasser MF et al. (2016) A multi-modal parcellation of human
       cerebral cortex. Nature 536:171-178.
.. [2] Khan S et al. (2018) Maturation trajectories of cortical
       resting-state networks depend on the mediating frequency band.
       Neuroimage 174 57-68.
Can you write Python code for it?

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

import mne
Brain = mne.viz.get_brain_class()

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

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

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

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


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

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


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

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


I am working on the file "0.22/_downloads/f5772cd483591ac49331a1b66e9b292b/plot_fix_bem_in_blender.ipynb".
The first task is:
Back in Python, you can read the fixed .obj files and save them as
FreeSurfer .surf files. For the :func:mne.make_bem_model function to find
them, they need to be saved using their original names in the surf
folder, e.g. surf/inner_skull.surf. Be sure to first backup the original
surfaces in case you make a mistake!
Can you write Python code for it?

# Read the fixed surface
coords, faces = mne.read_surface(op.join(conv_dir, 'inner_skull_fixed.obj'))

# Backup the original surface
shutil.copy(op.join(bem_dir, 'inner_skull.surf'),
            op.join(bem_dir, 'inner_skull_orig.surf'))

# Overwrite the original surface with the fixed version
mne.write_surface(op.join(bem_dir, 'inner_skull.surf'), coords, faces,
                  overwrite=True)


I am working on the file "0.22/_downloads/f5772cd483591ac49331a1b66e9b292b/plot_fix_bem_in_blender.ipynb".
The first task is:
Editing BEM surfaces in Blender
Sometimes when creating a BEM model the surfaces need manual correction because
of a series of problems that can arise (e.g. intersection between surfaces).
Here, we will see how this can be achieved by exporting the surfaces to the 3D
modeling program Blender <https://blender.org>_, editing them, and
re-importing them.
This tutorial is based on https://github.com/ezemikulan/blender_freesurfer by
Ezequiel Mikulan.
Can you write Python code for it?

# Authors: Marijn van Vliet <w.m.vanvliet@gmail.com>
#          Ezequiel Mikulan <e.mikulan@gmail.com>
#
# License: BSD (3-clause)

import os
import os.path as op
import shutil
import mne

data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
bem_dir = op.join(subjects_dir, 'sample', 'bem')


I am working on the file "0.22/_downloads/f5772cd483591ac49331a1b66e9b292b/plot_fix_bem_in_blender.ipynb".
The first task is:
Editing in Blender
We can now open Blender and import the surfaces. Go to File > Import >
Wavefront (.obj). Navigate to the conv folder and select the file you
want to import. Make sure to select the Keep Vert Order option. You can
also select the Y Forward option to load the axes in the correct direction
(RAS):

For convenience, you can save these settings by pressing the + button
next to Operator Presets.
Repeat the procedure for all surfaces you want to import (e.g. inner_skull
and outer_skull).
You can now edit the surfaces any way you like. See the
Beginner Blender Tutorial Series
<https://www.youtube.com/playlist?list=PLxLGgWrla12dEW5mjO09kR2_TzPqDTXdw>
to learn how to use Blender. Specifically, part 2
<http://www.youtube.com/watch?v=RaT-uG5wgUw&t=5m30s> will teach you how to
use the basic editing tools you need to fix the surface.

Using the fixed surfaces in MNE-Python
In Blender, you can export a surface as an .obj file by selecting it and go
to File > Export > Wavefront (.obj). You need to again select the Y
Forward option and check the Keep Vertex Order box.

Each surface needs to be exported as a separate file. We recommend saving
them in the conv folder and ending the file name with _fixed.obj,
although this is not strictly necessary.
In order to be able to run this tutorial script top to bottom, we here
simulate the edits you did manually in Blender using Python code:
Can you write Python code for it?

coords, faces = mne.read_surface(op.join(conv_dir, 'inner_skull.obj'))
coords[0] /= 1.1  # Move the first vertex back inside the skull
mne.write_surface(op.join(conv_dir, 'inner_skull_fixed.obj'), coords, faces,
                  overwrite=True)


I am working on the file "0.22/_downloads/f760cc2f1a5d6c625b1e14a0b05176dd/plot_ecog.ipynb".
The first task is:
Alternatively, we can project the sensor data to the nearest locations on
the pial surface and visualize that:
Can you write Python code for it?

evoked = mne.EvokedArray(
    gamma_power_t[:, sl], raw.info, tmin=raw.times[sl][0])
stc = mne.stc_near_sensors(evoked, trans, subject, subjects_dir=subjects_dir)
clim = dict(kind='value', lims=[vmin * 0.9, vmin, vmax])
brain = stc.plot(surface='pial', hemi='both', initial_time=0.68,
                 colormap='viridis', clim=clim, views='parietal',
                 subjects_dir=subjects_dir, size=(500, 500))

# You can save a movie like the one on our documentation website with:
# brain.save_movie(time_dilation=50, interpolation='linear', framerate=10,
#                  time_viewer=True)


I am working on the file "0.22/_downloads/f760cc2f1a5d6c625b1e14a0b05176dd/plot_ecog.ipynb".
The first task is:
Next, we'll compute the signal power in the gamma (30-90 Hz) and alpha
(8-12 Hz) bands.
Can you write Python code for it?

gamma_power_t = raw.copy().filter(30, 90).apply_hilbert(
    envelope=True).get_data()
alpha_power_t = raw.copy().filter(8, 12).apply_hilbert(
    envelope=True).get_data()
gamma_power = gamma_power_t.mean(axis=-1)
alpha_power = alpha_power_t.mean(axis=-1)


I am working on the file "0.22/_downloads/f760cc2f1a5d6c625b1e14a0b05176dd/plot_ecog.ipynb".
The first task is:
Now let's use matplotlib to overplot frequency band power onto the electrodes
which can be plotted on top of the brain from
:func:~mne.viz.snapshot_brain_montage.
Can you write Python code for it?

# Convert from a dictionary to array to plot
xy_pts = np.vstack([xy[ch] for ch in raw.info['ch_names']])

# colormap to view spectral power
cmap = 'viridis'

# Create a 1x2 figure showing the average power in gamma and alpha bands.
fig, axs = plt.subplots(1, 2, figsize=(20, 10))
# choose a colormap range wide enough for both frequency bands
_gamma_alpha_power = np.concatenate((gamma_power, alpha_power)).flatten()
vmin, vmax = np.percentile(_gamma_alpha_power, [10, 90])
for ax, band_power, band in zip(axs,
                                [gamma_power, alpha_power],
                                ['Gamma', 'Alpha']):
    ax.imshow(im)
    ax.set_axis_off()
    sc = ax.scatter(*xy_pts.T, c=band_power, s=200,
                    cmap=cmap, vmin=vmin, vmax=vmax)
    ax.set_title(f'{band} band power', size='x-large')
fig.colorbar(sc, ax=axs)


I am working on the file "0.22/_downloads/f760cc2f1a5d6c625b1e14a0b05176dd/plot_ecog.ipynb".
The first task is:
Now that we have our montage, we can load in our corresponding
time-series data and set the montage to the raw data.
Can you write Python code for it?

# first we'll load in the sample dataset
raw = mne.io.read_raw_edf(misc_path + '/ecog/sample_ecog.edf')

# drop bad channels
raw.info['bads'].extend([ch for ch in raw.ch_names if ch not in ch_names])
raw.load_data()
raw.drop_channels(raw.info['bads'])
raw.crop(0, 2)  # just process 2 sec of data for speed

# attach montage
raw.set_montage(montage)

# set channel types to ECoG (instead of EEG)
raw.set_channel_types({ch_name: 'ecog' for ch_name in raw.ch_names})


I am working on the file "0.22/_downloads/f760cc2f1a5d6c625b1e14a0b05176dd/plot_ecog.ipynb".
The first task is:
Now we make a :class:mne.channels.DigMontage stating that the ECoG
contacts are in the FreeSurfer surface RAS (i.e., MRI) coordinate system.
Can you write Python code for it?

montage = mne.channels.make_dig_montage(
    ch_pos, coord_frame='mri', nasion=nasion, lpa=lpa, rpa=rpa)
print('Created %s channel positions' % len(ch_names))


I am working on the file "0.22/_downloads/f760cc2f1a5d6c625b1e14a0b05176dd/plot_ecog.ipynb".
The first task is:
Say we want to visualize the evolution of the power in the gamma band,
instead of just plotting the average. We can use
matplotlib.animation.FuncAnimation to create an animation and apply this
to the brain figure.
Can you write Python code for it?

# create an initialization and animation function
# to pass to FuncAnimation
def init():
    """Create an empty frame."""
    return paths,

def animate(i, activity):
    """Animate the plot."""
    paths.set_array(activity[:, i])
    return paths,

# create the figure and apply the animation of the
# gamma frequency band activity
fig, ax = plt.subplots(figsize=(5, 5))
ax.imshow(im)
ax.set_axis_off()
paths = ax.scatter(*xy_pts.T, c=np.zeros(len(xy_pts)), s=200,
                   cmap=cmap, vmin=vmin, vmax=vmax)
fig.colorbar(paths, ax=ax)
ax.set_title('Gamma frequency over time (Hilbert transform)',
             size='large')

# avoid edge artifacts and decimate, showing just a short chunk
sl = slice(100, 150)
show_power = gamma_power_t[:, sl]
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               fargs=(show_power,),
                               frames=show_power.shape[1],
                               interval=100, blit=True)


I am working on the file "0.22/_downloads/f760cc2f1a5d6c625b1e14a0b05176dd/plot_ecog.ipynb".
The first task is:
Working with ECoG data
MNE supports working with more than just MEG and EEG data. Here we show some
of the functions that can be used to facilitate working with
electrocorticography (ECoG) data.
This example shows how to use:

ECoG data
channel locations in subject's MRI space
projection onto a surface

For an example that involves sEEG data, channel locations in
MNI space, or projection into a volume, see tut_working_with_seeg.
Can you write Python code for it?

# Authors: Eric Larson <larson.eric.d@gmail.com>
#          Chris Holdgraf <choldgraf@gmail.com>
#          Adam Li <adam2392@gmail.com>
#
# License: BSD (3-clause)

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

import mne
from mne.viz import plot_alignment, snapshot_brain_montage

print(__doc__)

# paths to mne datasets - sample ECoG and FreeSurfer subject
misc_path = mne.datasets.misc.data_path()
sample_path = mne.datasets.sample.data_path()
subject = 'sample'
subjects_dir = sample_path + '/subjects'


I am working on the file "0.22/_downloads/f781cba191074d5f4243e5933c1e870d/plot_find_ref_artifacts.ipynb".
The first task is:
Cleaned data:
Can you write Python code for it?


I am working on the file "0.22/_downloads/f781cba191074d5f4243e5933c1e870d/plot_find_ref_artifacts.ipynb".
The first task is:
Cleaned raw data PSD:
Can you write Python code for it?


I am working on the file "0.22/_downloads/f781cba191074d5f4243e5933c1e870d/plot_find_ref_artifacts.ipynb".
The first task is:
Cleaned raw data traces:
Can you write Python code for it?


I am working on the file "0.22/_downloads/f781cba191074d5f4243e5933c1e870d/plot_find_ref_artifacts.ipynb".
The first task is:
Note that even though standard noise removal has already
been applied to these data, much of the noise in the reference channels
(bottom of the plot) can still be seen in the standard channels.
Can you write Python code for it?

select_picks = np.concatenate(
    (mne.pick_types(raw.info, meg=True)[-32:],
     mne.pick_types(raw.info, meg=False, ref_meg=True)))
plot_kwargs = dict(
    duration=100, order=select_picks, n_channels=len(select_picks),
    scalings={"mag": 8e-13, "ref_meg": 2e-11})
raw.plot(**plot_kwargs)


I am working on the file "0.22/_downloads/f781cba191074d5f4243e5933c1e870d/plot_find_ref_artifacts.ipynb".
The first task is:
Now try the "separate" algorithm.
Can you write Python code for it?

raw_sep = raw.copy()

# Do ICA only on the reference channels.
ref_picks = mne.pick_types(raw_sep.info, meg=False, ref_meg=True)
ica_ref = ICA(n_components=2, allow_ref_meg=True, **ica_kwargs)
ica_ref.fit(raw_sep, picks=ref_picks)

# Do ICA on both reference and standard channels. Here, we can just reuse
# ica_tog from the section above.
ica_sep = ica_tog.copy()

# Extract the time courses of these components and add them as channels
# to the raw data. Think of them the same way as EOG/EKG channels, but instead
# of giving info about eye movements/cardiac activity, they give info about
# external magnetic noise.
ref_comps = ica_ref.get_sources(raw_sep)
for c in ref_comps.ch_names:  # they need to have REF_ prefix to be recognised
    ref_comps.rename_channels({c: "REF_" + c})
raw_sep.add_channels([ref_comps])

# Now that we have our noise channels, we run the separate algorithm.
bad_comps, scores = ica_sep.find_bads_ref(raw_sep, method="separate")

# Plot scores with bad components marked.
ica_sep.plot_scores(scores, bad_comps)

# Examine the properties of removed components.
ica_sep.plot_properties(raw_sep, picks=bad_comps)

# Remove the components.
raw_sep = ica_sep.apply(raw_sep, exclude=bad_comps)