I am working on the file "0.14/_downloads/plot_ecog.ipynb".
The first task is:
Sometimes it is useful to make a scatterplot for the current figure view.
This is best accomplished with matplotlib. We can capture an image of the
current mayavi view, along with the xy position of each electrode, with the
snapshot_brain_montage function.
Can you write Python code for it?

# We'll once again plot the surface, then take a snapshot.
fig = plot_trans(info, trans=None, subject='sample', subjects_dir=subjects_dir)
mlab.view(200, 70)
xy, im = snapshot_brain_montage(fig, mon)

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

# Define an arbitrary "activity" pattern for viz
activity = np.linspace(100, 200, xy_pts.shape[0])

# This allows us to use matplotlib to create arbitrary 2d scatterplots
_, ax = plt.subplots(figsize=(10, 10))
ax.imshow(im)
ax.scatter(*xy_pts.T, c=activity, s=200, cmap='coolwarm')
ax.set_axis_off()
plt.show()


I am working on the file "0.14/_downloads/plot_ecog.ipynb".
The first task is:
We can then plot the locations of our electrodes on our subject's brain.

Note

These are not real electrodes for this subject, so they
          do not align to the cortical surface perfectly.

Can you write Python code for it?

subjects_dir = mne.datasets.sample.data_path() + '/subjects'
fig = plot_trans(info, trans=None, subject='sample', subjects_dir=subjects_dir)
mlab.view(200, 70)


I am working on the file "0.14/_downloads/plot_ecog.ipynb".
The first task is:
Working with ECoG data
MNE supports working with more than just MEG and EEG data. Here we show some
of the functions that can be used to facilitate working with
electrocorticography (ECoG) data.
Can you write Python code for it?

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

import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
from mayavi import mlab

import mne
from mne.viz import plot_trans, snapshot_brain_montage

print(__doc__)


I am working on the file "0.14/_downloads/plot_eeg_erp.ipynb".
The first task is:
And it's actually possible to plot the channel locations using
the :func:mne.io.Raw.plot_sensors method
Can you write Python code for it?

raw.plot_sensors()
raw.plot_sensors('3d')  # in 3D


I am working on the file "0.14/_downloads/plot_eeg_erp.ipynb".
The first task is:
Average reference: This is normally added by default, but can also
be added explicitly.
Can you write Python code for it?

raw_car, _ = mne.set_eeg_reference(raw)
evoked_car = mne.Epochs(raw_car, **epochs_params).average()
del raw_car  # save memory

title = 'EEG Average reference'
evoked_car.plot(titles=dict(eeg=title))
evoked_car.plot_topomap(times=[0.1], size=3., title=title)


I am working on the file "0.14/_downloads/plot_eeg_erp.ipynb".
The first task is:
By looking at the measurement info you will see that we have now
59 EEG channels and 1 EOG channel
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_eeg_erp.ipynb".
The first task is:
Evoked arithmetics
Trial subsets from Epochs can be selected using 'tags' separated by '/'.
Evoked objects support basic arithmetic.
First, we create an Epochs object containing 4 conditions.
Can you write Python code for it?

event_id = {'left/auditory': 1, 'right/auditory': 2,
            'left/visual': 3, 'right/visual': 4}
epochs_params = dict(events=events, event_id=event_id, tmin=tmin, tmax=tmax,
                     reject=reject)
epochs = mne.Epochs(raw, **epochs_params)

print(epochs)


I am working on the file "0.14/_downloads/plot_eeg_erp.ipynb".
The first task is:
In practice it's quite common to have some EEG channels that are actually
EOG channels. To change a channel type you can use the
:func:mne.io.Raw.set_channel_types method. For example
to treat an EOG channel as EEG you can change its type using
Can you write Python code for it?

raw.set_channel_types(mapping={'EOG 061': 'eeg'})
print(raw.info)


I am working on the file "0.14/_downloads/plot_eeg_erp.ipynb".
The first task is:
Let's reset the EOG channel back to EOG type.
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_eeg_erp.ipynb".
The first task is:
Let's restrict the data to the EEG channels
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_eeg_erp.ipynb".
The first task is:
Next, we create averages of stimulation-left vs stimulation-right trials.
We can use basic arithmetic to, for example, construct and plot
difference ERPs.
Can you write Python code for it?

left, right = epochs["left"].average(), epochs["right"].average()

# create and plot difference ERP
mne.combine_evoked([left, -right], weights='equal').plot_joint()


I am working on the file "0.14/_downloads/plot_eeg_erp.ipynb".
The first task is:
Setting EEG montage
In the case where your data don't have locations you can set them
using a :func:mne.channels.Montage. MNE comes with a set of default
montages. To read one of them do:
Can you write Python code for it?

montage = mne.channels.read_montage('standard_1020')
print(montage)


I am working on the file "0.14/_downloads/plot_eeg_erp.ipynb".
The first task is:
Setup for reading the raw data
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'
raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.set_eeg_reference()  # set EEG average reference


I am working on the file "0.14/_downloads/plot_eeg_erp.ipynb".
The first task is:
The EEG channels in the sample dataset already have locations.
These locations are available in the 'loc' of each channel description.
For the first channel we get
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_eeg_erp.ipynb".
The first task is:
This can be simplified with a Python list comprehension:
Can you write Python code for it?

all_evokeds = [epochs[cond].average() for cond in sorted(event_id.keys())]
print(all_evokeds)

# Then, we construct and plot an unweighted average of left vs. right trials
# this way, too:
mne.combine_evoked(all_evokeds,
                   weights=(0.25, -0.25, 0.25, -0.25)).plot_joint()


I am working on the file "0.14/_downloads/plot_eeg_erp.ipynb".
The first task is:
This is an equal-weighting difference. If you have imbalanced trial numbers,
you could also consider either equalizing the number of events per
condition (using
:meth:epochs.equalize_event_counts <mne.Epochs.equalize_event_counts>).
As an example, first, we create individual ERPs for each condition.
Can you write Python code for it?

aud_l = epochs["auditory", "left"].average()
aud_r = epochs["auditory", "right"].average()
vis_l = epochs["visual", "left"].average()
vis_r = epochs["visual", "right"].average()

all_evokeds = [aud_l, aud_r, vis_l, vis_r]
print(all_evokeds)


I am working on the file "0.14/_downloads/plot_eeg_erp.ipynb".
The first task is:
We next define Epochs and compute an ERP for the left auditory condition.
Can you write Python code for it?

reject = dict(eeg=180e-6, eog=150e-6)
event_id, tmin, tmax = {'left/auditory': 1}, -0.2, 0.5
events = mne.read_events(event_fname)
epochs_params = dict(events=events, event_id=event_id, tmin=tmin, tmax=tmax,
                     reject=reject)

evoked_no_ref = mne.Epochs(raw_no_ref, **epochs_params).average()
del raw_no_ref  # save memory

title = 'EEG Original reference'
evoked_no_ref.plot(titles=dict(eeg=title))
evoked_no_ref.plot_topomap(times=[0.1], size=3., title=title)


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

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

import mne
import os
from mne.datasets import multimodal
from mne import AcqParserFIF

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

print(__doc__)


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


I am working on the file "0.14/_downloads/plot_elekta_epochs.ipynb".
The first task is:
Extract epochs corresponding to a category
Can you write Python code for it?

cond = ap.get_condition(raw, 'Auditory right')
epochs = mne.Epochs(raw, **cond)
epochs.average().plot_topo()


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

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


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

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

cond = ap.get_condition(raw, newcat)
epochs = mne.Epochs(raw, reject=ap.reject, flat=ap.flat, **cond)
epochs.average().plot()


I am working on the file "0.14/_downloads/plot_elekta_epochs.ipynb".
The first task is:
Read raw file and create parser instance
Can you write Python code for it?

raw = mne.io.read_raw_fif(fname_raw)
ap = AcqParserFIF(raw.info)


I am working on the file "0.14/_downloads/plot_ems_filtering.ipynb".
The first task is:
Note that a similar transformation can be applied with compute_ems
However, this function replicates Schurger et al's original paper, and thus
applies the normalization outside a leave-one-out cross-validation, which we
recommend not to do.
Can you write Python code for it?

epochs.equalize_event_counts(event_ids)
X_transform, filters, classes = compute_ems(epochs)


I am working on the file "0.14/_downloads/plot_epoching_and_averaging.ipynb".
The first task is:
Epoching and averaging (ERP/ERF)
Can you write Python code for it?

import os.path as op
import numpy as np

import mne


I am working on the file "0.14/_downloads/plot_epoching_and_averaging.ipynb".
The first task is:
Let's plot the epochs to see the results. The number at the top refers to the
id number. We can see that 128 good epochs out of total of 145 events got
through the rejection process. Visual inspection also reveals that some
epochs containing saccades or blinks got through. You can also reject epochs
by hand by clicking on the epoch in the browser window. The selected epochs
get rejected when you close the epochs browser. How you should reject the
epochs and which thresholds to use is not a trivial question and this
tutorial takes no stand on that matter.
To see all the interactive features of the epochs browser, click 'Help' in
the lower left corner of the browser window.
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_epoching_and_averaging.ipynb".
The first task is:
Notice channel STI 014 at the bottom. It is the trigger channel that
was used for combining all the events to a single channel. We can see that it
has several pulses of different amplitude throughout the recording. These
pulses correspond to different stimuli presented to the subject during the
acquisition. The pulses have values of 1, 2, 3, 4, 5 and 32. These are the
events we are going to align the epochs to. To create an event list from raw
data, we simply call a function dedicated just for that. Since the event list
is simply a numpy array, you can also manually create one. If you create one
from an outside source (like a separate file of events), pay special
attention in aligning the events correctly with the raw data.
Can you write Python code for it?

