I am working on the file "0.20/_downloads/2e7ef25ccf0fd2af7902f12debe11fc1/plot_stats_cluster_1samp_test_time_frequency.ipynb".
The first task is:
View time-frequency plots
Can you write Python code for it?

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

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

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

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

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


I am working on the file "0.20/_downloads/2ef14e30f2307383fca298e63d57a535/spm_faces_dataset.ipynb".
The first task is:
Compute forward model
Can you write Python code for it?

src = data_path + '/subjects/spm/bem/spm-oct-6-src.fif'
bem = data_path + '/subjects/spm/bem/spm-5120-5120-5120-bem-sol.fif'
forward = mne.make_forward_solution(contrast.info, trans_fname, src, bem)


I am working on the file "0.20/_downloads/2ef14e30f2307383fca298e63d57a535/spm_faces_dataset.ipynb".
The first task is:
Compute inverse solution
Can you write Python code for it?

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

evoked.append(contrast)

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

plt.show()

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


I am working on the file "0.20/_downloads/2ef14e30f2307383fca298e63d57a535/spm_faces_dataset.ipynb".
The first task is:
Look at the whitened evoked daat
Can you write Python code for it?


I am working on the file "0.20/_downloads/2ef14e30f2307383fca298e63d57a535/spm_faces_dataset.ipynb".
The first task is:
Visualize fields on MEG helmet
Can you write Python code for it?

# The transformation here was aligned using the dig-montage. It's included in
# the spm_faces dataset and is named SPM_dig_montage.fif.
trans_fname = data_path + ('/MEG/spm/SPM_CTF_MEG_example_faces1_3D_'
                           'raw-trans.fif')

maps = mne.make_field_map(evoked[0], trans_fname, subject='spm',
                          subjects_dir=subjects_dir, n_jobs=1)

evoked[0].plot_field(maps, time=0.170)


I am working on the file "0.20/_downloads/2fc30e4810d35d643811cc11759b3b9a/plot_resample.ipynb".
The first task is:
Because resampling also affects the stim channels, some trigger onsets might
be lost in this case. While MNE attempts to downsample the stim channels in
an intelligent manner to avoid this, the recommended approach is to find
events on the original data before downsampling.
Can you write Python code for it?

print('Number of events before resampling:', len(mne.find_events(raw)))

# Resample to 100 Hz (suppress the warning that would be emitted)
raw_resampled_100 = raw.copy().resample(100, npad='auto', verbose='error')
print('Number of events after resampling:',
      len(mne.find_events(raw_resampled_100)))

# To avoid losing events, jointly resample the data and event matrix
events = mne.find_events(raw)
raw_resampled, events_resampled = raw.copy().resample(
    100, npad='auto', events=events)
print('Number of events after resampling:', len(events_resampled))


I am working on the file "0.20/_downloads/2fc30e4810d35d643811cc11759b3b9a/plot_resample.ipynb".
The first task is:
Resampling data
When performing experiments where timing is critical, a signal with a high
sampling rate is desired. However, having a signal with a much higher sampling
rate than is necessary needlessly consumes memory and slows down computations
operating on the data.
This example downsamples from 600 Hz to 100 Hz. This achieves a 6-fold
reduction in data size, at the cost of an equal loss of temporal resolution.
Can you write Python code for it?

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

from matplotlib import pyplot as plt

import mne
from mne.datasets import sample


I am working on the file "0.20/_downloads/2fc30e4810d35d643811cc11759b3b9a/plot_resample.ipynb".
The first task is:
Setting up data paths and loading raw data (skip some data for speed)
Can you write Python code for it?

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
raw = mne.io.read_raw_fif(raw_fname).crop(120, 240).load_data()


I am working on the file "0.20/_downloads/2fc30e4810d35d643811cc11759b3b9a/plot_resample.ipynb".
The first task is:
Since downsampling reduces the timing precision of events, we recommend
first extracting epochs and downsampling the Epochs object:
Can you write Python code for it?

events = mne.find_events(raw)
epochs = mne.Epochs(raw, events, event_id=2, tmin=-0.1, tmax=0.8, preload=True)

# Downsample to 100 Hz
print('Original sampling rate:', epochs.info['sfreq'], 'Hz')
epochs_resampled = epochs.copy().resample(100, npad='auto')
print('New sampling rate:', epochs_resampled.info['sfreq'], 'Hz')

# Plot a piece of data to see the effects of downsampling
plt.figure(figsize=(7, 3))

n_samples_to_plot = int(0.5 * epochs.info['sfreq'])  # plot 0.5 seconds of data
plt.plot(epochs.times[:n_samples_to_plot],
         epochs.get_data()[0, 0, :n_samples_to_plot], color='black')

n_samples_to_plot = int(0.5 * epochs_resampled.info['sfreq'])
plt.plot(epochs_resampled.times[:n_samples_to_plot],
         epochs_resampled.get_data()[0, 0, :n_samples_to_plot],
         '-o', color='red')

plt.xlabel('time (s)')
plt.legend(['original', 'downsampled'], loc='best')
plt.title('Effect of downsampling')
mne.viz.tight_layout()


I am working on the file "0.20/_downloads/306dcf0b43a155a02804528d597e4e81/plot_roi_erpimage_by_rt.ipynb".
The first task is:
Create Epochs
Can you write Python code for it?

# define target events:
# 1. find response times: distance between "square" and "rt" events
# 2. extract A. "square" events B. followed by a button press within 700 msec
tmax = .7
sfreq = raw.info["sfreq"]
reference_id, target_id = 2, 1
new_events, rts = define_target_events(events, reference_id, target_id, sfreq,
                                       tmin=0., tmax=tmax, new_id=2)

epochs = mne.Epochs(raw, events=new_events, tmax=tmax + .1,
                    event_id={"square": 2})


I am working on the file "0.20/_downloads/306dcf0b43a155a02804528d597e4e81/plot_roi_erpimage_by_rt.ipynb".
The first task is:
Load EEGLAB example data (a small EEG dataset)
Can you write Python code for it?

data_path = mne.datasets.testing.data_path()
fname = data_path + "/EEGLAB/test_raw.set"

event_id = {"rt": 1, "square": 2}  # must be specified for str events
raw = mne.io.read_raw_eeglab(fname)

mapping = {
    'EEG 000': 'Fpz', 'EEG 001': 'EOG1', 'EEG 002': 'F3', 'EEG 003': 'Fz',
    'EEG 004': 'F4', 'EEG 005': 'EOG2', 'EEG 006': 'FC5', 'EEG 007': 'FC1',
    'EEG 008': 'FC2', 'EEG 009': 'FC6', 'EEG 010': 'T7', 'EEG 011': 'C3',
    'EEG 012': 'C4', 'EEG 013': 'Cz', 'EEG 014': 'T8', 'EEG 015': 'CP5',
    'EEG 016': 'CP1', 'EEG 017': 'CP2', 'EEG 018': 'CP6', 'EEG 019': 'P7',
    'EEG 020': 'P3', 'EEG 021': 'Pz', 'EEG 022': 'P4', 'EEG 023': 'P8',
    'EEG 024': 'PO7', 'EEG 025': 'PO3', 'EEG 026': 'POz', 'EEG 027': 'PO4',
    'EEG 028': 'PO8', 'EEG 029': 'O1', 'EEG 030': 'Oz', 'EEG 031': 'O2'
}
raw.rename_channels(mapping)
raw.set_channel_types({"EOG1": 'eog', "EOG2": 'eog'})
raw.set_montage('standard_1020')

events = mne.events_from_annotations(raw, event_id)[0]


I am working on the file "0.20/_downloads/306dcf0b43a155a02804528d597e4e81/plot_roi_erpimage_by_rt.ipynb".
The first task is:
Plot single trial activity, grouped by ROI and sorted by RT
This will produce what is sometimes called an event related
potential / field (ERP/ERF) image.
The EEGLAB example file, which contains an experiment with button press
responses to simple visual stimuli, is read in and response times are
calculated.
Regions of Interest are determined by the channel types (in 10/20 channel
notation, even channels are right, odd are left, and 'z' are central). The
median and the Global Field Power within each channel group is calculated,
and the trials are plotted, sorting by response time.
Can you write Python code for it?

# Authors: Jona Sassenhagen <jona.sassenhagen@gmail.com>
#
# License: BSD (3-clause)

import mne
from mne.event import define_target_events
from mne.channels import make_1020_channel_selections

print(__doc__)


I am working on the file "0.20/_downloads/306dcf0b43a155a02804528d597e4e81/plot_roi_erpimage_by_rt.ipynb".
The first task is:
Plot using :term:Global Field Power <GFP>
Can you write Python code for it?

# Parameters for plotting
order = rts.argsort()  # sorting from fast to slow trials

selections = make_1020_channel_selections(epochs.info, midline="12z")

# The actual plots (GFP)
epochs.plot_image(group_by=selections, order=order, sigma=1.5,
                  overlay_times=rts / 1000., combine='gfp',
                  ts_args=dict(vlines=[0, rts.mean() / 1000.]))


I am working on the file "0.20/_downloads/306dcf0b43a155a02804528d597e4e81/plot_roi_erpimage_by_rt.ipynb".
The first task is:
Plot using median
Can you write Python code for it?

epochs.plot_image(group_by=selections, order=order, sigma=1.5,
                  overlay_times=rts / 1000., combine='median',
                  ts_args=dict(vlines=[0, rts.mean() / 1000.]))


I am working on the file "0.20/_downloads/30d3f995eaa317ef564a8fb6d72c22bf/plot_left_cerebellum_volume_source.ipynb".
The first task is:
Generate a left cerebellum volume source space
Generate a volume source space of the left cerebellum and plot its vertices
relative to the left cortical surface source space and the freesurfer
segmentation file.
Can you write Python code for it?

# Author: Alan Leggitt <alan.leggitt@ucsf.edu>
#
# License: BSD (3-clause)

import mne
from mne import setup_source_space, setup_volume_source_space
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
subject = 'sample'
aseg_fname = subjects_dir + '/sample/mri/aseg.mgz'


I am working on the file "0.20/_downloads/30d3f995eaa317ef564a8fb6d72c22bf/plot_left_cerebellum_volume_source.ipynb".
The first task is:
Plot the positions of each source space
Can you write Python code for it?

fig = mne.viz.plot_alignment(subject=subject, subjects_dir=subjects_dir,
                             surfaces='white', coord_frame='head',
                             src=src)
