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

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

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

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 ex-linear-patterns
discusses the difference between patterns and filters.
These can be plotted with:
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.23/_downloads/e1c3654f77f904db443b548e9d93b8f9/50_decoding.ipynb".
The first task is:
Temporal generalization
Temporal generalization is an extension of the decoding over time approach.
It consists in evaluating whether the model estimated at a particular
time instant accurately predicts any other time instant. It is analogous to
transferring a trained model to a distinct learning problem, where the
problems correspond to decoding the patterns of brain activity recorded at
distinct time instants.
The object to for Temporal generalization is
:class:mne.decoding.GeneralizingEstimator. It expects as input $X$
and $y$ (similarly to :class:~mne.decoding.SlidingEstimator) but
generates predictions from each model for all time instants. The class
:class:~mne.decoding.GeneralizingEstimator is generic and will treat the
last dimension as the one to be used for generalization testing. For
convenience, here, we refer to it as different tasks. If $X$
corresponds to epochs data then the last dimension is time.
This runs the analysis used in :footcite:KingEtAl2014 and further detailed
in :footcite:KingDehaene2014:
Can you write Python code for it?

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

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

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

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


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

Note

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

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

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

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

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


I am working on the file "0.23/_downloads/e23ed246a9a354f899dfb3ce3b06e194/10_overview.ipynb".
The first task is:

Note

Both `~mne.io.Raw` and `~mne.Epochs` objects have `~mne.Epochs.get_data`
    methods that return the underlying data as a
    :class:`NumPy array <numpy.ndarray>`. Both methods have a ``picks``
    parameter for subselecting which channel(s) to return; ``raw.get_data()``
    has additional parameters for restricting the time domain. The resulting
    matrices have dimension ``(n_channels, n_times)`` for `~mne.io.Raw` and
    ``(n_epochs, n_channels, n_times)`` for `~mne.Epochs`.

Time-frequency analysis
The :mod:mne.time_frequency submodule provides implementations of several
algorithms to compute time-frequency representations, power spectral density,
and cross-spectral density. Here, for example, we'll compute for the auditory
epochs the induced power at different frequencies and times, using Morlet
wavelets. On this dataset the result is not especially informative (it just
shows the evoked "auditory N100" response); see here
<inter-trial-coherence> for a more extended example on a dataset with richer
frequency content.
Can you write Python code for it?

frequencies = np.arange(7, 30, 3)
power = mne.time_frequency.tfr_morlet(aud_epochs, n_cycles=2, return_itc=False,
                                      freqs=frequencies, decim=3)
power.plot(['MEG 1332'])


I am working on the file "0.23/_downloads/e23ed246a9a354f899dfb3ce3b06e194/10_overview.ipynb".
The first task is:
Estimating evoked responses
Now that we have our conditions in aud_epochs and vis_epochs, we can
get an estimate of evoked responses to auditory versus visual stimuli by
averaging together the epochs in each condition. This is as simple as calling
the ~mne.Epochs.average method on the ~mne.Epochs object, and then using
a function from the :mod:mne.viz module to compare the global field power
for each sensor type of the two ~mne.Evoked objects:
Can you write Python code for it?

aud_evoked = aud_epochs.average()
vis_evoked = vis_epochs.average()

mne.viz.plot_compare_evokeds(dict(auditory=aud_evoked, visual=vis_evoked),
                             legend='upper left', show_sensors='upper right')


I am working on the file "0.23/_downloads/e23ed246a9a354f899dfb3ce3b06e194/10_overview.ipynb".
The first task is:
Event dictionaries like this one are used when extracting epochs from
continuous data; the / character in the dictionary keys allows pooling
across conditions by requesting partial condition descriptors (i.e.,
requesting 'auditory' will select all epochs with Event IDs 1 and 2;
requesting 'left' will select all epochs with Event IDs 1 and 3). An
example of this is shown in the next section. There is also a convenient
~mne.viz.plot_events function for visualizing the distribution of events
across the duration of the recording (to make sure event detection worked as
expected). Here we'll also make use of the ~mne.Info attribute to get the
sampling frequency of the recording (so our x-axis will be in seconds instead
of in samples).
Can you write Python code for it?

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


I am working on the file "0.23/_downloads/e23ed246a9a354f899dfb3ce3b06e194/10_overview.ipynb".
The first task is:
Evoked objects can also be combined to show contrasts between conditions,
using the mne.combine_evoked function. A simple difference can be
generated by passing weights=[1, -1]. We'll then plot the difference wave
at each sensor using ~mne.Evoked.plot_topo:
Can you write Python code for it?

evoked_diff = mne.combine_evoked([aud_evoked, vis_evoked], weights=[1, -1])
evoked_diff.pick_types(meg='mag').plot_topo(color='r', legend=False)


I am working on the file "0.23/_downloads/e23ed246a9a354f899dfb3ce3b06e194/10_overview.ipynb".
The first task is:
Finally, in order to plot the source estimate on the subject's cortical
surface we'll also need the path to the sample subject's structural MRI files
(the subjects_dir):
Can you write Python code for it?

# path to subjects' MRI files
subjects_dir = os.path.join(sample_data_folder, 'subjects')
# plot
stc.plot(initial_time=0.1, hemi='split', views=['lat', 'med'],
         subjects_dir=subjects_dir)


I am working on the file "0.23/_downloads/e23ed246a9a354f899dfb3ce3b06e194/10_overview.ipynb".
The first task is:
Like ~mne.io.Raw objects, ~mne.Epochs objects also have a number of
built-in plotting methods. One is ~mne.Epochs.plot_image, which shows each
epoch as one row of an image map, with color representing signal magnitude;
the average evoked response and the sensor location are shown below the
image:
Can you write Python code for it?

aud_epochs.plot_image(picks=['MEG 1332', 'EEG 021'])


I am working on the file "0.23/_downloads/e23ed246a9a354f899dfb3ce3b06e194/10_overview.ipynb".
The first task is:
Loading data
MNE-Python data structures are based around the FIF file format from
Neuromag, but there are reader functions for a wide variety of other
data formats <data-formats>. MNE-Python also has interfaces to a
variety of publicly available datasets <datasets>,
which MNE-Python can download and manage for you.
We'll start this tutorial by loading one of the example datasets (called
"sample-dataset"), which contains EEG and MEG data from one subject
performing an audiovisual experiment, along with structural MRI scans for
that subject. The mne.datasets.sample.data_path function will automatically
download the dataset if it isn't found in one of the expected locations, then
return the directory path to the dataset (see the documentation of
~mne.datasets.sample.data_path for a list of places it checks before
downloading). Note also that for this tutorial to run smoothly on our
servers, we're using a filtered and downsampled version of the data
(:file:sample_audvis_filt-0-40_raw.fif), but an unfiltered version
(:file:sample_audvis_raw.fif) is also included in the sample dataset and
could be substituted here when running the tutorial locally.
Can you write Python code for it?

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_filt-0-40_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file)


I am working on the file "0.23/_downloads/e23ed246a9a354f899dfb3ce3b06e194/10_overview.ipynb".
The first task is:
Once we're confident about which component(s) we want to remove, we pass them
as the exclude parameter and then apply the ICA to the raw signal. The
~mne.preprocessing.ICA.apply method requires the raw data to be loaded into
memory (by default it's only read from disk as-needed), so we'll use
~mne.io.Raw.load_data first. We'll also make a copy of the ~mne.io.Raw
object so we can compare the signal before and after artifact removal
side-by-side:
Can you write Python code for it?

orig_raw = raw.copy()
raw.load_data()
ica.apply(raw)

# show some frontal channels to clearly illustrate the artifact removal
chs = ['MEG 0111', 'MEG 0121', 'MEG 0131', 'MEG 0211', 'MEG 0221', 'MEG 0231',
       'MEG 0311', 'MEG 0321', 'MEG 0331', 'MEG 1511', 'MEG 1521', 'MEG 1531',
       'EEG 001', 'EEG 002', 'EEG 003', 'EEG 004', 'EEG 005', 'EEG 006',
       'EEG 007', 'EEG 008']
chan_idxs = [raw.ch_names.index(ch) for ch in chs]
orig_raw.plot(order=chan_idxs, start=12, duration=4)
raw.plot(order=chan_idxs, start=12, duration=4)


I am working on the file "0.23/_downloads/e23ed246a9a354f899dfb3ce3b06e194/10_overview.ipynb".
The first task is:
Preprocessing
MNE-Python supports a variety of preprocessing approaches and techniques
(maxwell filtering, signal-space projection, independent components analysis,
filtering, downsampling, etc); see the full list of capabilities in the
:mod:mne.preprocessing and :mod:mne.filter submodules. Here we'll clean
up our data by performing independent components analysis
(~mne.preprocessing.ICA); for brevity we'll skip the steps that helped us
determined which components best capture the artifacts (see
tut-artifact-ica for a detailed walk-through of that process).
Can you write Python code for it?

# set up and fit the ICA
ica = mne.preprocessing.ICA(n_components=20, random_state=97, max_iter=800)
ica.fit(raw)
ica.exclude = [1, 2]  # details on how we picked these are omitted here
ica.plot_properties(raw, picks=ica.exclude)


event_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
              'visual/right': 4, 'smiley': 5, 'buttonpress': 32}