events = mne.find_events(raw)
print('Found %s events, first five:' % len(events))
print(events[:5])

# Plot the events to get an idea of the paradigm
# Specify colors and an event_id dictionary for the legend.
event_id = {'Auditory/Left': 1, 'Auditory/Right': 2,
            'Visual/Left': 3, 'Visual/Right': 4,
            'smiley': 5, 'button': 32}
color = {1: 'green', 2: 'yellow', 3: 'red', 4: 'c', 5: 'black', 32: 'blue'}

mne.viz.plot_events(events, raw.info['sfreq'], raw.first_samp, color=color,
                    event_id=event_id)


I am working on the file "0.14/_downloads/plot_epoching_and_averaging.ipynb".
The first task is:
Notice we have used forward slashes ('/') to separate the factors of the
conditions of the experiment. We can use these 'tags' to select for example
all left trials (both visual left and auditory right) ...
Can you write Python code for it?

epochs_left = epochs['Left']

# ... or to select a very specific subset. This is the same as above:
evoked_left = epochs['Left/Auditory'].average(picks=picks)


I am working on the file "0.14/_downloads/plot_epoching_and_averaging.ipynb".
The first task is:
Now we have everything we need to construct the epochs. To get some
meaningful results, we also want to baseline the epochs. Baselining computes
the mean over the baseline period and adjusts the data accordingly. The
epochs constructor uses a baseline period from tmin to 0.0 seconds by
default, but it is wise to be explicit. That way you are less likely to end
up with surprises along the way. None as the first element of the tuple
refers to the start of the time window (-200 ms in this case).
See :class:mne.Epochs for more.
We also define rejection thresholds to get rid of noisy epochs. The
rejection thresholds are defined as peak-to-peak values within the epoch time
window. They are defined as T/m for gradiometers, T for magnetometers and V
for EEG and EOG electrodes.

Note

In this tutorial, we don't preprocess the data. This is not
          something you would normally do. See our `tutorials` on
          preprocessing for more.

Can you write Python code for it?

baseline = (None, 0.0)
reject = {'mag': 4e-12, 'eog': 200e-6}
epochs = mne.Epochs(raw, events=events, event_id=event_id, tmin=tmin,
                    tmax=tmax, reject=reject, picks=picks)


I am working on the file "0.14/_downloads/plot_epoching_and_averaging.ipynb".
The first task is:
The event list contains three columns. The first column corresponds to
sample number. To convert this to seconds, you should divide the sample
number by the used sampling frequency. The second column is reserved for the
old value of the trigger channel at the time of transition, but is currently
not in use. The third column is the trigger id (amplitude of the pulse).
You might wonder why the samples don't seem to align with the plotted data.
For instance, the first event has a sample number of 27977 which should
translate to roughly 46.6 seconds (27977 / 600). However looking at
the pulses we see the first pulse at 3.6 seconds. This is because Neuromag
recordings have an attribute first_samp which refers to the offset
between the system start and the start of the recording. Our data has a
first_samp equal to 25800. This means that the first sample you see with
raw.plot is the sample number 25800. Generally you don't need to worry
about this offset as it is taken into account with MNE functions, but it is
good to be aware of. Just to confirm, let's plot the events together with the
raw data. Notice how the vertical lines (events) align nicely with the pulses
on STI 014.
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_epoching_and_averaging.ipynb".
The first task is:
To see why the epochs were rejected, we can plot the drop log.
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_epochs_objects.ipynb".
The first task is:
.. _tut_epochs_objects:
The :class:Epochs <mne.Epochs> data structure: epoched data
Can you write Python code for it?

from __future__ import print_function

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


I am working on the file "0.14/_downloads/plot_epochs_objects.ipynb".
The first task is:
Epochs behave similarly to :class:mne.io.Raw objects. They have an
:class:info <mne.io.meas_info.Info> attribute that has all of the same
information, as well as a number of attributes unique to the events contained
within the object.
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_epochs_objects.ipynb".
The first task is:
It is also possible to iterate through :class:Epochs <mne.Epochs> objects
in this way. Note that behavior is different if you iterate on Epochs
directly rather than indexing:
Can you write Python code for it?

# These will be epochs objects
for i in range(3):
    print(epochs[i])

# These will be arrays
for ep in epochs[:2]:
    print(ep)


I am working on the file "0.14/_downloads/plot_epochs_objects.ipynb".
The first task is:
You can select subsets of epochs by indexing the :class:Epochs <mne.Epochs>
object directly. Alternatively, if you have epoch names specified in
event_id then you may index with strings instead.
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_epochs_spectra.ipynb".
The first task is:
Compute the power spectral density of epochs
This script shows how to compute the power spectral density (PSD)
of measurements on epochs. It also shows how to plot its spatial
distribution.
Can you write Python code for it?

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

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

print(__doc__)


I am working on the file "0.14/_downloads/plot_epochs_spectra.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'

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

tmin, tmax, event_id = -1., 1., 1
raw.info['bads'] += ['MEG 2443']  # bads

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

# Let's first check out all channel types by averaging across epochs.
epochs.plot_psd(fmin=2, fmax=200)

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

# Now let's take a look at the spatial distributions of the psd.
epochs.plot_psd_topomap(ch_type='grad', normalize=True)


I am working on the file "0.14/_downloads/plot_epochs_to_data_frame.ipynb".
The first task is:
Export DataFrame
Can you write Python code for it?

# The following parameters will scale the channels and times plotting
# friendly. The info columns 'epoch' and 'time' will be used as hierarchical
# index whereas the condition is treated as categorial data. Note that
# this is optional. By passing None you could also print out all nesting
# factors in a long table style commonly used for analyzing repeated measure
# designs.

index, scale_time, scalings = ['epoch', 'time'], 1e3, dict(grad=1e13)

df = epochs.to_data_frame(picks=None, scalings=scalings, scale_time=scale_time,
                          index=index)

# Create MEG channel selector and drop EOG channel.
meg_chs = [c for c in df.columns if 'MEG' in c]

df.pop('EOG 061')  # this works just like with a list.


I am working on the file "0.14/_downloads/plot_epochs_to_data_frame.ipynb".
The first task is:
Export epochs to Pandas DataFrame
In this example the pandas exporter will be used to produce a DataFrame
object. After exploring some basic features a split-apply-combine
work flow will be conducted to examine the latencies of the response
maxima across epochs and conditions.
Note. Equivalent methods are available for raw and evoked data objects.
Short Pandas Primer
Pandas Data Frames
~~~~~~~~~~~~~~~~~~
A data frame can be thought of as a combination of matrix, list and dict:
It knows about linear algebra and element-wise operations but is size mutable
and allows for labeled access to its data. In addition, the pandas data frame
class provides many useful methods for restructuring, reshaping and visualizing
data. As most methods return data frame instances, operations can be chained
with ease; this allows to write efficient one-liners. Technically a DataFrame
can be seen as a high-level container for numpy arrays and hence switching
back and forth between numpy arrays and DataFrames is very easy.
Taken together, these features qualify data frames for inter operation with
databases and for interactive data exploration / analysis.
Additionally, pandas interfaces with the R statistical computing language that
covers a huge amount of statistical functionality.
Export Options
~~~~~~~~~~~~~~
The pandas exporter comes with a few options worth being commented.
Pandas DataFrame objects use a so called hierarchical index. This can be
thought of as an array of unique tuples, in our case, representing the higher
dimensional MEG data in a 2D data table. The column names are the channel names
from the epoch object. The channels can be accessed like entries of a
dictionary:
df['MEG 2333']

Epochs and time slices can be accessed with the .ix method:
epochs_df.ix[(1, 2), 'MEG 2333']

However, it is also possible to include this index as regular categorial data
columns which yields a long table format typically used for repeated measure
designs. To take control of this feature, on export, you can specify which
of the three...
Can you write Python code for it?

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

import mne
import matplotlib.pyplot as plt
import numpy as np
from mne.datasets import sample

print(__doc__)

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'

raw = mne.io.read_raw_fif(raw_fname)
raw.set_eeg_reference()  # set EEG average reference

# For simplicity we will only consider the first 10 epochs
events = mne.read_events(event_fname)[:10]

# Add a bad channel
raw.info['bads'] += ['MEG 2443']
picks = mne.pick_types(raw.info, meg='grad', eeg=False, eog=True,
                       stim=False, exclude='bads')

tmin, tmax = -0.2, 0.5
baseline = (None, 0)
reject = dict(grad=4000e-13, eog=150e-6)

event_id = dict(auditory_l=1, auditory_r=2, visual_l=3, visual_r=4)

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


I am working on the file "0.14/_downloads/plot_estimate_covariance_matrix_baseline.ipynb".
The first task is:
Estimate covariance matrix from Epochs baseline
We first define a set of Epochs from events and a raw file.
Then we estimate the noise covariance of prestimulus data,
a.k.a. baseline.
Can you write Python code for it?

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

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

print(__doc__)

data_path = sample.data_path()
fname = data_path + '/MEG/sample/sample_audvis_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

raw = io.Raw(fname)


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

raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'

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

#   Set up pick list: EEG + STI 014 - bad channels (modify to your needs)
include = []  # or stim channels ['STI 014']
raw.info['bads'] += ['EEG 053']  # bads + 1 more

# pick EEG channels
picks = mne.pick_types(raw.info, meg=True, eeg=True, stim=False, eog=True,
                       include=include, exclude='bads')