mne.viz.set_3d_view(fig, azimuth=173.78, elevation=101.75,
                    distance=0.30, focalpoint=(-0.03, -0.01, 0.03))


I am working on the file "0.20/_downloads/31a362832c6e14bb418b12340a063c91/plot_movement_detection.ipynb".
The first task is:
After checking the annotated movement artifacts, calculate the new transform
and plot it:
Can you write Python code for it?

new_dev_head_t = compute_average_dev_head_t(raw, head_pos)
raw.info['dev_head_t'] = new_dev_head_t
mne.viz.plot_alignment(
    raw.info, show_axes=True, subject=subject, trans=trans_fname,
    subjects_dir=subjects_dir)


I am working on the file "0.20/_downloads/31a362832c6e14bb418b12340a063c91/plot_movement_detection.ipynb".
The first task is:
Plot continuous head position with respect to the mean recording position
Can you write Python code for it?

# get cHPI time series and compute average
chpi_locs = mne.chpi.extract_chpi_locs_ctf(raw)
head_pos = mne.chpi.compute_head_pos(raw.info, chpi_locs)
original_head_dev_t = mne.transforms.invert_transform(
    raw.info['dev_head_t'])
average_head_dev_t = mne.transforms.invert_transform(
    compute_average_dev_head_t(raw, head_pos))
fig = mne.viz.plot_head_positions(head_pos)
for ax, val, val_ori in zip(fig.axes[::2], average_head_dev_t['trans'][:3, 3],
                            original_head_dev_t['trans'][:3, 3]):
    ax.axhline(1000 * val, color='r')
    ax.axhline(1000 * val_ori, color='g')

# The green horizontal lines represent the original head position, whereas the
# red lines are the new head position averaged over all the time points.


I am working on the file "0.20/_downloads/3292f41d8bad9e2a2bc48714f7f39668/plot_30_epochs_metadata.ipynb".
The first task is:
Although there's no obvious relationship in this case, such analyses may be
useful for metadata variables that more directly index the time course of
stimulus processing (such as reaction time).
Adding metadata to an Epochs object
You can add a metadata :class:~pandas.DataFrame to any
:class:~mne.Epochs object (or replace existing metadata) simply by
assigning to the :attr:~mne.Epochs.metadata attribute:
Can you write Python code for it?

new_metadata = pd.DataFrame(data=['foo'] * len(epochs), columns=['bar'],
                            index=range(len(epochs)))
epochs.metadata = new_metadata
epochs.metadata.head()


I am working on the file "0.20/_downloads/3292f41d8bad9e2a2bc48714f7f39668/plot_30_epochs_metadata.ipynb".
The first task is:
Modifying the metadata
Like any :class:pandas.DataFrame, you can modify the data or add columns as
needed. Here we convert the NumberOfLetters column from :class:float to
:class:integer <int> data type, and add a :class:boolean <bool> column
that arbitrarily divides the variable VisualComplexity into high and low
groups.
Can you write Python code for it?

epochs.metadata['NumberOfLetters'] = \
    epochs.metadata['NumberOfLetters'].map(int)

epochs.metadata['HighComplexity'] = epochs.metadata['VisualComplexity'] > 65
epochs.metadata.head()


I am working on the file "0.20/_downloads/3292f41d8bad9e2a2bc48714f7f39668/plot_30_epochs_metadata.ipynb".
The first task is:
Notice that in this dataset, each "condition" (A.K.A., each word) occurs only
once, whereas with the sample-dataset dataset each condition (e.g.,
"auditory/left", "visual/right", etc) occurred dozens of times. This makes
the Pandas querying methods especially useful when you want to aggregate
epochs that have different condition names but that share similar stimulus
properties. For example, here we group epochs based on the number of letters
in the stimulus word, and compare the average signal at electrode Pz for
each group:
Can you write Python code for it?

evokeds = dict()
query = 'NumberOfLetters == {}'
for n_letters in epochs.metadata['NumberOfLetters'].unique():
    evokeds[str(n_letters)] = epochs[query.format(n_letters)].average()

mne.viz.plot_compare_evokeds(evokeds, cmap=('word length', 'viridis'),
                             picks='Pz')


I am working on the file "0.20/_downloads/3292f41d8bad9e2a2bc48714f7f39668/plot_30_epochs_metadata.ipynb".
The first task is:
Selecting epochs using metadata queries
All :class:~mne.Epochs objects can be subselected by event name, index, or
:term:slice (see tut-section-subselect-epochs). But
:class:~mne.Epochs objects with metadata can also be queried using
Pandas query strings <pandas:indexing.query> by passing the query
string just as you would normally pass an event name. For example:
Can you write Python code for it?


I am working on the file "0.20/_downloads/3292f41d8bad9e2a2bc48714f7f39668/plot_30_epochs_metadata.ipynb".
The first task is:
Viewing Epochs metadata
.. sidebar:: Restrictions on metadata DataFrames
Metadata dataframes are less flexible than typical
   :class:Pandas DataFrames <pandas.DataFrame>. For example, the allowed
   data types are restricted to strings, floats, integers, or booleans;
   and the row labels are always integers corresponding to epoch numbers.
   Other capabilities of :class:DataFrames <pandas.DataFrame> such as
   :class:hierarchical indexing <pandas.MultiIndex> are possible while the
   :class:~mne.Epochs object is in memory, but will not survive saving and
   reloading the :class:~mne.Epochs object to/from disk.
The metadata attached to :class:~mne.Epochs objects is stored as a
:class:pandas.DataFrame containing one row for each epoch. The columns of
this :class:~pandas.DataFrame can contain just about any information you
want to store about each epoch; in this case, the metadata encodes
information about the stimulus seen on each trial, including properties of
the visual word form itself (e.g., NumberOfLetters, VisualComplexity)
as well as properties of what the word means (e.g., its Concreteness) and
its prominence in the English lexicon (e.g., WordFrequency). Here are all
the variables; note that in a Jupyter notebook, viewing a
:class:pandas.DataFrame gets rendered as an HTML table instead of the
normal Python output block:
Can you write Python code for it?


I am working on the file "0.20/_downloads/3292f41d8bad9e2a2bc48714f7f39668/plot_30_epochs_metadata.ipynb".
The first task is:
Viewing the metadata values for a given epoch and metadata variable is done
using any of the Pandas indexing <pandas:/reference/indexing.rst>
methods such as :obj:~pandas.DataFrame.loc,
:obj:~pandas.DataFrame.iloc, :obj:~pandas.DataFrame.at,
and :obj:~pandas.DataFrame.iat. Because the
index of the dataframe is the integer epoch number, the name- and index-based
selection methods will work similarly for selecting rows, except that
name-based selection (with :obj:~pandas.DataFrame.loc) is inclusive of the
endpoint:
Can you write Python code for it?

print('Name-based selection with .loc')
print(epochs.metadata.loc[2:4])

print('\nIndex-based selection with .iloc')
print(epochs.metadata.iloc[2:4])


I am working on the file "0.20/_downloads/3292f41d8bad9e2a2bc48714f7f39668/plot_30_epochs_metadata.ipynb".
The first task is:
Working with Epoch metadata
This tutorial shows how to add metadata to :class:~mne.Epochs objects, and
how to use Pandas query strings <pandas:indexing.query> to select and
plot epochs based on metadata properties.
   :depth: 2
For this tutorial we'll use a different dataset than usual: the
kiloword-dataset, which contains EEG data averaged across 75 subjects
who were performing a lexical decision (word/non-word) task. The data is in
:class:~mne.Epochs format, with each epoch representing the response to a
different stimulus (word). As usual we'll start by importing the modules we
need and loading the data:
Can you write Python code for it?

import os
import numpy as np
import pandas as pd
import mne

kiloword_data_folder = mne.datasets.kiloword.data_path()
kiloword_data_file = os.path.join(kiloword_data_folder,
                                  'kword_metadata-epo.fif')
epochs = mne.read_epochs(kiloword_data_file)


I am working on the file "0.20/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
Apply the spatial filter
The spatial filter can be applied to different data types: raw, epochs,
evoked data or the data covariance matrix to gain a static image of power.
The function to apply the spatial filter to :class:~mne.Evoked data is
:func:~mne.beamformer.apply_lcmv which is
what we will use here. The other functions are
:func:~mne.beamformer.apply_lcmv_raw,
:func:~mne.beamformer.apply_lcmv_epochs, and
:func:~mne.beamformer.apply_lcmv_cov.
Can you write Python code for it?

stc = apply_lcmv(evoked, filters, max_ori_out='signed')
stc_vec = apply_lcmv(evoked, filters_vec, max_ori_out='signed')


I am working on the file "0.20/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
Computing the covariance matrices
Spatial filters use the data covariance to estimate the filter
weights. The data covariance matrix will be inverted_ during the spatial
filter computation, so it is valuable to plot the covariance matrix and its
eigenvalues to gauge whether matrix inversion will be possible.
Also, because we want to combine different channel types (magnetometers and
gradiometers), we need to account for the different amplitude scales of these
channel types. To do this we will supply a noise covariance matrix to the
beamformer, which will be used for whitening.
The data covariance matrix should be estimated from a time window that
includes the brain signal of interest,
and incorporate enough samples for a stable estimate. A rule of thumb is to
use more samples than there are channels in the data set; see
:footcite:BrookesEtAl2008 for more detailed advice on covariance estimation
for beamformers. Here, we use a time
window incorporating the expected auditory response at around 100 ms post
stimulus and extend the period to account for a low number of trials (72) and
low sampling rate of 150 Hz.
Can you write Python code for it?

data_cov = mne.compute_covariance(epochs, tmin=0.01, tmax=0.25,
                                  method='empirical')
noise_cov = mne.compute_covariance(epochs, tmin=tmin, tmax=0,
                                   method='empirical')

data_cov.plot(epochs.info)


I am working on the file "0.20/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
Introduction to beamformers
A beamformer is a spatial filter that reconstructs source activity by
scanning through a grid of pre-defined source points and estimating activity
at each of those source points independently. A set of weights is
constructed for each defined source location which defines the contribution
of each sensor to this source.
Beamformers are often used for their focal reconstructions and their ability
to reconstruct deeper sources. They can also suppress external noise sources.
The beamforming method applied in this tutorial is the linearly constrained
minimum variance (LCMV) beamformer :footcite:VanVeenEtAl1997 operates on
time series.
Frequency-resolved data can be reconstructed with the dynamic imaging of
coherent sources (DICS) beamforming method :footcite:GrossEtAl2001.
As we will see in the following, the spatial filter is computed from two
ingredients: the forward model solution and the covariance matrix of the
data.
Data processing
We will use the sample data set for this tutorial and reconstruct source
activity on the trials with left auditory stimulation.
Can you write Python code for it?

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'

