I am working on the file "0.19/_downloads/85b80d223414f32365a9175978a38cb4/plot_limo_data.ipynb".
The first task is:
Before going on, we'll drop the EOG channels present in the LIMO epochs
(coded with EXG-prefix in limo_epochs.info['ch_names'], as data has
already been cleaned.
Can you write Python code for it?

limo_epochs.drop_channels(['EXG1', 'EXG2', 'EXG3', 'EXG4'])

# Furthermore, some datasets contain missing channels (stored in
# ``limo_epochs.info[‘bads’]``), which were dropped during preprocessing of the
# data. We’ll interpolate this channels for convenience.
limo_epochs.interpolate_bads(reset_bads=True)


I am working on the file "0.19/_downloads/85b80d223414f32365a9175978a38cb4/plot_limo_data.ipynb".
The first task is:
In the original LIMO experiment, participants performed a two-alternative
forced choice task discriminating between the same two faces.
The critical manipulation in the experiment was that the phase-coherence of
the presented face-stimuli was varied across a noise-signal continuum
spanning from 0 to 100 %. In other words, faces with high phase coherence
were easily discernible, while faces with low phase-coherence were hard to
identify as such).
The events coding the presentation of each of these two faces are stored in
limo_epochs.events.
We can visualise the distribution of the face events contained in the
epochs structure. Events should appear clearly grouped, as they are ordered
during the import process.
Can you write Python code for it?

fig, ax = plt.subplots(figsize=(7, 5))
mne.viz.plot_events(limo_epochs.events, event_id=limo_epochs.event_id, axes=ax)
ax.set(title="Distribution of events")
plt.legend(loc='lower left', borderaxespad=1.)
plt.tight_layout()
plt.show()


I am working on the file "0.19/_downloads/85b80d223414f32365a9175978a38cb4/plot_limo_data.ipynb".
The first task is:
Next, we can inspect the effect of phase-coherence on the activation
patterns evoked by the presented face-stimuli.
Here, one would expect that faces with high phase-coherence evoke a stronger
response, as participants should be better at identifying these faces.
Create design matrix for linear regression. We'll use the information
contained in the limo_epochs.metadata.
Can you write Python code for it?

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

# fit linear model
reg = linear_regression(limo_epochs, design[names], names=names)


I am working on the file "0.19/_downloads/85b80d223414f32365a9175978a38cb4/plot_limo_data.ipynb".
The first task is:
Now we can go ahead and plot the ERPs evoked by Face A and Face B
Can you write Python code for it?

# only show -250 to 500 ms
ts_args = dict(xlim=(-.25, 0.5))

# plot evoked response for faces A & B
limo_epochs['Face/A'].average().plot_joint(times=[.15],
                                           title='Evoked response: Face A',
                                           ts_args=ts_args)

limo_epochs['Face/B'].average().plot_joint(times=[.15],
                                           title='Evoked response: Face B',
                                           ts_args=ts_args)


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

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

# Plot difference between Face A and Face B
difference_wave.plot_joint(times=[.15], title='Difference Face A - Face B')


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

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


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

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


I am working on the file "0.19/_downloads/85e12f42707b248635bc0c477c2ffc2f/plot_mne_solutions.ipynb".
The first task is:
Computing various MNE solutions
This example shows example fixed- and free-orientation source localizations
produced by MNE, dSPM, sLORETA, and eLORETA.
Can you write Python code for it?

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

import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse

print(__doc__)

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

# Read data
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
evoked = mne.read_evokeds(fname_evoked, condition='Left Auditory',
                          baseline=(None, 0))
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
fname_cov = data_path + '/MEG/sample/sample_audvis-cov.fif'
fwd = mne.read_forward_solution(fname_fwd)
cov = mne.read_cov(fname_cov)


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

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


I am working on the file "0.19/_downloads/85e12f42707b248635bc0c477c2ffc2f/plot_mne_solutions.ipynb".
The first task is:
Free orientation
Now let's not constrain the orientation of the dipoles at all by creating
a free-orientation inverse.
Can you write Python code for it?

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


I am working on the file "0.19/_downloads/85e12f42707b248635bc0c477c2ffc2f/plot_mne_solutions.ipynb".
The first task is:
Let's look at the current estimates using MNE. We'll take the absolute
value of the source estimates to simplify the visualization.
Can you write Python code for it?

snr = 3.0
lambda2 = 1.0 / snr ** 2
kwargs = dict(initial_time=0.08, hemi='both', subjects_dir=subjects_dir,
              size=(600, 600))

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


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


I am working on the file "0.19/_downloads/85e12f42707b248635bc0c477c2ffc2f/plot_mne_solutions.ipynb".
The first task is:
Next let's use the default noise normalization, dSPM:
Can you write Python code for it?

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