# Read epochs, with proj off by default so we can plot either way later
reject = dict(grad=4000e-13, mag=4e-12, eeg=80e-6, eog=150e-6)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject, proj=False)

# Compute the covariance on baseline
cov = mne.compute_covariance(epochs, tmin=None, tmax=0)
print(cov)


I am working on the file "0.14/_downloads/plot_evoked_erf_erp.ipynb".
The first task is:
=================================
Plotting ERF/ERP with evoked data
=================================
Load evoked data and plot.
Can you write Python code for it?

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

import matplotlib.pyplot as plt
from mne.datasets import sample
from mne import read_evokeds

print(__doc__)

path = sample.data_path()
fname = path + '/MEG/sample/sample_audvis-ave.fif'

# load evoked and subtract baseline
condition = 'Left Auditory'
evoked = read_evokeds(fname, condition=condition, baseline=(None, 0))

# Plot the evoked response with spatially color coded lines.
# Note: You can paint the area with left mouse button to show the topographic
# map of the N100.
evoked.plot(spatial_colors=True)


I am working on the file "0.14/_downloads/plot_evoked_erf_erp.ipynb".
The first task is:
Or plot manually after extracting peak latency
Can you write Python code for it?

evoked = evoked.pick_types(meg=False, eeg=True)
times = 1e3 * evoked.times  # time in milliseconds

ch_max_name, latency = evoked.get_peak(mode='neg')

plt.figure()
plt.plot(times, 1e6 * evoked.data.T, 'k-')
plt.xlim([times[0], times[-1]])
plt.xlabel('time (ms)')
plt.ylabel('Potential (uV)')
plt.title('EEG evoked potential')

plt.axvline(latency * 1e3, color='red',
            label=ch_max_name, linewidth=2,
            linestyle='--')
plt.legend(loc='best')

plt.show()


I am working on the file "0.14/_downloads/plot_evoked_topomap_delayed_ssp.ipynb".
The first task is:
Interactively select / deselect the SSP projection vectors
Can you write Python code for it?

# set time instants in seconds (from 50 to 150ms in a step of 10ms)
times = np.arange(0.05, 0.15, 0.01)

evoked.plot_topomap(times, proj='interactive')
# Hint: the same works for evoked.plot and evoked.plot_topo


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

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

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

# delete EEG projections (we know it's the last one)
raw.del_proj(-1)
# add ECG projs for magnetometers
[raw.add_proj(p) for p in mne.read_proj(ecg_fname) if 'axial' in p['desc']]

# pick magnetometer channels
picks = mne.pick_types(raw.info, meg='mag', stim=False, eog=True,
                       include=[], exclude='bads')

# We will make of the proj `delayed` option to
# interactively select projections at the evoked stage.
# more information can be found in the example/plot_evoked_delayed_ssp.py
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=dict(mag=4e-12), proj='delayed')

evoked = epochs.average()  # average epochs and get an Evoked dataset.


I am working on the file "0.14/_downloads/plot_evoked_whitening.ipynb".
The first task is:
Show whitening
Can you write Python code for it?

evoked = epochs.average()

evoked.plot()  # plot evoked response

# plot the whitened evoked data for to see if baseline signals match the
# assumption of Gaussian white noise from which we expect values around
# 0 with less than 2 standard deviations. For the Global field power we expect
# a value of 1.

evoked.plot_white(noise_covs)


I am working on the file "0.14/_downloads/plot_fdr_stats_evoked.ipynb".
The first task is:
Compute statistic
Can you write Python code for it?

T, pval = stats.ttest_1samp(X, 0)
alpha = 0.05

n_samples, n_tests = X.shape
threshold_uncorrected = stats.t.ppf(1.0 - alpha, n_samples - 1)

reject_bonferroni, pval_bonferroni = bonferroni_correction(pval, alpha=alpha)
threshold_bonferroni = stats.t.ppf(1.0 - alpha / n_tests, n_samples - 1)

reject_fdr, pval_fdr = fdr_correction(pval, alpha=alpha, method='indep')
threshold_fdr = np.min(np.abs(T)[reject_fdr])


I am working on the file "0.14/_downloads/plot_forward.ipynb".
The first task is:
Compute Source Space
The source space defines the position of the candidate source locations.
The following code compute such a cortical source space with
an OCT-6 resolution.
See setting_up_source_space for details on source space definition
and spacing parameter.
Can you write Python code for it?

src = mne.setup_source_space(subject, spacing='oct6',
                             subjects_dir=subjects_dir,
                             add_dist=False, overwrite=True)
print(src)


I am working on the file "0.14/_downloads/plot_forward.ipynb".
The first task is:
Computing the forward operator
To compute a forward operator we need:

a -trans.fif file that contains the coregistration info.
a source space
the BEM surfaces

Compute and visualize BEM surfaces
The BEM surfaces are the triangulations of the interfaces between different
tissues needed for forward computation. These surfaces are for example
the inner skull surface, the outer skull surface and the outer skill
surface.
Computing the BEM surfaces requires FreeSurfer and makes use of either of
the two following command line tools:

gen_mne_watershed_bem
gen_mne_flash_bem

Here we'll assume it's already computed. It takes a few minutes per subject.
For EEG we use 3 layers (inner skull, outer skull, and skin) while for
MEG 1 layer (inner skull) is enough.
Let's look at these surfaces. The function :func:mne.viz.plot_bem
assumes that you have the the bem folder of your subject FreeSurfer
reconstruction the necessary files.
Can you write Python code for it?

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


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

import mne
from mne.datasets import sample
data_path = sample.data_path()

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


I am working on the file "0.14/_downloads/plot_forward.ipynb".
The first task is:
However, only sources that lie in the plotted MRI slices are shown.
Let's write a few lines of mayavi to see all sources.
Can you write Python code for it?

import numpy as np  # noqa
from mayavi import mlab  # noqa
from surfer import Brain  # noqa

brain = Brain('sample', 'lh', 'inflated', subjects_dir=subjects_dir)
surf = brain._geo

vertidx = np.where(src[0]['inuse'])[0]

mlab.points3d(surf.x[vertidx], surf.y[vertidx],
              surf.z[vertidx], color=(1, 1, 0), scale_factor=1.5)


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

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


I am working on the file "0.14/_downloads/plot_forward.ipynb".
The first task is:
Visualization the coregistration
The coregistration is operation that allows to position the head and the
sensors in a common coordinate system. In the MNE software the transformation
to align the head and the sensors in stored in a so-called trans file.
It is a FIF file that ends with -trans.fif. It can be obtained with
mne_analyze (Unix tools), mne.gui.coregistration (in Python) or mrilab
if you're using a Neuromag system.
For the Python version see func:mne.gui.coregistration
Here we assume the coregistration is done, so we just visually check the
alignment with the following code.
Can you write Python code for it?

# The transformation file obtained by coregistration
trans = data_path + '/MEG/sample/sample_audvis_raw-trans.fif'

info = mne.io.read_info(raw_fname)
mne.viz.plot_trans(info, trans, subject=subject, dig=True,
                   meg_sensors=True, subjects_dir=subjects_dir)


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

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


I am working on the file "0.14/_downloads/plot_forward_sensitivity_maps.ipynb".
The first task is:
Compute sensitivity maps
Can you write Python code for it?

grad_map = mne.sensitivity_map(fwd, ch_type='grad', mode='fixed')
mag_map = mne.sensitivity_map(fwd, ch_type='mag', mode='fixed')
eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed')


I am working on the file "0.14/_downloads/plot_forward_sensitivity_maps.ipynb".
The first task is:
Display sensitivity maps for EEG and MEG sensors
Sensitivity maps can be produced from forward operators that
indicate how well different sensor types will be able to detect
neural currents from different regions of the brain.
To get started with forward modeling see ref:tut_forward.
Can you write Python code for it?

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

import mne
from mne.datasets import sample
import matplotlib.pyplot as plt

print(__doc__)

data_path = sample.data_path()

raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'

subjects_dir = data_path + '/subjects'

# Read the forward solutions with surface orientation
fwd = mne.read_forward_solution(fwd_fname, surf_ori=True)
leadfield = fwd['sol']['data']
print("Leadfield size : %d x %d" % leadfield.shape)


I am working on the file "0.14/_downloads/plot_forward_sensitivity_maps.ipynb".
The first task is:
Show gain matrix a.k.a. leadfield matrix with sensitivity map
Can you write Python code for it?

picks_meg = mne.pick_types(fwd['info'], meg=True, eeg=False)
picks_eeg = mne.pick_types(fwd['info'], meg=False, eeg=True)

fig, axes = plt.subplots(2, 1, figsize=(10, 8), sharex=True)
fig.suptitle('Lead field matrix (500 dipoles only)', fontsize=14)
for ax, picks, ch_type in zip(axes, [picks_meg, picks_eeg], ['meg', 'eeg']):
    im = ax.imshow(leadfield[picks, :500], origin='lower', aspect='auto',
                   cmap='RdBu_r')
    ax.set_title(ch_type.upper())
    ax.set_xlabel('sources')
    ax.set_ylabel('sensors')
    plt.colorbar(im, ax=ax, cmap='RdBu_r')
plt.show()

plt.figure()
plt.hist([grad_map.data.ravel(), mag_map.data.ravel(), eeg_map.data.ravel()],
         bins=20, label=['Gradiometers', 'Magnetometers', 'EEG'],
         color=['c', 'b', 'k'])
