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

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

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


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

.. role:: pink
.. role:: blue
.. role:: gray
.. role:: magenta
.. role:: purple
.. role:: green
.. role:: red

Neuromag head coordinate frame ("head", :pink:pink axes)
     Defined by the intersection of 1) the line between the LPA
     (:red:red sphere) and RPA (:purple:purple sphere), and
     2) the line perpendicular to this LPA-RPA line one that goes through
     the Nasion (:green:green sphere).
     The axes are oriented as X origin→RPA, Y origin→Nasion,
     Z origin→upward (orthogonal to X and Y).
.. note:: This gets defined during the head digitization stage during
           acquisition, often by use of a Polhemus or other digitizer.

MEG device coordinate frame ("meg", :blue:blue axes)
     This is defined by the MEG manufacturers. From the Elekta user manual:
 The origin of the device coordinate system is located at the center
 of the posterior spherical section of the helmet with axis going
 from left to right and axis pointing front. The axis is, again
 normal to the plane with positive direction up.

.. note:: The device is coregistered with the head coordinate frame
           during acquisition via emission of sinusoidal currents in
           head position indicator (HPI) coils
           (:magenta:magenta spheres) at the beginning of the
           recording. This is stored in raw.info['dev_head_t'].

MRI coordinate frame ("mri", :gray:gray axes)
     Defined by Freesurfer, the MRI (surface RAS) origin is at the
     center of a 256×256×256 1mm anisotropic volume (may not be in the center
     of the head).
.. note:: This is aligned to the head coordinate frame that we
           typically...
Can you write Python code for it?

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


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

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

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


I am working on the file "0.18/_downloads/71cfddd254cf5ed46db1e09ba59a76f2/plot_source_alignment.ipynb".
The first task is:
It is quite clear that the MRI surfaces (head, brain) are not well aligned
to the head digitization points (dots).
A good example
Here is the same plot, this time with the trans properly defined
(using a precomputed matrix).
Can you write Python code for it?

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


I am working on the file "0.18/_downloads/71cfddd254cf5ed46db1e09ba59a76f2/plot_source_alignment.ipynb".
The first task is:
Understanding coordinate frames
For M/EEG source imaging, there are three coordinate frames that we must
bring into alignment using two 3D
transformation matrices <trans_matrices_>_
that define how to rotate and translate points in one coordinate frame
to their equivalent locations in another.
:func:mne.viz.plot_alignment is a very useful function for inspecting
these transformations, and the resulting alignment of EEG sensors, MEG
sensors, brain sources, and conductor models. If the subjects_dir and
subject parameters are provided, the function automatically looks for the
Freesurfer MRI surfaces to show from the subject's folder.
We can use the show_axes argument to see the various coordinate frames
given our transformation matrices. These are shown by axis arrows for each
coordinate frame:

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

i.e., a RAS coordinate system in each case. We can also set
the coord_frame argument to choose which coordinate
frame the camera should initially be aligned with.
Let's take a look:
Can you write Python code for it?

mne.viz.plot_alignment(raw.info, trans=trans, subject='sample',
                       subjects_dir=subjects_dir, surfaces='head-dense',
                       show_axes=True, dig=True, eeg=[], meg='sensors',
                       coord_frame='meg')
mlab.view(45, 90, distance=0.6, focalpoint=(0., 0., 0.))
print('Distance from head origin to MEG origin: %0.1f mm'
      % (1000 * np.linalg.norm(raw.info['dev_head_t']['trans'][:3, 3])))
print('Distance from head origin to MRI origin: %0.1f mm'
      % (1000 * np.linalg.norm(trans['trans'][:3, 3])))


I am working on the file "0.18/_downloads/73d54262ed918b5836ccb242d27450bb/plot_read_noise_covariance_matrix.ipynb".
The first task is:
=========================================
Reading/Writing a noise covariance matrix
=========================================
Plot a noise covariance matrix.
Can you write Python code for it?

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

from os import path as op
import mne
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()
fname_cov = op.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif')
fname_evo = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')

cov = mne.read_cov(fname_cov)
print(cov)
evoked = mne.read_evokeds(fname_evo)[0]


I am working on the file "0.18/_downloads/7b57fca16e7c12b88411529a749018d6/plot_sensors_decoding.ipynb".
The first task is:
Decoding over time
This strategy consists in fitting a multivariate predictive model on each
time instant and evaluating its performance at the same instant on new
epochs. The :class:mne.decoding.SlidingEstimator will take as input a
pair of features $X$ and targets $y$, where $X$ has
more than 2 dimensions. For decoding over time the data $X$
is the epochs data of shape n_epochs x n_channels x n_times. As the
last dimension of $X$ is the time, an estimator will be fit
on every time instant.
This approach is analogous to SlidingEstimator-based approaches in fMRI,
where here we are interested in when one can discriminate experimental
conditions and therefore figure out when the effect of interest happens.
When working with linear models as estimators, this approach boils
down to estimating a discriminative spatial filter for each time instant.
Temporal decoding
^^^^^^^^^^^^^^^^^
We'll use a Logistic Regression for a binary classification as machine
learning model.
Can you write Python code for it?

# We will train the classifier on all left visual vs auditory trials on MEG

clf = make_pipeline(StandardScaler(), LogisticRegression(solver='lbfgs'))

time_decod = SlidingEstimator(clf, n_jobs=1, scoring='roc_auc', verbose=True)
scores = cross_val_multiscore(time_decod, X, y, cv=5, n_jobs=1)

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

# Plot
fig, ax = plt.subplots()
ax.plot(epochs.times, scores, label='score')
ax.axhline(.5, color='k', linestyle='--', label='chance')
ax.set_xlabel('Times')
ax.set_ylabel('AUC')  # Area Under the Curve
ax.legend()
ax.axvline(.0, color='k', linestyle='-')
ax.set_title('Sensor space decoding')


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

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


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

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

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

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

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


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

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

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

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

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


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

Note

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

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

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

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

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


I am working on the file "0.18/_downloads/7bb2e6f1056f5cae3a98ccc12aac266f/plot_eeg_no_mri.ipynb".
The first task is:
Load the data
We use here EEG data from the BCI dataset.
Can you write Python code for it?

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

# Clean channel names to be able to use a standard 1005 montage
ch_names = [c.replace('.', '') for c in raw.ch_names]
raw.rename_channels({old: new for old, new in zip(raw.ch_names, ch_names)})

# Read and set the EEG electrode locations
montage = mne.channels.read_montage('standard_1005', ch_names=raw.ch_names,
                                    transform=True)

raw.set_montage(montage)
raw.set_eeg_reference(projection=True)  # needed for inverse modeling

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


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

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

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


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

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

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

Source-based source space is computed using
:func:mne.setup_source_space, while volumetric source space is computed
using :func:mne.setup_volume_source_space.
We will now compute a source-based 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)
print(src)


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

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


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

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

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


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

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


I am working on the file "0.18/_downloads/7df5cd97aa959dd7e2627aba5e552081/plot_forward.ipynb".
The first task is:
The surface based source space 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
in purple.
Can you write Python code for it?

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


I am working on the file "0.18/_downloads/7df5cd97aa959dd7e2627aba5e552081/plot_forward.ipynb".
The first task is:
This is equivalent to the following code that explicitly applies the
forward operator to a source estimate composed of the identity operator:
Can you write Python code for it?

n_dipoles = leadfield.shape[1]
vertices = [src_hemi['vertno'] for src_hemi in fwd_fixed['src']]
stc = mne.SourceEstimate(1e-9 * np.eye(n_dipoles), vertices, tmin=0., tstep=1)
leadfield = mne.apply_forward(fwd_fixed, stc, info).data / 1e-9


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

sphere = (0.0, 0.0, 40.0, 90.0)
vol_src = mne.setup_volume_source_space(subject, subjects_dir=subjects_dir,
                                        sphere=sphere)
print(vol_src)

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


I am working on the file "0.18/_downloads/7df5cd97aa959dd7e2627aba5e552081/plot_forward.ipynb".
The first task is:
To extract the numpy array containing the forward operator corresponding to
the source space fwd['src'] with cortical orientation constraint
we can use the following:
Can you write Python code for it?

fwd_fixed = mne.convert_forward_solution(fwd, surf_ori=True, force_fixed=True,
                                         use_cps=True)
leadfield = fwd_fixed['sol']['data']
print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape)