I am working on the file "0.19/_downloads/8763e6c899a8b9971980be1308b5f693/plot_dics.ipynb".
The first task is:
Before we simulate the sensor-level data, let's define a signal-to-noise
ratio. You are encouraged to play with this parameter and see the effect of
noise on our results.
Can you write Python code for it?

snr = 1.  # Signal-to-noise ratio. Decrease to add more noise.


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

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


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

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

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

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

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

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

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

    return signal


I am working on the file "0.19/_downloads/8763e6c899a8b9971980be1308b5f693/plot_dics.ipynb".
The first task is:
Now we run the signal through the forward model to obtain simulated sensor
data. To save computation time, we'll only simulate gradiometer data. You can
try simulating other types of sensors as well.
Some noise is added based on the baseline noise covariance matrix from the
sample dataset, scaled to implement the desired SNR.
Can you write Python code for it?

# Read the info from the sample dataset. This defines the location of the
# sensors and such.
info = mne.io.read_info(raw_fname)
info.update(sfreq=sfreq, bads=[])

# Only use gradiometers
picks = mne.pick_types(info, meg='grad', stim=True, exclude=())
mne.pick_info(info, picks, copy=False)

# Define a covariance matrix for the simulated noise. In this tutorial, we use
# a simple diagonal matrix.
cov = mne.cov.make_ad_hoc_cov(info)
cov['data'] *= (20. / snr) ** 2  # Scale the noise to achieve the desired SNR

# Simulate the raw data, with a lowpass filter on the noise
stcs = [(stc_signal, unit_impulse(n_samp, dtype=int) * 1),
        (stc_noise, unit_impulse(n_samp, dtype=int) * 2)]  # stacked in time
duration = (len(stc_signal.times) * 2) / sfreq
raw = simulate_raw(info, stcs, forward=fwd)
add_noise(raw, cov, iir_filter=[4, -4, 0.8], random_state=rand)


I am working on the file "0.19/_downloads/8763e6c899a8b9971980be1308b5f693/plot_dics.ipynb".
The first task is:
Power mapping
With our simulated dataset ready, we can now pretend to be researchers that
have just recorded this from a real subject and are going to study what parts
of the brain communicate with each other.
First, we'll create a source estimate of the MEG data. We'll use both a
straightforward MNE-dSPM inverse solution for this, and the DICS beamformer
which is specifically designed to work with oscillatory data.
Computing the inverse using MNE-dSPM:
Can you write Python code for it?

# Compute the inverse operator
fwd = mne.read_forward_solution(fwd_fname)
inv = make_inverse_operator(epochs.info, fwd, cov)

# Apply the inverse model to the trial that also contains the signal.
s = apply_inverse(epochs['signal'].average(), inv)

# Take the root-mean square along the time dimension and plot the result.
s_rms = np.sqrt((s ** 2).mean())
title = 'MNE-dSPM inverse (RMS)'
brain = s_rms.plot('sample', subjects_dir=subjects_dir, hemi='both', figure=1,
                   size=600, time_label=title, title=title)

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

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


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

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

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

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

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

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


I am working on the file "0.19/_downloads/8763e6c899a8b9971980be1308b5f693/plot_dics.ipynb".
The first task is:
We create an :class:mne.Epochs object containing two trials: one with
both noise and signal and one with just noise
Can you write Python code for it?

events = mne.find_events(raw, initial_event=True)
tmax = (len(stc_signal.times) - 1) / sfreq
epochs = mne.Epochs(raw, events, event_id=dict(signal=1, noise=2),
                    tmin=0, tmax=tmax, baseline=None, preload=True)
assert len(epochs) == 2  # ensure that we got the two expected events

# Plot some of the channels of the simulated data that are situated above one
# of our simulated sources.
picks = mne.pick_channels(epochs.ch_names, mne.read_selection('Left-frontal'))
epochs.plot(picks=picks)


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

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

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

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

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

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

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

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

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

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


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

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

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


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


I am working on the file "0.19/_downloads/89050e30106bf5c25f0fafb6d50732da/plot_phantom_4DBTi.ipynb".
The first task is:
Plot the dipoles in 3D
Can you write Python code for it?

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

fig = mne.viz.plot_alignment(evoked.info, bem=sphere, surfaces=[])

# Plot the position of the actual dipole
fig = mne.viz.plot_dipole_locations(dipoles=dip_true, mode='sphere',
                                    color=(1., 0., 0.), fig=fig)
# Plot the position of the estimated dipole
fig = mne.viz.plot_dipole_locations(dipoles=dip, mode='sphere',
                                    color=(1., 1., 0.), fig=fig)


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

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

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

t0 = 0.07  # peak of the response

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

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


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

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

import matplotlib.pyplot as plt

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

print(__doc__)

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

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

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

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

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

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


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

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

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