plt.legend()
plt.title('Normal orientation sensitivity')
plt.xlabel('sensitivity')
plt.ylabel('count')
plt.show()

grad_map.plot(time_label='Gradiometer sensitivity', subjects_dir=subjects_dir,
              clim=dict(lims=[0, 50, 100]))


I am working on the file "0.14/_downloads/plot_from_raw_to_epochs_to_evoked.ipynb".
The first task is:
========================================================
Extract epochs, average and save evoked response to disk
========================================================
This script shows how to read the epochs from a raw file given
a list of events. The epochs are averaged to produce evoked
data and then saved to disk.
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Denis A. Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)

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

print(__doc__)

data_path = sample.data_path()


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

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

# Select events to extract epochs from.
event_id = {'Auditory/Left': 1, 'Auditory/Right': 2}

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

#   Plot raw data
raw.plot(events=events, event_color={1: 'cyan', -1: 'lightgray'})

#   Set up pick list: EEG + STI 014 - bad channels (modify to your needs)
include = []  # or stim channels ['STI 014']
raw.info['bads'] = ['MEG 2443', 'EEG 053']  # set bads

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

# Plot epochs.
epochs.plot(title='Auditory left/right')

# Look at channels that caused dropped events, showing that the subject's
# blinks were likely to blame for most epochs being dropped
epochs.drop_bad_epochs()
epochs.plot_drop_log(subject='sample')

# Average epochs and get evoked data corresponding to the left stimulation
evoked = epochs['Left'].average()

evoked.save('sample_audvis_eeg-ave.fif')  # save evoked data to disk


I am working on the file "0.14/_downloads/plot_from_raw_to_epochs_to_evoked.ipynb".
The first task is:
View evoked response
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_head_positions.ipynb".
The first task is:
Or we can visualize them as a continuous field (with the vectors pointing
in the head-upward direction):
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_head_positions.ipynb".
The first task is:
Visualize subject head movement
Show how subjects move as a function of time.
Can you write Python code for it?

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

from os import path as op

import mne

print(__doc__)

data_path = op.join(mne.datasets.testing.data_path(verbose=True), 'SSS')

pos = mne.chpi.read_head_pos(op.join(data_path, 'test_move_anon_raw.pos'))


I am working on the file "0.14/_downloads/plot_head_positions.ipynb".
The first task is:
Visualize the subject head movements as traces:
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_ica_from_raw.ipynb".
The first task is:
2) identify bad components by analyzing latent sources.
Can you write Python code for it?

title = 'Sources related to %s artifacts (red)'

# generate ECG epochs use detection via phase statistics

ecg_epochs = create_ecg_epochs(raw, tmin=-.5, tmax=.5, picks=picks)

ecg_inds, scores = ica.find_bads_ecg(ecg_epochs, method='ctps')
ica.plot_scores(scores, exclude=ecg_inds, title=title % 'ecg', labels='ecg')

show_picks = np.abs(scores).argsort()[::-1][:5]

ica.plot_sources(raw, show_picks, exclude=ecg_inds, title=title % 'ecg')
ica.plot_components(ecg_inds, title=title % 'ecg', colorbar=True)

ecg_inds = ecg_inds[:n_max_ecg]
ica.exclude += ecg_inds

# detect EOG by correlation

eog_inds, scores = ica.find_bads_eog(raw)
ica.plot_scores(scores, exclude=eog_inds, title=title % 'eog', labels='eog')

show_picks = np.abs(scores).argsort()[::-1][:5]

ica.plot_sources(raw, show_picks, exclude=eog_inds, title=title % 'eog')
ica.plot_components(eog_inds, title=title % 'eog', colorbar=True)

eog_inds = eog_inds[:n_max_eog]
ica.exclude += eog_inds


I am working on the file "0.14/_downloads/plot_ica_from_raw.ipynb".
The first task is:
3) Assess component selection and unmixing quality.
Can you write Python code for it?

# estimate average artifact
ecg_evoked = ecg_epochs.average()
ica.plot_sources(ecg_evoked, exclude=ecg_inds)  # plot ECG sources + selection
ica.plot_overlay(ecg_evoked, exclude=ecg_inds)  # plot ECG cleaning

eog_evoked = create_eog_epochs(raw, tmin=-.5, tmax=.5, picks=picks).average()
ica.plot_sources(eog_evoked, exclude=eog_inds)  # plot EOG sources + selection
ica.plot_overlay(eog_evoked, exclude=eog_inds)  # plot EOG cleaning

# check the amplitudes do not change
ica.plot_overlay(raw)  # EOG artifacts remain

# To save an ICA solution you can say:
# ica.save('my_ica.fif')

# You can later load the solution by saying:
# from mne.preprocessing import read_ica
# read_ica('my_ica.fif')

# Apply the solution to Raw, Epochs or Evoked like this:
# ica.apply(epochs)


I am working on the file "0.14/_downloads/plot_ica_from_raw.ipynb".
The first task is:
Compute ICA on MEG data and remove artifacts
ICA is fit to MEG raw data.
The sources matching the ECG and EOG are automatically found and displayed.
Subsequently, artifact detection and rejection quality are assessed.
Can you write Python code for it?

# Authors: Denis Engemann <denis.engemann@gmail.com>
#          Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)

import numpy as np

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


I am working on the file "0.14/_downloads/plot_ica_from_raw.ipynb".
The first task is:
Setup paths and prepare raw data.
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'

raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.filter(1, 45, n_jobs=1, l_trans_bandwidth=0.5, h_trans_bandwidth=0.5,
           filter_length='10s', phase='zero-double')
raw.annotations = mne.Annotations([1], [10], 'BAD')
raw.plot(block=True)

# For the sake of example we annotate first 10 seconds of the recording as
# 'BAD'. This part of data is excluded from the ICA decomposition by default.
# To turn this behavior off, pass ``reject_by_annotation=False`` to
# :meth:`mne.preprocessing.ICA.fit`.
raw.annotations = mne.Annotations([0], [10], 'BAD')


I am working on the file "0.14/_downloads/plot_info.ipynb".
The first task is:
Get a dictionary of channel indices, grouped by channel type
Can you write Python code for it?

channel_indices_by_type = mne.io.pick.channel_indices_by_type(info)
print('The first three magnetometers:', channel_indices_by_type['mag'][:3])


I am working on the file "0.14/_downloads/plot_info.ipynb".
The first task is:
Get channel indices by regular expression
Can you write Python code for it?

channel_indices = mne.pick_channels_regexp(info['ch_names'], 'MEG *')


I am working on the file "0.14/_downloads/plot_info.ipynb".
The first task is:
Get channel indices by type
Can you write Python code for it?

channel_indices = mne.pick_types(info, meg=True)  # MEG only
channel_indices = mne.pick_types(info, eeg=True)  # EEG only


I am working on the file "0.14/_downloads/plot_info.ipynb".
The first task is:
List all the fields in the info object
Can you write Python code for it?

print('Keys in info dictionary:\n', info.keys())


I am working on the file "0.14/_downloads/plot_info.ipynb".
The first task is:
Obtain the sampling rate of the data
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_info.ipynb".
The first task is:
Obtaining information about channels
Can you write Python code for it?

# Channel type of a specific channel
channel_type = mne.io.pick.channel_type(info, 75)
print('Channel #75 is of type:', channel_type)


I am working on the file "0.14/_downloads/plot_info.ipynb".
The first task is:
Obtaining subsets of channels
There are a number of convenience functions to obtain channel indices, given
an :class:mne.Info object.
Get channel indices by name
Can you write Python code for it?

channel_indices = mne.pick_channels(info['ch_names'], ['MEG 0312', 'EEG 005'])


I am working on the file "0.14/_downloads/plot_info.ipynb".
The first task is:
The :class:Info <mne.Info> data structure
Can you write Python code for it?

from __future__ import print_function

import mne
import os.path as op


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:

Note

The MNE sample dataset should be downloaded automatically but be
          patient (approx. 2GB)

Read data from file:
Can you write Python code for it?

raw = mne.io.read_raw_fif(raw_fname)
print(raw)
print(raw.info)


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Alternatively one can restrict to magnetometers or gradiometers with:
Can you write Python code for it?

mag_picks = mne.pick_types(raw.info, meg='mag', eog=True, exclude='bads')
grad_picks = mne.pick_types(raw.info, meg='grad', eog=True, exclude='bads')


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
But it's generally a good idea to leave them on:
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
By default logging messages print to the console, but look at
:func:mne.set_log_file to save output to a file.
Access raw data
^^^^^^^^^^^^^^^
Can you write Python code for it?

from mne.datasets import sample  # noqa
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
print(raw_fname)


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Compute evoked responses for auditory responses by averaging and plot it:
Can you write Python code for it?

evoked = epochs['aud_l'].average()
print(evoked)
evoked.plot()


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Compute induced power and phase-locking values and plot gradiometers:
Can you write Python code for it?

from mne.time_frequency import tfr_morlet  # noqa
power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles,
                        return_itc=True, decim=3, n_jobs=1)
power.plot([power.ch_names.index('MEG 1332')])


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Compute inverse solution during the first 15s:
Can you write Python code for it?

from mne.minimum_norm import apply_inverse_raw  # noqa
start, stop = raw.time_as_index([0, 15])  # read the first 15s of data
stc = apply_inverse_raw(raw, inverse_operator, lambda2, method, label,
                        start, stop)


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Define and read epochs
^^^^^^^^^^^^^^^^^^^^^^
First extract events:
Can you write Python code for it?