I am working on the file "0.23/_downloads/e23ed246a9a354f899dfb3ce3b06e194/10_overview.ipynb".
The first task is:
~mne.io.Raw objects also have several built-in plotting methods; here we
show the power spectral density (PSD) for each sensor type with
~mne.io.Raw.plot_psd, as well as a plot of the raw sensor traces with
~mne.io.Raw.plot. In the PSD plot, we'll only plot frequencies below 50 Hz
(since our data are low-pass filtered at 40 Hz). In interactive Python
sessions, ~mne.io.Raw.plot is interactive and allows scrolling, scaling,
bad channel marking, annotation, projector toggling, etc.
Can you write Python code for it?


I am working on the file "0.23/_downloads/e41b6a898e7a75f8a9f1a6c00ca73857/20_visualize_epochs.ipynb".
The first task is:
If you prefer untransformed power estimates, you can pass dB=False. It is
also possible to normalize the power estimates by dividing by the total power
across all frequencies, by passing normalize=True. See the docstring of
~mne.Epochs.plot_psd_topomap for details.
Plotting Epochs as an image map
A convenient way to visualize many epochs simultaneously is to plot them as
an image map, with each row of pixels in the image representing a single
epoch, the horizontal axis representing time, and each pixel's color
representing the signal value at that time sample for that epoch. Of course,
this requires either a separate image map for each channel, or some way of
combining information across channels. The latter is possible using the
~mne.Epochs.plot_image method; the former can be achieved with the
~mne.Epochs.plot_image method (one channel at a time) or with the
~mne.Epochs.plot_topo_image method (all sensors at once).
By default, the image map generated by ~mne.Epochs.plot_image will be
accompanied by a scalebar indicating the range of the colormap, and a time
series showing the average signal across epochs and a bootstrapped 95%
confidence band around the mean. ~mne.Epochs.plot_image is a highly
customizable method with many parameters, including customization of the
auxiliary colorbar and averaged time series subplots. See the docstrings of
~mne.Epochs.plot_image and mne.viz.plot_compare_evokeds (which is
used to plot the average time series) for full details. Here we'll show the
mean across magnetometers for all epochs with an auditory stimulus:
Can you write Python code for it?


I am working on the file "0.23/_downloads/e41b6a898e7a75f8a9f1a6c00ca73857/20_visualize_epochs.ipynb".
The first task is:
Just as we saw in the tut-section-raw-plot-proj section, we can plot
the projectors present in an ~mne.Epochs object using the same
~mne.Epochs.plot_projs_topomap method. Since the original three
empty-room magnetometer projectors were inherited from the
~mne.io.Raw file, and we added two ECG projectors for each sensor
type, we should see nine projector topomaps:
Can you write Python code for it?


I am working on the file "0.23/_downloads/e41b6a898e7a75f8a9f1a6c00ca73857/20_visualize_epochs.ipynb".
The first task is:
Plotting Epochs as time series
.. sidebar:: Interactivity in pipelines and scripts
To use the interactive features of the `~mne.Epochs.plot` method
when running your code non-interactively, pass the ``block=True``
parameter, which halts the Python interpreter until the figure window is
closed. That way, any channels or epochs that you mark as "bad" will be
taken into account in subsequent processing steps.

To visualize epoched data as time series (one time series per channel), the
mne.Epochs.plot method is available. It creates an interactive window
where you can scroll through epochs and channels, enable/disable any
unapplied :term:SSP projectors <projector> to see how they affect the
signal, and even manually mark bad channels (by clicking the channel name) or
bad epochs (by clicking the data) for later dropping. Channels marked "bad"
will be shown in light grey color and will be added to
epochs.info['bads']; epochs marked as bad will be indicated as 'USER'
in epochs.drop_log.
Here we'll plot only the "catch" trials from the sample dataset
<sample-dataset>, and pass in our events array so that the button press
responses also get marked (we'll plot them in red, and plot the "face" events
defining time zero for each epoch in blue). We also need to pass in
our event_dict so that the ~mne.Epochs.plot method will know what
we mean by "button" — this is because subsetting the conditions by
calling epochs['face'] automatically purges the dropped entries from
epochs.event_id:
Can you write Python code for it?

catch_trials_and_buttonpresses = mne.pick_events(events, include=[5, 32])
epochs['face'].plot(events=catch_trials_and_buttonpresses, event_id=event_dict,
                    event_color=dict(button='red', face='blue'))


I am working on the file "0.23/_downloads/e41b6a898e7a75f8a9f1a6c00ca73857/20_visualize_epochs.ipynb".
The first task is:
Plotting sensor locations
Just like ~mne.io.Raw objects, ~mne.Epochs objects
keep track of sensor locations, which can be visualized with the
~mne.Epochs.plot_sensors method:
Can you write Python code for it?

epochs.plot_sensors(kind='3d', ch_type='all')
epochs.plot_sensors(kind='topomap', ch_type='all')


I am working on the file "0.23/_downloads/e41b6a898e7a75f8a9f1a6c00ca73857/20_visualize_epochs.ipynb".
The first task is:
To create the ~mne.Epochs data structure, we'll extract the event
IDs stored in the :term:stim channel, map those integer event IDs to more
descriptive condition labels using an event dictionary, and pass those to the
~mne.Epochs constructor, along with the ~mne.io.Raw data
and the desired temporal limits of our epochs, tmin and tmax (for a
detailed explanation of these steps, see tut-epochs-class).
Can you write Python code for it?

events = mne.find_events(raw, stim_channel='STI 014')
event_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
              'visual/right': 4, 'face': 5, 'button': 32}
epochs = mne.Epochs(raw, events, tmin=-0.2, tmax=0.5, event_id=event_dict,
                    preload=True)
del raw


I am working on the file "0.23/_downloads/e41b6a898e7a75f8a9f1a6c00ca73857/20_visualize_epochs.ipynb".
The first task is:
To plot image maps for all EEG sensors, pass an EEG layout as the layout
parameter of ~mne.Epochs.plot_topo_image. Note also here the use of
the sigma parameter, which smooths each image map along the vertical
dimension (across epochs) which can make it easier to see patterns across the
small image maps (by smearing noisy epochs onto their neighbors, while
reinforcing parts of the image where adjacent epochs are similar). However,
sigma can also disguise epochs that have persistent extreme values and
maybe should have been excluded, so it should be used with caution.
Can you write Python code for it?

layout = mne.channels.find_layout(epochs.info, ch_type='eeg')
epochs['auditory/left'].plot_topo_image(layout=layout, fig_facecolor='w',
                                        font_color='k', sigma=1)


I am working on the file "0.23/_downloads/e41b6a898e7a75f8a9f1a6c00ca73857/20_visualize_epochs.ipynb".
The first task is:
To plot image maps for individual sensors or a small group of sensors, use
the picks parameter. Passing combine=None (the default) will yield
separate plots for each sensor in picks; passing combine='gfp' will
plot the global field power (useful for combining sensors that respond with
opposite polarity).
Can you write Python code for it?

epochs['auditory'].plot_image(picks=['MEG 0242', 'MEG 0243'])
epochs['auditory'].plot_image(picks=['MEG 0242', 'MEG 0243'], combine='gfp')


I am working on the file "0.23/_downloads/e41b6a898e7a75f8a9f1a6c00ca73857/20_visualize_epochs.ipynb".
The first task is:
To see all sensors at once, we can use butterfly mode and group by selection:
Can you write Python code for it?

epochs['face'].plot(events=catch_trials_and_buttonpresses, event_id=event_dict,
                    event_color=dict(button='red', face='blue'),
                    group_by='selection', butterfly=True)


I am working on the file "0.23/_downloads/e41b6a898e7a75f8a9f1a6c00ca73857/20_visualize_epochs.ipynb".
The first task is:
Visualizing epoched data
This tutorial shows how to plot epoched data as time series, how to plot the
spectral density of epoched data, how to plot epochs as an imagemap, and how to
plot the sensor locations and projectors stored in ~mne.Epochs
objects.
We'll start by importing the modules we need, loading the continuous (raw)
sample data, and cropping it to save memory:
Can you write Python code for it?

import os
import mne

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


I am working on the file "0.23/_downloads/e51cf7d76ca7b5745c35997ababd9c86/covariance_whitening_dspm.ipynb".
The first task is:
Get data
Can you write Python code for it?

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

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

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

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

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

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


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

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

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

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

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

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

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


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

Note

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

Can you write Python code for it?

bem = mne.read_bem_solution(bem_fname)
trans = None

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

fwd = mne.read_forward_solution(fwd_fname)
# use fixed orientation here just to save memory later
mne.convert_forward_solution(fwd, force_fixed=True, copy=False)

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

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


I am working on the file "0.23/_downloads/e7de7baffeeb4beff147bad8657b46dc/opm_data.ipynb".
The first task is:
Optically pumped magnetometer (OPM) data
In this dataset, electrical median nerve stimulation was delivered to the
left wrist of the subject. Somatosensory evoked fields were measured using
nine QuSpin SERF OPMs placed over the right-hand side somatomotor area.
Here we demonstrate how to localize these custom OPM data in MNE.
Can you write Python code for it?

import os.path as op

import numpy as np
import mne