I am working on the file "0.19/_downloads/8ea66c2199216e6ce0647e90bf50c6c1/plot_compute_source_psd_epochs.ipynb".
The first task is:
Visualize the 10 Hz PSD:
Can you write Python code for it?

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


I am working on the file "0.19/_downloads/8ea66c2199216e6ce0647e90bf50c6c1/plot_compute_source_psd_epochs.ipynb".
The first task is:
Visualize the entire spectrum:
Can you write Python code for it?

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


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

Note

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

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

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


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

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


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

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


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

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


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

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

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

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

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

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


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

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


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

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


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

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


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

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

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


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

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


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

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


I am working on the file "0.19/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Repairing artifacts with ICA
This tutorial covers the basics of independent components analysis (ICA) and
shows how ICA can be used for artifact repair; an extended example illustrates
repair of ocular and heartbeat artifacts.
   :depth: 2
We begin as always by importing the necessary Python modules and loading some
example data <sample-dataset>. Because ICA can be computationally
intense, we'll also crop the data to 60 seconds; and to save ourselves from
repeatedly typing mne.preprocessing we'll directly import a few functions
and classes from that submodule:
Can you write Python code for it?

import os
import mne
from mne.preprocessing import (ICA, create_eog_epochs, create_ecg_epochs,
                               corrmap)

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.)


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


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

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


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

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

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

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

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

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

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


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


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

import os.path as op

import mne
from mne.datasets import sample


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

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


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

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


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

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

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


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

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


I am working on the file "0.19/_downloads/90c71f0d36d740bc290fd9fa30bddd8c/plot_compute_covariance.ipynb".
The first task is:
This will plot the whitened evoked for the optimal estimator and display the
:term:GFPs <GFP> for all estimators as separate lines in the related panel.
Finally, let's have a look at the difference between empty room and
event related covariance, hacking the "method" option so that their types
are shown in the legend of the plot.
Can you write Python code for it?

evoked_meg = evoked.copy().pick('meg')
noise_cov['method'] = 'empty_room'
noise_cov_baseline['method'] = 'baseline'
evoked_meg.plot_white([noise_cov_baseline, noise_cov], time_unit='s')


I am working on the file "0.19/_downloads/9256698a6dc1e67585812dacb4e9f960/plot_elekta_epochs.ipynb".
The first task is:
======================================
Getting averaging info from .fif files
======================================
Parse averaging information defined in Elekta Vectorview/TRIUX DACQ (data
acquisition). Extract and average epochs accordingly. Modify some
averaging parameters and get epochs.
Can you write Python code for it?

# Author: Jussi Nurminen (jnu@iki.fi)
#
# License: BSD (3-clause)

import mne
import os
from mne.datasets import multimodal

fname_raw = os.path.join(multimodal.data_path(), 'multimodal_raw.fif')

print(__doc__)


I am working on the file "0.19/_downloads/9256698a6dc1e67585812dacb4e9f960/plot_elekta_epochs.ipynb".
The first task is:
Check DACQ defined averaging categories and other info
Can you write Python code for it?


I am working on the file "0.19/_downloads/9256698a6dc1e67585812dacb4e9f960/plot_elekta_epochs.ipynb".
The first task is:
Get epochs from all conditions, average
Can you write Python code for it?

evokeds = []
for cat in raw.acqparser.categories:
    cond = raw.acqparser.get_condition(raw, cat)
    # copy (supported) rejection parameters from DACQ settings
    epochs = mne.Epochs(raw, reject=raw.acqparser.reject,
                        flat=raw.acqparser.flat, **cond)
    evoked = epochs.average()
    evoked.comment = cat['comment']
    evokeds.append(evoked)
# save all averages to an evoked fiff file
# fname_out = 'multimodal-ave.fif'
# mne.write_evokeds(fname_out, evokeds)


I am working on the file "0.19/_downloads/9256698a6dc1e67585812dacb4e9f960/plot_elekta_epochs.ipynb".
The first task is:
Make a new averaging category
Can you write Python code for it?

newcat = dict()
newcat['comment'] = 'Visual lower left, longer epochs'
newcat['event'] = 3  # reference event
newcat['start'] = -.2  # epoch start rel. to ref. event (in seconds)
newcat['end'] = .7  # epoch end
newcat['reqevent'] = 0  # additional required event; 0 if none
newcat['reqwithin'] = .5  # ...required within .5 sec (before or after)
newcat['reqwhen'] = 2  # ...required before (1) or after (2) ref. event
newcat['index'] = 9  # can be set freely

cond = raw.acqparser.get_condition(raw, newcat)
epochs = mne.Epochs(raw, reject=raw.acqparser.reject,
                    flat=raw.acqparser.flat, **cond)
epochs.average().plot(time_unit='s')