# Read the raw data
raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.info['bads'] = ['MEG 2443']  # bad MEG channel

# Set up the epoching
event_id = 1  # those are the trials with left-ear auditory stimuli
tmin, tmax = -0.2, 0.5
events = mne.find_events(raw)

# pick relevant channels
raw.pick(['meg', 'eog'])  # pick channels of interest

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

# Visualize averaged sensor space data
evoked = epochs.average()
evoked.plot_joint()

del raw  # save memory


I am working on the file "0.20/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
Source reconstruction using an LCMV beamformer
This tutorial gives an overview of the beamformer method
and shows how to use an LCMV beamformer to reconstruct source
activity.
   :depth: 2
Can you write Python code for it?

# Author: Britta Westner <britta.wstnr@gmail.com>
#
# License: BSD (3-clause)

import matplotlib.pyplot as plt
import mne
from mne.datasets import sample, fetch_fsaverage
from mne.beamformer import make_lcmv, apply_lcmv


I am working on the file "0.20/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
Visualize the activity of the maximum voxel with all three components
We can also visualize all three components in the peak voxel. For this, we
will first find the peak voxel and then plot the time courses of this voxel.
Can you write Python code for it?

peak_vox, _ = stc_vec.get_peak(tmin=0.08, tmax=0.1, vert_as_index=True)

ori_labels = ['x', 'y', 'z']
fig, ax = plt.subplots(1)
for ori, label in zip(stc_vec.data[peak_vox, :, :], ori_labels):
    ax.plot(stc_vec.times, ori, label='%s component' % label)
ax.legend(loc='lower right')
ax.set(title='Activity per orientation in the peak voxel', xlabel='Time (s)',
       ylabel='Amplitude (a. u.)')
mne.viz.utils.plt_show()


I am working on the file "0.20/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
Visualize the reconstructed source activity
We can visualize the source estimate in different ways, e.g. as an overlay
onto the MRI or as a glass brain.
The plots for the scalar beamformer show brain activity in the right temporal
lobe around 100 ms post stimulus. This is expected given the left-ear
auditory stimulation of the experiment.
Can you write Python code for it?

lims = [0.3, 0.45, 0.6]

kwargs = dict(src=forward['src'], subject='sample', subjects_dir=subjects_dir,
              initial_time=0.087, verbose=True)

stc.plot(mode='stat_map', clim=dict(kind='value', pos_lims=lims), **kwargs)

stc.plot(mode='glass_brain', clim=dict(kind='value', lims=lims), **kwargs)


I am working on the file "0.20/_downloads/34fd5b71616977c61ebac55c010819c1/plot_beamformer_lcmv.ipynb".
The first task is:
When looking at the covariance matrix plots, we can see that our data is
slightly rank-deficient as the rank is not equal to the number of channels.
Thus, we will have to regularize the covariance matrix before inverting it
in the beamformer calculation. This can be achieved by setting the parameter
reg=0.05 when calculating the spatial filter with
:func:~mne.beamformer.make_lcmv. This corresponds to loading the diagonal
of the covariance matrix with 5% of the sensor power.
The forward model
The forward model is the other important ingredient for the computation of a
spatial filter. Here, we will load the forward model from disk; more
information on how to create a forward model can be found in this tutorial:
tut-forward.
Note that beamformers are usually computed in a :class:volume source space
<mne.VolSourceEstimate>, because estimating only cortical surface
activation can misrepresent the data.
Can you write Python code for it?

# Read forward model

fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-vol-7-fwd.fif'
forward = mne.read_forward_solution(fwd_fname)


I am working on the file "0.20/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
Here again we can visualize the spatial pattern of the associated field at
various times relative to the peak of the EOG response:
Can you write Python code for it?


I am working on the file "0.20/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
Here we see narrow frequency peaks at 60, 120, 180, and 240 Hz — the power
line frequency of the USA (where the sample data was recorded) and its 2nd,
3rd, and 4th harmonics. Other peaks (around 25 to 30 Hz, and the second
harmonic of those) are probably related to the heartbeat, which is more
easily seen in the time domain using a dedicated heartbeat detection function
as described in the next section.
Heartbeat artifacts (ECG)
MNE-Python includes a dedicated function
:func:~mne.preprocessing.find_ecg_events in the :mod:mne.preprocessing
submodule, for detecting heartbeat artifacts from either dedicated ECG
channels or from magnetometers (if no ECG channel is present). Additionally,
the function :func:~mne.preprocessing.create_ecg_epochs will call
:func:~mne.preprocessing.find_ecg_events under the hood, and use the
resulting events array to extract epochs centered around the detected
heartbeat artifacts. Here we create those epochs, then show an image plot of
the detected ECG artifacts along with the average ERF across artifacts. We'll
show all three channel types, even though EEG channels are less strongly
affected by heartbeat artifacts:
Can you write Python code for it?

ecg_epochs = mne.preprocessing.create_ecg_epochs(raw)
ecg_epochs.plot_image(combine='mean')


I am working on the file "0.20/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
Low-frequency drifts
Low-frequency drifts are most readily detected by visual inspection using the
basic :meth:~mne.io.Raw.plot method, though it is helpful to plot a
relatively long time span and to disable channel-wise DC shift correction.
Here we plot 60 seconds and show all the magnetometer channels:
Can you write Python code for it?

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


I am working on the file "0.20/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
Or, we can get an ERP/F plot with :meth:~mne.Evoked.plot or a combined
scalp field maps and ERP/F plot with :meth:~mne.Evoked.plot_joint. Here
we've specified the times for scalp field maps manually, but if not provided
they will be chosen automatically based on peaks in the signal:
Can you write Python code for it?


I am working on the file "0.20/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
Overview of artifact detection
This tutorial covers the basics of artifact detection, and introduces the
artifact detection tools available in MNE-Python.
   :depth: 2
We begin as always by importing the necessary Python modules and loading some
example data <sample-dataset>:
Can you write Python code for it?

import os
import numpy as np
import mne

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file)
raw.crop(0, 60).load_data()  # just use a fraction of data for speed here


I am working on the file "0.20/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
The horizontal streaks in the magnetometer image plot reflect the fact that
the heartbeat artifacts are superimposed on low-frequency drifts like the one
we saw in an earlier section; to avoid this you could pass
baseline=(-0.5, -0.2) in the call to
:func:~mne.preprocessing.create_ecg_epochs.
You can also get a quick look at the
ECG-related field pattern across sensors by averaging the ECG epochs together
via the :meth:~mne.Epochs.average method, and then using the
:meth:mne.Evoked.plot_topomap method:
Can you write Python code for it?


I am working on the file "0.20/_downloads/3674b896fc4e4a279156fa5c0f61aea8/plot_10_preprocessing_overview.ipynb".
The first task is:
What are artifacts?
Artifacts are parts of the recorded signal that arise from sources other than
the source of interest (i.e., neuronal activity in the brain). As such,
artifacts are a form of interference or noise relative to the signal of
interest. There are many possible causes of such interference, for example:

Environmental artifacts

Persistent oscillations centered around the AC power line frequency_
  (typically 50 or 60 Hz)
Brief signal jumps due to building vibration (such as a door slamming)
Electromagnetic field noise from nearby elevators, cell phones, the
  geomagnetic field, etc.

Instrumentation artifacts

Electromagnetic interference from stimulus presentation (such as EEG
  sensors picking up the field generated by unshielded headphones)
Continuous oscillations at specific frequencies used by head position
  indicator (HPI) coils
Random high-amplitude fluctuations (or alternatively, constant zero
  signal) in a single channel due to sensor malfunction (e.g., in surface
  electrodes, poor scalp contact)

Biological artifacts

Periodic QRS_-like signal patterns (especially in magnetometer
  channels) due to electrical activity of the heart
Short step-like deflections (especially in frontal EEG channels) due to
  eye movements
Large transient deflections (especially in frontal EEG channels) due to
  blinking
Brief bursts of high frequency fluctuations across several channels due
  to the muscular activity during swallowing

There are also some cases where signals from within the brain can be
considered artifactual. For example, if a researcher is primarily interested
in the sensory response to a stimulus, but the experimental paradigm involves
a behavioral response (such as button press), the neural activity associated
with the planning and executing the button press could be considered an
artifact relative to signal of interest (i.e., the evoked sensory response).

Note

Artifacts of the same genesis may appear different in recordings made by
   ...
Can you write Python code for it?

ssp_projectors = raw.info['projs']
raw.del_proj()


I am working on the file "0.20/_downloads/36ac16a286b47b66f1b51a959c65b5b9/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
A stat_fun must deal with a variable number of input arguments.
Inside the clustering function each condition will be passed as flattened
array, necessitated by the clustering procedure. The ANOVA however expects an
input array of dimensions: subjects X conditions X observations (optional).
The following function catches the list input and swaps the first and
the second dimension and finally calls the ANOVA function.
Can you write Python code for it?

def stat_fun(*args):
    return f_mway_rm(np.swapaxes(args, 1, 0), factor_levels=factor_levels,
                     effects=effects, return_pvals=False)[0]

# The ANOVA returns a tuple f-values and p-values, we will pick the former.
pthresh = 0.001  # set threshold rather high to save some time
f_thresh = f_threshold_mway_rm(n_replications, factor_levels, effects,
                               pthresh)
tail = 1  # f-test, so tail > 0
n_permutations = 256  # Save some time (the test won't be too sensitive ...)
T_obs, clusters, cluster_p_values, h0 = mne.stats.permutation_cluster_test(
    epochs_power, stat_fun=stat_fun, threshold=f_thresh, tail=tail, n_jobs=1,
    n_permutations=n_permutations, buffer_size=None)


I am working on the file "0.20/_downloads/36ac16a286b47b66f1b51a959c65b5b9/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
Create TFR representations for all conditions
Can you write Python code for it?