data_path = mne.datasets.opm.data_path()
subject = 'OPM_sample'
subjects_dir = op.join(data_path, 'subjects')
raw_fname = op.join(data_path, 'MEG', 'OPM', 'OPM_SEF_raw.fif')
bem_fname = op.join(subjects_dir, subject, 'bem',
                    subject + '-5120-5120-5120-bem-sol.fif')
fwd_fname = op.join(data_path, 'MEG', 'OPM', 'OPM_sample-fwd.fif')
coil_def_fname = op.join(data_path, 'MEG', 'OPM', 'coil_def.dat')


I am working on the file "0.23/_downloads/e7de7baffeeb4beff147bad8657b46dc/opm_data.ipynb".
The first task is:
Perform dipole fitting
Can you write Python code for it?

# Fit dipoles on a subset of time points
with mne.use_coil_def(coil_def_fname):
    dip_opm, _ = mne.fit_dipole(evoked.copy().crop(0.015, 0.080),
                                cov, bem, trans, verbose=True)
idx = np.argmax(dip_opm.gof)
print('Best dipole at t=%0.1f ms with %0.1f%% GOF'
      % (1000 * dip_opm.times[idx], dip_opm.gof[idx]))

# Plot N20m dipole as an example
dip_opm.plot_locations(trans, subject, subjects_dir,
                       mode='orthoview', idx=idx)


I am working on the file "0.23/_downloads/e7de7baffeeb4beff147bad8657b46dc/opm_data.ipynb".
The first task is:
Perform minimum-norm localization
Due to the small number of sensors, there will be some leakage of activity
to areas with low/no sensitivity. Constraining the source space to
areas we are sensitive to might be a good idea.
Can you write Python code for it?

inverse_operator = mne.minimum_norm.make_inverse_operator(
    evoked.info, fwd, cov, loose=0., depth=None)
del fwd, cov

method = "MNE"
snr = 3.
lambda2 = 1. / snr ** 2
stc = mne.minimum_norm.apply_inverse(
    evoked, inverse_operator, lambda2, method=method,
    pick_ori=None, verbose=True)

# Plot source estimate at time of best dipole fit
brain = stc.plot(hemi='rh', views='lat', subjects_dir=subjects_dir,
                 initial_time=dip_opm.times[idx],
                 clim=dict(kind='percent', lims=[99, 99.9, 99.99]))


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

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

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

# Find median nerve stimulator trigger
event_id = dict(Median=257)
events = mne.find_events(raw, stim_channel='STI101', mask=257, mask_type='and')
picks = mne.pick_types(raw.info, meg=True, eeg=False)
# We use verbose='error' to suppress warning about decimation causing aliasing,
# ideally we would low-pass and then decimate instead
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, verbose='error',
                    reject=reject, picks=picks, proj=False, decim=10,
                    preload=True)
evoked = epochs.average()
evoked.plot()
cov = mne.compute_covariance(epochs, tmax=0.)
del epochs, raw


I am working on the file "0.23/_downloads/e9e4cb40a9dfa8201d4c1c7323f42a0a/35_artifact_correction_regression.ipynb".
The first task is:
Compute and apply EOG regression
Next we'll compare the ~mne.Evoked data (average across epochs) before and
after we regress out the EOG signal. We do this by first estimating the
regression coefficients on epoch data with the evoked response subtracted
out. As long as the EOG artifacts are in the epochs, then the algorithm
should be able to estimate regression coefficients. The EOG artifacts do not
need to be time-locked to the stimulus/epoch event timing of the epochs.
Can you write Python code for it?

# do regression
_, betas = mne.preprocessing.regress_artifact(epochs.copy().subtract_evoked())


I am working on the file "0.23/_downloads/e9e4cb40a9dfa8201d4c1c7323f42a0a/35_artifact_correction_regression.ipynb".
The first task is:
For this dataset and example we'll use just event type 1 (only the
"standard" trials) for simplicity. Event timing is adjusted by comparing the
trigger times on detected sound onsets on channel UADC001-4408.
Can you write Python code for it?

events = mne.find_events(raw, stim_channel='UPPT001')
sound_data = raw[raw.ch_names.index('UADC001-4408')][0][0]
onsets = np.where(np.abs(sound_data) > 2. * np.std(sound_data))[0]
min_diff = int(0.5 * raw.info['sfreq'])
diffs = np.concatenate([[min_diff + 1], np.diff(onsets)])
onsets = onsets[diffs > min_diff]
assert len(onsets) == len(events)
events[:, 0] = onsets
epochs = mne.Epochs(raw, events, event_id=1, decim=decim, preload=True)


I am working on the file "0.23/_downloads/e9e4cb40a9dfa8201d4c1c7323f42a0a/35_artifact_correction_regression.ipynb".
The first task is:
Repairing artifacts with regression
This tutorial covers removal of artifacts using regression as in Gratton et al.
(1983) :footcite:GrattonEtAl1983.
Generally speaking, artifacts that result in time waveforms on the sensors
that are accurately reflected by some reference signal can be removed by
regression. Blink artifacts captured by bipolar EOG channels serve as a good
example of this, so we will demonstrate this here.
Although ECG signals are well captured by bipolar ECG electrodes,
regression-based removal of ECG artifacts usually does not work very well.
This is likely because the heart acts like a rotating dipole, and
therefore the ECG channel time waveform recorded from the ECG electrode sites
does not reflect the same temporal dynamics that manifest at each MEG channel
(obtained by sampling some component of the related magnetic vector field).
Other approaches like ICA <tut-artifact-ica> or
SSP <tut-artifact-ssp> will likely work better for ECG.
Prepare the data
We begin as always by importing the necessary Python modules and loading some
data. In this case we use data from Brainstorm <tut-brainstorm-auditory>
because it has some clear, large blink artifacts. We then crop it to 60
seconds, set some channel information, then process the auditory evoked data.
Note that there are other corrections that are useful for this dataset that we
will not apply here (see tut-brainstorm-auditory for more information).
Can you write Python code for it?

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

data_path = mne.datasets.brainstorm.bst_auditory.data_path()
raw_fname = op.join(data_path, 'MEG', 'bst_auditory', 'S01_AEF_20131218_01.ds')
raw = mne.io.read_raw_ctf(raw_fname).crop(0, 60)
raw.set_channel_types({'HEOG': 'eog', 'VEOG': 'eog', 'ECG': 'ecg'})
raw.pick_types(meg=True, stim=True, misc=True,
               eog=True, ecg=True, ref_meg=False).load_data()
raw.info['bads'] = ['MLO52-4408', 'MRT51-4408', 'MLO42-4408', 'MLO43-4408']
raw.filter(None, 40)
decim = 12  # 2400 -> 200 Hz sample rate for epochs


I am working on the file "0.23/_downloads/e9e4cb40a9dfa8201d4c1c7323f42a0a/35_artifact_correction_regression.ipynb".
The first task is:
The effect is subtle in these evoked data, but you can see that a bump toward
the end of the window has had its amplitude decreased.
Visualize the effect on EOG epochs
The effect is clearer if we create epochs around (autodetected) blink events,
and plot the average blink artifact before and after the regression based on
the same regression coefficients we computed earlier. If the resulting
blink evoked data are reduced to near zero, it helps validate
that the regression efficiently removes blink artifacts.
Can you write Python code for it?

# extract epochs around each blink
evo_kwargs['ylim'].update(mag=[-4000, 3000], eog=[-600, 100])
eog_epochs = mne.preprocessing.create_eog_epochs(raw, decim=decim)
eog_epochs.apply_baseline((None, None))

# regress, using the `betas` we already found above
eog_epochs_clean, _ = mne.preprocessing.regress_artifact(eog_epochs,
                                                         betas=betas)

# plot original blink epochs
fig = eog_epochs.average(picks=plot_picks).plot(**evo_kwargs)
fig.suptitle('EOG epochs')
mne.viz.tight_layout()

# plot regressed blink epochs
fig = eog_epochs_clean.average(picks=plot_picks).plot(**evo_kwargs)
fig.suptitle('EOG epochs, EOG regressed')
mne.viz.tight_layout()


I am working on the file "0.23/_downloads/e9e4cb40a9dfa8201d4c1c7323f42a0a/35_artifact_correction_regression.ipynb".
The first task is:
Visualize the effect on auditory epochs
Now we can plot the auditory evoked response before and after regression:
Can you write Python code for it?

# get ready to plot
plot_picks = ['meg', 'eog']
evo_kwargs = dict(picks=plot_picks, spatial_colors=True,
                  verbose='error')  # ignore warnings about spatial colors

evo_kwargs['ylim'] = dict(mag=[-350, 300], eog=[-35, 5])
# plot original data (averaged across epochs)
fig = epochs.average(picks=plot_picks).plot(**evo_kwargs)
fig.suptitle('Auditory epochs')
mne.viz.tight_layout()

# plot regressed data
fig = epochs_clean.average(picks=plot_picks).plot(**evo_kwargs)
fig.suptitle('Auditory epochs, EOG regressed')
mne.viz.tight_layout()

# clean up
del epochs, epochs_clean


I am working on the file "0.23/_downloads/e9e4cb40a9dfa8201d4c1c7323f42a0a/35_artifact_correction_regression.ipynb".
The first task is:
We then use those coefficients to remove the EOG signal from the original
data:
Can you write Python code for it?