I am working on the file "0.18/_downloads/7df5cd97aa959dd7e2627aba5e552081/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
:func:mne.gui.coregistration (or its convenient command line
equivalent gen_mne_coreg), 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)
# Here we look at the dense head, which isn't used for BEM computations but
# is useful for coregistration.
mne.viz.plot_alignment(info, trans, subject=subject, dig=True,
                       meg=['helmet', 'sensors'], subjects_dir=subjects_dir,
                       surfaces='head-dense')


I am working on the file "0.18/_downloads/7df5cd97aa959dd7e2627aba5e552081/plot_forward.ipynb".
The first task is:
With the surface-based source space only sources that lie in the plotted MRI
slices are shown. Let's write a few lines of mayavi to see all sources in 3D.
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['lh']

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.18/_downloads/82dd66e6bdf7150b8691eaa46b63bcf9/plot_read_events.ipynb".
The first task is:
Events objects are essentially numpy arrays with three columns:
event_sample | previous_event_id | event_id
Can you write Python code for it?

print(events_1[:5], '\n\n---\n\n', events_1_2[:5], '\n\n')

for ind, before, after in events_1[:5]:
    print("At sample %d stim channel went from %d to %d"
          % (ind, before, after))


I am working on the file "0.18/_downloads/82dd66e6bdf7150b8691eaa46b63bcf9/plot_read_events.ipynb".
The first task is:
Plotting events
We can also plot events in order to visualize how events occur over the
course of our recording session. Below we'll plot our three event types
to see which ones were included.
Can you write Python code for it?

fig, axs = plt.subplots(1, 3, figsize=(15, 5))

mne.viz.plot_events(events_1, axes=axs[0], show=False)
axs[0].set(title="restricted to event 1")

mne.viz.plot_events(events_1_2, axes=axs[1], show=False)
axs[1].set(title="restricted to event 1 or 2")

mne.viz.plot_events(events_not_4_32, axes=axs[2], show=False)
axs[2].set(title="keep all but 4 and 32")
plt.setp([ax.get_xticklabels() for ax in axs], rotation=45)
plt.tight_layout()
plt.show()


I am working on the file "0.18/_downloads/82dd66e6bdf7150b8691eaa46b63bcf9/plot_read_events.ipynb".
The first task is:
Reading events
Below we'll read in an events file. We suggest that this file end in
-eve.fif. Note that we can read in the entire events file, or only
events corresponding to particular event types with the include and
exclude parameters.
Can you write Python code for it?

events_1 = mne.read_events(fname, include=1)
events_1_2 = mne.read_events(fname, include=[1, 2])
events_not_4_32 = mne.read_events(fname, exclude=[4, 32])


I am working on the file "0.18/_downloads/846c9103e2de535e71d8b76a75654d36/plot_background_statistics.ipynb".
The first task is:
Clustering
^^^^^^^^^^
Each of the aforementioned multiple comparisons corrections have the
disadvantage of not fully incorporating the correlation structure of the
data, namely that points close to one another (e.g., in space or time) tend
to be correlated. However, by defining the connectivity/adjacency/neighbor
structure in our data, we can use clustering to compensate.
To use this, we need to rethink our null hypothesis. Instead
of thinking about a null hypothesis about means per voxel (with one
independent test per voxel), we consider a null hypothesis about sizes
of clusters in our data, which could be stated like:
The distribution of spatial cluster sizes observed in two experimental
conditions are drawn from the same probability distribution.

Here we only have a single condition and we contrast to zero, which can
be thought of as:
The distribution of spatial cluster sizes is independent of the sign
of the data.

In this case, we again do permutations with a maximum statistic, but, under
each permutation, we:

Compute the test statistic for each voxel individually.
Threshold the test statistic values.
Cluster voxels that exceed this threshold (with the same sign) based on
   adjacency.
Retain the size of the largest cluster (measured, e.g., by a simple voxel
   count, or by the sum of voxel t-values within the cluster) to build the
   null distribution.

After doing these permutations, the cluster sizes in our veridical data
are compared to this null distribution. The p-value associated with each
cluster is again given by the proportion of smaller null distribution
values. This can then be subjected to a standard p-value threshold
(e.g., p < 0.05) to reject the null hypothesis (i.e., find an effect of
interest).
This reframing to consider cluster sizes rather than individual means
maintains the advantages of the standard non-parametric permutation
test -- namely controlling FWER and making no assumptions of parametric
data distribution.
Critically, though, it also accounts for the correlation structure...
Can you write Python code for it?

from sklearn.feature_extraction.image import grid_to_graph  # noqa: E402
mini_connectivity = grid_to_graph(3, 3).toarray()
assert mini_connectivity.shape == (9, 9)
print(mini_connectivity[0])


I am working on the file "0.18/_downloads/846c9103e2de535e71d8b76a75654d36/plot_background_statistics.ipynb".
The first task is:
Hypothesis testing
Null hypothesis
^^^^^^^^^^^^^^^
From Wikipedia <https://en.wikipedia.org/wiki/Null_hypothesis>__:
In inferential statistics, a general statement or default position that
there is no relationship between two measured phenomena, or no
association among groups.

We typically want to reject a null hypothesis with
some probability (e.g., p < 0.05). This probability is also called the
significance level $\alpha$.
To think about what this means, let's follow the illustrative example from
[1]_ and construct a toy dataset consisting of a 40 x 40 square with a
"signal" present in the center with white noise added and a Gaussian
smoothing kernel applied.
Can you write Python code for it?

width = 40
n_subjects = 10
signal_mean = 100
signal_sd = 100
noise_sd = 0.01
gaussian_sd = 5
sigma = 1e-3  # sigma for the "hat" method
n_permutations = 'all'  # run an exact test
n_src = width * width