epochs_power = list()
for condition in [epochs[k] for k in event_id]:
    this_tfr = tfr_morlet(condition, freqs, n_cycles=n_cycles,
                          decim=decim, average=False, zero_mean=zero_mean,
                          return_itc=False)
    this_tfr.apply_baseline(mode='ratio', baseline=(None, 0))
    this_power = this_tfr.data[:, 0, :, :]  # we only have one channel.
    epochs_power.append(this_power)


I am working on the file "0.20/_downloads/36ac16a286b47b66f1b51a959c65b5b9/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
Create new stats image with only significant clusters:
Can you write Python code for it?

good_clusters = np.where(cluster_p_values < .05)[0]
T_obs_plot = np.ma.masked_array(T_obs,
                                np.invert(clusters[np.squeeze(good_clusters)]))

plt.figure()
for f_image, cmap in zip([T_obs, T_obs_plot], [plt.cm.gray, 'RdBu_r']):
    plt.imshow(f_image, cmap=cmap, extent=[times[0], times[-1],
               freqs[0], freqs[-1]], aspect='auto',
               origin='lower')
plt.xlabel('Time (ms)')
plt.ylabel('Frequency (Hz)')
plt.title("Time-locked response for 'modality by location' (%s)\n"
          " cluster-level corrected (p <= 0.05)" % ch_name)
plt.show()


I am working on the file "0.20/_downloads/36ac16a286b47b66f1b51a959c65b5b9/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
Mass-univariate twoway repeated measures ANOVA on single trial power
This script shows how to conduct a mass-univariate repeated measures
ANOVA. As the model to be fitted assumes two fully crossed factors,
we will study the interplay between perceptual modality
(auditory VS visual) and the location of stimulus presentation
(left VS right). Here we use single trials as replications
(subjects) while iterating over time slices plus frequency bands
for to fit our mass-univariate model. For the sake of simplicity we
will confine this analysis to one single channel of which we know
that it exposes a strong induced response. We will then visualize
each effect by creating a corresponding mass-univariate effect
image. We conclude with accounting for multiple comparisons by
performing a permutation clustering test using the ANOVA as
clustering function. The results final will be compared to multiple
comparisons using False Discovery Rate correction.
Can you write Python code for it?

# Authors: Denis Engemann <denis.engemann@gmail.com>
#          Eric Larson <larson.eric.d@gmail.com>
#          Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.time_frequency import tfr_morlet
from mne.stats import f_threshold_mway_rm, f_mway_rm, fdr_correction
from mne.datasets import sample

print(__doc__)


I am working on the file "0.20/_downloads/36ac16a286b47b66f1b51a959c65b5b9/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
Now using FDR:
Can you write Python code for it?

mask, _ = fdr_correction(pvals[2])
T_obs_plot2 = np.ma.masked_array(T_obs, np.invert(mask))

plt.figure()
for f_image, cmap in zip([T_obs, T_obs_plot2], [plt.cm.gray, 'RdBu_r']):
    plt.imshow(f_image, cmap=cmap, extent=[times[0], times[-1],
               freqs[0], freqs[-1]], aspect='auto',
               origin='lower')

plt.xlabel('Time (ms)')
plt.ylabel('Frequency (Hz)')
plt.title("Time-locked response for 'modality by location' (%s)\n"
          " FDR corrected (p <= 0.05)" % ch_name)
plt.show()


I am working on the file "0.20/_downloads/36ac16a286b47b66f1b51a959c65b5b9/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
Now we'll assemble the data matrix and swap axes so the trial replications
are the first dimension and the conditions are the second dimension.
Can you write Python code for it?

data = np.swapaxes(np.asarray(epochs_power), 1, 0)
# reshape last two dimensions in one mass-univariate observation-vector
data = data.reshape(n_replications, n_conditions, n_freqs * n_times)

# so we have replications * conditions * observations:
print(data.shape)


I am working on the file "0.20/_downloads/36ac16a286b47b66f1b51a959c65b5b9/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_raw-eve.fif'
tmin, tmax = -0.2, 0.5

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

include = []
raw.info['bads'] += ['MEG 2443']  # bads

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

ch_name = 'MEG 1332'

# Load conditions
reject = dict(grad=4000e-13, eog=150e-6)
event_id = dict(aud_l=1, aud_r=2, vis_l=3, vis_r=4)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                    picks=picks, baseline=(None, 0), preload=True,
                    reject=reject)
epochs.pick_channels([ch_name])  # restrict example to one channel


I am working on the file "0.20/_downloads/36ac16a286b47b66f1b51a959c65b5b9/plot_stats_cluster_time_frequency_repeated_measures_anova.ipynb".
The first task is:
Setup repeated measures ANOVA
We will tell the ANOVA how to interpret the data matrix in terms of factors.
This is done via the factor levels argument which is a list of the number
factor levels for each factor.
Can you write Python code for it?

n_conditions = len(epochs.event_id)
n_replications = epochs.events.shape[0] // n_conditions

factor_levels = [2, 2]  # number of levels in each factor
effects = 'A*B'  # this is the default signature for computing all effects
# Other possible options are 'A' or 'B' for the corresponding main effects
# or 'A:B' for the interaction effect only (this notation is borrowed from the
# R formula language)
n_freqs = len(freqs)
times = 1e3 * epochs.times[::decim]
n_times = len(times)


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:

Warning

Be careful when concatenating :class:`~mne.io.Raw` objects from different
    recordings, especially when saving: :meth:`~mne.io.Raw.append` only
    preserves the ``info`` attribute of the initial :class:`~mne.io.Raw`
    object (the one outside the :meth:`~mne.io.Raw.append` method call).

Extracting data from Raw objects
So far we've been looking at ways to modify a :class:~mne.io.Raw object.
This section shows how to extract the data from a :class:~mne.io.Raw object
into a :class:NumPy array <numpy.ndarray>, for analysis or plotting using
functions outside of MNE-Python. To select portions of the data,
:class:~mne.io.Raw objects can be indexed using square brackets. However,
indexing :class:~mne.io.Raw works differently than indexing a :class:NumPy
array <numpy.ndarray> in two ways:

Along with the requested sample value(s) MNE-Python also returns an array
   of times (in seconds) corresponding to the requested samples. The data
   array and the times array are returned together as elements of a tuple.

The data array will always be 2-dimensional even if you request only a
   single time sample or a single channel.

Extracting data by index
To illustrate the above two points, let's select a couple seconds of data
from the first channel:
Can you write Python code for it?

sampling_freq = raw.info['sfreq']
start_stop_seconds = np.array([11, 13])
start_sample, stop_sample = (start_stop_seconds * sampling_freq).astype(int)
channel_index = 0
raw_selection = raw[channel_index, start_sample:stop_sample]
print(raw_selection)


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:

Note

Most of the fields of ``raw.info`` reflect metadata recorded at
    acquisition time, and should not be changed by the user. There are a few
    exceptions (such as ``raw.info['bads']`` and ``raw.info['projs']``), but
    in most cases there are dedicated MNE-Python functions or methods to
    update the :class:`~mne.Info` object safely (such as
    :meth:`~mne.io.Raw.add_proj` to update ``raw.info['projs']``).

Time, sample number, and sample index
.. sidebar:: Sample numbering in VectorView data
For data from VectorView systems, it is important to distinguish *sample
number* from *sample index*. See :term:`first_samp` for more information.

One method of :class:~mne.io.Raw objects that is frequently useful is
:meth:~mne.io.Raw.time_as_index, which converts a time (in seconds) into
the integer index of the sample occurring closest to that time. The method
can also take a list or array of times, and will return an array of indices.
It is important to remember that there may not be a data sample at exactly
the time requested, so the number of samples between time = 1 second and
time = 2 seconds may be different than the number of samples between
time = 2 and time = 3:
Can you write Python code for it?

print(raw.time_as_index(20))
print(raw.time_as_index([20, 30, 40]), '\n')

print(np.diff(raw.time_as_index([1, 2, 3])))


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
As you can see above, :func:~mne.io.read_raw_fif automatically displays
some information about the file it's loading. For example, here it tells us
that there are three "projection items" in the file along with the recorded
data; those are :term:SSP projectors <projector> calculated to remove
environmental noise from the MEG signals, and are discussed in a the tutorial
tut-projectors-background.
In addition to the information displayed during loading, you can
get a glimpse of the basic details of a :class:~mne.io.Raw object by
printing it:
Can you write Python code for it?


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Changing channel name and type
.. sidebar:: Long channel names
Due to limitations in the :file:`.fif` file format (which MNE-Python uses
to save :class:`~mne.io.Raw` objects), channel names are limited to a
maximum of 15 characters.

You may have noticed that the EEG channel names in the sample data are
numbered rather than labelled according to a standard nomenclature such as
the 10-20 <ten_twenty_> or 10-05 <ten_oh_five_> systems, or perhaps it
bothers you that the channel names contain spaces. It is possible to rename
channels using the :meth:~mne.io.Raw.rename_channels method, which takes a
Python dictionary to map old names to new names. You need not rename all
channels at once; provide only the dictionary entries for the channels you
want to rename. Here's a frivolous example:
Can you write Python code for it?

raw.rename_channels({'EOG 061': 'blink detector'})


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Extracting channels by name
The :class:~mne.io.Raw object can also be indexed with the names of
channels instead of their index numbers. You can pass a single string to get
just one channel, or a list of strings to select multiple channels. As with
integer indexing, this will return a tuple of (data_array, times_array)
that can be easily plotted. Since we're plotting 2 channels this time, we'll
add a vertical offset to one channel so it's not plotted right on top
of the other one:
Can you write Python code for it?

channel_names = ['MEG_0712', 'MEG_1022']
two_meg_chans = raw[channel_names, start_sample:stop_sample]
y_offset = np.array([5e-11, 0])  # just enough to separate the channel traces
x = two_meg_chans[1]
y = two_meg_chans[0].T + y_offset
lines = plt.plot(x, y)
plt.legend(lines, channel_names)


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
If for some reason the channel types in your :class:~mne.io.Raw object are
inaccurate, you can change the type of any channel with the
:meth:~mne.io.Raw.set_channel_types method. The method takes a
:class:dictionary <dict> mapping channel names to types; allowed types are
ecg, eeg, emg, eog, exci, ias, misc, resp, seeg, stim, syst, ecog, hbo,
hbr. A common use case for changing channel type is when using frontal EEG
electrodes as makeshift EOG channels:
Can you write Python code for it?