events = mne.find_events(raw, stim_channel='STI 014')
print(events[:5])


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Define peak-to-peak rejection parameters for gradiometers, magnetometers
and EOG:
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Define the baseline period:
Can you write Python code for it?

baseline = (None, 0)  # means from the first instant to t = 0


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

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


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Events are stored as a 2D numpy array where the first column is the time
instant and the last one is the event number. It is therefore easy to
manipulate.
Define epochs parameters:
Can you write Python code for it?

event_id = dict(aud_l=1, aud_r=2)  # event trigger and conditions
tmin = -0.2  # start of each epoch (200ms before the trigger)
tmax = 0.5  # end of each epoch (500ms after the trigger)


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Get single epochs for one condition:
Can you write Python code for it?

epochs_data = epochs['aud_l'].get_data()
print(epochs_data.shape)


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
If you'd like to turn information status messages off:
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Instead of dealing with mismatches in the number of averages, we can use
trial-count equalization before computing a contrast, which can have some
benefits in inverse imaging (note that here weights='nave' will
give the same result as weights='equal'):
Can you write Python code for it?

epochs_eq = epochs.copy().equalize_event_counts(['aud_l', 'aud_r'])[0]
evoked1, evoked2 = epochs_eq['aud_l'].average(), epochs_eq['aud_r'].average()
print(evoked1)
print(evoked2)
contrast = mne.combine_evoked([evoked1, -evoked2], weights='equal')
print(contrast)


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Inverse modeling: MNE and dSPM on evoked and raw data
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Import the required functions:
Can you write Python code for it?

from mne.minimum_norm import apply_inverse, read_inverse_operator  # noqa


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
It is also possible to read evoked data stored in a fif file:
Can you write Python code for it?

evoked_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
evoked1 = mne.read_evokeds(
    evoked_fname, condition='Left Auditory', baseline=(None, 0), proj=True)


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Look at the channels in raw:
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Note that the location of the mne-python preferences file (for easier manual
editing) can be found using:
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Now, let's compute dSPM on a raw file within a label:
Can you write Python code for it?

fname_label = data_path + '/MEG/sample/labels/Aud-lh.label'
label = mne.read_label(fname_label)


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Read and plot a segment of raw data
Can you write Python code for it?

start, stop = raw.time_as_index([100, 115])  # 100 s to 115 s data segment
data, times = raw[:, start:stop]
print(data.shape)
print(times.shape)
data, times = raw[2:20:3, start:stop]  # access underlying data
raw.plot()


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Save a segment of 150s of raw data (MEG only):
Can you write Python code for it?

picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True,
                       exclude='bads')
raw.save('sample_audvis_meg_raw.fif', tmin=0, tmax=150, picks=picks,
         overwrite=True)


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Save result in stc files:
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
The variable raw.info['bads'] is just a python list.
Pick the good channels, excluding raw.info['bads']:
Can you write Python code for it?

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


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
Time-Frequency: Induced power and inter trial coherence
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Define parameters:
Can you write Python code for it?

import numpy as np  # noqa
n_cycles = 2  # number of cycles in Morlet wavelet
freqs = np.arange(7, 30, 3)  # frequencies of interest


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
What else can you do?
^^^^^^^^^^^^^^^^^^^^^
- detect heart beat QRS component
- detect eye blinks and EOG artifacts
- compute SSP projections to remove ECG or EOG artifacts
- compute Independent Component Analysis (ICA) to remove artifacts or
  select latent sources
- estimate noise covariance matrix from Raw and Epochs
- visualize cross-trial response dynamics using epochs images
- compute forward solutions
- estimate power in the source space
- estimate connectivity in sensor and source space
- morph stc from one brain to another for group studies
- compute mass univariate statistics base on custom contrasts
- visualize source estimates
- export raw, epochs, and evoked data to other python data analysis
  libraries e.g. pandas
- and many more things ...

Want to know more ?
^^^^^^^^^^^^^^^^^^^
Browse the examples gallery <auto_examples/index.html>_.
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
and read them later with:
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_introduction.ipynb".
The first task is:
epochs_data is a 3D array of dimension (55 epochs, 365 channels, 106 time
instants).
Scipy supports read and write of matlab files. You can save your single
trials with:
Can you write Python code for it?

from scipy import io  # noqa
io.savemat('epochs_data.mat', dict(epochs_data=epochs_data), oned_as='row')


I am working on the file "0.14/_downloads/plot_label_from_stc.ipynb".
The first task is:
Generate a functional label from source estimates
Threshold source estimates and produce a functional label. The label
is typically the region of interest that contains high values.
Here we compare the average time course in the anatomical label obtained
by FreeSurfer segmentation and the average time course from the
functional label. As expected the time course in the functional
label yields higher values.
Can you write Python code for it?

# Author: Luke Bloy <luke.bloy@gmail.com>
#         Alex Gramfort <alexandre.gramfort@telecom-paristech.fr>
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

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

print(__doc__)

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
subjects_dir = data_path + '/subjects'
subject = 'sample'

snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

# Compute a label/ROI based on the peak power between 80 and 120 ms.
# The label bankssts-lh is used for the comparison.
aparc_label_name = 'bankssts-lh'
tmin, tmax = 0.080, 0.120

# Load data
evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
inverse_operator = read_inverse_operator(fname_inv)
src = inverse_operator['src']  # get the source space

# Compute inverse solution
stc = apply_inverse(evoked, inverse_operator, lambda2, method,
                    pick_ori='normal')

# Make an STC in the time interval of interest and take the mean
stc_mean = stc.copy().crop(tmin, tmax).mean()

# use the stc_mean to generate a functional label
# region growing is halted at 60% of the peak value within the
# anatomical label / ROI specified by aparc_label_name
label = mne.read_labels_from_annot(subject, parc='aparc',
                                   subjects_dir=subjects_dir,
                                   regexp=aparc_label_name)[0]
stc_mean_label = stc_mean.in_label(label)
data = np.abs(stc_mean_label.data)
stc_mean_label.data[data < 0.6 * np.max(data)] = 0.

func_labels, _ = mne.stc_to_label(stc_mean_label, src=src, smooth=True,
                                  subjects_dir=subjects_dir, connected=True)

# take first as func_labels are ordered based on maximum values in stc
func_label = func_labels[0]

# load the...


I am working on the file "0.14/_downloads/plot_label_from_stc.ipynb".
The first task is:
plot the time courses....
Can you write Python code for it?

plt.figure()
plt.plot(1e3 * stc_anat_label.times, pca_anat, 'k',
         label='Anatomical %s' % aparc_label_name)
plt.plot(1e3 * stc_func_label.times, pca_func, 'b',
         label='Functional %s' % aparc_label_name)
plt.legend()
plt.show()


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

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

import matplotlib.pyplot as plt
import numpy as np

import mne
from mne.datasets import sample
from mne.beamformer import lcmv

print(__doc__)

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


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

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

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

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

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

# Read epochs
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))
evoked = epochs.average()

forward = mne.read_forward_solution(fname_fwd)

# Read regularized noise covariance and compute regularized data covariance
noise_cov = mne.compute_covariance(epochs, tmin=tmin, tmax=0, method='shrunk')
data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15,
                                  method='shrunk')

# Run free orientation (vector) beamformer. Source orientation can be
# restricted by setting pick_ori to 'max-power' (or 'normal' but only when
# using a surface-based source space)
stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.05, pick_ori=None)

# Save result in stc files
stc.save('lcmv-vol')

stc.crop(0.0, 0.2)

# Save result in a 4D nifti file
img = mne.save_stc_as_volume('lcmv_inverse.nii.gz', stc,
                             forward['src'], mri_resolution=False)

t1_fname = data_path + '/subjects/sample/mri/T1.mgz'

# Plotting with nilearn ######################################################
plot_stat_map(index_img(img, 61), t1_fname, threshold=0.8,
              title='LCMV (t=%.1f s.)' % stc.times[61])

# plot source time courses with...


I am working on the file "0.14/_downloads/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 numpy as np
from scipy.spatial import ConvexHull
from mayavi import mlab
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'
subj = 'sample'
aseg_fname = subjects_dir + '/sample/mri/aseg.mgz'


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

# extract left cortical surface vertices, triangle faces, and surface normals
x1, y1, z1 = lh_surf['rr'].T
faces = lh_surf['use_tris']
normals = lh_surf['nn']
# normalize for mayavi
normals /= np.sum(normals * normals, axis=1)[:, np.newaxis]

# extract left cerebellum cortex source positions
x2, y2, z2 = lh_cereb[0]['rr'][lh_cereb[0]['inuse'].astype(bool)].T

# open a 3d figure in mayavi
mlab.figure(1, bgcolor=(0, 0, 0))

# plot the left cortical surface
mesh = mlab.pipeline.triangular_mesh_source(x1, y1, z1, faces)
mesh.data.point_data.normals = normals
mlab.pipeline.surface(mesh, color=3 * (0.7,))

# plot the convex hull bounding the left cerebellum
hull = ConvexHull(np.c_[x2, y2, z2])
mlab.triangular_mesh(x2, y2, z2, hull.simplices, color=3 * (0.5,), opacity=0.3)

# plot the left cerebellum sources
mlab.points3d(x2, y2, z2, color=(1, 1, 0), scale_factor=0.001)

# adjust view parameters
mlab.view(173.78, 101.75, 0.30, np.array([-0.03, -0.01,  0.03]))
mlab.roll(85)


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

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

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

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