# For each "subject", make a smoothed noisy signal with a centered peak
rng = np.random.RandomState(2)
X = noise_sd * rng.randn(n_subjects, width, width)
# Add a signal at the center
X[:, width // 2, width // 2] = signal_mean + rng.randn(n_subjects) * signal_sd
# Spatially smooth with a 2D Gaussian kernel
size = width // 2 - 1
gaussian = np.exp(-(np.arange(-size, size + 1) ** 2 / float(gaussian_sd ** 2)))
for si in range(X.shape[0]):
    for ri in range(X.shape[1]):
        X[si, ri, :] = np.convolve(X[si, ri, :], gaussian, 'same')
    for ci in range(X.shape[2]):
        X[si, :, ci] = np.convolve(X[si, :, ci], gaussian, 'same')


I am working on the file "0.18/_downloads/846c9103e2de535e71d8b76a75654d36/plot_background_statistics.ipynb".
The first task is:
In general the connectivity between voxels can be more complex, such as
those between sensors in 3D space, or time-varying activation at brain
vertices on a cortical surface. MNE provides several convenience functions
for computing connectivity/neighbor/adjacency matrices (see the
Statistics API <api_reference_statistics>).
Standard clustering
~~~~~~~~~~~~~~~~~~~
Here, since our data are on a grid, we can use connectivity=None to
trigger optimized grid-based code, and run the clustering algorithm.
Can you write Python code for it?

titles.append('Clustering')
# Reshape data to what is equivalent to (n_samples, n_space, n_time)
X.shape = (n_subjects, width, width)
# Compute threshold from t distribution (this is also the default)
threshold = stats.distributions.t.ppf(1 - alpha, n_subjects - 1)
t_clust, clusters, p_values, H0 = permutation_cluster_1samp_test(
    X, n_jobs=1, threshold=threshold, connectivity=None,
    n_permutations=n_permutations)
# Put the cluster data in a viewable format
p_clust = np.ones((width, width))
for cl, p in zip(clusters, p_values):
    p_clust[cl] = p
ts.append(t_clust)
ps.append(p_clust)
mccs.append(True)
plot_t_p(ts[-1], ps[-1], titles[-1], mccs[-1])


I am working on the file "0.18/_downloads/846c9103e2de535e71d8b76a75654d36/plot_background_statistics.ipynb".
The first task is:
In this case, a null hypothesis we could test for each voxel is:
There is no difference between the mean value and zero
($H_0 \colon \mu = 0$).

The alternative hypothesis, then, is that the voxel has a non-zero mean
($H_1 \colon \mu \neq 0$).
This is a two-tailed test because the mean could be less than
or greater than zero, whereas a one-tailed test would test only one of
these possibilities, i.e. $H_1 \colon \mu \geq 0$ or
$H_1 \colon \mu \leq 0$.

Note

Here we will refer to each spatial location as a "voxel".
          In general, though, it could be any sort of data value,
          including cortical vertex at a specific time, pixel in a
          time-frequency decomposition, etc.

Parametric tests
^^^^^^^^^^^^^^^^
Let's start with a paired t-test, which is a standard test
for differences in paired samples. Mathematically, it is equivalent
to a 1-sample t-test on the difference between the samples in each condition.
The paired t-test is parametric
because it assumes that the underlying sample distribution is Gaussian, and
is only valid in this case. This happens to be satisfied by our toy dataset,
but is not always satisfied for neuroimaging data.
In the context of our toy dataset, which has many voxels
($40 \cdot 40 = 1600$), applying the paired t-test is called a
mass-univariate approach as it treats each voxel independently.
Can you write Python code for it?

titles = ['t']
out = stats.ttest_1samp(X, 0, axis=0)
ts = [out[0]]
ps = [out[1]]
mccs = [False]  # these are not multiple-comparisons corrected

def plot_t_p(t, p, title, mcc, axes=None):
    if axes is None:
        fig = plt.figure(figsize=(6, 3))
        axes = [fig.add_subplot(121, projection='3d'), fig.add_subplot(122)]
        show = True
    else:
        show = False
    p_lims = [0.1, 0.001]
    t_lims = -stats.distributions.t.ppf(p_lims, n_subjects - 1)
    p_lims = [-np.log10(p) for p in p_lims]
    # t plot
    x, y = np.mgrid[0:width, 0:width]
    surf = axes[0].plot_surface(x, y, np.reshape(t, (width, width)),
                                rstride=1, cstride=1, linewidth=0,
                                vmin=t_lims[0], vmax=t_lims[1], cmap='viridis')
    axes[0].set(xticks=[], yticks=[], zticks=[],
                xlim=[0, width - 1], ylim=[0, width - 1])
    axes[0].view_init(30, 15)
    cbar = plt.colorbar(ax=axes[0], shrink=0.75, orientation='horizontal',
                        fraction=0.1, pad=0.025, mappable=surf)
    cbar.set_ticks(t_lims)
    cbar.set_ticklabels(['%0.1f' % t_lim for t_lim in t_lims])
    cbar.set_label('t-value')
    cbar.ax.get_xaxis().set_label_coords(0.5, -0.3)
    if not show:
        axes[0].set(title=title)
        if mcc:
            axes[0].title.set_weight('bold')
    # p plot
    use_p = -np.log10(np.reshape(np.maximum(p, 1e-5), (width, width)))
    img = axes[1].imshow(use_p, cmap='inferno', vmin=p_lims[0], vmax=p_lims[1],
                         interpolation='nearest')
    axes[1].set(xticks=[], yticks=[])
    cbar = plt.colorbar(ax=axes[1], shrink=0.75, orientation='horizontal',
                        fraction=0.1, pad=0.025, mappable=img)
    cbar.set_ticks(p_lims)
    cbar.set_ticklabels(['%0.1f' % p_lim for p_lim in p_lims])
    cbar.set_label(r'$-\log_{10}(p)$')
    cbar.ax.get_xaxis().set_label_coords(0.5, -0.3)
    if show:
        text = fig.suptitle(title)
        if mcc:
            text.set_weight('bold')
        plt.subplots_adjust(0,...


I am working on the file "0.18/_downloads/846c9103e2de535e71d8b76a75654d36/plot_background_statistics.ipynb".
The first task is:
Non-parametric tests
^^^^^^^^^^^^^^^^^^^^
Instead of assuming an underlying Gaussian distribution, we could instead
use a non-parametric resampling method. In the case of a paired t-test
between two conditions A and B, which is mathematically equivalent to a
one-sample t-test between the difference in the conditions A-B, under the
null hypothesis we have the principle of exchangeability. This means
that, if the null is true, we can exchange conditions and not change
the distribution of the test statistic.
When using a paired t-test, exchangeability thus means that we can flip the
signs of the difference between A and B. Therefore, we can construct the
null distribution values for each voxel by taking random subsets of
samples (subjects), flipping the sign of their difference, and recording the
absolute value of the resulting statistic (we record the absolute value
because we conduct a two-tailed test). The absolute value of the statistic
evaluated on the veridical data can then be compared to this distribution,
and the p-value is simply the proportion of null distribution values that
are smaller.

Warning

In the case of a true one-sample t-test, i.e. analyzing a single
             condition rather than the difference between two conditions,
             it is not clear where/how exchangeability applies; see
             `this FieldTrip discussion <ft_exch_>`_.

In the case where n_permutations is large enough (or "all") so
that the complete set of unique resampling exchanges can be done
(which is $2^{N_{samp}}-1$ for a one-tailed and
$2^{N_{samp}-1}-1$ for a two-tailed test, not counting the
veridical distribution), instead of randomly exchanging conditions
the null is formed from using all possible exchanges. This is known
as a permutation test (or exact test).
Can you write Python code for it?

# Here we have to do a bit of gymnastics to get our function to do
# a permutation test without correcting for multiple comparisons:

X.shape = (n_subjects, n_src)  # flatten the array for simplicity
titles.append('Permutation')
ts.append(np.zeros(width * width))
ps.append(np.zeros(width * width))
mccs.append(False)
for ii in range(n_src):
    ts[-1][ii], ps[-1][ii] = permutation_t_test(X[:, [ii]], verbose=False)[:2]
plot_t_p(ts[-1], ps[-1], titles[-1], mccs[-1])


I am working on the file "0.18/_downloads/846c9103e2de535e71d8b76a75654d36/plot_background_statistics.ipynb".
The first task is:
Statistical inference
Here we will briefly cover multiple concepts of inferential statistics in an
introductory manner, and demonstrate how to use some MNE statistical functions.
   :depth: 3
Can you write Python code for it?

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

from functools import partial

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D  # noqa, analysis:ignore

import mne
from mne.stats import (ttest_1samp_no_p, bonferroni_correction, fdr_correction,
                       permutation_t_test, permutation_cluster_1samp_test)

print(__doc__)


I am working on the file "0.18/_downloads/846c9103e2de535e71d8b76a75654d36/plot_background_statistics.ipynb".
The first task is:
Threshold-free cluster enhancement (TFCE)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TFCE eliminates the free parameter initial threshold value that
determines which points are included in clustering by approximating
a continuous integration across possible threshold values with a standard
Riemann sum <https://en.wikipedia.org/wiki/Riemann_sum>__ [2]_.
This requires giving a starting threshold start and a step
size step, which in MNE is supplied as a dict.
The smaller the step and closer to 0 the start value,
the better the approximation, but the longer it takes.
A significant advantage of TFCE is that, rather than modifying the
statistical null hypothesis under test (from one about individual voxels
to one about the distribution of clusters in the data), it modifies the data
under test while still controlling for multiple comparisons.
The statistical test is then done at the level of individual voxels rather
than clusters. This allows for evaluation of each point
independently for significance rather than only as cluster groups.
Can you write Python code for it?

titles.append(r'$\mathbf{C_{TFCE}}$')
threshold_tfce = dict(start=0, step=0.2)
t_tfce, _, p_tfce, H0 = permutation_cluster_1samp_test(
    X, n_jobs=1, threshold=threshold_tfce, connectivity=None,
    n_permutations=n_permutations)
ts.append(t_tfce)
ps.append(p_tfce)
mccs.append(True)
plot_t_p(ts[-1], ps[-1], titles[-1], mccs[-1])


I am working on the file "0.18/_downloads/846c9103e2de535e71d8b76a75654d36/plot_background_statistics.ipynb".
The first task is:
To combat this problem, several methods exist. Typically these
provide control over either one of the following two measures:

Familywise error rate (FWER) <fwer_>_
     The probability of making one or more type I errors:
.. math::
   \mathrm{P}(N_{\mathrm{type\ I}} >= 1 \mid H_0)

False discovery rate (FDR) <fdr_>_
     The expected proportion of rejected null hypotheses that are
     actually true:
.. math::
   \mathrm{E}(\frac{N_{\mathrm{type\ I}}}{N_{\mathrm{reject}}}
   \mid N_{\mathrm{reject}} > 0) \cdot
   \mathrm{P}(N_{\mathrm{reject}} > 0 \mid H_0)

We cover some techniques that control FWER and FDR below.
Bonferroni correction
^^^^^^^^^^^^^^^^^^^^^
Perhaps the simplest way to deal with multiple comparisons, Bonferroni
correction <https://en.wikipedia.org/wiki/Bonferroni_correction>__
conservatively multiplies the p-values by the number of comparisons to
control the FWER.
Can you write Python code for it?

titles.append('Bonferroni')
ts.append(ts[-1])
ps.append(bonferroni_correction(ps[0])[1])
mccs.append(True)
plot_t_p(ts[-1], ps[-1], titles[-1], mccs[-1])


I am working on the file "0.18/_downloads/846c9103e2de535e71d8b76a75654d36/plot_background_statistics.ipynb".
The first task is:
Visualize and compare methods
Let's take a look at these statistics. The top row shows each test statistic,
and the bottom shows p-values for various statistical tests, with the ones
with proper control over FWER or FDR with bold titles.
Can you write Python code for it?

fig = plt.figure(facecolor='w', figsize=(14, 3))
assert len(ts) == len(titles) == len(ps)
for ii in range(len(ts)):
    ax = [fig.add_subplot(2, 10, ii + 1, projection='3d'),
          fig.add_subplot(2, 10, 11 + ii)]
    plot_t_p(ts[ii], ps[ii], titles[ii], mccs[ii], ax)
fig.tight_layout(pad=0, w_pad=0.05, h_pad=0.1)
plt.show()


I am working on the file "0.18/_downloads/846c9103e2de535e71d8b76a75654d36/plot_background_statistics.ipynb".
The first task is:
We can also combine TFCE and the "hat" correction:
Can you write Python code for it?

titles.append(r'$\mathbf{C_{hat,TFCE}}$')
t_tfce_hat, _, p_tfce_hat, H0 = permutation_cluster_1samp_test(
    X, n_jobs=1, threshold=threshold_tfce, connectivity=None,
    n_permutations=n_permutations, stat_fun=stat_fun_hat, buffer_size=None)
ts.append(t_tfce_hat)
ps.append(p_tfce_hat)
mccs.append(True)
plot_t_p(ts[-1], ps[-1], titles[-1], mccs[-1])


I am working on the file "0.18/_downloads/8a8a7b741ef485e4d3d3772b252fcb81/plot_configuration.ipynb".
The first task is:
Configuring MNE python
This tutorial gives a short introduction to MNE configurations.
Can you write Python code for it?

import os.path as op

import mne
from mne.datasets.sample import data_path

fname = op.join(data_path(), 'MEG', 'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(fname).crop(0, 10)
original_level = mne.get_config('MNE_LOGGING_LEVEL', 'INFO')


I am working on the file "0.18/_downloads/8a8a7b741ef485e4d3d3772b252fcb81/plot_configuration.ipynb".
The first task is:
MNE-python stores configurations to a folder called .mne in the user's
home directory, or to AppData directory on Windows. The path to the config
file can be found out by calling :func:mne.get_config_path.
Can you write Python code for it?


I am working on the file "0.18/_downloads/8a8a7b741ef485e4d3d3772b252fcb81/plot_configuration.ipynb".
The first task is:
Nothing. This means that no warnings were emitted during the computation. If
you look at the documentation of :func:mne.compute_raw_covariance, you
notice the verbose keyword. Setting this parameter does not touch the
configurations, but sets the logging level for just this one function call.
Let's see what happens with logging level of INFO.
Can you write Python code for it?

cov = mne.compute_raw_covariance(raw, verbose=True)


I am working on the file "0.18/_downloads/8a8a7b741ef485e4d3d3772b252fcb81/plot_configuration.ipynb".
The first task is:
The default value is now set to INFO. This level will now be used by default
every time we call a function in MNE. We can set the global logging level for
only this session by calling :func:mne.set_log_level function.
Can you write Python code for it?


I am working on the file "0.18/_downloads/8e91c4d84fe688d78859cf6274554a8b/plot_compute_csd.ipynb".
The first task is:
==================================================
Compute a cross-spectral density (CSD) matrix
==================================================
A cross-spectral density (CSD) matrix is similar to a covariance matrix, but in
the time-frequency domain. It is the first step towards computing
sensor-to-sensor coherence or a DICS beamformer.
This script demonstrates the three methods that MNE-Python provides to compute
the CSD:

Using short-term Fourier transform: :func:mne.time_frequency.csd_fourier
Using a multitaper approach: :func:mne.time_frequency.csd_multitaper
Using Morlet wavelets: :func:mne.time_frequency.csd_morlet
Can you write Python code for it?

# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
# License: BSD (3-clause)
from matplotlib import pyplot as plt

import mne
from mne.datasets import sample
from mne.time_frequency import csd_fourier, csd_multitaper, csd_morlet

print(__doc__)


I am working on the file "0.18/_downloads/8e91c4d84fe688d78859cf6274554a8b/plot_compute_csd.ipynb".
The first task is:
By default, CSD matrices are computed using all MEG/EEG channels. When
interpreting a CSD matrix with mixed sensor types, be aware that the
measurement units, and thus the scalings, differ across sensors. In this
example, for speed and clarity, we select a single channel type:
gradiometers.
Can you write Python code for it?

picks = mne.pick_types(raw.info, meg='grad')

# Make some epochs, based on events with trigger code 1
epochs = mne.Epochs(raw, events, event_id=1, tmin=0, tmax=1,
                    picks=picks, baseline=(None, 0),
                    reject=dict(grad=4000e-13), preload=True)


I am working on the file "0.18/_downloads/8e91c4d84fe688d78859cf6274554a8b/plot_compute_csd.ipynb".
The first task is:
Computing CSD matrices using short-term Fourier transform and (adaptive)
multitapers is straightforward:
Can you write Python code for it?

csd_fft = csd_fourier(epochs, fmin=15, fmax=20, n_jobs=n_jobs)
csd_mt = csd_multitaper(epochs, fmin=15, fmax=20, adaptive=True, n_jobs=n_jobs)


I am working on the file "0.18/_downloads/8e91c4d84fe688d78859cf6274554a8b/plot_compute_csd.ipynb".
The first task is:
In the following example, the computation of the CSD matrices can be
performed using multiple cores. Set n_jobs to a value >1 to select the
number of cores to use.
Can you write Python code for it?


I am working on the file "0.18/_downloads/8e91c4d84fe688d78859cf6274554a8b/plot_compute_csd.ipynb".
The first task is:
Loading the sample dataset.
Can you write Python code for it?

data_path = sample.data_path()
fname_raw = data_path + '/MEG/sample/sample_audvis_raw.fif'
fname_event = data_path + '/MEG/sample/sample_audvis_raw-eve.fif'
raw = mne.io.read_raw_fif(fname_raw)
events = mne.read_events(fname_event)


I am working on the file "0.18/_downloads/8e91c4d84fe688d78859cf6274554a8b/plot_compute_csd.ipynb".
The first task is:
The resulting :class:mne.time_frequency.CrossSpectralDensity objects have a
plotting function we can use to compare the results of the different methods.
We're plotting the mean CSD across frequencies.
Can you write Python code for it?

csd_fft.mean().plot()
plt.suptitle('short-term Fourier transform')

csd_mt.mean().plot()
plt.suptitle('adaptive multitapers')

csd_wav.mean().plot()
plt.suptitle('Morlet wavelet transform')


I am working on the file "0.18/_downloads/8e91c4d84fe688d78859cf6274554a8b/plot_compute_csd.ipynb".
The first task is:
When computing the CSD with Morlet wavelets, you specify the exact
frequencies at which to compute it. For each frequency, a corresponding
wavelet will be constructed and convolved with the signal, resulting in a
time-frequency decomposition.
The CSD is constructed by computing the correlation between the
time-frequency representations between all sensor-to-sensor pairs. The
time-frequency decomposition originally has the same sampling rate as the
signal, in our case ~600Hz. This means the decomposition is over-specified in
time and we may not need to use all samples during our CSD computation, just
enough to get a reliable correlation statistic. By specifying decim=10,
we use every 10th sample, which will greatly speed up the computation and
will have a minimal effect on the CSD.
Can you write Python code for it?

frequencies = [16, 17, 18, 19, 20]
csd_wav = csd_morlet(epochs, frequencies, decim=10, n_jobs=n_jobs)


I am working on the file "0.18/_downloads/91bce2f7850f38d948be352bfc02e16c/plot_montage.ipynb".
The first task is:
Plotting sensor layouts of EEG Systems
This example illustrates how to load all the EEG system montages
shipped in MNE-python, and display it on fsaverage template.
Can you write Python code for it?

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

from mayavi import mlab
import os.path as op

import mne
from mne.channels.montage import get_builtin_montages
from mne.datasets import fetch_fsaverage
from mne.viz import plot_alignment

subjects_dir = op.dirname(fetch_fsaverage())


I am working on the file "0.18/_downloads/925ca2811e0c01ab2f8d558f074c31a3/plot_simulated_raw_data_using_subject_anatomy.ipynb".
The first task is:
In order to simulate source time courses, labels of desired active regions
need to be specified for each of the 4 simulation conditions.
Make a dictionary that maps conditions to activation strengths within
aparc.a2009s [1]_ labels. In the aparc.a2009s parcellation:

'G_temp_sup-G_T_transv' is the label for primary auditory area
'S_calcarine' is the label for primary visual area

In each of the 4 conditions, only the primary area is activated. This means
that during the activations of auditory areas, there are no activations in
visual areas and vice versa.
Moreover, for each condition, contralateral region is more active (here, 2
times more) than the ipsilateral.
Can you write Python code for it?

activations = {
    'auditory/left':
        [('G_temp_sup-G_T_transv-lh', 100),          # label, activation (nAm)
         ('G_temp_sup-G_T_transv-rh', 200)],
    'auditory/right':
        [('G_temp_sup-G_T_transv-lh', 200),
         ('G_temp_sup-G_T_transv-rh', 100)],
    'visual/left':
        [('S_calcarine-lh', 100),
         ('S_calcarine-rh', 200)],
    'visual/right':
        [('S_calcarine-lh', 200),
         ('S_calcarine-rh', 100)],
}

annot = 'aparc.a2009s'

# Load the 4 necessary label names.
label_names = sorted(set(activation[0]
                         for activation_list in activations.values()
                         for activation in activation_list))
region_names = list(activations.keys())

#  Define the time course of the activity for each region to activate. We use a
#  sine wave and it will be the same for all 4 regions.
source_time_series = np.sin(np.linspace(0, 4 * np.pi, 100)) * 10e-9


I am working on the file "0.18/_downloads/925ca2811e0c01ab2f8d558f074c31a3/plot_simulated_raw_data_using_subject_anatomy.ipynb".
The first task is:
Simulate raw data
Project the source time series to sensor space. Three types of noise will be
added to the simulated raw data:

multivariate Gaussian noise obtained from the noise covariance from the
  sample data
blink (EOG) noise
ECG noise

The :class:~mne.simulation.SourceSimulator can be given directly to the
:func:~mne.simulation.simulate_raw function.
Can you write Python code for it?

raw_sim = mne.simulation.simulate_raw(info, source_simulator, forward=fwd,
                                      cov=None)
raw_sim.set_eeg_reference(projection=True).crop(0, 60)  # for speed

mne.simulation.add_noise(raw_sim, cov=noise_cov, random_state=0)
mne.simulation.add_eog(raw_sim, random_state=0)
mne.simulation.add_ecg(raw_sim, random_state=0)

# Plot original and simulated raw data.
raw_sim.plot(title='Simulated raw data')


I am working on the file "0.18/_downloads/925ca2811e0c01ab2f8d558f074c31a3/plot_simulated_raw_data_using_subject_anatomy.ipynb".
The first task is:
Simulate raw data using subject anatomy
This example illustrates how to generate source estimates and simulate raw data
using subject anatomy with the :class:mne.simulation.SourceSimulator class.
Once the raw data is simulated, generated source estimates are reconstructed
using dynamic statistical parametric mapping (dSPM) inverse operator.
Can you write Python code for it?

# Author: Ivana Kojcic <ivana.kojcic@gmail.com>
#         Eric Larson <larson.eric.d@gmail.com>
#         Kostiantyn Maksymenko <kostiantyn.maksymenko@gmail.com>
#         Samuel Deslauriers-Gauthier <sam.deslauriers@gmail.com>

# License: BSD (3-clause)

import os.path as op

import numpy as np

import mne
from mne.datasets import sample

print(__doc__)

# To simulate the sample dataset, information of the sample subject needs to be
# loaded. This step will download the data if it not already on your machine.
# Subjects directory is also set so it doesn't need to be given to functions.
data_path = sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
subject = 'sample'
meg_path = op.join(data_path, 'MEG', subject)

# First, we get an info structure from the sample subject.
fname_info = op.join(meg_path, 'sample_audvis_raw.fif')
info = mne.io.read_info(fname_info)
tstep = 1 / info['sfreq']

# To simulate sources, we also need a source space. It can be obtained from the
# forward solution of the sample subject.
fwd_fname = op.join(meg_path, 'sample_audvis-meg-eeg-oct-6-fwd.fif')
fwd = mne.read_forward_solution(fwd_fname)
src = fwd['src']

# To simulate raw data, we need to define when the activity occurs using events
# matrix and specify the IDs of each event.
# Noise covariance matrix also needs to be defined.
# Here, both are loaded from the sample dataset, but they can also be specified
# by the user.

fname_event = op.join(meg_path, 'sample_audvis_raw-eve.fif')
fname_cov = op.join(meg_path, 'sample_audvis-cov.fif')

events = mne.read_events(fname_event)
noise_cov = mne.read_cov(fname_cov)

# Standard sample event IDs. These values will correspond to the third column
# in the events matrix.
event_id = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
            'visual/right': 4, 'smiley': 5, 'button': 32}


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

threshold = 6.0
T_obs, clusters, cluster_p_values, H0 = \
    permutation_cluster_test([condition1, condition2], n_permutations=1000,
                             threshold=threshold, tail=1, n_jobs=1)


I am working on the file "0.18/_downloads/9460321824116e4964fbe6d88d27462e/plot_cluster_stats_evoked.ipynb".
The first task is:
Permutation F-test on sensor data with 1D cluster level
One tests if the evoked response is significantly different
between conditions. Multiple comparison problem is addressed
with cluster level permutation test.
Can you write Python code for it?

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

import matplotlib.pyplot as plt

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

print(__doc__)


I am working on the file "0.18/_downloads/9460321824116e4964fbe6d88d27462e/plot_cluster_stats_evoked.ipynb".
The first task is:
Plot
Can you write Python code for it?

times = epochs1.times
plt.close('all')
plt.subplot(211)
plt.title('Channel : ' + channel)
plt.plot(times, condition1.mean(axis=0) - condition2.mean(axis=0),
         label="ERF Contrast (Event 1 - Event 2)")
plt.ylabel("MEG (T / m)")
plt.legend()
plt.subplot(212)
for i_c, c in enumerate(clusters):
    c = c[0]
    if cluster_p_values[i_c] <= 0.05:
        h = plt.axvspan(times[c.start], times[c.stop - 1],
                        color='r', alpha=0.3)
    else:
        plt.axvspan(times[c.start], times[c.stop - 1], color=(0.3, 0.3, 0.3),
                    alpha=0.3)
hf = plt.plot(times, T_obs, 'g')
plt.legend((h, ), ('cluster p-value < 0.05', ))
plt.xlabel("time (ms)")
plt.ylabel("f-values")
plt.show()


I am working on the file "0.18/_downloads/9794ea6d3b7fc21947e9529fb55249c9/plot_read_proj.ipynb".
The first task is:
==============================================
Read and visualize projections (SSP and other)
==============================================
This example shows how to read and visualize Signal Subspace Projectors (SSP)
vector. Such projections are sometimes referred to as PCA projections.
Can you write Python code for it?

# Author: Joan Massich <mailsik@gmail.com>
#
# License: BSD (3-clause)

import matplotlib.pyplot as plt

import mne
from mne import read_proj
from mne.io import read_raw_fif

from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

subjects_dir = data_path + '/subjects'
fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
ecg_fname = data_path + '/MEG/sample/sample_audvis_ecg-proj.fif'


I am working on the file "0.18/_downloads/9794ea6d3b7fc21947e9529fb55249c9/plot_read_proj.ipynb".
The first task is:
Display the projections one by one
Can you write Python code for it?

fig, axes = plt.subplots(1, len(empty_room_proj))
for proj, ax in zip(empty_room_proj, axes):
    proj.plot_topomap(axes=ax)


I am working on the file "0.18/_downloads/9794ea6d3b7fc21947e9529fb55249c9/plot_read_proj.ipynb".
The first task is:
Load the FIF file and display the projections present in the file. Here the
projections are added to the file during the acquisition and are obtained
from empty room recordings.
Can you write Python code for it?

raw = read_raw_fif(fname)
empty_room_proj = raw.info['projs']

# Display the projections stored in `info['projs']` from the raw object
raw.plot_projs_topomap()


I am working on the file "0.18/_downloads/9794ea6d3b7fc21947e9529fb55249c9/plot_read_proj.ipynb".
The first task is:
Use the function in mne.viz to display a list of projections
Can you write Python code for it?

assert isinstance(empty_room_proj, list)
mne.viz.plot_projs_topomap(empty_room_proj)


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

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

# sphinx_gallery_thumbnail_number = 3

import matplotlib.pyplot as plt
import numpy as np

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

print(__doc__)

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


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

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

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

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

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

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

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

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


I am working on the file "0.18/_downloads/9e4342323002225573aae6032a789805/plot_lcmv_beamformer.ipynb".
The first task is:
Run beamformers and look at maximum outputs
Can you write Python code for it?

pick_oris = [None, 'normal', 'max-power', None]
descriptions = ['Free', 'Normal', 'Max-power', 'Fixed']

fig, ax = plt.subplots(1)
max_voxs = list()
colors = list()
for pick_ori, desc in zip(pick_oris, descriptions):
    # compute unit-noise-gain beamformer with whitening of the leadfield and
    # data (enabled by passing a noise covariance matrix)
    if desc == 'Fixed':
        use_forward = mne.convert_forward_solution(forward, force_fixed=True)
    else:
        use_forward = forward
    filters = make_lcmv(evoked.info, use_forward, data_cov, reg=0.05,
                        noise_cov=noise_cov, pick_ori=pick_ori,
                        weight_norm='unit-noise-gain', rank=None)
    print(filters)
    # apply this spatial filter to source-reconstruct the evoked data
    stc = apply_lcmv(evoked, filters, max_ori_out='signed')

    # View activation time-series in maximum voxel at 100 ms:
    time_idx = stc.time_as_index(0.1)
    max_idx = np.argmax(np.abs(stc.data[:, time_idx]))
    # we know these are all left hemi, so we can just use vertices[0]
    max_voxs.append(stc.vertices[0][max_idx])
    h = ax.plot(stc.times, stc.data[max_idx, :],
                label='%s, voxel: %i' % (desc, max_idx))[0]
    colors.append(h.get_color())
    if pick_ori == 'max-power':
        max_stc = stc
ax.axhline(0, color='k')

ax.set(xlabel='Time (ms)', ylabel='LCMV value',
       title='LCMV in maximum voxel')
ax.legend(loc='lower right')
mne.viz.utils.plt_show()


I am working on the file "0.18/_downloads/9efe11126cdcc2ec888d5af516acf1cf/plot_object_evoked.ipynb".
The first task is:
Here for convenience we read the evoked dataset from a file.
Can you write Python code for it?

data_path = mne.datasets.sample.data_path()
fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')
evokeds = mne.read_evokeds(fname, baseline=(None, 0), proj=True)
print(evokeds)


I am working on the file "0.18/_downloads/9efe11126cdcc2ec888d5af516acf1cf/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(time_unit='s')


I am working on the file "0.18/_downloads/9efe11126cdcc2ec888d5af516acf1cf/plot_object_evoked.ipynb".
The first task is:
If you're gone through the tutorials of raw and epochs datasets, you're
probably already familiar with the :class:Info <mne.Info> attribute.
There is nothing new or special with the evoked.info. All the relevant
info is still there.
Can you write Python code for it?


I am working on the file "0.18/_downloads/9efe11126cdcc2ec888d5af516acf1cf/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.18/_downloads/9efe11126cdcc2ec888d5af516acf1cf/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.18/_downloads/9efe11126cdcc2ec888d5af516acf1cf/plot_object_evoked.ipynb".
The first task is:
The data is arranged in an array of shape (n_channels, n_times). Notice
that unlike epochs, evoked object does not support indexing. This means that
to access the data of a specific channel you must use the data array
directly.
Can you write Python code for it?

print('Data from channel {0}:'.format(evoked.ch_names[10]))
print(data[10])


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

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

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

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

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


I am working on the file "0.18/_downloads/a271bc382505fca1eb3f2c32f85b865f/spm_faces_dataset.ipynb".
The first task is:
From raw data to dSPM on SPM Faces dataset
Runs a full pipeline using MNE-Python:
- artifact removal
- averaging Epochs
- forward model computation
- source reconstruction using dSPM on the contrast : "faces - scrambled"

Note

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

Can you write Python code for it?

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

# sphinx_gallery_thumbnail_number = 10

import matplotlib.pyplot as plt

import mne
from mne.datasets import spm_face
from mne.preprocessing import ICA, create_eog_epochs
from mne import io, combine_evoked
from mne.minimum_norm import make_inverse_operator, apply_inverse

print(__doc__)

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


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

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

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

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

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

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

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

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

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

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

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

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

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

evoked.append(contrast)

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

plt.show()

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


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

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

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

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


I am working on the file "0.18/_downloads/a2f9ac57d4ad1150827afb5348fa4e73/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_scatter = plot_alignment(info, subject='sample', subjects_dir=subjects_dir,
                             surfaces='pial')
mlab.view(200, 70)
xy, im = snapshot_brain_montage(fig_scatter, 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.18/_downloads/a2f9ac57d4ad1150827afb5348fa4e73/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_alignment(info, subject='sample', subjects_dir=subjects_dir,
                     surfaces=['pial'])
mlab.view(200, 70)


I am working on the file "0.18/_downloads/a2f9ac57d4ad1150827afb5348fa4e73/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_alignment, snapshot_brain_montage

print(__doc__)


I am working on the file "0.18/_downloads/a35e576fa66929a73782579dc334f91a/plot_time_frequency_mixed_norm_inverse.ipynb".
The first task is:
Generate stc from dipoles
Can you write Python code for it?

stc = make_stc_from_dipoles(dipoles, forward['src'])


I am working on the file "0.18/_downloads/a489b01e2c31005c72c56777df4ed4f7/plot_mixed_norm_inverse.ipynb".
The first task is:
Plot residual
Can you write Python code for it?

ylim = dict(eeg=[-10, 10], grad=[-400, 400], mag=[-600, 600])
evoked.pick_types(meg=True, eeg=True, exclude='bads')
evoked.plot(ylim=ylim, proj=True, time_unit='s')
residual.pick_types(meg=True, eeg=True, exclude='bads')
residual.plot(ylim=ylim, proj=True, time_unit='s')


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

alpha = 55  # 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,
                                         depth=depth, fixed=True,
                                         use_cps=True)
stc_dspm = apply_inverse(evoked, inverse_operator, lambda2=1. / 9.,
                         method='dSPM')

# Compute (ir)MxNE inverse solution with dipole output
dipoles, 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,
    return_as_dipoles=True)