I am working on the file "0.19/_downloads/9256698a6dc1e67585812dacb4e9f960/plot_elekta_epochs.ipynb".
The first task is:
Read raw file
Can you write Python code for it?


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

Warning

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

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

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

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

print(__doc__)

data_path = sample.data_path()


I am working on the file "0.19/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Dipole fits
For computing a dipole fit, we need to load the noise covariance, the BEM
solution, and the coregistration transformation files. Note that for the
other methods, these were already used to generate the inverse operator.
Can you write Python code for it?

fname_cov = os.path.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif')
fname_bem = os.path.join(subjects_dir, 'sample', 'bem',
                         'sample-5120-bem-sol.fif')
fname_trans = os.path.join(data_path, 'MEG', 'sample',
                           'sample_audvis_raw-trans.fif')


I am working on the file "0.19/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Finally, we can visualize the dipole.
Can you write Python code for it?


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

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


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

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


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

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


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

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


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


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

import os

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

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

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


I am working on the file "0.19/_downloads/96cdfef13f5475e2f32b862fa94904b7/plot_visualize_stc.ipynb".
The first task is:
Volume Source Estimates
We can also visualize volume source estimates (used for deep structures).
Let us load the sensor-level evoked data. We select the MEG channels
to keep things simple.
Can you write Python code for it?

evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
evoked.pick_types(meg=True, eeg=False)


I am working on the file "0.19/_downloads/974f822d2280f83b67727ee3355c7c2f/plot_sensor_connectivity.ipynb".
The first task is:
Compute all-to-all connectivity in sensor space
Computes the Phase Lag Index (PLI) between all gradiometers and shows the
connectivity in 3D using the helmet geometry. The left visual stimulation data
are used which produces strong connectvitiy in the right occipital sensors.
Can you write Python code for it?

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

import mne
from mne import io
from mne.connectivity import spectral_connectivity
from mne.datasets import sample
from mne.viz import plot_sensors_connectivity

print(__doc__)


I am working on the file "0.19/_downloads/995d3b6a9ece3566320943b2dcc13e22/plot_opm_data.ipynb".
The first task is:
Examine our coordinate alignment for source localization and compute a
forward operator:

Note

The Head<->MRI transform is an identity matrix, as the
          co-registration method used equates the two coordinate
          systems. This mis-defines the head coordinate system
          (which should be based on the LPA, Nasion, and RPA)
          but should be fine for these analyses.

Can you write Python code for it?

bem = mne.read_bem_solution(bem_fname)
trans = None

# To compute the forward solution, we must
# provide our temporary/custom coil definitions, which can be done as::
#
# with mne.use_coil_def(coil_def_fname):
#     fwd = mne.make_forward_solution(
#         raw.info, trans, src, bem, eeg=False, mindist=5.0,
#         n_jobs=1, verbose=True)

fwd = mne.read_forward_solution(fwd_fname)

with mne.use_coil_def(coil_def_fname):
    fig = mne.viz.plot_alignment(
        raw.info, trans, subject, subjects_dir, ('head', 'pial'), bem=bem)

mne.viz.set_3d_view(figure=fig, azimuth=45, elevation=60, distance=0.4,
                    focalpoint=(0.02, 0, 0.04))


I am working on the file "0.19/_downloads/995d3b6a9ece3566320943b2dcc13e22/plot_opm_data.ipynb".
The first task is:
Prepare data for localization
First we filter and epoch the data:
Can you write Python code for it?

raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.filter(None, 90, h_trans_bandwidth=10.)
raw.notch_filter(50., notch_widths=1)

# Set epoch rejection threshold a bit larger than for SQUIDs
reject = dict(mag=2e-10)
tmin, tmax = -0.5, 1

# Find Median nerve stimulator trigger
event_id = dict(Median=257)
events = mne.find_events(raw, stim_channel='STI101', mask=257, mask_type='and')
picks = mne.pick_types(raw.info, meg=True, eeg=False)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                    reject=reject, picks=picks, proj=False, decim=4)
evoked = epochs.average()
evoked.plot()
cov = mne.compute_covariance(epochs, tmax=0.)


I am working on the file "0.19/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Creating the empty-room projectors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We create the SSP vectors using :func:~mne.compute_proj_raw, and control
the number of projectors with parameters n_grad and n_mag. Once
created, the field pattern of the projectors can be easily visualized with
:func:~mne.viz.plot_projs_topomap.
Can you write Python code for it?

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