raw.set_channel_types({'EEG_001': 'eog'})
print(raw.copy().pick_types(meg=False, eog=True).ch_names)


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
If you want the channels in a specific order (e.g., for plotting),
:meth:~mne.io.Raw.reorder_channels works just like
:meth:~mne.io.Raw.pick_channels but also reorders the channels; for
example, here we pick the EOG and frontal EEG channels, putting the EOG
first and the EEG in reverse order:
Can you write Python code for it?

channel_names = ['EOG 061', 'EEG 003', 'EEG 002', 'EEG 001']
eog_and_frontal_eeg = raw.copy().reorder_channels(channel_names)
print(eog_and_frontal_eeg.ch_names)


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
It is also possible to export the data to a :class:Pandas DataFrame
<pandas.DataFrame> object, and use the saving methods that :mod:Pandas
<pandas> affords. The :class:~mne.io.Raw object's
:meth:~mne.io.Raw.to_data_frame method is similar to
:meth:~mne.io.Raw.get_data in that it has a picks parameter for
restricting which channels are exported, and start and stop
parameters for restricting the time domain. Note that, by default, times will
be converted to milliseconds, rounded to the nearest millisecond, and used as
the DataFrame index; see the scaling_time parameter in the documentation
of :meth:~mne.io.Raw.to_data_frame for more details.
Can you write Python code for it?

sampling_freq = raw.info['sfreq']
start_end_secs = np.array([10, 13])
start_sample, stop_sample = (start_end_secs * sampling_freq).astype(int)
df = raw.to_data_frame(picks=['eeg'], start=start_sample, stop=stop_sample)
# then save using df.to_csv(...), df.to_hdf(...), etc
print(df.head())


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Loading continuous data
.. sidebar:: Datasets in MNE-Python
There are ``data_path`` functions for several example datasets in
MNE-Python (e.g., :func:`mne.datasets.kiloword.data_path`,
:func:`mne.datasets.spm_face.data_path`, etc). All of them will check the
default download location first to see if the dataset is already on your
computer, and only download it if necessary.  The default download
location is also configurable; see the documentation of any of the
``data_path`` functions for more information.

As mentioned in the introductory tutorial <tut-overview>,
MNE-Python data structures are based around
the :file:.fif file format from Neuromag. This tutorial uses an
example dataset <sample-dataset> in :file:.fif format, so here we'll
use the function :func:mne.io.read_raw_fif to load the raw data; there are
reader functions for a wide variety of other data formats
<data-formats> as well.
There are also several other example datasets
<datasets> that can be downloaded with just a few lines
of code. Functions for downloading example datasets are in the
:mod:mne.datasets submodule; here we'll use
:func:mne.datasets.sample.data_path to download the "sample-dataset"
dataset, which contains EEG, MEG, and structural MRI data from one subject
performing an audiovisual experiment. When it's done downloading,
:func:~mne.datasets.sample.data_path will return the folder location where
it put the files; you can navigate there with your file browser if you want
to examine the files yourself. Once we have the file path, we can load the
data with :func:~mne.io.read_raw_fif. This will return a
:class:~mne.io.Raw object, which we'll store in a variable called raw.
Can you write Python code for it?

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


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Querying the Raw object
.. sidebar:: Attributes vs. Methods
**Attributes** are usually static properties of Python objects — things
that are pre-computed and stored as part of the object's representation
in memory. Attributes are accessed with the ``.`` operator and do not
require parentheses after the attribute name (example: ``raw.ch_names``).

**Methods** are like specialized functions attached to an object.
Usually they require additional user input and/or need some computation
to yield a result. Methods always have parentheses at the end; additional
arguments (if any) go inside those parentheses (examples:
``raw.estimate_rank()``, ``raw.drop_channels(['EEG 030', 'MEG 2242'])``).

We saw above that printing the :class:~mne.io.Raw object displays some
basic information like the total number of channels, the number of time
points at which the data were sampled, total duration, and the approximate
size in memory. Much more information is available through the various
attributes and methods of the :class:~mne.io.Raw class. Some useful
attributes of :class:~mne.io.Raw objects include a list of the channel
names (:attr:~mne.io.Raw.ch_names), an array of the sample times in seconds
(:attr:~mne.io.Raw.times), and the total number of samples
(:attr:~mne.io.Raw.n_times); a list of all attributes and methods is given
in the documentation of the :class:~mne.io.Raw class.
The Raw.info attribute
There is also quite a lot of information stored in the raw.info
attribute, which stores an :class:~mne.Info object that is similar to a
:class:Python dictionary <dict> (in that it has fields accessed via named
keys). Like Python dictionaries, raw.info has a .keys() method that
shows all the available field names; unlike Python dictionaries, printing
raw.info will print a nicely-formatted glimpse of each field's data. See
tut-info-class for more on what is stored in :class:~mne.Info
objects, and how to interact with them.
Can you write Python code for it?

n_time_samps = raw.n_times
time_secs = raw.times
ch_names = raw.ch_names
n_chan = len(ch_names)  # note: there is no raw.n_channels attribute
print('the (cropped) sample data object has {} time samples and {} channels.'
      ''.format(n_time_samps, n_chan))
print('The last time sample is at {} seconds.'.format(time_secs[-1]))
print('The first few channel names are {}.'.format(', '.join(ch_names[:3])))
print()  # insert a blank line in the output

# some examples of raw.info:
print('bad channels:', raw.info['bads'])  # chs marked "bad" during acquisition
print(raw.info['sfreq'], 'Hz')            # sampling frequency
print(raw.info['description'], '\n')      # miscellaneous acquisition info

print(raw.info)


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Remember that sample times don't always align exactly with requested tmin
or tmax values (due to sampling), which is why the max values of the
cropped files don't exactly match the requested tmax (see
time-as-index for further details).
If you need to select discontinuous spans of a :class:~mne.io.Raw object —
or combine two or more separate :class:~mne.io.Raw objects — you can use
the :meth:~mne.io.Raw.append method:
Can you write Python code for it?

raw_selection1 = raw.copy().crop(tmin=30, tmax=30.1)     # 0.1 seconds
raw_selection2 = raw.copy().crop(tmin=40, tmax=41.1)     # 1.1 seconds
raw_selection3 = raw.copy().crop(tmin=50, tmax=51.3)     # 1.3 seconds
raw_selection1.append([raw_selection2, raw_selection3])  # 2.5 seconds total
print(raw_selection1.times.min(), raw_selection1.times.max())


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Selection in the time domain
If you want to limit the time domain of a :class:~mne.io.Raw object, you
can use the :meth:~mne.io.Raw.crop method, which modifies the
:class:~mne.io.Raw object in place (we've seen this already at the start of
this tutorial, when we cropped the :class:~mne.io.Raw object to 60 seconds
to reduce memory demands). :meth:~mne.io.Raw.crop takes parameters tmin
and tmax, both in seconds (here we'll again use :meth:~mne.io.Raw.copy
first to avoid changing the original :class:~mne.io.Raw object):
Can you write Python code for it?

raw_selection = raw.copy().crop(tmin=10, tmax=12.5)
print(raw_selection)


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Similar to the :meth:~mne.io.Raw.pick_types method, there is also the
:meth:~mne.io.Raw.pick_channels method to pick channels by name, and a
corresponding :meth:~mne.io.Raw.drop_channels method to remove channels by
name:
Can you write Python code for it?

raw_temp = raw.copy()
print('Number of channels in raw_temp:')
print(len(raw_temp.ch_names), end=' → drop two → ')
raw_temp.drop_channels(['EEG 037', 'EEG 059'])
print(len(raw_temp.ch_names), end=' → pick three → ')
raw_temp.pick_channels(['MEG 1811', 'EEG 017', 'EOG 061'])
print(len(raw_temp.ch_names))


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
Some of the parameters of :func:mne.pick_types accept string arguments as
well as booleans. For example, the meg parameter can take values
'mag', 'grad', 'planar1', or 'planar2' to select only
magnetometers, all gradiometers, or a specific type of gradiometer. See the
docstring of :meth:mne.pick_types for full details.
The Raw.get_data() method
If you only want the data (not the corresponding array of times),
:class:~mne.io.Raw objects have a :meth:~mne.io.Raw.get_data method. Used
with no parameters specified, it will extract all data from all channels, in
a (n_channels, n_timepoints) :class:NumPy array <numpy.ndarray>:
Can you write Python code for it?


data = raw.get_data()
np.save(file='my_data.npy', arr=data)


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
The :meth:~mne.io.Raw.get_data method can also be used to extract specific
channel(s) and sample ranges, via its picks, start, and stop
parameters. The picks parameter accepts integer channel indices, channel
names, or channel types, and preserves the requested channel order given as
its picks parameter.
Can you write Python code for it?

first_channel_data = raw.get_data(picks=0)
eeg_and_eog_data = raw.get_data(picks=['eeg', 'eog'])
two_meg_chans_data = raw.get_data(picks=['MEG_0712', 'MEG_1022'],
                                  start=1000, stop=2000)

print(first_channel_data.shape)
print(eeg_and_eog_data.shape)
print(two_meg_chans_data.shape)


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
This next example replaces spaces in the channel names with underscores,
using a Python dict comprehension_:
Can you write Python code for it?

print(raw.ch_names[-3:])
channel_renaming_dict = {name: name.replace(' ', '_') for name in raw.ch_names}
raw.rename_channels(channel_renaming_dict)
print(raw.ch_names[-3:])


I am working on the file "0.20/_downloads/374e7fb88f562b8ceb7b99b07e106d9b/plot_10_raw_overview.ipynb".
The first task is:
You can see that it contains 2 arrays. This combination of data and times
makes it easy to plot selections of raw data (although note that we're
transposing the data array so that each channel is a column instead of a row,
to match what matplotlib expects when plotting 2-dimensional y against
1-dimensional x):
Can you write Python code for it?

x = raw_selection[1]
y = raw_selection[0].T
plt.plot(x, y)


I am working on the file "0.20/_downloads/38f243960dd98f9910f9b981f0b54dd0/plot_fdr_stats_evoked.ipynb".
The first task is:
FDR correction on T-test on sensor data
One tests if the evoked response significantly deviates from 0.
Multiple comparison problem is addressed with
False Discovery Rate (FDR) correction.
Can you write Python code for it?

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

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

import mne
from mne import io
from mne.datasets import sample
from mne.stats import bonferroni_correction, fdr_correction

print(__doc__)