I am working on the file "0.18/_downloads/a489b01e2c31005c72c56777df4ed4f7/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?

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


I am working on the file "0.18/_downloads/a5584729990e006da9e18ae51f01bafe/plot_compute_mne_inverse_epochs_in_label.ipynb".
The first task is:
Viewing single trial dSPM and average dSPM for unflipped pooling over label
Compare to (1) Inverse (dSPM) then average, (2) Evoked then dSPM
Can you write Python code for it?

# Single trial
plt.figure()
for k, stc_trial in enumerate(stcs):
    plt.plot(times, np.mean(stc_trial.data, axis=0).T, 'k--',
             label='Single Trials' if k == 0 else '_nolegend_',
             alpha=0.5)

# Single trial inverse then average.. making linewidth large to not be masked
plt.plot(times, label_mean, 'b', linewidth=6,
         label='dSPM first, then average')

# Evoked and then inverse
plt.plot(times, label_mean_evoked, 'r', linewidth=2,
         label='Average first, then dSPM')

plt.xlabel('time (ms)')
plt.ylabel('dSPM value')
plt.legend()
plt.show()


I am working on the file "0.18/_downloads/a663da19dfef335563cab63585276d60/plot_object_annotations.ipynb".
The first task is:
Add :term:annotations to :term:raw objects
An important element of :class:~mne.Annotations is
orig_time which is the time reference for the onset.
It is key to understand that when calling
:func:raw.set_annotations <mne.io.Raw.set_annotations>, given
annotations are copied and transformed so that
:class:raw.annotations.orig_time <mne.Annotations>
matches the recording time of the raw object.
Refer to the documentation of :class:~mne.Annotations to see
the expected behavior depending on meas_date and orig_time.
Where meas_date is the recording time stored in
:class:Info <mne.Info>.
You can find more information about :class:Info <mne.Info> in
tut-info-class.
We'll now manipulate some simulated annotations.
The first annotations has orig_time set to None while the
second is set to a chosen POSIX timestamp for illustration purposes.
Note that both annotations have different onset values.
Can you write Python code for it?