epochs_clean, _ = mne.preprocessing.regress_artifact(epochs, betas=betas)


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

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


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

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

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

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

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


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

seed = 42

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

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

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

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


I am working on the file "0.23/_downloads/ead9220acec394667b95e490359e08e7/70_point_spread.ipynb".
The first task is:
Plot the point-spread of corrupted signal
Notice that after applying the forward- and inverse-operators to the known
point sources that the point sources have spread across the source-space.
This spread is due to the minimum norm solution so that the signal leaks to
nearby vertices with similar orientations so that signal ends up crossing the
sulci and gyri.
Can you write Python code for it?


I am working on the file "0.23/_downloads/ead9220acec394667b95e490359e08e7/70_point_spread.ipynb".
The first task is:
Simulate sensor-space signals
Use the forward solution and add Gaussian noise to simulate sensor-space
(evoked) data from the known source-space signals. The amount of noise is
controlled by nave (higher values imply less noise).
Can you write Python code for it?

evoked_gen = simulate_evoked(fwd, stc_gen, evoked.info, cov, nave,
                             random_state=seed)

# Map the simulated sensor-space data to source-space using the inverse
# operator.
stc_inv = apply_inverse(evoked_gen, inv_op, lambda2, method=method)


I am working on the file "0.23/_downloads/eb0c29f55af0173daab811d4f4dc2f40/simulated_raw_data_using_subject_anatomy.ipynb".
The first task is:
Create simulated source activity
Generate source time courses for each region. In this example, we want to
simulate source activity for a single condition at a time. Therefore, each
evoked response will be parametrized by latency and duration.
Can you write Python code for it?

def data_fun(times, latency, duration):
    """Function to generate source time courses for evoked responses,
    parametrized by latency and duration."""
    f = 15  # oscillating frequency, beta band [Hz]
    sigma = 0.375 * duration
    sinusoid = np.sin(2 * np.pi * f * (times - latency))
    gf = np.exp(- (times - latency - (sigma / 4.) * rng.rand(1)) ** 2 /
                (2 * (sigma ** 2)))
    return 1e-9 * sinusoid * gf


I am working on the file "0.23/_downloads/eb0c29f55af0173daab811d4f4dc2f40/simulated_raw_data_using_subject_anatomy.ipynb".
The first task is:
Here, :class:~mne.simulation.SourceSimulator is used, which allows to
specify where (label), what (source_time_series), and when (events) event
type will occur.
We will add data for 4 areas, each of which contains 2 labels. Since add_data
method accepts 1 label per call, it will be called 2 times per area.
Evoked responses are generated such that the main component peaks at 100ms
with a duration of around 30ms, which first appears in the contralateral
cortex. This is followed by a response in the ipsilateral cortex with a peak
about 15ms after. The amplitude of the activations will be 2 times higher in
the contralateral region, as explained before.
When the activity occurs is defined using events. In this case, they are
taken from the original raw data. The first column is the sample of the
event, the second is not used. The third one is the event id, which is
different for each of the 4 areas.
Can you write Python code for it?

times = np.arange(150, dtype=np.float64) / info['sfreq']
duration = 0.03
rng = np.random.RandomState(7)
source_simulator = mne.simulation.SourceSimulator(src, tstep=tstep)

for region_id, region_name in enumerate(region_names, 1):
    events_tmp = events[np.where(events[:, 2] == region_id)[0], :]
    for i in range(2):
        label_name = activations[region_name][i][0]
        label_tmp = mne.read_labels_from_annot(subject, annot,
                                               subjects_dir=subjects_dir,
                                               regexp=label_name,
                                               verbose=False)
        label_tmp = label_tmp[0]
        amplitude_tmp = activations[region_name][i][1]
        if region_name.split('/')[1][0] == label_tmp.hemi[0]:
            latency_tmp = 0.115
        else:
            latency_tmp = 0.1
        wf_tmp = data_fun(times, latency_tmp, duration)
        source_simulator.add_data(label_tmp,
                                  amplitude_tmp * wf_tmp,
                                  events_tmp)

# To obtain a SourceEstimate object, we need to use `get_stc()` method of
# SourceSimulator class.
stc_data = source_simulator.get_stc()


I am working on the file "0.23/_downloads/eb0c29f55af0173daab811d4f4dc2f40/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 :footcite:DestrieuxEtAl2010 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', 30),          # label, activation (nAm)
         ('G_temp_sup-G_T_transv-rh', 60)],
    'auditory/right':
        [('G_temp_sup-G_T_transv-lh', 60),
         ('G_temp_sup-G_T_transv-rh', 30)],
    'visual/left':
        [('S_calcarine-lh', 30),
         ('S_calcarine-rh', 60)],
    'visual/right':
        [('S_calcarine-lh', 60),
         ('S_calcarine-rh', 30)],
}

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


I am working on the file "0.23/_downloads/eb0c29f55af0173daab811d4f4dc2f40/simulated_raw_data_using_subject_anatomy.ipynb".
The first task is:
Reconstruct simulated source time courses using dSPM inverse operator
Here, source time courses for auditory and visual areas are reconstructed
separately and their difference is shown. This was done merely for better
visual representation of source reconstruction.
As expected, when high activations appear in primary auditory areas, primary
visual areas will have low activations and vice versa.
Can you write Python code for it?

method, lambda2 = 'dSPM', 1. / 9.
inv = mne.minimum_norm.make_inverse_operator(epochs.info, fwd, noise_cov)
stc_aud = mne.minimum_norm.apply_inverse(
    evoked_aud_left, inv, lambda2, method)
stc_vis = mne.minimum_norm.apply_inverse(
    evoked_vis_right, inv, lambda2, method)
stc_diff = stc_aud - stc_vis

brain = stc_diff.plot(subjects_dir=subjects_dir, initial_time=0.1,
                      hemi='split', views=['lat', 'med'])


I am working on the file "0.23/_downloads/eb0c29f55af0173daab811d4f4dc2f40/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__)

# In this example, raw data will be simulated for the sample subject, so its
# information 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}

# Take only a few events for speed
events = events[:80]


I am working on the file "0.23/_downloads/ed1a04dd775648ca869bfcffae26faca/30_mne_dspm_loreta.ipynb".
The first task is:
Compute the evoked response
Let's just use the MEG channels for simplicity.
Can you write Python code for it?

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


I am working on the file "0.23/_downloads/ed1a04dd775648ca869bfcffae26faca/30_mne_dspm_loreta.ipynb".
The first task is:
Here we use peak getter to move visualization to the time point of the peak
and draw a marker at the maximum peak vertex.
Can you write Python code for it?

vertno_max, time_max = stc.get_peak(hemi='rh')

subjects_dir = data_path + '/subjects'
surfer_kwargs = dict(
    hemi='rh', subjects_dir=subjects_dir,
    clim=dict(kind='value', lims=[8, 12, 15]), views='lateral',
    initial_time=time_max, time_unit='s', size=(800, 800), smoothing_steps=10)
brain = stc.plot(**surfer_kwargs)
brain.add_foci(vertno_max, coords_as_verts=True, hemi='rh', color='blue',
               scale_factor=0.6, alpha=0.5)
brain.add_text(0.1, 0.9, 'dSPM (plus location of maximal activation)', 'title',
               font_size=14)

# The documentation website's movie is generated with:
# brain.save_movie(..., tmin=0.05, tmax=0.15, interpolation='linear',
#                  time_dilation=20, framerate=10, time_viewer=True)


I am working on the file "0.23/_downloads/ed1a04dd775648ca869bfcffae26faca/30_mne_dspm_loreta.ipynb".
The first task is:
Inverse modeling: MNE/dSPM on evoked and raw data
Here we first read the forward solution. You will likely need to compute
one for your own data -- see tut-forward for information on how
to do it.
Can you write Python code for it?

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


I am working on the file "0.23/_downloads/ed1a04dd775648ca869bfcffae26faca/30_mne_dspm_loreta.ipynb".
The first task is:
Process MEG data
Can you write Python code for it?

data_path = sample.data_path()
raw_fname = op.join(data_path, 'MEG', 'sample',
                    'sample_audvis_filt-0-40_raw.fif')

raw = mne.io.read_raw_fif(raw_fname)  # already has an average reference
events = mne.find_events(raw, stim_channel='STI 014')

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

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


I am working on the file "0.23/_downloads/ed1a04dd775648ca869bfcffae26faca/30_mne_dspm_loreta.ipynb".
The first task is:
Source localization with MNE/dSPM/sLORETA/eLORETA
The aim of this tutorial is to teach you how to compute and apply a linear
minimum-norm inverse method on evoked/raw/epochs data.
Can you write Python code for it?

import os.path as op

import numpy as np
import matplotlib.pyplot as plt

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


I am working on the file "0.23/_downloads/ed1a04dd775648ca869bfcffae26faca/30_mne_dspm_loreta.ipynb".
The first task is:
Visualization
We can look at different dipole activations:
Can you write Python code for it?

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


I am working on the file "0.23/_downloads/ed3aac2f41b33de8577252a462d2798c/mne_inverse_envelope_correlation_volume.ipynb".
The first task is:
Compute envelope correlations in volume source space
Compute envelope correlations of orthogonalized activity
:footcite:HippEtAl2012,KhanEtAl2018 in source space using resting state
CTF data in a volume source space.
Can you write Python code for it?

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