I am working on the file "0.20/_downloads/38f243960dd98f9910f9b981f0b54dd0/plot_fdr_stats_evoked.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_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)[:30]

channel = 'MEG 1332'  # include only this channel in analysis
include = [channel]


I am working on the file "0.20/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
By default, MEG sensors will be used to estimate the field on the helmet
surface, while EEG sensors will be used to estimate the field on the scalp.
Once the maps are computed, you can plot them with :meth:evoked.plot_field()
<mne.Evoked.plot_field>:
Can you write Python code for it?

maps = mne.make_field_map(evks['aud/left'], trans=sample_data_trans_file,
                          subject='sample', subjects_dir=subjects_dir)
evks['aud/left'].plot_field(maps, time=0.1)


I am working on the file "0.20/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
For larger numbers of sensors, the method :meth:evoked.plot_topo()
<mne.Evoked.plot_topo> and the function :func:mne.viz.plot_evoked_topo
can both be used. The :meth:~mne.Evoked.plot_topo method will plot only a
single condition, while the :func:~mne.viz.plot_evoked_topo function can
plot one or more conditions on the same axes, if passed a list of
:class:~mne.Evoked objects. The legend entries will be automatically drawn
from the :class:~mne.Evoked objects' comment attribute:
Can you write Python code for it?


I am working on the file "0.20/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
Image plots
Like :class:~mne.Epochs, :class:~mne.Evoked objects also have a
:meth:~mne.Evoked.plot_image method, but unlike :meth:epochs.plot_image()
<mne.Epochs.plot_image>, :meth:evoked.plot_image() <mne.Evoked.plot_image>
shows one channel per row instead of one epoch per row. Again, a
picks parameter is available, as well as several other customization
options; see :meth:~mne.Evoked.plot_image for details.
Can you write Python code for it?


I am working on the file "0.20/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
Joint plots
Joint plots combine butterfly plots with scalp topographies, and provide an
excellent first-look at evoked data; by default, topographies will be
automatically placed based on peak finding. Here we plot the
right-visual-field condition; if no picks are specified we get a separate
figure for each channel type:
Can you write Python code for it?


I am working on the file "0.20/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
Like :meth:~mne.Evoked.plot_topomap you can specify the times at which
you want the scalp topographies calculated, and you can customize the plot in
various other ways as well. See :meth:mne.Evoked.plot_joint for details.
Comparing Evoked objects
To compare :class:~mne.Evoked objects from different experimental
conditions, the function :func:mne.viz.plot_compare_evokeds can take a
:class:list or :class:dict of :class:~mne.Evoked objects and plot them
all on the same axes. Like most MNE-Python visualization functions, it has a
picks parameter for selecting channels, but by default will generate one
figure for each channel type, and combine information across channels of the
same type by calculating the :term:global field power <GFP>. Information
may be combined across channels in other ways too; support for combining via
mean, median, or standard deviation are built-in, and custom callable
functions may also be used, as shown here:
Can you write Python code for it?

def custom_func(x):
    return x.max(axis=1)

for combine in ('mean', 'median', 'gfp', custom_func):
    mne.viz.plot_compare_evokeds(evks, picks='eeg', combine=combine)


I am working on the file "0.20/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
Notice the completely flat EEG channel and the noisy gradiometer channel
plotted in red color. Like many MNE-Python plotting functions,
:meth:evoked.plot() <mne.Evoked.plot> has a picks parameter that can
select channels to plot by name, index, or type. In the next plot we'll show
only magnetometer channels, and also color-code the channel traces by their
location by passing spatial_colors=True. Finally, we'll superimpose a
trace of the :term:global field power <GFP> across channels:
Can you write Python code for it?


I am working on the file "0.20/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
One nice feature of :func:~mne.viz.plot_compare_evokeds is that when
passing evokeds in a dictionary, it allows specifying plot styles based on
/-separated substrings of the dictionary keys (similar to epoch
selection; see tut-section-subselect-epochs). Here, we specify colors
for "aud" and "vis" conditions, and linestyles for "left" and "right"
conditions, and the traces and legend are styled accordingly.
Can you write Python code for it?

mne.viz.plot_compare_evokeds(evks, picks='MEG 1811', colors=dict(aud=0, vis=1),
                             linestyles=dict(left='solid', right='dashed'))


I am working on the file "0.20/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
Plotting signal traces
.. sidebar:: Butterfly plots
Plots of superimposed sensor timeseries are called "butterfly plots"
   because the positive- and negative-going traces can resemble
   butterfly wings.
The most basic plot of :class:~mne.Evoked objects is a butterfly plot of
each channel type, generated by the :meth:evoked.plot() <mne.Evoked.plot>
method. By default, channels marked as "bad" are suppressed, but you can
control this by passing an empty :class:list to the exclude parameter
(default is exclude='bads'):
Can you write Python code for it?


I am working on the file "0.20/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
To make our life easier, let's convert that list of :class:~mne.Evoked
objects into a :class:dictionary <dict>. We'll use /-separated
dictionary keys to encode the conditions (like is often done when epoching)
because some of the plotting methods can take advantage of that style of
coding.
Can you write Python code for it?

conds = ('aud/left', 'aud/right', 'vis/left', 'vis/right')
evks = dict(zip(conds, evokeds_list))
#      ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ this is equivalent to:
# {'aud/left': evokeds_list[0], 'aud/right': evokeds_list[1],
#  'vis/left': evokeds_list[2], 'vis/right': evokeds_list[3]}


I am working on the file "0.20/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
Visualizing Evoked data
This tutorial shows the different visualization methods for
:class:~mne.Evoked objects.
   :depth: 2
As usual we'll start by importing the modules we need:
Can you write Python code for it?


I am working on the file "0.20/_downloads/3927e2933ae8d1b19effcbd5c5341bd0/plot_20_visualize_evoked.ipynb".
The first task is:
You can also use MEG sensors to estimate the scalp field by passing
meg_surf='head'. By selecting each sensor type in turn, you can compare
the scalp field estimates from each.
Can you write Python code for it?

for ch_type in ('mag', 'grad', 'eeg'):
    evk = evks['aud/right'].copy().pick(ch_type)
    _map = mne.make_field_map(evk, trans=sample_data_trans_file,
                              subject='sample', subjects_dir=subjects_dir,
                              meg_surf='head')
    fig = evk.plot_field(_map, time=0.1)
    mne.viz.set_3d_title(fig, ch_type, size=20)


I am working on the file "0.20/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
Additional ways of visualizing projectors are covered in the tutorial
tut-artifact-ssp.
Loading and saving projectors
SSP can be used for other types of signal cleaning besides just reduction of
environmental noise. You probably noticed two large deflections in the
magnetometer signals in the previous plot that were not removed by the
empty-room projectors — those are artifacts of the subject's heartbeat. SSP
can be used to remove those artifacts as well. The sample data includes
projectors for heartbeat noise reduction that were saved in a separate file
from the raw data, which can be loaded with the :func:mne.read_proj
function:
Can you write Python code for it?

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


I am working on the file "0.20/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
Computing projectors
In MNE-Python, SSP vectors can be computed using general purpose functions
:func:mne.compute_proj_raw, :func:mne.compute_proj_epochs, and
:func:mne.compute_proj_evoked. The general assumption these functions make
is that the data passed contains raw data, epochs or averages of the artifact
you want to repair via projection. In practice this typically involves
continuous raw data of empty room recordings or averaged ECG or EOG
artifacts. A second set of high-level convenience functions is provided to
compute projection vectors for typical use cases. This includes
:func:mne.preprocessing.compute_proj_ecg and
:func:mne.preprocessing.compute_proj_eog for computing the ECG and EOG
related artifact components, respectively; see tut-artifact-ssp for
examples of these uses. For computing the EEG reference signal as a
projector, the function :func:mne.set_eeg_reference can be used; see
tut-set-eeg-ref for more information.

Warning

It is best to compute projectors only on channels that will be
             used (e.g., excluding bad channels). This ensures that
             projection vectors will remain ortho-normalized and that they
             properly capture the activity of interest.

Visualizing the effect of projectors
You can see the effect the projectors are having on the measured signal by
comparing plots with and without the projectors applied. By default,
raw.plot() will apply the projectors in the background before plotting
(without modifying the :class:~mne.io.Raw object); you can control this
with the boolean proj parameter as shown below, or you can turn them on
and off interactively with the projectors interface, accessed via the
:kbd:Proj button in the lower right corner of the plot window. Here we'll
look at just the magnetometers, and a 2-second sample from the beginning of
the file.
Can you write Python code for it?

mags = raw.copy().crop(tmax=2).pick_types(meg='mag')
for proj in (False, True):
    fig = mags.plot(butterfly=True, proj=proj)
    fig.subplots_adjust(top=0.9)
    fig.suptitle('proj={}'.format(proj), size='xx-large', weight='bold')


I am working on the file "0.20/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
Computing the projection matrix from the trigger_effect vector is done
using singular value decomposition <svd_>_ (SVD); interested readers may
consult the internet or a linear algebra textbook for details on this method.
With the projection matrix in place, we can project our original vector
$(3, 2, 5)$ to remove the effect of the trigger, and then plot it:
Can you write Python code for it?

# compute the projection matrix
U, S, V = svd(trigger_effect, full_matrices=False)
trigger_projection_matrix = np.eye(3) - U @ U.T

# project the vector onto the orthogonal plane
projected_point = trigger_projection_matrix @ point
projected_vector = trigger_projection_matrix @ vector

# plot the trigger effect and its orthogonal plane
ax = setup_3d_axes()
ax.plot_trisurf(x, y, z, color='C2', shade=False, alpha=0.25)
ax.quiver3D(*np.concatenate([origin, trigger_effect]).flatten(),
            arrow_length_ratio=0.1, color='C2', alpha=0.5)

# plot the original vector
ax.plot(*vector, color='k')
ax.plot(*point, color='k', marker='o')
offset = np.full((3, 1), 0.1)
ax.text(*(point + offset).flat, '({}, {}, {})'.format(*point.flat), color='k')

# plot the projected vector
ax.plot(*projected_vector, color='C0')
ax.plot(*projected_point, color='C0', marker='o')
offset = np.full((3, 1), -0.2)
ax.text(*(projected_point + offset).flat,
        '({}, {}, {})'.format(*np.round(projected_point.flat, 2)),
        color='C0', horizontalalignment='right')