# Create an annotation object with orig_time undefined (default)
annot_none = mne.Annotations(onset=[0, 2, 9], duration=[0.5, 4, 0],
                             description=['foo', 'bar', 'foo'],
                             orig_time=None)
print(annot_none)

# Create an annotation object with orig_time
orig_time = '2002-12-03 19:01:31.676071'
annot_orig = mne.Annotations(onset=[22, 24, 31], duration=[0.5, 4, 0],
                             description=['foo', 'bar', 'foo'],
                             orig_time=orig_time)
print(annot_orig)


I am working on the file "0.18/_downloads/a663da19dfef335563cab63585276d60/plot_object_annotations.ipynb".
The first task is:
First we'll create and plot events associated with the experimental paradigm:
Can you write Python code for it?

# extract the events array from the stim channel
events = mne.find_events(raw)

# Specify event_id dictionary based on the meaning of experimental triggers
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.18/_downloads/a663da19dfef335563cab63585276d60/plot_object_annotations.ipynb".
The first task is:
How about iterations?
Can you write Python code for it?

for key, val in annot[0].items():  # iterate on one element which is dictionary
    print(key, val)

for idx, my_annot in enumerate(annot):  # iterate on the Annotations object
    print('annot #{0}: onset={1}'.format(idx, my_annot['onset']))
    print('annot #{0}: duration={1}'.format(idx, my_annot['duration']))
    print('annot #{0}: description={1}'.format(idx, my_annot['description']))