I am working on the file "0.14/_downloads/plot_linear_model_patterns.ipynb".
The first task is:
Linear classifier on sensor data with plot patterns and filters
Decoding, a.k.a MVPA or supervised machine learning applied to MEG and EEG
data in sensor space. Fit a linear classifier with the LinearModel object
providing topographical patterns which are more neurophysiologically
interpretable [1]_ than the classifier filters (weight vectors).
The patterns explain how the MEG and EEG data were generated from the
discriminant neural sources which are extracted by the filters.
Note patterns/filters in MEG data are more similar than EEG data
because the noise is less spatially correlated in MEG than EEG.
References
.. [1] Haufe, S., Meinecke, F., Görgen, K., Dähne, S., Haynes, J.-D.,
       Blankertz, B., & Bießmann, F. (2014). On the interpretation of
       weight vectors of linear models in multivariate neuroimaging.
       NeuroImage, 87, 96–110. doi:10.1016/j.neuroimage.2013.10.067
Can you write Python code for it?

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

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

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

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

print(__doc__)

data_path = sample.data_path()


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

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

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

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

labels = epochs.events[:, -1]

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


I am working on the file "0.14/_downloads/plot_make_forward.ipynb".
The first task is:
Create a forward operator and display sensitivity maps
Sensitivity maps can be produced from forward operators that
indicate how well different sensor types will be able to detect
neural currents from different regions of the brain.
Can you write Python code for it?

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

import mne
from mne.datasets import sample
import matplotlib.pyplot as plt

print(__doc__)

data_path = sample.data_path()

raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
trans = data_path + '/MEG/sample/sample_audvis_raw-trans.fif'
src = data_path + '/subjects/sample/bem/sample-oct-6-src.fif'
bem = data_path + '/subjects/sample/bem/sample-5120-5120-5120-bem-sol.fif'
subjects_dir = data_path + '/subjects'

# Note that forward solutions can also be read with read_forward_solution
fwd = mne.make_forward_solution(raw_fname, trans, src, bem,
                                fname=None, meg=True, eeg=True, mindist=5.0,
                                n_jobs=2, overwrite=True)

# convert to surface orientation for better visualization
fwd = mne.convert_forward_solution(fwd, surf_ori=True)
leadfield = fwd['sol']['data']

print("Leadfield size : %d x %d" % leadfield.shape)

grad_map = mne.sensitivity_map(fwd, ch_type='grad', mode='fixed')
mag_map = mne.sensitivity_map(fwd, ch_type='mag', mode='fixed')
eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed')


I am working on the file "0.14/_downloads/plot_make_forward.ipynb".
The first task is:
Show gain matrix a.k.a. leadfield matrix with sensitivity map
Can you write Python code for it?

picks_meg = mne.pick_types(fwd['info'], meg=True, eeg=False)
picks_eeg = mne.pick_types(fwd['info'], meg=False, eeg=True)

fig, axes = plt.subplots(2, 1, figsize=(10, 8), sharex=True)
fig.suptitle('Lead field matrix (500 dipoles only)', fontsize=14)
for ax, picks, ch_type in zip(axes, [picks_meg, picks_eeg], ['meg', 'eeg']):
    im = ax.imshow(leadfield[picks, :500], origin='lower', aspect='auto',
                   cmap='RdBu_r')
    ax.set_title(ch_type.upper())
    ax.set_xlabel('sources')
    ax.set_ylabel('sensors')
    plt.colorbar(im, ax=ax, cmap='RdBu_r')
plt.show()

plt.figure()
plt.hist([grad_map.data.ravel(), mag_map.data.ravel(), eeg_map.data.ravel()],
         bins=20, label=['Gradiometers', 'Magnetometers', 'EEG'],
         color=['c', 'b', 'k'])
plt.legend()
plt.title('Normal orientation sensitivity')
plt.xlabel('sensitivity')
plt.ylabel('count')
plt.show()

grad_map.plot(time_label='Gradiometer sensitivity', subjects_dir=subjects_dir,
              clim=dict(lims=[0, 50, 100]))


I am working on the file "0.14/_downloads/plot_make_inverse_operator.ipynb".
The first task is:
Assemble inverse operator and compute MNE-dSPM inverse solution
Assemble M/EEG, MEG, and EEG inverse operators and compute dSPM
inverse solution on MNE evoked dataset and stores the solution
in stc files for visualisation.
Can you write Python code for it?

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

import matplotlib.pyplot as plt

import mne
from mne.datasets import sample
from mne.minimum_norm import (make_inverse_operator, apply_inverse,
                              write_inverse_operator)

print(__doc__)

data_path = sample.data_path()
fname_fwd_meeg = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
fname_fwd_eeg = data_path + '/MEG/sample/sample_audvis-eeg-oct-6-fwd.fif'
fname_cov = data_path + '/MEG/sample/sample_audvis-shrunk-cov.fif'
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'

snr = 3.0
lambda2 = 1.0 / snr ** 2

# Load data
evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
forward_meeg = mne.read_forward_solution(fname_fwd_meeg, surf_ori=True)
noise_cov = mne.read_cov(fname_cov)

# Restrict forward solution as necessary for MEG
forward_meg = mne.pick_types_forward(forward_meeg, meg=True, eeg=False)
# Alternatively, you can just load a forward solution that is restricted
forward_eeg = mne.read_forward_solution(fname_fwd_eeg, surf_ori=True)

# make an M/EEG, MEG-only, and EEG-only inverse operators
info = evoked.info
inverse_operator_meeg = make_inverse_operator(info, forward_meeg, noise_cov,
                                              loose=0.2, depth=0.8)
inverse_operator_meg = make_inverse_operator(info, forward_meg, noise_cov,
                                             loose=0.2, depth=0.8)
inverse_operator_eeg = make_inverse_operator(info, forward_eeg, noise_cov,
                                             loose=0.2, depth=0.8)

write_inverse_operator('sample_audvis-meeg-oct-6-inv.fif',
                       inverse_operator_meeg)
write_inverse_operator('sample_audvis-meg-oct-6-inv.fif',
                       inverse_operator_meg)
write_inverse_operator('sample_audvis-eeg-oct-6-inv.fif',
                       inverse_operator_eeg)

# Compute inverse solution
stcs = dict()
stcs['meeg'] = apply_inverse(evoked, inverse_operator_meeg,...


I am working on the file "0.14/_downloads/plot_make_inverse_operator.ipynb".
The first task is:
View activation time-series
Can you write Python code for it?

plt.close('all')
plt.figure(figsize=(8, 6))
for ii in range(len(stcs)):
    name = names[ii]
    stc = stcs[name]
    plt.subplot(len(stcs), 1, ii + 1)
    plt.plot(1e3 * stc.times, stc.data[::150, :].T)
    plt.ylabel('%s\ndSPM value' % str.upper(name))
plt.xlabel('time (ms)')
plt.show()


I am working on the file "0.14/_downloads/plot_maxwell_filter.ipynb".
The first task is:
Maxwell filter raw data
This example shows how to process M/EEG data with Maxwell filtering
in mne-python.
Can you write Python code for it?

# Authors: Eric Larson <larson.eric.d@gmail.com>
#          Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Mark Wronkiewicz <wronk.mark@gmail.com>
#
# License: BSD (3-clause)

import mne
from mne.preprocessing import maxwell_filter

print(__doc__)

data_path = mne.datasets.sample.data_path()


I am working on the file "0.14/_downloads/plot_mixed_norm_inverse.ipynb".
The first task is:
Run solver
Can you write Python code for it?

alpha = 50  # regularization parameter between 0 and 100 (100 is high)
loose, depth = 0.2, 0.9  # loose orientation & depth weighting
n_mxne_iter = 10  # if > 1 use L0.5/L2 reweighted mixed norm solver
# if n_mxne_iter > 1 dSPM weighting can be avoided.

# Compute dSPM solution to be used as weights in MxNE
inverse_operator = make_inverse_operator(evoked.info, forward, cov,
                                         loose=None, depth=depth, fixed=True)
stc_dspm = apply_inverse(evoked, inverse_operator, lambda2=1. / 9.,
                         method='dSPM')

# Compute (ir)MxNE inverse solution
stc, residual = mixed_norm(
    evoked, forward, cov, alpha, loose=loose, depth=depth, maxit=3000,
    tol=1e-4, active_set_size=10, debias=True, weights=stc_dspm,
    weights_min=8., n_mxne_iter=n_mxne_iter, return_residual=True)
residual.plot(ylim=ylim, proj=True)


I am working on the file "0.14/_downloads/plot_mixed_norm_inverse.ipynb".
The first task is:
View in 2D and 3D ("glass" brain like 3D plot)
Can you write Python code for it?

plot_sparse_source_estimates(forward['src'], stc, bgcolor=(1, 1, 1),
                             fig_name="MxNE (cond %s)" % condition,
                             opacity=0.1)

# and on the fsaverage brain after morphing
stc_fsaverage = stc.morph(subject_from='sample', subject_to='fsaverage',
                          grade=None, sparse=True, subjects_dir=subjects_dir)
src_fsaverage_fname = subjects_dir + '/fsaverage/bem/fsaverage-ico-5-src.fif'
src_fsaverage = mne.read_source_spaces(src_fsaverage_fname)

plot_sparse_source_estimates(src_fsaverage, stc_fsaverage, bgcolor=(1, 1, 1),
                             opacity=0.1)


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

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

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

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

from nilearn import plotting

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

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

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

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


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

method = "dSPM"
snr = 3.
lambda2 = 1. / snr ** 2
stc = apply_inverse(evoked, inverse_operator, lambda2,
                    method=method, pick_ori=None)

del fwd, inverse_operator, epochs  # to save memory


I am working on the file "0.14/_downloads/plot_mne_dspm_source_localization.ipynb".
The first task is:
Compute regularized noise covariance
For more details see tut_compute_covariance.
Can you write Python code for it?

noise_cov = mne.compute_covariance(
    epochs, tmax=0., method=['shrunk', 'empirical'])

fig_cov, fig_spectra = mne.viz.plot_cov(noise_cov, raw.info)


I am working on the file "0.14/_downloads/plot_mne_dspm_source_localization.ipynb".
The first task is:
Compute the evoked response
Can you write Python code for it?

evoked = epochs.average()
evoked.plot()
evoked.plot_topomap(times=np.linspace(0.05, 0.15, 5), ch_type='mag')

# Show whitening
evoked.plot_white(noise_cov)


I am working on the file "0.14/_downloads/plot_mne_dspm_source_localization.ipynb".
The first task is:
Inverse modeling: MNE/dSPM on evoked and raw data
Can you write Python code for it?

# Read the forward solution and compute the inverse operator

fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif'
fwd = mne.read_forward_solution(fname_fwd, surf_ori=True)

# Restrict forward solution as necessary for MEG
fwd = mne.pick_types_forward(fwd, meg=True, eeg=False)

# make an MEG inverse operator
info = evoked.info
inverse_operator = make_inverse_operator(info, fwd, noise_cov,
                                         loose=0.2, depth=0.8)

write_inverse_operator('sample_audvis-meg-oct-6-inv.fif',
                       inverse_operator)


I am working on the file "0.14/_downloads/plot_mne_dspm_source_localization.ipynb".
The first task is:
Process MEG data
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'

raw = mne.io.read_raw_fif(raw_fname)
raw.set_eeg_reference()  # set EEG average reference
events = mne.find_events(raw, stim_channel='STI 014')

event_id = dict(aud_r=1)  # event trigger and conditions
tmin = -0.2  # start of each epoch (200ms before the trigger)
tmax = 0.5  # end of each epoch (500ms after the trigger)
raw.info['bads'] = ['MEG 2443', 'EEG 053']
picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=True,
                       exclude='bads')