I am working on the file "0.19/_downloads/99730d9046b115c3e40e7e01cb975635/plot_50_artifact_correction_ssp.ipynb".
The first task is:
Finally, note that above we passed reject=None to the
:func:~mne.preprocessing.compute_proj_ecg function, meaning that all
detected ECG epochs would be used when computing the projectors (regardless
of signal quality in the data sensors during those epochs). The default
behavior is to reject epochs based on signal amplitude: epochs with
peak-to-peak amplitudes exceeding 50 μV in EEG channels, 250 μV in EOG
channels, 2000 fT/cm in gradiometer channels, or 3000 fT in magnetometer
channels. You can change these thresholds by passing a dictionary with keys
eeg, eog, mag, and grad (though be sure to pass the threshold
values in volts, teslas, or teslas/meter). Generally, it is a good idea to
reject such epochs when computing the ECG projectors (since presumably the
high-amplitude fluctuations in the channels are noise, not reflective of
brain activity); passing reject=None above was done simply to avoid the
dozens of extra lines of output (enumerating which sensor(s) were responsible
for each rejected epoch) from cluttering up the tutorial.

Note

:func:`~mne.preprocessing.compute_proj_ecg` has a similar parameter
    ``flat`` for specifying the *minimum* acceptable peak-to-peak amplitude
    for each channel type.

While :func:~mne.preprocessing.compute_proj_ecg conveniently combines
several operations into a single function, MNE-Python also provides functions
for performing each part of the process. Specifically:

:func:mne.preprocessing.find_ecg_events for detecting heartbeats in a
  :class:~mne.io.Raw object and returning a corresponding :term:events
  array

:func:mne.preprocessing.create_ecg_epochs for detecting heartbeats in a
  :class:~mne.io.Raw object and returning an :class:~mne.Epochs object

:func:mne.compute_proj_epochs for creating projector(s) from any
  :class:~mne.Epochs object

See the documentation of each function for further details.
Repairing EOG artifacts with SSP
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Once again let's visualize our artifact...
Can you write Python code for it?

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


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

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


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


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


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

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


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

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


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

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


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

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


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

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

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

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

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


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

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


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

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


I am working on the file "0.19/_downloads/99d2306f38e4ae32ce5d28d8fa3bcba5/plot_lcmv_beamformer.ipynb".
The first task is:
Compute LCMV beamformer on evoked data
Compute LCMV beamformer on an evoked dataset for three different choices of
source orientation and store the solutions in stc files for visualization.
Can you write Python code for it?

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

import matplotlib.pyplot as plt
import numpy as np

import mne
from mne.datasets import sample
from mne.beamformer import make_lcmv, apply_lcmv

print(__doc__)

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_raw-eve.fif'
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
label_name = 'Aud-lh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name
subjects_dir = data_path + '/subjects'


I am working on the file "0.19/_downloads/99d2306f38e4ae32ce5d28d8fa3bcba5/plot_lcmv_beamformer.ipynb".
The first task is:
Get epochs
Can you write Python code for it?

event_id, tmin, tmax = 1, -0.2, 0.5

# Setup for reading the raw data
raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.info['bads'] = ['MEG 2443', 'EEG 053']  # 2 bads channels
events = mne.read_events(event_fname)

# Set up pick list: EEG + MEG - bad channels (modify to your needs)
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True,
                       exclude='bads')

# Pick the channels of interest
raw.pick_channels([raw.ch_names[pick] for pick in picks])
# Re-normalize our empty-room projectors, so they are fine after subselection
raw.info.normalize_proj()

# Read epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                    baseline=(None, 0), preload=True, proj=True,
                    reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6))
evoked = epochs.average()

forward = mne.read_forward_solution(fname_fwd)
forward = mne.convert_forward_solution(forward, surf_ori=True)

# Compute regularized noise and data covariances
noise_cov = mne.compute_covariance(epochs, tmin=tmin, tmax=0, method='shrunk',
                                   rank=None)
data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15,
                                  method='shrunk', rank=None)
evoked.plot(time_unit='s')


I am working on the file "0.19/_downloads/99d2306f38e4ae32ce5d28d8fa3bcba5/plot_lcmv_beamformer.ipynb".
The first task is:
We can also look at the spatial distribution
Can you write Python code for it?

# Plot last stc in the brain in 3D with PySurfer if available
brain = max_stc.plot(hemi='lh', views='lat', subjects_dir=subjects_dir,
                     initial_time=0.1, time_unit='s', smoothing_steps=5)
for color, vertex in zip(colors, max_voxs):
    brain.add_foci([vertex], coords_as_verts=True, scale_factor=0.5,
                   hemi='lh', color=color)


I am working on the file "0.19/_downloads/a09c964ce37825f750704113fa863276/plot_mne_inverse_envelope_correlation_volume.ipynb".
The first task is:
Compute label time series and do envelope correlation
Can you write Python code for it?

epochs.apply_hilbert()  # faster to do in sensor space
stcs = apply_lcmv_epochs(epochs, filters, return_generator=True)
corr = envelope_correlation(stcs, verbose=True)


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

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