for idx, my_annot in enumerate(annot[:1]):
    for key, val in my_annot.items():
        print('annot #{0}: {1} = {2}'.format(idx, key, val))


I am working on the file "0.18/_downloads/a663da19dfef335563cab63585276d60/plot_object_annotations.ipynb".
The first task is:
Iterating, Indexing and Slicing :class:mne.Annotations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:class:~mne.Annotations supports iterating, indexing and slicing.
Iterating over :class:~mne.Annotations and indexing with an integer returns
a dictionary. While slicing returns a new :class:~mne.Annotations instance.
See the following examples and usages:
Can you write Python code for it?

# difference between indexing and slicing a single element
print(annot[0])  # indexing
print(annot[:1])  # slicing


I am working on the file "0.18/_downloads/a663da19dfef335563cab63585276d60/plot_object_annotations.ipynb".
The first task is:
Iterating, indexing and slicing return a copy. This has implications like the
fact that changes are not kept.
Can you write Python code for it?

# this change is not kept
annot[0]['onset'] = 42
print(annot[0])

# this change is kept
annot.onset[0] = 42
print(annot[0])


I am working on the file "0.18/_downloads/a663da19dfef335563cab63585276d60/plot_object_annotations.ipynb".
The first task is:
Next, we're going to detect eye blinks and turn them into
:class:~mne.Annotations:
Can you write Python code for it?