import os.path as op

import mne
from mne.beamformer import make_lcmv, apply_lcmv_epochs
from mne.connectivity import envelope_correlation
from mne.preprocessing import compute_proj_ecg, compute_proj_eog

data_path = mne.datasets.brainstorm.bst_resting.data_path()
subjects_dir = op.join(data_path, 'subjects')
subject = 'bst_resting'
trans = op.join(data_path, 'MEG', 'bst_resting', 'bst_resting-trans.fif')
bem = op.join(subjects_dir, subject, 'bem', subject + '-5120-bem-sol.fif')
raw_fname = op.join(data_path, 'MEG', 'bst_resting',
                    'subj002_spontaneous_20111102_01_AUX.ds')
crop_to = 60.


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

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


I am working on the file "0.23/_downloads/ed3aac2f41b33de8577252a462d2798c/mne_inverse_envelope_correlation_volume.ipynb".
The first task is:
Compute the degree and plot it
Can you write Python code for it?

degree = mne.connectivity.degree(corr, 0.15)
stc = mne.VolSourceEstimate(degree, [src[0]['vertno']], 0, 1, 'bst_resting')
brain = stc.plot(
    src, clim=dict(kind='percent', lims=[75, 85, 95]), colormap='gnuplot',
    subjects_dir=subjects_dir, mode='glass_brain')


I am working on the file "0.23/_downloads/ed3aac2f41b33de8577252a462d2798c/mne_inverse_envelope_correlation_volume.ipynb".
The first task is:
Here we do some things in the name of speed, such as crop (which will
hurt SNR) and downsample. Then we compute SSP projectors and apply them.
Can you write Python code for it?

raw = mne.io.read_raw_ctf(raw_fname, verbose='error')
raw.crop(0, crop_to).pick_types(meg=True, eeg=False).load_data().resample(80)
raw.apply_gradient_compensation(3)
projs_ecg, _ = compute_proj_ecg(raw, n_grad=1, n_mag=2)
projs_eog, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='MLT31-4407')
raw.info['projs'] += projs_ecg
raw.info['projs'] += projs_eog
raw.apply_proj()
cov = mne.compute_raw_covariance(raw)  # compute before band-pass of interest


I am working on the file "0.23/_downloads/efd09079125b2bd222e2dd62aaaccfa4/source_space_snr.ipynb".
The first task is:
Computing source space SNR
This example shows how to compute and plot source space SNR as in
:footcite:GoldenholzEtAl2009.
Can you write Python code for it?

# Author: Padma Sundaram <tottochan@gmail.com>
#         Kaisu Lankinen <klankinen@mgh.harvard.edu>
#
# License: BSD (3-clause)

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

print(__doc__)

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

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

# Read inverse operator:
inv_op = make_inverse_operator(evoked.info, fwd, cov, fixed=True, verbose=True)

# Calculate MNE:
snr = 3.0
lambda2 = 1.0 / snr ** 2
stc = apply_inverse(evoked, inv_op, lambda2, 'MNE', verbose=True)

# Calculate SNR in source space:
snr_stc = stc.estimate_snr(evoked.info, fwd, cov)

# Plot an average SNR across source points over time:
ave = np.mean(snr_stc.data, axis=0)

fig, ax = plt.subplots()
ax.plot(evoked.times, ave)
ax.set(xlabel='Time (sec)', ylabel='SNR MEG-EEG')
fig.tight_layout()

# Find time point of maximum SNR
maxidx = np.argmax(ave)

# Plot SNR on source space at the time point of maximum SNR:
kwargs = dict(initial_time=evoked.times[maxidx], hemi='split',
              views=['lat', 'med'], subjects_dir=subjects_dir, size=(600, 600),
              clim=dict(kind='value', lims=(-100, -70, -40)),
              transparent=True, colormap='viridis')
brain = snr_stc.plot(**kwargs)


I am working on the file "0.23/_downloads/efd09079125b2bd222e2dd62aaaccfa4/source_space_snr.ipynb".
The first task is:
EEG
Next we do the same for EEG and plot the result on the cortex:
Can you write Python code for it?

evoked_eeg = evoked.copy().pick_types(eeg=True, meg=False)
inv_op_eeg = make_inverse_operator(evoked_eeg.info, fwd, cov, fixed=True,
                                   verbose=True)
stc_eeg = apply_inverse(evoked_eeg, inv_op_eeg, lambda2, 'MNE', verbose=True)
snr_stc_eeg = stc_eeg.estimate_snr(evoked_eeg.info, fwd, cov)
brain = snr_stc_eeg.plot(**kwargs)


I am working on the file "0.23/_downloads/f1d68aba13226287585e777005a39f0a/15_handling_bad_channels.ipynb".
The first task is:
Handling bad channels
This tutorial covers manual marking of bad channels and reconstructing bad
channels based on good signals at other sensors.
As usual we'll start by importing the modules we need, and loading some example
data:
Can you write Python code for it?

import os
from copy import deepcopy
import numpy as np
import mne

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


I am working on the file "0.23/_downloads/f1d68aba13226287585e777005a39f0a/15_handling_bad_channels.ipynb".
The first task is:
Here you can see that the :file:.fif file we loaded from disk must have
been keeping track of channels marked as "bad" — which is good news, because
it means any changes we make to the list of bad channels will be preserved if
we save our data at intermediate stages and re-load it later. Since we saw
above that EEG 053 is one of the bad channels, let's look at it alongside
some other EEG channels to see what's bad about it. We can do this using the
standard :meth:~mne.io.Raw.plot method, and instead of listing the channel
names one by one (['EEG 050', 'EEG 051', ...]) we'll use a regular
expression_ to pick all the EEG channels between 050 and 059 with the
:func:~mne.pick_channels_regexp function (the . is a wildcard
character):
Can you write Python code for it?

picks = mne.pick_channels_regexp(raw.ch_names, regexp='EEG 05.')
raw.plot(order=picks, n_channels=len(picks))


I am working on the file "0.23/_downloads/f1d68aba13226287585e777005a39f0a/15_handling_bad_channels.ipynb".
The first task is:
Marking bad channels
Sometimes individual channels malfunction and provide data that is too noisy
to be usable. MNE-Python makes it easy to ignore those channels in the
analysis stream without actually deleting the data in those channels. It does
this by
keeping track of the bad channel indices in a list and looking at that list
when doing analysis or plotting tasks. The list of bad channels is stored in
the 'bads' field of the :class:~mne.Info object that is attached to
:class:~mne.io.Raw, :class:~mne.Epochs, and :class:~mne.Evoked objects.
Can you write Python code for it?


I am working on the file "0.23/_downloads/f1d68aba13226287585e777005a39f0a/15_handling_bad_channels.ipynb".
The first task is:
Note that we used the exclude=[] trick in the call to
:meth:~mne.io.Raw.pick_types to make sure the bad channels were not
automatically dropped from the selection. Here is the corresponding example
with the interpolated gradiometer channel; since there are more channels
we'll use a more transparent gray color this time:
Can you write Python code for it?

grad_data = raw.copy().pick_types(meg='grad', exclude=[])
grad_data_interp = grad_data.copy().interpolate_bads(reset_bads=False)

for data in (grad_data, grad_data_interp):
    data.plot(butterfly=True, color='#00000009', bad_color='r')


I am working on the file "0.23/_downloads/f1d68aba13226287585e777005a39f0a/15_handling_bad_channels.ipynb".
The first task is:
Notice first of all that the channels marked as "bad" are plotted in a light
gray color in a layer behind the other channels, to make it easy to
distinguish them from "good" channels. The plots make it clear that EEG
053 is not picking up scalp potentials at all, and MEG 2443 looks like
it's got a lot more internal noise than its neighbors — its signal is a few
orders of magnitude greater than the other MEG channels, making it a clear
candidate for exclusion.
If you want to change which channels are marked as bad, you can edit
raw.info['bads'] directly; it's an ordinary Python :class:list so the
usual list methods will work:
Can you write Python code for it?

original_bads = deepcopy(raw.info['bads'])
raw.info['bads'].append('EEG 050')               # add a single channel
raw.info['bads'].extend(['EEG 051', 'EEG 052'])  # add a list of channels
bad_chan = raw.info['bads'].pop(-1)  # remove the last entry in the list
raw.info['bads'] = original_bads     # change the whole list at once


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

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
label_name = 'Aud-rh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name

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

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

include = []
raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more

# Picks MEG channels
picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=True,
                       stim=False, include=include, exclude='bads')
reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)

# Load epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject,
                    preload=True)

# Compute a source estimate per frequency band including and excluding the
# evoked response
freqs = np.arange(7, 30, 2)  # define frequencies of interest
label = mne.read_label(fname_label)
n_cycles = freqs / 3.  # different number of cycle per frequency

# subtract the evoked response in order to exclude evoked activity
epochs_induced = epochs.copy().subtract_evoked()

plt.close('all')