baseline = (None, 0)  # means from the first instant to t = 0
reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)

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


I am working on the file "0.14/_downloads/plot_mne_dspm_source_localization.ipynb".
The first task is:
Visualization
View activation time-series
Can you write Python code for it?

plt.plot(1e3 * stc.times, stc.data[::100, :].T)
plt.xlabel('time (ms)')
plt.ylabel('%s value' % method)
plt.show()


I am working on the file "0.14/_downloads/plot_modifying_data_inplace.ipynb".
The first task is:
In addition, there are functions for applying the Hilbert transform, which is
useful to calculate phase / amplitude of your signal.
Can you write Python code for it?

# Filter signal with a fairly steep filter, then take hilbert transform

raw_band = raw.copy()
raw_band.filter(12, 18, l_trans_bandwidth=2., h_trans_bandwidth=2.,
                filter_length='auto', phase='zero')
raw_hilb = raw_band.copy()
hilb_picks = mne.pick_types(raw_band.info, meg=False, eeg=True)
raw_hilb.apply_hilbert(hilb_picks)
print(raw_hilb._data.dtype)


I am working on the file "0.14/_downloads/plot_modifying_data_inplace.ipynb".
The first task is:
It is often necessary to modify data once you have loaded it into memory.
Common examples of this are signal processing, feature extraction, and data
cleaning. Some functionality is pre-built into MNE-python, though it is also
possible to apply an arbitrary function to the data.
Can you write Python code for it?