# find blinks
annotated_blink_raw = raw.copy()
eog_events = mne.preprocessing.find_eog_events(raw)
n_blinks = len(eog_events)

# Turn blink events into Annotations of 0.5 seconds duration,
# each centered on the blink event:
onset = eog_events[:, 0] / raw.info['sfreq'] - 0.25
duration = np.repeat(0.5, n_blinks)
description = ['bad blink'] * n_blinks
annot = mne.Annotations(onset, duration, description,
                        orig_time=raw.info['meas_date'])
annotated_blink_raw.set_annotations(annot)

# plot the annotated raw
annotated_blink_raw.plot()


I am working on the file "0.18/_downloads/a663da19dfef335563cab63585276d60/plot_object_annotations.ipynb".
The first task is:
Note that although the onset values of both annotations were different,
due to complementary orig_time they are now identical. This is because
the first one (annot_none), once set in raw, adopted its orig_time.
The second one (annot_orig) already had an orig_time, so its
orig_time was changed to match the onset time of the raw. Changing an
already defined orig_time of annotations caused its onset to be
recalibrated with respect to the new orig_time. As a result both
annotations have now identical onset and identical orig_time:
Can you write Python code for it?

# Show the annotations in the raw objects
print(raw_a.annotations)
print(raw_b.annotations)

# Show that the onsets are the same
np.set_printoptions(precision=6)
print(raw_a.annotations.onset)
print(raw_b.annotations.onset)


I am working on the file "0.18/_downloads/a663da19dfef335563cab63585276d60/plot_object_annotations.ipynb".
The first task is:
Now we create two raw objects and set each with different annotations.
Then we plot both raw objects to compare the annotations.
Can you write Python code for it?

# Create two cropped copies of raw with the two previous annotations
raw_a = raw.copy().crop(tmax=12).set_annotations(annot_none)
raw_b = raw.copy().crop(tmax=12).set_annotations(annot_orig)

# Plot the raw objects
raw_a.plot()
raw_b.plot()


I am working on the file "0.18/_downloads/a663da19dfef335563cab63585276d60/plot_object_annotations.ipynb".
The first task is:
The :term:Events <events> and :class:~mne.Annotations data structures
:term:Events <events> and :term:annotations are quite similar.
This tutorial highlights their differences and similarities, and tries to shed
some light on which one is preferred to use in different situations when using
MNE.
Both events and :class:~mne.Annotations can be seen as triplets
where the first element answers to when something happens and the last
element refers to what it is.
The main difference is that events represent the onset in samples taking into
account the first sample value
(:attr:raw.first_samp <mne.io.Raw.first_samp>), and the description is
an integer value.
In contrast, :class:~mne.Annotations represents the
onset in seconds (relative to the reference orig_time),
and the description is an arbitrary string.
There is no correspondence between the second element of events and
:class:~mne.Annotations.
For events, the second element corresponds to the previous value on the
stimulus channel from which events are extracted. In practice, the second
element is therefore in most cases zero.
The second element of :class:~mne.Annotations is a float
indicating its duration in seconds.
See ex-read-events
for a complete example of how to read, select, and visualize events;
and tut-artifact-rejection to
learn how :class:~mne.Annotations are used to mark bad segments
of data.
An example of events and annotations
The following example shows the recorded events in sample_audvis_raw.fif and
marks bad segments due to eye blinks.
Can you write Python code for it?

import os.path as op
import numpy as np

import mne

# Load the data
data_path = mne.datasets.sample.data_path()
fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(fname)


I am working on the file "0.18/_downloads/a663da19dfef335563cab63585276d60/plot_object_annotations.ipynb".
The first task is:
Valid operations in :class:mne.Annotations
Concatenate
~~~~~~~~~~~
It is possible to concatenate two annotations with the + operator (just like
lists) if both share the same orig_time
Can you write Python code for it?

annot = mne.Annotations(onset=[10], duration=[0.5],
                        description=['foobar'],
                        orig_time=orig_time)
annot = annot_orig + annot  # concatenation
print(annot)


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

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

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


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

def plot_pos(pos, color=(0., 0., 0.)):
    mlab.points3d(pos[:, 0], pos[:, 1], pos[:, 2], scale_factor=0.005,
                  color=color)

mne.viz.plot_alignment(evoked.info, bem=sphere, surfaces=[])
# Plot the position of the actual dipole
plot_pos(actual_pos, color=(1., 0., 0.))
# Plot the position of the estimated dipole
plot_pos(pos, color=(1., 1., 0.))


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

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

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

t0 = 0.07  # peak of the response

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

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


I am working on the file "0.18/_downloads/ac6935fd2f56d2a7d16c589c65a46140/plot_artifacts_correction_maxwell_filtering.ipynb".
The first task is:
Artifact correction with Maxwell filter
This tutorial shows how to clean MEG data with Maxwell filtering.
Maxwell filtering in MNE can be used to suppress sources of external
interference and compensate for subject head movements.
See maxwell for more details.
Can you write Python code for it?

import mne
from mne.preprocessing import maxwell_filter

data_path = mne.datasets.sample.data_path()


I am working on the file "0.18/_downloads/ac6935fd2f56d2a7d16c589c65a46140/plot_artifacts_correction_maxwell_filtering.ipynb".
The first task is:
Preprocess with Maxwell filtering
Can you write Python code for it?

raw = mne.io.read_raw_fif(raw_fname)
raw.info['bads'] = ['MEG 2443', 'EEG 053', 'MEG 1032', 'MEG 2313']  # set bads
# Here we don't use tSSS (set st_duration) because MGH data is very clean
raw_sss = maxwell_filter(raw, cross_talk=ctc_fname, calibration=fine_cal_fname)


I am working on the file "0.18/_downloads/ac6935fd2f56d2a7d16c589c65a46140/plot_artifacts_correction_maxwell_filtering.ipynb".
The first task is:
Select events to extract epochs from, pick M/EEG channels, and plot evoked
Can you write Python code for it?