for ii, (this_epochs, title) in enumerate(zip([epochs, epochs_induced],
                                              ['evoked + induced',
                                               'induced only'])):
    # compute the source space power and the inter-trial coherence
    power, itc = source_induced_power(
        this_epochs, inverse_operator, freqs, label, baseline=(-0.1, 0),
        baseline_mode='percent', n_cycles=n_cycles, n_jobs=1)

    power = np.mean(power, axis=0)  # average over sources
    itc = np.mean(itc, axis=0)  # average over sources
    times = epochs.times

    ##########################################################################
    # View time-frequency plots
    plt.subplots_adjust(0.1, 0.08,...


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

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


I am working on the file "0.23/_downloads/f398f296c84e53a14339d2c3c36e91a4/movement_detection.ipynb".
The first task is:
Annotate movement artifacts and reestimate dev_head_t
Periods, where the participant moved considerably, are contaminated by low
amplitude artifacts. When averaging the magnetic fields, the more spread the
head position, the bigger the cancellation due to different locations.
Similarly, the covariance will also be affected by severe head movement,
and source estimation will suffer low/smeared coregistration accuracy.
This example uses the continuous head position indicators (cHPI) times series
to annotate periods of head movement, then the device to head transformation
matrix is estimated from the artifact-free segments. The new head position will
be more representative of the actual head position during the recording.
Can you write Python code for it?

# Authors: Adonay Nunes <adonay.s.nunes@gmail.com>
#          Luke Bloy <luke.bloy@gmail.com>
# License: BSD (3-clause)

import os.path as op

import mne
from mne.datasets.brainstorm import bst_auditory
from mne.io import read_raw_ctf
from mne.preprocessing import annotate_movement, compute_average_dev_head_t

# Load data
data_path = bst_auditory.data_path()
data_path_MEG = op.join(data_path, 'MEG')
subject = 'bst_auditory'
subjects_dir = op.join(data_path, 'subjects')
trans_fname = op.join(data_path, 'MEG', 'bst_auditory',
                      'bst_auditory-trans.fif')
raw_fname1 = op.join(data_path_MEG, 'bst_auditory', 'S01_AEF_20131218_01.ds')
raw_fname2 = op.join(data_path_MEG, 'bst_auditory', 'S01_AEF_20131218_02.ds')
# read and concatenate two files
raw = read_raw_ctf(raw_fname1, preload=False)
mne.io.concatenate_raws([raw, read_raw_ctf(raw_fname2, preload=False)])
raw.crop(350, 410).load_data()
raw.resample(100, npad="auto")


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

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

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


I am working on the file "0.23/_downloads/f47934a488455dcef7b3567776837d1a/limo_data.ipynb".
The first task is:
About the data
In the original LIMO experiment (see :footcite:RousseletEtAl2010),
participants performed a
two-alternative forced choice task, discriminating between two face stimuli.
The same two faces were used during the whole experiment,
with varying levels of noise added, making the faces more or less
discernible to the observer (see Fig 1_ in :footcite:RousseletEtAl2008
for a similar approach).
The presented faces varied across a noise-signal (or phase-coherence)
continuum spanning from 0 to 85% in increasing steps of 5%.
In other words, faces with high phase-coherence (e.g., 85%) were easy to
identify, while faces with low phase-coherence (e.g., 5%) were hard to
identify and by extension very hard to discriminate.
Load the data
We'll begin by loading the data from subject 1 of the LIMO dataset.
Can you write Python code for it?

# This step can take a little while if you're loading the data for the
# first time.
limo_epochs = load_data(subject=subj)


I am working on the file "0.23/_downloads/f47934a488455dcef7b3567776837d1a/limo_data.ipynb".
The first task is:
As it can be seen above, conditions are coded as Face/A and Face/B.
Information about the phase-coherence of the presented faces is stored in the
epochs metadata. These information can be easily accessed by calling
limo_epochs.metadata. As shown below, the epochs metadata also contains
information about the presented faces for convenience.
Can you write Python code for it?


I am working on the file "0.23/_downloads/f47934a488455dcef7b3567776837d1a/limo_data.ipynb".
The first task is:
As shown above, there are some considerable differences between the
activation patterns evoked by stimuli with low vs. high phase-coherence at
the chosen electrodes.
Prepare data for linear regression analysis
Before we test the significance of these differences using linear
regression, we'll interpolate missing channels that were
dropped during preprocessing of the data.
Furthermore, we'll drop the EOG channels (marked by the "EXG" prefix)
present in the data:
Can you write Python code for it?

limo_epochs.interpolate_bads(reset_bads=True)
limo_epochs.drop_channels(['EXG1', 'EXG2', 'EXG3', 'EXG4'])


I am working on the file "0.23/_downloads/f47934a488455dcef7b3567776837d1a/limo_data.ipynb".
The first task is:
Conversely, there appears to be no (or very small) systematic effects when
comparing Face A and Face B stimuli. This is largely consistent with the
difference wave approach presented above.
Can you write Python code for it?

ts_args = dict(xlim=(-0.25, 0.5))

reg['face a - face b'].beta.plot_joint(ts_args=ts_args,
                                       title='Effect of Face A vs. Face B',
                                       times=[0.23])


I am working on the file "0.23/_downloads/f47934a488455dcef7b3567776837d1a/limo_data.ipynb".
The first task is:
Define predictor variables and design matrix
To run the regression analysis,
we need to create a design matrix containing information about the
variables (i.e., predictors) we want to use for prediction of brain
activity patterns. For this purpose, we'll use the information we have in
limo_epochs.metadata: phase-coherence and Face A vs. Face B.
Can you write Python code for it?

# name of predictors + intercept
predictor_vars = ['face a - face b', 'phase-coherence', 'intercept']

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


I am working on the file "0.23/_downloads/f47934a488455dcef7b3567776837d1a/limo_data.ipynb".
The first task is:
Extract regression coefficients
The results are stored within the object reg,
which is a dictionary of evoked objects containing
multiple inferential measures for each predictor in the design matrix.
Can you write Python code for it?

print('predictors are:', list(reg))
print('fields are:', [field for field in getattr(reg['intercept'], '_fields')])


I am working on the file "0.23/_downloads/f47934a488455dcef7b3567776837d1a/limo_data.ipynb".
The first task is:
Now let's take a closer look at the information in the epochs
metadata.
Can you write Python code for it?

# We want include all columns in the summary table
epochs_summary = limo_epochs.metadata.describe(include='all').round(3)
print(epochs_summary)


I am working on the file "0.23/_downloads/f47934a488455dcef7b3567776837d1a/limo_data.ipynb".
The first task is:
Now we can set up the linear model to be used in the analysis using
MNE-Python's func:~mne.stats.linear_regression function.
Can you write Python code for it?

reg = linear_regression(limo_epochs,
                        design_matrix=design,
                        names=predictor_vars)


I am working on the file "0.23/_downloads/f47934a488455dcef7b3567776837d1a/limo_data.ipynb".
The first task is:
Plot model results
Now we can access and plot the results of the linear regression analysis by
calling :samp:reg['{<name of predictor>}'].{<measure of interest>} and
using the
:meth:~mne.Evoked.plot_joint method just as we would do with any other
evoked object.
Below we can see a clear effect of phase-coherence, with higher
phase-coherence (i.e., better "face visibility") having a negative effect on
the activity measured at occipital electrodes around 200 to 250 ms following
stimulus onset.
Can you write Python code for it?

reg['phase-coherence'].beta.plot_joint(ts_args=ts_args,
                                       title='Effect of Phase-coherence',
                                       times=[0.23])


I am working on the file "0.23/_downloads/f47934a488455dcef7b3567776837d1a/limo_data.ipynb".
The first task is:
Single trial linear regression analysis with the LIMO dataset
Here we explore the structure of the data contained in the
LIMO dataset.
This example replicates and extends some of the main analysis
and tools integrated in LIMO MEEG, a MATLAB toolbox originally designed
to interface with EEGLAB_.
In summary, the example:

Fetches epoched data files for a single subject of the LIMO dataset
  :footcite:Rousselet2016. If the LIMO files are not found on disk, the
  fetcher mne.datasets.limo.load_data() will automatically download
  the files from a remote repository.

During import, information about the data (i.e., sampling rate, number of
  epochs per condition, number and name of EEG channels per subject, etc.) is
  extracted from the LIMO :file:.mat files stored on disk and added to the
  epochs structure as metadata.

Fits linear models on the single subject's data and visualizes inferential
  measures to evaluate the significance of the estimated effects.
Can you write Python code for it?

# Authors: Jose C. Garcia Alanis <alanis.jcg@gmail.com>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

from mne.datasets.limo import load_data
from mne.stats import linear_regression
from mne.viz import plot_events, plot_compare_evokeds
from mne import combine_evoked

print(__doc__)

# subject to use
subj = 1


I am working on the file "0.23/_downloads/f47934a488455dcef7b3567776837d1a/limo_data.ipynb".
The first task is:
Visualize events
We can visualise the distribution of the face events contained in the
limo_epochs structure. Events should appear clearly grouped, as the
epochs are ordered by condition.
Can you write Python code for it?

fig = plot_events(limo_epochs.events, event_id=limo_epochs.event_id)
fig.suptitle("Distribution of events in LIMO epochs")


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

# Face A minus Face B
difference_wave = combine_evoked([limo_epochs['Face/A'].average(),
                                  limo_epochs['Face/B'].average()],
                                 weights=[1, -1])

# plot difference wave
difference_wave.plot_joint(times=[0.15], title='Difference Face A - Face B')


I am working on the file "0.23/_downloads/f47934a488455dcef7b3567776837d1a/limo_data.ipynb".
The first task is:
We can also plot the corresponding T values.
Can you write Python code for it?

# use unit=False and scale=1 to keep values at their original
# scale (i.e., avoid conversion to micro-volt).
ts_args = dict(xlim=(-0.25, 0.5),
               unit=False)
topomap_args = dict(scalings=dict(eeg=1),
                    average=0.05)

fig = reg['phase-coherence'].t_val.plot_joint(ts_args=ts_args,
                                              topomap_args=topomap_args,
                                              times=[0.23])
fig.axes[0].set_ylabel('T-value')


I am working on the file "0.23/_downloads/f574d1e7527e4460eb09a16f6f836e35/60_maxwell_filtering_sss.ipynb".
The first task is:

Note

You can use the very same code as above to produce figures for
          *flat* channel detection. Simply replace the word "noisy" with
          "flat", and replace ``vmin=np.nanmin(limits)`` with
          ``vmax=np.nanmax(limits)``.

You can see the un-altered scores for each channel and time segment in the
left subplots, and thresholded scores – those which exceeded a certain limit
of noisiness – in the right subplots. While the right subplot is entirely
white for the magnetometers, we can see a horizontal line extending all the
way from left to right for the gradiometers. This line corresponds to channel
MEG 2443, which was reported as auto-detected noisy channel in the step
above. But we can also see another channel exceeding the limits, apparently
in a more transient fashion. It was therefore not detected as bad, because
the number of segments in which it exceeded the limits was less than 5,
which MNE-Python uses by default.

Note

You can request a different number of segments that must be
          found to be problematic before
          `~mne.preprocessing.find_bad_channels_maxwell` reports them as bad.
          To do this, pass the keyword argument ``min_count`` to the
          function.

Obviously, this algorithm is not perfect. Specifically, on closer inspection
of the raw data after looking at the diagnostic plots above, it becomes clear
that the channel exceeding the "noise" limits in some segments without
qualifying as "bad", in fact contains some flux jumps. There were just not
enough flux jumps in the recording for our automated procedure to report
the channel as bad. So it can still be useful to manually inspect and mark
bad channels. The channel in question is MEG 2313. Let's mark it as bad:
Can you write Python code for it?

raw.info['bads'] += ['MEG 2313']  # from manual inspection


I am working on the file "0.23/_downloads/f574d1e7527e4460eb09a16f6f836e35/60_maxwell_filtering_sss.ipynb".
The first task is:
After that, performing SSS and Maxwell filtering is done with a
single call to :func:~mne.preprocessing.maxwell_filter, with the crosstalk
and fine calibration filenames provided (if available):
Can you write Python code for it?

raw_sss = mne.preprocessing.maxwell_filter(
    raw, cross_talk=crosstalk_file, calibration=fine_cal_file, verbose=True)


I am working on the file "0.23/_downloads/f574d1e7527e4460eb09a16f6f836e35/60_maxwell_filtering_sss.ipynb".
The first task is:
Background on SSS and Maxwell filtering
Signal-space separation (SSS) :footcite:TauluKajola2005,TauluSimola2006
is a technique based on the physics
of electromagnetic fields. SSS separates the measured signal into components
attributable to sources inside the measurement volume of the sensor array
(the internal components), and components attributable to sources outside
the measurement volume (the external components). The internal and external
components are linearly independent, so it is possible to simply discard the
external components to reduce environmental noise. Maxwell filtering is a
related procedure that omits the higher-order components of the internal
subspace, which are dominated by sensor noise. Typically, Maxwell filtering
and SSS are performed together (in MNE-Python they are implemented together
in a single function).
Like SSP <tut-artifact-ssp>, SSS is a form of projection. Whereas SSP
empirically determines a noise subspace based on data (empty-room recordings,
EOG or ECG activity, etc) and projects the measurements onto a subspace
orthogonal to the noise, SSS mathematically constructs the external and
internal subspaces from spherical harmonics_ and reconstructs the sensor
signals using only the internal subspace (i.e., does an oblique projection).

Warning

Maxwell filtering was originally developed for Elekta Neuromag® systems,
    and should be considered *experimental* for non-Neuromag data. See the
    Notes section of the :func:`~mne.preprocessing.maxwell_filter` docstring
    for details.

The MNE-Python implementation of SSS / Maxwell filtering currently provides
the following features:

Basic bad channel detection
  (:func:~mne.preprocessing.find_bad_channels_maxwell)
Bad channel reconstruction
Cross-talk cancellation
Fine calibration correction
tSSS
Coordinate frame translation
Regularization of internal components using information theory
Raw movement compensation (using head positions estimated by MaxFilter)
cHPI...
Can you write Python code for it?

fine_cal_file = os.path.join(sample_data_folder, 'SSS', 'sss_cal_mgh.dat')
crosstalk_file = os.path.join(sample_data_folder, 'SSS', 'ct_sparse_mgh.fif')


I am working on the file "0.23/_downloads/f574d1e7527e4460eb09a16f6f836e35/60_maxwell_filtering_sss.ipynb".
The first task is:
Signal-space separation (SSS) and Maxwell filtering
This tutorial covers reducing environmental noise and compensating for head
movement with SSS and Maxwell filtering.
As usual we'll start by importing the modules we need, loading some
example data <sample-dataset>, and cropping it to save on memory:
Can you write Python code for it?

import os
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
import mne
from mne.preprocessing import find_bad_channels_maxwell

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


I am working on the file "0.23/_downloads/f574d1e7527e4460eb09a16f6f836e35/60_maxwell_filtering_sss.ipynb".
The first task is:
To see the effect, we can plot the data before and after SSS / Maxwell
filtering.
Can you write Python code for it?

raw.pick(['meg']).plot(duration=2, butterfly=True)
raw_sss.pick(['meg']).plot(duration=2, butterfly=True)


I am working on the file "0.23/_downloads/f574d1e7527e4460eb09a16f6f836e35/60_maxwell_filtering_sss.ipynb".
The first task is:
We called ~mne.preprocessing.find_bad_channels_maxwell with the optional
keyword argument return_scores=True, causing the function to return a
dictionary of all data related to the scoring used to classify channels as
noisy or flat. This information can be used to produce diagnostic figures.
In the following, we will generate such visualizations for
the automated detection of noisy gradiometer channels.
Can you write Python code for it?

# Only select the data forgradiometer channels.
ch_type = 'grad'
ch_subset = auto_scores['ch_types'] == ch_type
ch_names = auto_scores['ch_names'][ch_subset]
scores = auto_scores['scores_noisy'][ch_subset]
limits = auto_scores['limits_noisy'][ch_subset]
bins = auto_scores['bins']  # The the windows that were evaluated.
# We will label each segment by its start and stop time, with up to 3
# digits before and 3 digits after the decimal place (1 ms precision).
bin_labels = [f'{start:3.3f} – {stop:3.3f}'
              for start, stop in bins]

# We store the data in a Pandas DataFrame. The seaborn heatmap function
# we will call below will then be able to automatically assign the correct
# labels to all axes.
data_to_plot = pd.DataFrame(data=scores,
                            columns=pd.Index(bin_labels, name='Time (s)'),
                            index=pd.Index(ch_names, name='Channel'))

# First, plot the "raw" scores.
fig, ax = plt.subplots(1, 2, figsize=(12, 8))
fig.suptitle(f'Automated noisy channel detection: {ch_type}',
             fontsize=16, fontweight='bold')
sns.heatmap(data=data_to_plot, cmap='Reds', cbar_kws=dict(label='Score'),
            ax=ax[0])
[ax[0].axvline(x, ls='dashed', lw=0.25, dashes=(25, 15), color='gray')
    for x in range(1, len(bins))]
ax[0].set_title('All Scores', fontweight='bold')

# Now, adjust the color range to highlight segments that exceeded the limit.
sns.heatmap(data=data_to_plot,
            vmin=np.nanmin(limits),  # bads in input data have NaN limits
            cmap='Reds', cbar_kws=dict(label='Score'), ax=ax[1])
[ax[1].axvline(x, ls='dashed', lw=0.25, dashes=(25, 15), color='gray')
    for x in range(1, len(bins))]
ax[1].set_title('Scores > Limit', fontweight='bold')

# The figure title should not overlap with the subplots.
fig.tight_layout(rect=[0, 0.03, 1, 0.95])


I am working on the file "0.23/_downloads/f5853db1ea98f82173310d147f23289c/compute_mne_inverse_epochs_in_label.ipynb".
The first task is:
Compute MNE-dSPM inverse solution on single epochs
Compute dSPM inverse solution on single trial epochs restricted
to a brain label.
Can you write Python code for it?

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

import numpy as np
import matplotlib.pyplot as plt

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

print(__doc__)

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

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

# Using the same inverse operator when inspecting single trials Vs. evoked
snr = 3.0  # Standard assumption for average data but using it for single trial
lambda2 = 1.0 / snr ** 2

method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

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

# Set up pick list
include = []

# Add a bad channel
raw.info['bads'] += ['EEG 053']  # bads + 1 more

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

# Get evoked data (averaging across trials in sensor space)
evoked = epochs.average()

# Compute inverse solution and stcs for each epoch
# Use the same inverse operator as with evoked data (i.e., set nave)
# If you use a different nave, dSPM just scales by a factor sqrt(nave)
stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, label,
                            pick_ori="normal", nave=evoked.nave)