# add dashed arrow showing projection
arrow_coords = np.concatenate([point, projected_point - point]).flatten()
ax.quiver3D(*arrow_coords, length=0.96, arrow_length_ratio=0.1,
            color='C1', linewidth=1, linestyle='dashed')


I am working on the file "0.20/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
The :class:~mne.io.Raw, :class:~mne.Epochs, and :class:~mne.Evoked
objects all have a boolean :attr:~mne.io.Raw.proj attribute that indicates
whether there are any unapplied / inactive projectors stored in the object.
In other words, the :attr:~mne.io.Raw.proj attribute is True if at
least one :term:projector is present and all of them are active. In
addition, each individual projector also has a boolean active field:
Can you write Python code for it?


I am working on the file "0.20/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
There is a corresponding :func:mne.write_proj function that can be used to
save projectors to disk in .fif format:
.. code-block:: python3
mne.write_proj('heartbeat-proj.fif', ecg_projs)

Note

By convention, MNE-Python expects projectors to be saved with a filename
    ending in ``-proj.fif`` (or ``-proj.fif.gz``), and will issue a warning
    if you forgo this recommendation.

Adding and removing projectors
Above, when we printed the ecg_projs list that we loaded from a file, it
showed two projectors for gradiometers (the first two, marked "planar"), two
for magnetometers (the middle two, marked "axial"), and two for EEG sensors
(the last two, marked "eeg"). We can add them to the :class:~mne.io.Raw
object using the :meth:~mne.io.Raw.add_proj method:
Can you write Python code for it?


I am working on the file "0.20/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
To remove projectors, there is a corresponding method
:meth:~mne.io.Raw.del_proj that will remove projectors based on their index
within the raw.info['projs'] list. For the special case of replacing the
existing projectors with new ones, use
raw.add_proj(ecg_projs, remove_existing=True).
To see how the ECG projectors affect the measured signal, we can once again
plot the data with and without the projectors applied (though remember that
the :meth:~mne.io.Raw.plot method only temporarily applies the projectors
for visualization, and does not permanently change the underlying data).
We'll compare the mags variable we created above, which had only the
empty room SSP projectors, to the data with both empty room and ECG
projectors:
Can you write Python code for it?

mags_ecg = raw.copy().crop(tmax=2).pick_types(meg='mag')
for data, title in zip([mags, mags_ecg], ['Without', 'With']):
    fig = data.plot(butterfly=True, proj=True)
    fig.subplots_adjust(top=0.9)
    fig.suptitle('{} ECG projector'.format(title), size='xx-large',
                 weight='bold')


I am working on the file "0.20/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
What is a projection?
In the most basic terms, a projection is an operation that converts one set
of points into another set of points, where repeating the projection
operation on the resulting points has no effect. To give a simple geometric
example, imagine the point $(3, 2, 5)$ in 3-dimensional space. A
projection of that point onto the $x, y$ plane looks a lot like a
shadow cast by that point if the sun were directly above it:
Can you write Python code for it?

ax = setup_3d_axes()

# plot the vector (3, 2, 5)
origin = np.zeros((3, 1))
point = np.array([[3, 2, 5]]).T
vector = np.hstack([origin, point])
ax.plot(*vector, color='k')
ax.plot(*point, color='k', marker='o')

# project the vector onto the x,y plane and plot it
xy_projection_matrix = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 0]])
projected_point = xy_projection_matrix @ point
projected_vector = xy_projection_matrix @ vector
ax.plot(*projected_vector, color='C0')
ax.plot(*projected_point, color='C0', marker='o')

# add dashed arrow showing projection
arrow_coords = np.concatenate([point, projected_point - point]).flatten()
ax.quiver3D(*arrow_coords, length=0.96, arrow_length_ratio=0.1, color='C1',
            linewidth=1, linestyle='dashed')


I am working on the file "0.20/_downloads/3ca4dabff6bcea5b8da3afc9052669d2/plot_45_projectors_background.ipynb".
The first task is:
raw.info['projs'] is an ordinary Python :class:list of
:class:~mne.Projection objects, so you can access individual projectors by
indexing into it. The :class:~mne.Projection object itself is similar to a
Python :class:dict, so you can use its .keys() method to see what
fields it contains (normally you don't need to access its properties
directly, but you can if necessary):
Can you write Python code for it?

first_projector = raw.info['projs'][0]
print(first_projector)
print(first_projector.keys())


I am working on the file "0.20/_downloads/4395f5fd5291fa48208a82dab72d1893/plot_sensor_regression.ipynb".
The first task is:
Analysing continuous features with binning and regression in sensor space
Predict single trial activity from a continuous variable.
A single-trial regression is performed in each sensor and timepoint
individually, resulting in an :class:mne.Evoked object which contains the
regression coefficient (beta value) for each combination of sensor and
timepoint. This example shows the regression coefficient; the t and p values
are also calculated automatically.
Here, we repeat a few of the analyses from [1]_. This can be easily performed
by accessing the metadata object, which contains word-level information about
various psycholinguistically relevant features of the words for which we have
EEG activity.
For the general methodology, see e.g. [2]_.
References
.. [1] Dufau, S., Grainger, J., Midgley, KJ., Holcomb, PJ. A thousand
   words are worth a picture: Snapshots of printed-word processing in an
   event-related potential megastudy. Psychological Science, 2015
.. [2] Hauk et al. The time course of visual word recognition as revealed by
   linear regression analysis of ERP data. Neuroimage, 2006
Can you write Python code for it?

# Authors: Tal Linzen <linzen@nyu.edu>
#          Denis A. Engemann <denis.engemann@gmail.com>
#          Jona Sassenhagen <jona.sassenhagen@gmail.com>
#
# License: BSD (3-clause)

import pandas as pd
import mne
from mne.stats import linear_regression, fdr_correction
from mne.viz import plot_compare_evokeds
from mne.datasets import kiloword

# Load the data
path = kiloword.data_path() + '/kword_metadata-epo.fif'
epochs = mne.read_epochs(path)
print(epochs.metadata.head())


I am working on the file "0.20/_downloads/4395f5fd5291fa48208a82dab72d1893/plot_sensor_regression.ipynb".
The first task is:
Because the linear_regression function also estimates p values, we can --
after applying FDR correction for multiple comparisons -- also visualise the
statistical significance of the regression of word concreteness.
The :func:mne.viz.plot_evoked_image function takes a mask parameter.
If we supply it with a boolean mask of the positions where we can reject
the null hypothesis, points that are not significant will be shown
transparently, and if desired, in a different colour palette and surrounded
by dark contour lines.
Can you write Python code for it?

reject_H0, fdr_pvals = fdr_correction(res["Concreteness"].p_val.data)
evoked = res["Concreteness"].beta
evoked.plot_image(mask=reject_H0, time_unit='s')


I am working on the file "0.20/_downloads/4395f5fd5291fa48208a82dab72d1893/plot_sensor_regression.ipynb".
The first task is:
Psycholinguistically relevant word characteristics are continuous. I.e.,
concreteness or imaginability is a graded property. In the metadata,
we have concreteness ratings on a 5-point scale. We can show the dependence
of the EEG on concreteness by dividing the data into bins and plotting the
mean activity per bin, color coded.
Can you write Python code for it?

name = "Concreteness"
df = epochs.metadata
df[name] = pd.cut(df[name], 11, labels=False) / 10
colors = {str(val): val for val in df[name].unique()}
epochs.metadata = df.assign(Intercept=1)  # Add an intercept for later
evokeds = {val: epochs[name + " == " + val].average() for val in colors}
plot_compare_evokeds(evokeds, colors=colors, split_legend=True,
                     cmap=(name + " Percentile", "viridis"))


I am working on the file "0.20/_downloads/460fe4a441caf01fe3a0ace1c9325a0d/plot_tf_lcmv.ipynb".
The first task is:
Time-frequency beamforming based on LCMV
Can you write Python code for it?

# Setting frequency bins as in Dalal et al. 2008 (high gamma was subdivided)
freq_bins = [(4, 12), (12, 30), (30, 55), (65, 299)]  # Hz
win_lengths = [0.3, 0.2, 0.15, 0.1]  # s

# Setting the time step
tstep = 0.05

# Setting the whitened data covariance regularization parameter
data_reg = 0.001

# Subtract evoked response prior to computation?
subtract_evoked = False

# Calculating covariance from empty room noise. To use baseline data as noise
# substitute raw for raw_noise, epochs.events for epochs_noise.events, tmin for
# desired baseline length, and 0 for tmax_plot.
# Note, if using baseline data, the averaged evoked response in the baseline
# period should be flat.
noise_covs = []
for (l_freq, h_freq) in freq_bins:
    raw_band = raw_noise.copy()
    raw_band.filter(l_freq, h_freq, n_jobs=1, fir_design='firwin')
    epochs_band = mne.Epochs(raw_band, epochs_noise.events, event_id,
                             tmin=tmin_plot, tmax=tmax_plot, baseline=None,
                             proj=True)

    noise_cov = compute_covariance(epochs_band, method='shrunk', rank=None)
    noise_covs.append(noise_cov)
    del raw_band  # to save memory

# Computing LCMV solutions for time-frequency windows in a label in source
# space for faster computation, use label=None for full solution
stcs = tf_lcmv(epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths,
               freq_bins=freq_bins, subtract_evoked=subtract_evoked,
               reg=data_reg, label=label, rank=None)

# Plotting source spectrogram for source with maximum activity.
# Note that tmin and tmax are set to display a time range that is smaller than
# the one for which beamforming estimates were calculated. This ensures that
# all time bins shown are a result of smoothing across an identical number of
# time windows.
plot_source_spectrogram(stcs, freq_bins, tmin=tmin_plot, tmax=tmax_plot,
                        source_index=None, colorbar=True)


I am working on the file "0.20/_downloads/460fe4a441caf01fe3a0ace1c9325a0d/plot_tf_lcmv.ipynb".
The first task is:
Time-frequency beamforming using LCMV
Compute LCMV source power [1]_ in a grid of time-frequency windows and
display results.
References
.. [1] Dalal et al. Five-dimensional neuroimaging: Localization of the
       time-frequency dynamics of cortical activity.
       NeuroImage (2008) vol. 40 (4) pp. 1686-1700
Can you write Python code for it?

# Author: Roman Goj <roman.goj@gmail.com>
#
# License: BSD (3-clause)