tmin, tmax = -0.2, 0.5
event_id = {'Auditory/Left': 1}
events = mne.find_events(raw, 'STI 014')
for r, kind in zip((raw, raw_sss), ('Raw data', 'Maxwell filtered data')):
    epochs = mne.Epochs(r, events, event_id, tmin, tmax,
                        picks=('meg', 'eog'),
                        baseline=(None, 0), reject=dict(eog=150e-6))
    evoked = epochs.average()
    evoked.plot(window_title=kind, ylim=dict(grad=(-200, 250),
                                             mag=(-600, 700)), time_unit='s')


I am working on the file "0.18/_downloads/ad203e57e0d21d6623eb90e7bd84fa3c/plot_morph_surface_stc.ipynb".
The first task is:
Apply morph to (Vector) SourceEstimate
The morph will be applied to the source estimate data, by giving it as the
first argument to the morph we computed above.
Can you write Python code for it?


I am working on the file "0.18/_downloads/ad203e57e0d21d6623eb90e7bd84fa3c/plot_morph_surface_stc.ipynb".
The first task is:
Plot results
Can you write Python code for it?

# Define plotting parameters
surfer_kwargs = dict(
    hemi='lh', subjects_dir=subjects_dir,
    clim=dict(kind='value', lims=[8, 12, 15]), views='lateral',
    initial_time=0.09, time_unit='s', size=(800, 800),
    smoothing_steps=5)

# As spherical surface
brain = stc_fsaverage.plot(surface='sphere', **surfer_kwargs)

# Add title
brain.add_text(0.1, 0.9, 'Morphed to fsaverage (spherical)', 'title',
               font_size=16)


I am working on the file "0.18/_downloads/ad203e57e0d21d6623eb90e7bd84fa3c/plot_morph_surface_stc.ipynb".
The first task is:
Reading and writing SourceMorph from and to disk
An instance of SourceMorph can be saved, by calling
:meth:morph.save <mne.SourceMorph.save>.
This method allows for specification of a filename under which the morph
will be save in ".h5" format. If no file extension is provided, "-morph.h5"
will be appended to the respective defined filename::
>>> morph.save('my-file-name')

Reading a saved source morph can be achieved by using
:func:mne.read_source_morph::
>>> morph = mne.read_source_morph('my-file-name-morph.h5')

Once the environment is set up correctly, no information such as
subject_from or subjects_dir must be provided, since it can be
inferred from the data and use morph to 'fsaverage' by default. SourceMorph
can further be used without creating an instance and assigning it to a
variable. Instead :func:mne.compute_source_morph and
:meth:mne.SourceMorph.apply can be
easily chained into a handy one-liner. Taking this together the shortest
possible way to morph data directly would be:
Can you write Python code for it?

stc_fsaverage = mne.compute_source_morph(stc,
                                         subjects_dir=subjects_dir).apply(stc)


I am working on the file "0.18/_downloads/ad203e57e0d21d6623eb90e7bd84fa3c/plot_morph_surface_stc.ipynb".
The first task is:
Setup paths
Can you write Python code for it?

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

fname_stc = os.path.join(sample_dir, 'sample_audvis-meg')


I am working on the file "0.18/_downloads/ae1f146de31a4665192262a211d6d103/plot_metadata_epochs.ipynb".
The first task is:

Note

Creating an :class:`mne.Epochs` object with metadata is done by passing
   a :class:`pandas.DataFrame` to the ``metadata`` kwarg as follows:

Can you write Python code for it?

data = epochs.get_data()
metadata = epochs.metadata.copy()
epochs_new = mne.EpochsArray(data, epochs.info, metadata=metadata)


I am working on the file "0.18/_downloads/ae1f146de31a4665192262a211d6d103/plot_metadata_epochs.ipynb".
The first task is:
And finally, for the interaction between concreteness and continuous length
in letters:
Can you write Python code for it?

evokeds = dict()
query = "is_concrete == '{0}' & NumberOfLetters == {1}"
for concreteness in ("Concrete", "Abstract"):
    for n_letters in letters:
        subset = epochs[query.format(concreteness, n_letters)]
        evokeds["/".join((concreteness, n_letters))] = subset.average()

style_plot["linestyles"] = {"Concrete": "-", "Abstract": ":"}

fig, ax = plt.subplots(figsize=(6, 4))
mne.viz.plot_compare_evokeds(evokeds, axes=ax, **style_plot)
plt.show()


I am working on the file "0.18/_downloads/ae1f146de31a4665192262a211d6d103/plot_metadata_epochs.ipynb".
The first task is:
Below we'll show a more involved example that leverages the metadata
of each epoch. We'll create a new column in our metadata object and use
it to generate averages for many subsets of trials.
Can you write Python code for it?

# Create two new metadata columns
metadata = epochs.metadata
is_concrete = metadata["Concreteness"] > metadata["Concreteness"].median()
metadata["is_concrete"] = np.where(is_concrete, 'Concrete', 'Abstract')
is_long = metadata["NumberOfLetters"] > 5
metadata["is_long"] = np.where(is_long, 'Long', 'Short')
epochs.metadata = metadata


I am working on the file "0.18/_downloads/ae1f146de31a4665192262a211d6d103/plot_metadata_epochs.ipynb".
The first task is:
Note that traditional epochs sub-selection still works. The traditional
MNE methods for selecting epochs will supersede the rich metadata querying.
Can you write Python code for it?


I am working on the file "0.18/_downloads/ae1f146de31a4665192262a211d6d103/plot_metadata_epochs.ipynb".
The first task is:
Now we can quickly extract (and plot) subsets of the data. For example, to
look at words split by word length and concreteness:
Can you write Python code for it?

query = "is_long == '{0}' & is_concrete == '{1}'"
evokeds = dict()
for concreteness in ("Concrete", "Abstract"):
    for length in ("Long", "Short"):
        subset = epochs[query.format(length, concreteness)]
        evokeds["/".join((concreteness, length))] = list(subset.iter_evoked())

# For the actual visualisation, we store a number of shared parameters.
style_plot = dict(
    colors={"Long": "Crimson", "Short": "Cornflowerblue"},
    linestyles={"Concrete": "-", "Abstract": ":"},
    split_legend=True,
    ci=.68,
    show_sensors='lower right',
    show_legend='lower left',
    truncate_yaxis="max_ticks",
    picks=epochs.ch_names.index("Pz"),
)

fig, ax = plt.subplots(figsize=(6, 4))
mne.viz.plot_compare_evokeds(evokeds, axes=ax, **style_plot)
plt.show()


I am working on the file "0.18/_downloads/ae1f146de31a4665192262a211d6d103/plot_metadata_epochs.ipynb".
The first task is:
Pandas querying and metadata with Epochs objects
Demonstrating pandas-style string querying with Epochs metadata.
For related uses of :class:mne.Epochs, see the starting tutorial
tut-epochs-class.
Sometimes you may have a complex trial structure that cannot be easily
summarized as a set of unique integers. In this case, it may be useful to use
the metadata attribute of :class:mne.Epochs objects. This must be a
:class:pandas.DataFrame where each row corresponds to an epoch, and each
column corresponds to a metadata attribute of each epoch. Columns must
contain either strings, ints, or floats.
In this dataset, subjects were presented with individual words
on a screen, and the EEG activity in response to each word was recorded.
We know which word was displayed in each epoch, as well as
extra information about the word (e.g., word frequency).
Loading the data
First we'll load the data. If metadata exists for an :class:mne.Epochs
fif file, it will automatically be loaded in the metadata attribute.
Can you write Python code for it?

# Authors: Chris Holdgraf <choldgraf@gmail.com>
#          Jona Sassenhagen <jona.sassenhagen@gmail.com>
#          Eric Larson <larson.eric.d@gmail.com>

# License: BSD (3-clause)

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

# Load the data from the internet
path = mne.datasets.kiloword.data_path() + '/kword_metadata-epo.fif'
epochs = mne.read_epochs(path)

# The metadata exists as a Pandas DataFrame
print(epochs.metadata.head(10))


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

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

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


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

mlab.figure(size=(600, 400), bgcolor=white)

# Plot the cortex
mlab.triangular_mesh(verts[:, 0], verts[:, 1], verts[:, 2], tris, color=gray)

# Show the dipoles as arrows pointing along the surface normal
normals = lh['nn'][lh['vertno']]
mlab.quiver3d(dip_pos[:, 0], dip_pos[:, 1], dip_pos[:, 2],
              normals[:, 0], normals[:, 1], normals[:, 2],
              color=red, scale_factor=1E-3)

mlab.view(azimuth=180, distance=0.1)