I am working on the file "0.19/_downloads/a09c964ce37825f750704113fa863276/plot_mne_inverse_envelope_correlation_volume.ipynb".
The first task is:
Now we band-pass filter our data and create epochs.
Can you write Python code for it?

raw.filter(14, 30)
events = mne.make_fixed_length_events(raw, duration=5.)
epochs = mne.Epochs(raw, events=events, tmin=0, tmax=5.,
                    baseline=None, reject=dict(mag=8e-13), preload=True)
del raw


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

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

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


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

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

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

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

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


I am working on the file "0.19/_downloads/a1ab4842a5aa341564b4fa0a6bf60065/plot_dipole_orientations.ipynb".
The first task is:
Restricting the dipole orientations in this manner leads to the following
source estimate for the sample data:
Can you write Python code for it?

# Compute the source estimate for the 'left - auditory' condition in the sample
# dataset.
inv = make_inverse_operator(left_auditory.info, fwd, noise_cov, fixed=True)
stc = apply_inverse(left_auditory, inv, pick_ori=None)

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


I am working on the file "0.19/_downloads/a1ab4842a5aa341564b4fa0a6bf60065/plot_dipole_orientations.ipynb".
The first task is:
The direction of the estimated current is now restricted to two directions:
inward and outward. In the plot, blue areas indicate current flowing inwards
and red areas indicate current flowing outwards. Given the curvature of the
cortex, groups of dipoles tend to point in the same direction: the direction
of the electromagnetic field picked up by the sensors.
Loose dipole orientations
Forcing the source dipoles to be strictly orthogonal to the cortex makes the
source estimate sensitive to the spacing of the dipoles along the cortex,
since the curvature of the cortex changes within each ~10 square mm patch.
Furthermore, misalignment of the MEG/EEG and MRI coordinate frames is more
critical when the source dipole orientations are strictly constrained [2]_.
To lift the restriction on the orientation of the dipoles, the inverse
operator has the ability to place not one, but three dipoles at each
location defined by the source space. These three dipoles are placed
orthogonally to form a Cartesian coordinate system. Let's visualize this:
Can you write Python code for it?

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

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

# Show the three dipoles defined at each location in the source space
fig = mne.viz.plot_alignment(subject=subject, subjects_dir=subjects_dir,
                             trans=trans, fwd=fwd,
                             surfaces='white', coord_frame='head', fig=fig)

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


I am working on the file "0.19/_downloads/a1ab4842a5aa341564b4fa0a6bf60065/plot_dipole_orientations.ipynb".
The first task is:
The role of dipole orientations in distributed source localization
When performing source localization in a distributed manner
(MNE/dSPM/sLORETA/eLORETA),
the source space is defined as a grid of dipoles that spans a large portion of
the cortex. These dipoles have both a position and an orientation. In this
tutorial, we will look at the various options available to restrict the
orientation of the dipoles and the impact on the resulting source estimate.
See inverse_orientation_constrains
Loading data
Load everything we need to perform source localization on the sample dataset.
Can you write Python code for it?

import mne
import numpy as np
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse

data_path = sample.data_path()
evokeds = mne.read_evokeds(data_path + '/MEG/sample/sample_audvis-ave.fif')
left_auditory = evokeds[0].apply_baseline()
fwd = mne.read_forward_solution(
    data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif')
mne.convert_forward_solution(fwd, surf_ori=True, copy=False)
noise_cov = mne.read_cov(data_path + '/MEG/sample/sample_audvis-cov.fif')
subject = 'sample'
subjects_dir = data_path + '/subjects'
trans_fname = data_path + '/MEG/sample/sample_audvis_raw-trans.fif'


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

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

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

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


I am working on the file "0.19/_downloads/a2556d0f8dd65be2930ab61c812863c7/plot_read_epochs.ipynb".
The first task is:
Reading epochs from a raw FIF file
This script shows how to read the epochs from a raw file given
a list of events. For illustration, we compute the evoked responses
for both MEG and EEG data by averaging all the epochs.
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#          Matti Hamalainen <msh@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)

import mne
from mne import io
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()


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

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

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

# Set up pick list: EEG + MEG - bad channels (modify to your needs)
raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True,
                       exclude='bads')

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

evoked = epochs.average()  # average epochs to get the evoked response


I am working on the file "0.19/_downloads/a2556d0f8dd65be2930ab61c812863c7/plot_read_epochs.ipynb".
The first task is:
Show result
Can you write Python code for it?