import mne
from mne import compute_covariance
from mne.datasets import sample
from mne.event import make_fixed_length_events
from mne.beamformer import tf_lcmv
from mne.viz import plot_source_spectrogram

print(__doc__)

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
noise_fname = data_path + '/MEG/sample/ernoise_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'
subjects_dir = data_path + '/subjects'
label_name = 'Aud-lh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name


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

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

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


I am working on the file "0.20/_downloads/481587b48f7ba7c5e977b66e26948141/plot_psf_ctf_vertices_lcmv.ipynb".
The first task is:
Compute cross-talk functions for LCMV beamformers
Visualise cross-talk functions at one vertex for LCMV beamformers computed
with different data covariance matrices, which affects their cross-talk
functions.
Can you write Python code for it?

# Author: Olaf Hauk <olaf.hauk@mrc-cbu.cam.ac.uk>
#
# License: BSD (3-clause)

import mne
from mne.datasets import sample
from mne.beamformer import make_lcmv, make_lcmv_resolution_matrix
from mne.minimum_norm import get_cross_talk

print(__doc__)

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

# Read raw data
raw = mne.io.read_raw_fif(raw_fname, preload=True)

# only pick good EEG/MEG sensors
raw.info['bads'] += ['EEG 053']  # bads + 1 more
picks = mne.pick_types(raw.info, meg=True, eeg=True, exclude='bads')

# Find events
events = mne.find_events(raw)

# event_id = {'aud/l': 1, 'aud/r': 2, 'vis/l': 3, 'vis/r': 4}
event_id = {'vis/l': 3, 'vis/r': 4}

tmin, tmax = -.2, .25  # epoch duration
epochs = mne.Epochs(raw, events, event_id=event_id, tmin=tmin, tmax=tmax,
                    picks=picks, baseline=(-.2, 0.), preload=True)

# covariance matrix for pre-stimulus interval
tmin, tmax = -.2, 0.
cov_pre = mne.compute_covariance(epochs, tmin=tmin, tmax=tmax,
                                 method='empirical')

# covariance matrix for post-stimulus interval (around main evoked responses)
tmin, tmax = 0.05, .25
cov_post = mne.compute_covariance(epochs, tmin=tmin, tmax=tmax,
                                  method='empirical')

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

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

# get valid measurement info
raw = raw.pick_types(meg=True, eeg=True, exclude='bads')
info = raw.info

# regularize noise covariance (we used 'empirical' above)
noise_cov =...


I am working on the file "0.20/_downloads/481587b48f7ba7c5e977b66e26948141/plot_psf_ctf_vertices_lcmv.ipynb".
The first task is:
Compute resolution matrices for the two LCMV beamformers
Can you write Python code for it?

rm_pre = make_lcmv_resolution_matrix(filters_pre, forward, info)

rm_post = make_lcmv_resolution_matrix(filters_post, forward, info)

# compute cross-talk functions (CTFs) for one target vertex
sources = [3000]

stc_pre = get_cross_talk(rm_pre, forward['src'], sources, norm=True)

stc_post = get_cross_talk(rm_post, forward['src'], sources, norm=True)


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

vertno_lh = forward['src'][0]['vertno']  # vertex of selected source
verttrue = [vertno_lh[sources[0]]]  # pick one vertex

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

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

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

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

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

brain_post.add_foci(verttrue, coords_as_verts=True, scale_factor=1.,
                    hemi='lh', color='green')


I am working on the file "0.20/_downloads/4a27e3735cff9a10082eb2938ef41c34/plot_sensor_permutation_test.ipynb".
The first task is:
Permutation T-test on sensor data
One tests if the signal significantly deviates from 0
during a fixed time window of interest. Here computation
is performed on MNE sample dataset between 40 and 60 ms.
Can you write Python code for it?

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

import numpy as np

import mne
from mne import io
from mne.stats import permutation_t_test
from mne.datasets import sample

print(__doc__)


I am working on the file "0.20/_downloads/4a39dd4a31cad8a0e098b02526b9c3d3/plot_covariance_whitening_dspm.ipynb".
The first task is:
Demonstrate impact of whitening on source estimates
This example demonstrates the relationship between the noise covariance
estimate and the MNE / dSPM source amplitudes. It computes source estimates for
the SPM faces data and compares proper regularization with insufficient
regularization based on the methods described in [1]. The example demonstrates
that improper regularization can lead to overestimation of source amplitudes.
This example makes use of the previous, non-optimized code path that was used
before implementing the suggestions presented in [1].
This example does quite a bit of processing, so even on a
fast machine it can take a couple of minutes to complete.

Warning

Please do not copy the patterns presented here for your own
             analysis, this is example is purely illustrative.

References
.. [1] Engemann D. and Gramfort A. (2015) Automated model selection in
       covariance estimation and spatial whitening of MEG and EEG signals,
       vol. 108, 328-342, NeuroImage.
Can you write Python code for it?

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

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne import io
from mne.datasets import spm_face
from mne.minimum_norm import apply_inverse, make_inverse_operator
from mne.cov import compute_covariance

print(__doc__)


I am working on the file "0.20/_downloads/4a39dd4a31cad8a0e098b02526b9c3d3/plot_covariance_whitening_dspm.ipynb".
The first task is:
Estimate covariances
Can you write Python code for it?

samples_epochs = 5, 15,
method = 'empirical', 'shrunk'
colors = 'steelblue', 'red'

evokeds = list()
stcs = list()
methods_ordered = list()
for n_train in samples_epochs:
    # estimate covs based on a subset of samples
    # make sure we have the same number of conditions.
    events_ = np.concatenate([events[events[:, 2] == id_][:n_train]
                              for id_ in [event_ids[k] for k in conditions]])
    events_ = events_[np.argsort(events_[:, 0])]
    epochs_train = mne.Epochs(raw, events_, event_ids, tmin, tmax, picks=picks,
                              baseline=baseline, preload=True, reject=reject,
                              decim=8)
    epochs_train.equalize_event_counts(event_ids)
    assert len(epochs_train) == 2 * n_train

    # We know some of these have too few samples, so suppress warning
    # with verbose='error'
    noise_covs = compute_covariance(
        epochs_train, method=method, tmin=None, tmax=0,  # baseline only
        return_estimators=True, rank=None, verbose='error')  # returns list
    # prepare contrast
    evokeds = [epochs_train[k].average() for k in conditions]
    del epochs_train, events_
    # do contrast

    # We skip empirical rank estimation that we introduced in response to
    # the findings in reference [1] to use the naive code path that
    # triggered the behavior described in [1]. The expected true rank is
    # 274 for this dataset. Please do not do this with your data but
    # rely on the default rank estimator that helps regularizing the
    # covariance.
    stcs.append(list())
    methods_ordered.append(list())
    for cov in noise_covs:
        inverse_operator = make_inverse_operator(evokeds[0].info, forward,
                                                 cov, loose=0.2, depth=0.8)
        assert len(inverse_operator['sing']) == 274  # sanity check
        stc_a, stc_b = (apply_inverse(e, inverse_operator, lambda2, "dSPM",
                                      pick_ori=None) for e in evokeds)
        stc = stc_a - stc_b
       ...


I am working on the file "0.20/_downloads/4a39dd4a31cad8a0e098b02526b9c3d3/plot_covariance_whitening_dspm.ipynb".
The first task is:
Get data
Can you write Python code for it?

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

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

raw = io.read_raw_ctf(raw_fname % 1)  # Take first run
# To save time and memory for this demo, we'll just use the first
# 2.5 minutes (all we need to get 30 total events) and heavily
# resample 480->60 Hz (usually you wouldn't do either of these!)
raw = raw.crop(0, 150.).load_data()

picks = mne.pick_types(raw.info, meg=True, exclude='bads')
raw.filter(None, 20.)

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

event_ids = {"faces": 1, "scrambled": 2}
tmin, tmax = -0.2, 0.5
baseline = (None, 0)
reject = dict(mag=3e-12)

# Make forward
trans = data_path + '/MEG/spm/SPM_CTF_MEG_example_faces1_3D_raw-trans.fif'
src = data_path + '/subjects/spm/bem/spm-oct-6-src.fif'
bem = data_path + '/subjects/spm/bem/spm-5120-5120-5120-bem-sol.fif'
forward = mne.make_forward_solution(raw.info, trans, src, bem)
del src

# inverse parameters
conditions = 'faces', 'scrambled'
snr = 3.0
lambda2 = 1.0 / snr ** 2
clim = dict(kind='value', lims=[0, 2.5, 5])


I am working on the file "0.20/_downloads/4a39dd4a31cad8a0e098b02526b9c3d3/plot_covariance_whitening_dspm.ipynb".
The first task is:
Show the resulting source estimates
Can you write Python code for it?

fig, (axes1, axes2) = plt.subplots(2, 3, figsize=(9.5, 5))

for ni, (n_train, axes) in enumerate(zip(samples_epochs, (axes1, axes2))):
    # compute stc based on worst and best
    ax_dynamics = axes[1]
    for stc, ax, method, kind, color in zip(stcs[ni],
                                            axes[::2],
                                            methods_ordered[ni],
                                            ['best', 'worst'],
                                            colors):
        brain = stc.plot(subjects_dir=subjects_dir, hemi='both', clim=clim,
                         initial_time=0.175, background='w', foreground='k')
        brain.show_view('ven')
        im = brain.screenshot()
        brain.close()

        ax.axis('off')
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        ax.imshow(im)
        ax.set_title('{0} ({1} epochs)'.format(kind, n_train * 2))

        # plot spatial mean
        stc_mean = stc.data.mean(0)
        ax_dynamics.plot(stc.times * 1e3, stc_mean,
                         label='{0} ({1})'.format(method, kind),
                         color=color)
        # plot spatial std
        stc_var = stc.data.std(0)
        ax_dynamics.fill_between(stc.times * 1e3, stc_mean - stc_var,
                                 stc_mean + stc_var, alpha=0.2, color=color)

    # signal dynamics worst and best
    ax_dynamics.set(title='{0} epochs'.format(n_train * 2),
                    xlabel='Time (ms)', ylabel='Source Activation (dSPM)',
                    xlim=(tmin * 1e3, tmax * 1e3), ylim=(-3, 3))
    ax_dynamics.legend(loc='upper left', fontsize=10)

fig.subplots_adjust(hspace=0.2, left=0.01, right=0.99, wspace=0.03)