# Load an example dataset, the preload flag loads the data into memory now
data_path = op.join(mne.datasets.sample.data_path(), 'MEG',
                    'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(data_path, preload=True)
raw = raw.crop(0, 10)
print(raw)


I am working on the file "0.14/_downloads/plot_modifying_data_inplace.ipynb".
The first task is:
Modifying data in-place
Can you write Python code for it?

from __future__ import print_function

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


I am working on the file "0.14/_downloads/plot_movement_compensation.ipynb".
The first task is:
Maxwell filter data with movement compensation
Demonstrate movement compensation on simulated data. The simulated data
contains bilateral activation of auditory cortices, repeated over 14
different head rotations (head center held fixed). See the following for
details:
https://github.com/mne-tools/mne-misc-data/blob/master/movement/simulate.py
Can you write Python code for it?

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

from os import path as op

import mne
from mne.preprocessing import maxwell_filter

print(__doc__)

data_path = op.join(mne.datasets.misc.data_path(verbose=True), 'movement')

pos = mne.chpi.read_head_pos(op.join(data_path, 'simulated_quats.pos'))
raw = mne.io.read_raw_fif(op.join(data_path, 'simulated_movement_raw.fif'))
raw_stat = mne.io.read_raw_fif(op.join(data_path,
                                       'simulated_stationary_raw.fif'))


I am working on the file "0.14/_downloads/plot_movement_compensation.ipynb".
The first task is:
Visualize the "subject" head movements (traces)
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_object_epochs.ipynb".
The first task is:
:class:Epochs <mne.Epochs> objects are a way of representing continuous
data as a collection of time-locked trials, stored in an array of
shape(n_events, n_channels, n_times). They are useful for many statistical
methods in neuroscience, and make it easy to quickly overview what occurs
during a trial.
:class:Epochs <mne.Epochs> objects can be created in three ways:
 1. From a :class:Raw <mne.io.RawFIF> object, along with event times
 2. From an :class:Epochs <mne.Epochs> object that has been saved as a
    .fif file
 3. From scratch using :class:EpochsArray <mne.EpochsArray>. See
    tut_creating_data_structures
Can you write Python code for it?

data_path = mne.datasets.sample.data_path()
# Load a dataset that contains events
raw = mne.io.read_raw_fif(
    op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif'))

# If your raw object has a stim channel, you can construct an event array
# easily
events = mne.find_events(raw, stim_channel='STI 014')

# Show the number of events (number of rows)
print('Number of events:', len(events))

# Show all unique event codes (3rd column)
print('Unique event codes:', np.unique(events[:, 2]))

# Specify event codes of interest with descriptive labels.
# This dataset also has visual left (3) and right (4) events, but
# to save time and memory we'll just look at the auditory conditions
# for now.
event_id = {'Auditory/Left': 1, 'Auditory/Right': 2}


I am working on the file "0.14/_downloads/plot_object_epochs.ipynb".
The first task is:
Epochs behave similarly to :class:mne.io.Raw objects. They have an
:class:info <mne.Info> attribute that has all of the same
information, as well as a number of attributes unique to the events contained
within the object.
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_object_epochs.ipynb".
The first task is:
It is also possible to iterate through :class:Epochs <mne.Epochs> objects
in this way. Note that behavior is different if you iterate on Epochs
directly rather than indexing:
Can you write Python code for it?

# These will be epochs objects
for i in range(3):
    print(epochs[i])

# These will be arrays
for ep in epochs[:2]:
    print(ep)


I am working on the file "0.14/_downloads/plot_object_epochs.ipynb".
The first task is:
Later on you can read the epochs with :func:mne.read_epochs. For reading
EEGLAB epochs files see :func:mne.read_epochs_eeglab. We can also use
preload=False to save memory, loading the epochs from disk on demand.
Can you write Python code for it?

epochs = mne.read_epochs(epochs_fname, preload=False)


I am working on the file "0.14/_downloads/plot_object_epochs.ipynb".
The first task is:
Now, we can create an :class:mne.Epochs object with the events we've
extracted. Note that epochs constructed in this manner will not have their
data available until explicitly read into memory, which you can do with
:func:get_data <mne.Epochs.get_data>. Alternatively, you can use
preload=True.
Expose the raw data as epochs, cut from -0.1 s to 1.0 s relative to the event
onsets
Can you write Python code for it?

epochs = mne.Epochs(raw, events, event_id, tmin=-0.1, tmax=1,
                    baseline=(None, 0), preload=True)
print(epochs)


I am working on the file "0.14/_downloads/plot_object_epochs.ipynb".
The first task is:
The :class:Epochs <mne.Epochs> data structure: epoched data
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_object_epochs.ipynb".
The first task is:
You can manually remove epochs from the Epochs object by using
:func:epochs.drop(idx) <mne.Epochs.drop>, or by using rejection or flat
thresholds with :func:epochs.drop_bad(reject, flat) <mne.Epochs.drop_bad>.
You can also inspect the reason why epochs were dropped by looking at the
list stored in epochs.drop_log or plot them with
:func:epochs.plot_drop_log() <mne.Epochs.plot_drop_log>. The indices
from the original set of events are stored in epochs.selection.
Can you write Python code for it?

epochs.drop([0], reason='User reason')
epochs.drop_bad(reject=dict(grad=2500e-13, mag=4e-12, eog=200e-6), flat=None)
print(epochs.drop_log)
epochs.plot_drop_log()
print('Selection from original events:\n%s' % epochs.selection)
print('Removed events (from numpy setdiff1d):\n%s'
      % (np.setdiff1d(np.arange(len(events)), epochs.selection).tolist(),))
print('Removed events (from list comprehension -- should match!):\n%s'
      % ([li for li, log in enumerate(epochs.drop_log) if len(log) > 0]))


I am working on the file "0.14/_downloads/plot_object_epochs.ipynb".
The first task is:
You can select subsets of epochs by indexing the :class:Epochs <mne.Epochs>
object directly. Alternatively, if you have epoch names specified in
event_id then you may index with strings instead.
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_object_evoked.ipynb".
The first task is:
If you want to import evoked data from some other system and you have it in a
numpy array you can use :class:mne.EvokedArray for that. All you need is
the data and some info about the evoked data. For more information, see
tut_creating_data_structures.
Can you write Python code for it?

evoked = mne.EvokedArray(data, evoked.info, tmin=evoked.times[0])
evoked.plot()


I am working on the file "0.14/_downloads/plot_object_evoked.ipynb".
The first task is:
Notice that the reader function returned a list of evoked instances. This is
because you can store multiple categories into a single file. Here we have
categories of
['Left Auditory', 'Right Auditory', 'Left Visual', 'Right Visual'].
We can also use condition parameter to read in only one category.
Can you write Python code for it?

evoked = mne.read_evokeds(fname, condition='Left Auditory')
evoked.apply_baseline((None, 0)).apply_proj()
print(evoked)


I am working on the file "0.14/_downloads/plot_object_evoked.ipynb".
The first task is:
The :class:Evoked <mne.Evoked> data structure: evoked/averaged data
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_object_evoked.ipynb".
The first task is:
The data is also easily accessible. Since the evoked data arrays are usually
much smaller than raw or epochs datasets, they are preloaded into the memory
when the evoked object is constructed. You can access the data as a numpy
array.
Can you write Python code for it?


I am working on the file "0.14/_downloads/plot_object_raw.ipynb".
The first task is:
Concatenating :class:Raw <mne.io.Raw> objects
:class:Raw <mne.io.Raw> objects can be concatenated in time by using the
:func:append <mne.io.Raw.append> function. For this to work, they must
have the same number of channels and their :class:Info
<mne.Info> structures should be compatible.
Can you write Python code for it?

# Create multiple :class:`Raw <mne.io.RawFIF>` objects
raw1 = raw.copy().crop(0, 10)
raw2 = raw.copy().crop(10, 20)
raw3 = raw.copy().crop(20, 40)

# Concatenate in time (also works without preloading)
raw1.append([raw2, raw3])
print('Time extends from', raw1.times.min(), 's to', raw1.times.max(), 's')


I am working on the file "0.14/_downloads/plot_object_raw.ipynb".
The first task is:
Selecting subsets of channels and samples
It is possible to use more intelligent indexing to extract data, using
channel names, types or time ranges.
Can you write Python code for it?

# Pull all MEG gradiometer channels:
# Make sure to use .copy() or it will overwrite the data
meg_only = raw.copy().pick_types(meg=True)
eeg_only = raw.copy().pick_types(meg=False, eeg=True)

# The MEG flag in particular lets you specify a string for more specificity
grad_only = raw.copy().pick_types(meg='grad')

# Or you can use custom channel names
pick_chans = ['MEG 0112', 'MEG 0111', 'MEG 0122', 'MEG 0123']
specific_chans = raw.copy().pick_channels(pick_chans)
print(meg_only)
print(eeg_only)
print(grad_only)
print(specific_chans)


I am working on the file "0.14/_downloads/plot_object_raw.ipynb".
The first task is:
The :class:Raw <mne.io.Raw> data structure: continuous data
Can you write Python code for it?

from __future__ import print_function

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


I am working on the file "0.14/_downloads/plot_objects_from_arrays.ipynb".
The first task is:
Create a dummy :class:mne.io.RawArray object
Can you write Python code for it?

raw = mne.io.RawArray(data, info)

# Scaling of the figure.
# For actual EEG/MEG data different scaling factors should be used.
scalings = {'mag': 2, 'grad': 2}

raw.plot(n_channels=4, scalings=scalings, title='Data from arrays',
         show=True, block=True)

# It is also possible to auto-compute scalings
scalings = 'auto'  # Could also pass a dictionary with some value == 'auto'
raw.plot(n_channels=4, scalings=scalings, title='Auto-scaled Data from arrays',
         show=True, block=True)


I am working on the file "0.14/_downloads/plot_objects_from_arrays.ipynb".
The first task is:
Create arbitrary data
Can you write Python code for it?

sfreq = 1000  # Sampling frequency
times = np.arange(0, 10, 0.001)  # Use 10000 samples (10s)

sin = np.sin(times * 10)  # Multiplied by 10 for shorter cycles
cos = np.cos(times * 10)
sinX2 = sin * 2
cosX2 = cos * 2

# Numpy array of size 4 X 10000.
data = np.array([sin, cos, sinX2, cosX2])

# Definition of channel types and names.
ch_types = ['mag', 'mag', 'grad', 'grad']
ch_names = ['sin', 'cos', 'sinX2', 'cosX2']


I am working on the file "0.14/_downloads/plot_objects_from_arrays.ipynb".
The first task is:
Create epochs by windowing the raw data.
Can you write Python code for it?

# The events are spaced evenly every 1 second.
duration = 1.

# create a fixed size events array
# start=0 and stop=None by default
events = mne.make_fixed_length_events(raw, event_id, duration=duration)
print(events)

# for fixed size events no start time before and after event
tmin = 0.
tmax = 0.99  # inclusive tmax, 1 second epochs

# create :class:`Epochs <mne.Epochs>` object
epochs = mne.Epochs(raw, events=events, event_id=event_id, tmin=tmin,
                    tmax=tmax, baseline=None, verbose=True)
epochs.plot(scalings='auto', block=True)


I am working on the file "0.14/_downloads/plot_objects_from_arrays.ipynb".
The first task is:
Create overlapping epochs using :func:mne.make_fixed_length_events (50 %
overlap). This also roughly doubles the amount of events compared to the
previous event list.
Can you write Python code for it?

duration = 0.5
events = mne.make_fixed_length_events(raw, event_id, duration=duration)
print(events)
epochs = mne.Epochs(raw, events=events, tmin=tmin, tmax=tmax, baseline=None,
                    verbose=True)
epochs.plot(scalings='auto', block=True)


I am working on the file "0.14/_downloads/plot_objects_from_arrays.ipynb".
The first task is:
Creating MNE objects from data arrays
In this simple example, the creation of MNE objects from
numpy arrays is demonstrated. In the last example case, a
NEO file format is used as a source for the data.
Can you write Python code for it?

# Author: Jaakko Leppakangas <jaeilepp@student.jyu.fi>
#
# License: BSD (3-clause)

import numpy as np
import neo

import mne

print(__doc__)


I am working on the file "0.14/_downloads/plot_objects_from_arrays.ipynb".
The first task is:
EpochsArray
Can you write Python code for it?

event_id = 1  # This is used to identify the events.
# First column is for the sample number.
events = np.array([[200, 0, event_id],
                   [1200, 0, event_id],
                   [2000, 0, event_id]])  # List of three arbitrary events

# Here a data set of 700 ms epochs from 2 channels is
# created from sin and cos data.
# Any data in shape (n_epochs, n_channels, n_times) can be used.
epochs_data = np.array([[sin[:700], cos[:700]],
                        [sin[1000:1700], cos[1000:1700]],
                        [sin[1800:2500], cos[1800:2500]]])

ch_names = ['sin', 'cos']
ch_types = ['mag', 'mag']
info = mne.create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)

epochs = mne.EpochsArray(epochs_data, info=info, events=events,
                         event_id={'arbitrary': 1})

picks = mne.pick_types(info, meg=True, eeg=False, misc=False)

epochs.plot(picks=picks, scalings='auto', show=True, block=True)


I am working on the file "0.14/_downloads/plot_objects_from_arrays.ipynb".
The first task is:
EvokedArray
Can you write Python code for it?

nave = len(epochs_data)  # Number of averaged epochs
evoked_data = np.mean(epochs_data, axis=0)

evokeds = mne.EvokedArray(evoked_data, info=info, tmin=-0.2,
                          comment='Arbitrary', nave=nave)
evokeds.plot(picks=picks, show=True, units={'mag': '-'},
             titles={'mag': 'sin and cos averaged'})


I am working on the file "0.14/_downloads/plot_objects_from_arrays.ipynb".
The first task is:
Extracting data from NEO file
Can you write Python code for it?

# The example here uses the ExampleIO object for creating fake data.
# For actual data and different file formats, consult the NEO documentation.
reader = neo.io.ExampleIO('fakedata.nof')
bl = reader.read(cascade=True, lazy=False)[0]

# Get data from first (and only) segment
seg = bl.segments[0]
title = seg.file_origin

ch_names = list()
data = list()
for ai, asig in enumerate(seg.analogsignals):
    # Since the data does not contain channel names, channel indices are used.
    ch_names.append('Neo %02d' % (ai + 1,))
    # We need the ravel() here because Neo < 0.5 gave 1D, Neo 0.5 gives
    # 2D (but still a single channel).
    data.append(asig.rescale('V').magnitude.ravel())

data = np.array(data, float)

sfreq = int(seg.analogsignals[0].sampling_rate.magnitude)

# By default, the channel types are assumed to be 'misc'.
info = mne.create_info(ch_names=ch_names, sfreq=sfreq)

raw = mne.io.RawArray(data, info)
raw.plot(n_channels=4, scalings={'misc': 1}, title='Data from NEO',
         show=True, block=True, clipping='clamp')


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

import os.path as op

import numpy as np
from mayavi import mlab

import mne
from mne.datasets import sample

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


I am working on the file "0.14/_downloads/plot_point_spread.ipynb".
The first task is:
Estimate the background noise covariance from the baseline period
Can you write Python code for it?

cov = mne.compute_covariance(epochs, tmin=None, tmax=0.)


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

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

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

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

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


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

seed = 42

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

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

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

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


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

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