I am working on the file "0.19/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
Also by default, :func:~mne.set_config will set values in both the JSON
file and in :data:os.environ; to set a config variable only in the JSON
file use set_env=False. Here we'll use :func:print statement to confirm
that an environment variable is being created and deleted (we could have used
the Python assert statement <assert> instead, but it doesn't print any
output when it succeeds so it's a little less obvious):
Can you write Python code for it?

mne.set_config('foo', 'bar', set_env=False)
print('foo' in os.environ.keys())
mne.set_config('foo', 'bar')
print('foo' in os.environ.keys())
mne.set_config('foo', None)  # unsetting a key deletes var from environment
print('foo' in os.environ.keys())


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


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


I am working on the file "0.19/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
If you're unsure whether a config variable has been set, there is a
convenient way to check it and provide a fallback in case it doesn't exist:
:func:~mne.get_config has a default parameter.
Can you write Python code for it?


I am working on the file "0.19/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
It is possible to add config variables that are not part of the recognized
list, by passing any arbitrary key to :func:~mne.set_config. This will
yield a warning, however, which is a nice check in cases where you meant to
set a valid key but simply misspelled it:
Can you write Python code for it?


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

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


I am working on the file "0.19/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
Note that the string values read from the JSON file are not parsed in any
way, so :func:~mne.get_config returns a string even for true/false config
values, rather than a Python boolean <bltin-boolean-values>.
Similarly, :func:~mne.set_config will only set string values (or None
values, to unset a variable):
Can you write Python code for it?

try:
    mne.set_config('MNE_USE_CUDA', True)
except TypeError as err:
    print(err)


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

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


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


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

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


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

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


I am working on the file "0.19/_downloads/a47d41a5d6e12802ada8e8ab7ecc9ffc/plot_50_configure_mne.ipynb".
The first task is:
Where configurations are stored
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
MNE-Python stores configuration variables in a JSON_ file. By default, this
file is located in :file:{%USERPROFILE%}\\.mne\\mne-python.json on Windows
and :file:{$HOME}/.mne/mne-python.json on Linux or macOS. You can get the
full path to the config file with :func:mne.get_config_path.
Can you write Python code for it?


I am working on the file "0.19/_downloads/a4d4c1a667c2374c09eed24ac047d840/plot_decoding_csp_eeg.ipynb".
The first task is:
Classification with linear discrimant analysis
Can you write Python code for it?

# Define a monte-carlo cross-validation generator (reduce variance):
scores = []
epochs_data = epochs.get_data()
epochs_data_train = epochs_train.get_data()
cv = ShuffleSplit(10, test_size=0.2, random_state=42)
cv_split = cv.split(epochs_data_train)

# Assemble a classifier
lda = LinearDiscriminantAnalysis()
csp = CSP(n_components=4, reg=None, log=True, norm_trace=False)

# Use scikit-learn Pipeline with cross_val_score function
clf = Pipeline([('CSP', csp), ('LDA', lda)])
scores = cross_val_score(clf, epochs_data_train, labels, cv=cv, n_jobs=1)

# Printing the results
class_balance = np.mean(labels == labels[0])
class_balance = max(class_balance, 1. - class_balance)
print("Classification accuracy: %f / Chance level: %f" % (np.mean(scores),
                                                          class_balance))

# plot CSP patterns estimated on full data for visualization
csp.fit_transform(epochs_data, labels)

layout = read_layout('EEG1005')
csp.plot_patterns(epochs.info, layout=layout, ch_type='eeg',
                  units='Patterns (AU)', size=1.5)


I am working on the file "0.19/_downloads/a4d4c1a667c2374c09eed24ac047d840/plot_decoding_csp_eeg.ipynb".
The first task is:
Look at performance over time
Can you write Python code for it?

sfreq = raw.info['sfreq']
w_length = int(sfreq * 0.5)   # running classifier: window length
w_step = int(sfreq * 0.1)  # running classifier: window step size
w_start = np.arange(0, epochs_data.shape[2] - w_length, w_step)

scores_windows = []

for train_idx, test_idx in cv_split:
    y_train, y_test = labels[train_idx], labels[test_idx]

    X_train = csp.fit_transform(epochs_data_train[train_idx], y_train)
    X_test = csp.transform(epochs_data_train[test_idx])

    # fit classifier
    lda.fit(X_train, y_train)

    # running classifier: test classifier on sliding window
    score_this_window = []
    for n in w_start:
        X_test = csp.transform(epochs_data[test_idx][:, :, n:(n + w_length)])
        score_this_window.append(lda.score(X_test, y_test))
    scores_windows.append(score_this_window)

# Plot scores over time
w_times = (w_start + w_length / 2.) / sfreq + epochs.tmin

plt.figure()
plt.plot(w_times, np.mean(scores_windows, 0), label='Score')
plt.axvline(0, linestyle='--', color='k', label='Onset')
plt.axhline(0.5, linestyle='-', color='k', label='Chance')
plt.xlabel('time (s)')
plt.ylabel('classification accuracy')
plt.title('Classification score over time')
plt.legend(loc='lower right')
plt.show()


I am working on the file "0.19/_downloads/a68128275cc59b074b8c9782296d1d4a/decoding_rsa.ipynb".
The first task is:
Compute confusion matrix using ROC-AUC
Can you write Python code for it?

confusion = np.zeros((len(classes), len(classes)))
for ii, train_class in enumerate(classes):
    for jj in range(ii, len(classes)):
        confusion[ii, jj] = roc_auc_score(y == train_class, y_pred[:, jj])
        confusion[jj, ii] = confusion[ii, jj]


I am working on the file "0.19/_downloads/a68128275cc59b074b8c9782296d1d4a/decoding_rsa.ipynb".
The first task is:
Confusion matrix related to mental representations have been historically
summarized with dimensionality reduction using multi-dimensional scaling [1].
See how the face samples cluster together.
Can you write Python code for it?

fig, ax = plt.subplots(1)
mds = MDS(2, random_state=0, dissimilarity='precomputed')
chance = 0.5
summary = mds.fit_transform(chance - confusion)
cmap = plt.get_cmap('rainbow')
colors = ['r', 'b']
names = list(conds['condition'].values)
for color, name in zip(colors, set(names)):
    sel = np.where([this_name == name for this_name in names])[0]
    size = 500 if name == 'human face' else 100
    ax.scatter(summary[sel, 0], summary[sel, 1], s=size,
               facecolors=color, label=name, edgecolors='k')
ax.axis('off')
ax.legend(loc='lower right', scatterpoints=1, ncol=2)
plt.tight_layout()
plt.show()


I am working on the file "0.19/_downloads/a68128275cc59b074b8c9782296d1d4a/decoding_rsa.ipynb".
The first task is:
Define stimulus - trigger mapping
Can you write Python code for it?

conditions = []
for c in conds.values:
    cond_tags = list(c[:2])
    cond_tags += [('not-' if i == 0 else '') + conds.columns[k]
                  for k, i in enumerate(c[2:], 2)]
    conditions.append('/'.join(map(str, cond_tags)))
print(conditions[:10])


I am working on the file "0.19/_downloads/a68128275cc59b074b8c9782296d1d4a/decoding_rsa.ipynb".
The first task is:
Epoch data
Can you write Python code for it?

picks = mne.pick_types(raw.info, meg=True)
epochs = mne.Epochs(raw, events=events, event_id=event_id, baseline=None,
                    picks=picks, tmin=-.1, tmax=.500, preload=True)


I am working on the file "0.19/_downloads/a68128275cc59b074b8c9782296d1d4a/decoding_rsa.ipynb".
The first task is:
Let's make the event_id dictionary
Can you write Python code for it?

event_id = dict(zip(conditions, conds.trigger + 1))
event_id['0/human bodypart/human/not-face/animal/natural']


I am working on the file "0.19/_downloads/a68128275cc59b074b8c9782296d1d4a/decoding_rsa.ipynb".
The first task is:
Let's restrict the number of conditions to speed up computation
Can you write Python code for it?

max_trigger = 24
conds = conds[:max_trigger]  # take only the first 24 rows


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

labels = [''] * 5 + ['face'] + [''] * 11 + ['bodypart'] + [''] * 6
fig, ax = plt.subplots(1)
im = ax.matshow(confusion, cmap='RdBu_r', clim=[0.3, 0.7])
ax.set_yticks(range(len(classes)))
ax.set_yticklabels(labels)
ax.set_xticks(range(len(classes)))
ax.set_xticklabels(labels, rotation=40, ha='left')
ax.axhline(11.5, color='k')
ax.axvline(11.5, color='k')
plt.colorbar(im)
plt.tight_layout()
plt.show()


I am working on the file "0.19/_downloads/a68128275cc59b074b8c9782296d1d4a/decoding_rsa.ipynb".
The first task is:
Read MEG data
Can you write Python code for it?

n_runs = 4  # 4 for full data (use less to speed up computations)
fname = op.join(data_path, 'sample_subject_%i_tsss_mc.fif')
raws = [read_raw_fif(fname % block, verbose='error')
        for block in range(n_runs)]  # ignore filename warnings
raw = concatenate_raws(raws)

events = mne.find_events(raw, min_duration=.002)

events = events[events[:, 2] <= max_trigger]


I am working on the file "0.19/_downloads/aa221dc65413caee3ba4b18802f88d21/plot_topo_compare_conditions.ipynb".
The first task is:
Show topography for two different conditions
Can you write Python code for it?

colors = 'blue', 'red'
title = 'MNE sample data\nleft vs right (A/V combined)'

plot_evoked_topo(evokeds, color=colors, title=title, background_color='w')

plt.show()


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

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

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

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

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

print(__doc__)


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

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

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


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

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


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

data_path = bst_phantom_ctf.data_path(verbose=True)

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


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

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


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

Warning

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

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


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