# Mean across trials...


I am working on the file "0.23/_downloads/f5853db1ea98f82173310d147f23289c/compute_mne_inverse_epochs_in_label.ipynb".
The first task is:
View activation time-series to illustrate the benefit of aligning/flipping
Can you write Python code for it?

times = 1e3 * stcs[0].times  # times in ms

plt.figure()
h0 = plt.plot(times, mean_stc.data.T, 'k')
h1, = plt.plot(times, label_mean, 'r', linewidth=3)
h2, = plt.plot(times, label_mean_flip, 'g', linewidth=3)
plt.legend((h0[0], h1, h2), ('all dipoles in label', 'mean',
                             'mean with sign flip'))
plt.xlabel('time (ms)')
plt.ylabel('dSPM value')
plt.show()


I am working on the file "0.23/_downloads/f5853db1ea98f82173310d147f23289c/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.23/_downloads/f61f2c2f6132bd3b1076dab7ac194713/20_events_from_raw.ipynb".
The first task is:
If you want to control which integers are mapped to each unique description
value, you can pass a :class:dict specifying the mapping as the
event_id parameter of :func:~mne.events_from_annotations; this
:class:dict will be returned unmodified as the event_dict.
.. TODO add this when the other tutorial is nailed down:
   Note that this event_dict can be used when creating
   :class:~mne.Epochs from :class:~mne.io.Raw objects, as demonstrated
   in :doc:epoching_tutorial_whatever_its_name_is.
Can you write Python code for it?

custom_mapping = {'rt': 77, 'square': 42}
(events_from_annot,
 event_dict) = mne.events_from_annotations(eeglab_raw, event_id=custom_mapping)
print(event_dict)
print(events_from_annot[:5])


I am working on the file "0.23/_downloads/f61f2c2f6132bd3b1076dab7ac194713/20_events_from_raw.ipynb".
The first task is:
Making multiple events per annotation
As mentioned above, you can generate equally-spaced events from an
:class:~mne.Annotations object using the chunk_duration parameter of
:func:~mne.events_from_annotations. For example, suppose we have an
annotation in our :class:~mne.io.Raw object indicating when the subject was
in REM sleep, and we want to perform a resting-state analysis on those spans
of data. We can create an Events array with a series of equally-spaced events
within each "REM" span, and then use those events to generate (potentially
overlapping) epochs that we can analyze further.
Can you write Python code for it?

# create the REM annotations
rem_annot = mne.Annotations(onset=[5, 41],
                            duration=[16, 11],
                            description=['REM'] * 2)
raw.set_annotations(rem_annot)
(rem_events,
 rem_event_dict) = mne.events_from_annotations(raw, chunk_duration=1.5)


I am working on the file "0.23/_downloads/f61f2c2f6132bd3b1076dab7ac194713/20_events_from_raw.ipynb".
The first task is:
More information on working with :class:~mne.Annotations objects, including
how to add annotations to :class:~mne.io.Raw objects interactively, and how
to plot, concatenate, load, save, and export :class:~mne.Annotations
objects can be found in the tutorial tut-annotate-raw.
Converting between Events arrays and Annotations objects
Once your experimental events are read into MNE-Python (as either an Events
array or an :class:~mne.Annotations object), you can easily convert between
the two formats as needed. You might do this because, e.g., an Events array
is needed for epoching continuous data, or because you want to take advantage
of the "annotation-aware" capability of some functions, which automatically
omit spans of data if they overlap with certain annotations.
To convert an :class:~mne.Annotations object to an Events array, use the
function :func:mne.events_from_annotations on the :class:~mne.io.Raw file
containing the annotations. This function will assign an integer Event ID to
each unique element of raw.annotations.description, and will return the
mapping of descriptions to integer Event IDs along with the derived Event
array. By default, one event will be created at the onset of each annotation;
this can be modified via the chunk_duration parameter of
:func:~mne.events_from_annotations to create equally spaced events within
each annotation span (see chunk-duration, below, or see
fixed-length-events for direct creation of an Events array of
equally-spaced events).
Can you write Python code for it?

events_from_annot, event_dict = mne.events_from_annotations(eeglab_raw)
print(event_dict)
print(events_from_annot[:5])


I am working on the file "0.23/_downloads/f61f2c2f6132bd3b1076dab7ac194713/20_events_from_raw.ipynb".
The first task is:
Now we can check that our events indeed fall in the ranges 5-21 seconds and
41-52 seconds, and are ~1.5 seconds apart (modulo some jitter due to the
sampling frequency). Here are the event times rounded to the nearest
millisecond:
Can you write Python code for it?

print(np.round((rem_events[:, 0] - raw.first_samp) / raw.info['sfreq'], 3))


I am working on the file "0.23/_downloads/f61f2c2f6132bd3b1076dab7ac194713/20_events_from_raw.ipynb".
The first task is:
Now, the annotations will appear automatically when plotting the raw data,
and will be color-coded by their label value:
Can you write Python code for it?


I am working on the file "0.23/_downloads/f61f2c2f6132bd3b1076dab7ac194713/20_events_from_raw.ipynb".
The first task is:
Parsing events from raw data
This tutorial describes how to read experimental events from raw recordings,
and how to convert between the two different representations of events within
MNE-Python (Events arrays and Annotations objects).
In the introductory tutorial <overview-tut-events-section> we saw an
example of reading experimental events from a :term:"STIM" channel <stim
channel>; here we'll discuss :term:events and :term:annotations more
broadly, give more detailed information about reading from STIM channels, and
give an example of reading events that are in a marker file or included in
the data file as an embedded array. The tutorials tut-event-arrays and
tut-annotate-raw discuss how to plot, combine, load, save, and
export :term:events and :class:~mne.Annotations (respectively), and the
latter tutorial also covers interactive annotation of :class:~mne.io.Raw
objects.
We'll begin by loading the Python modules we need, and loading the same
example data <sample-dataset> we used in the introductory tutorial
<tut-overview>, but to save memory we'll crop the :class:~mne.io.Raw object
to just 60 seconds before loading it into RAM:
Can you write Python code for it?

import os
import numpy as np
import mne

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


I am working on the file "0.23/_downloads/f61f2c2f6132bd3b1076dab7ac194713/20_events_from_raw.ipynb".
The first task is:
To make the opposite conversion (from an Events array to an
:class:~mne.Annotations object), you can create a mapping from integer
Event ID to string descriptions, use ~mne.annotations_from_events
to construct the :class:~mne.Annotations object, and call the
:meth:~mne.io.Raw.set_annotations method to add the annotations to the
:class:~mne.io.Raw object.
Because the sample data <sample-dataset> was recorded on a Neuromag
system (where sample numbering starts when the acquisition system is
initiated, not when the recording is initiated), we also need to pass in
the orig_time parameter so that the onsets are properly aligned relative
to the start of recording:
Can you write Python code for it?

mapping = {1: 'auditory/left', 2: 'auditory/right', 3: 'visual/left',
           4: 'visual/right', 5: 'smiley', 32: 'buttonpress'}
annot_from_events = mne.annotations_from_events(
    events=events, event_desc=mapping, sfreq=raw.info['sfreq'],
    orig_time=raw.info['meas_date'])
raw.set_annotations(annot_from_events)


I am working on the file "0.23/_downloads/fb92190904499e5a95e92ab70177abf7/60_make_fixed_length_epochs.ipynb".
The first task is:
Characteristics of Fixed Length Epochs
Fixed length epochs are generally unsuitable for event-related analyses. This
can be seen in an image map of our fixed length
epochs. When the epochs are averaged, as seen at the bottom of the plot,
misalignment between onsets of event-related activity results in noise.
Can you write Python code for it?

event_related_plot = epochs.plot_image(picks=['MEG 1142'])


I am working on the file "0.23/_downloads/fb92190904499e5a95e92ab70177abf7/60_make_fixed_length_epochs.ipynb".
The first task is:
Creating epochs of equal length
This tutorial shows how to create equal length epochs and briefly demonstrates
an example of their use in connectivity analysis.
First, we import necessary modules and read in a sample raw
data set. This data set contains brain activity that is event-related, i.e.
synchronized to the onset of auditory stimuli. However, rather than creating
epochs by segmenting the data around the onset of each stimulus, we will
create 30 second epochs that allow us to perform non-event-related analyses of
the signal.
Can you write Python code for it?

import os
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.preprocessing import compute_proj_ecg

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

raw = mne.io.read_raw_fif(sample_data_raw_file)


I am working on the file "0.23/_downloads/fb92190904499e5a95e92ab70177abf7/60_make_fixed_length_epochs.ipynb".
The first task is:
For this tutorial we'll crop and resample the raw data to a manageable size
for our web server to handle, ignore EEG channels, and remove the heartbeat
artifact so we don't get spurious correlations just because of that.
Can you write Python code for it?

raw.crop(tmax=150).resample(100).pick('meg')
ecg_proj, _ = compute_proj_ecg(raw, ch_name='MEG 0511')  # No ECG chan
raw.add_proj(ecg_proj)
raw.apply_proj()