I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
And now an example of a minimum-phase filter:
Can you write Python code for it?

h = mne.filter.create_filter(x, sfreq, l_freq=None, h_freq=f_p,
                             phase='minimum', fir_design='firwin')
x_min = np.convolve(h, x)
transition_band = 0.25 * f_p
f_s = f_p + transition_band
filter_dur = 6.6 / transition_band  # sec
n = int(sfreq * filter_dur)
freq = [0., f_p, f_s, sfreq / 2.]
gain = [1., 1., 0., 0.]
plot_filter(h, sfreq, freq, gain, 'Minimum-phase filter', flim=flim)


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
Applying FIR filters
Now lets look at some practical effects of these filters by applying
them to some data.
Let's construct a Gaussian-windowed sinusoid (i.e., Morlet imaginary part)
plus noise (random + line). Note that the original, clean signal contains
frequency content in both the pass band and transition bands of our
low-pass filter.
Can you write Python code for it?

dur = 10.
center = 2.
morlet_freq = f_p
tlim = [center - 0.2, center + 0.2]
tticks = [tlim[0], center, tlim[1]]
flim = [20, 70]

x = np.zeros(int(sfreq * dur) + 1)
blip = morlet(sfreq, [morlet_freq], n_cycles=7)[0].imag / 20.
n_onset = int(center * sfreq) - len(blip) // 2
x[n_onset:n_onset + len(blip)] += blip
x_orig = x.copy()

rng = np.random.RandomState(0)
x += rng.randn(len(x)) / 1000.
x += np.sin(2. * np.pi * 60. * np.arange(len(x)) / sfreq) / 2000.


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
Applying IIR filters
Now let's look at how our shallow and steep Butterworth IIR filters
perform on our Morlet signal from before:
Can you write Python code for it?

axes = plt.subplots(1, 2)[1]
yticks = np.arange(4) / -30.
yticklabels = ['Original', 'Noisy', 'Butterworth-2', 'Butterworth-8']
plot_signal(x_orig, offset=yticks[0])
plot_signal(x, offset=yticks[1])
plot_signal(x_shallow, offset=yticks[2])
plot_signal(x_steep, offset=yticks[3])
axes[0].set(xlim=tlim, title='IIR, Lowpass=%d Hz' % f_p, xticks=tticks,
            ylim=[-0.125, 0.025], yticks=yticks, yticklabels=yticklabels,)
for text in axes[0].get_yticklabels():
    text.set(rotation=45, size=8)
axes[1].set(xlim=flim, ylim=(-60, 10), xlabel='Frequency (Hz)',
            ylabel='Magnitude (dB)')
mne.viz.adjust_axes(axes)
mne.viz.tight_layout()
plt.show()


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
Background information on filtering
Here we give some background information on filtering in general,
and how it is done in MNE-Python in particular.
Recommended reading for practical applications of digital
filter design can be found in Parks & Burrus [1] and
Ifeachor and Jervis [2], and for filtering in an
M/EEG context we recommend reading Widmann et al. 2015 [7]_.
To see how to use the default filters in MNE-Python on actual data, see
the sphx_glr_auto_tutorials_plot_artifacts_correction_filtering.py
tutorial.
Problem statement
The practical issues with filtering electrophysiological data are covered
well by Widmann et al. in [7]_, in a follow-up to an article where they
conclude with this statement:
Filtering can result in considerable distortions of the time course
(and amplitude) of a signal as demonstrated by VanRullen (2011) [[3]_].
Thus, filtering should not be used lightly. However, if effects of
filtering are cautiously considered and filter artifacts are minimized,
a valid interpretation of the temporal dynamics of filtered
electrophysiological data is possible and signals missed otherwise
can be detected with filtering.

In other words, filtering can increase SNR, but if it is not used carefully,
it can distort data. Here we hope to cover some filtering basics so
users can better understand filtering tradeoffs, and why MNE-Python has
chosen particular defaults.
Filtering basics
Let's get some of the basic math down. In the frequency domain, digital
filters have a transfer function that is given by:
\begin{align}H(z) &= \frac{b_0 + b_1 z^{-1} + b_2 z^{-2} + ... + b_M z^{-M}}
                 {1 + a_1 z^{-1} + a_2 z^{-2} + ... + a_N z^{-M}} \
         &= \frac{\sum_0^Mb_kz^{-k}}{\sum_1^Na_kz^{-k}}\end{align}
In the time domain, the numerator coefficients $b_k$ and denominator
coefficients $a_k$ can be used to obtain our output data
$y(n)$ in terms of our input data $x(n)$ as:
\begin{align}:label: summations
y(n) &= b_0 x(n) + b_1 x(n-1) + ... + b_M x(n-M)
        - a_1 y(n-1) - a_2 y(n - 2) -...
Can you write Python code for it?

import numpy as np
from scipy import signal, fftpack
import matplotlib.pyplot as plt

from mne.time_frequency.tfr import morlet
from mne.viz import plot_filter, plot_ideal_filter

import mne

sfreq = 1000.
f_p = 40.
flim = (1., sfreq / 2.)  # limits for plotting


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
Both groups seem to acknowledge that the choices of filtering cutoffs, and
perhaps even the application of baseline correction, depend on the
characteristics of the data being investigated, especially when it comes to:

The frequency content of the underlying evoked activity relative
      to the filtering parameters.
The validity of the assumption of no consistent evoked activity
      in the baseline period.

We thus recommend carefully applying baseline correction and/or high-pass
values based on the characteristics of the data to be analyzed.
Filtering defaults
Defaults in MNE-Python
Most often, filtering in MNE-Python is done at the :class:mne.io.Raw level,
and thus :func:mne.io.Raw.filter is used. This function under the hood
(among other things) calls :func:mne.filter.filter_data to actually
filter the data, which by default applies a zero-phase FIR filter designed
using :func:scipy.signal.firwin. In Widmann et al. 2015 [7]_, they
suggest a specific set of parameters to use for high-pass filtering,
including:
"... providing a transition bandwidth of 25% of the lower passband
edge but, where possible, not lower than 2 Hz and otherwise the
distance from the passband edge to the critical frequency.”

In practice, this means that for each high-pass value l_freq or
low-pass value h_freq below, you would get this corresponding
l_trans_bandwidth or h_trans_bandwidth, respectively,
if the sample rate were 100 Hz (i.e., Nyquist frequency of 50 Hz):
+------------------+-------------------+-------------------+
| l_freq or h_freq | l_trans_bandwidth | h_trans_bandwidth |
+==================+===================+===================+
|             0.01 |              0.01 |               2.0 |
+------------------+-------------------+-------------------+
|              0.1 |               0.1 |               2.0 |
+------------------+-------------------+-------------------+
|              1.0 |               1.0 |               2.0 |
+------------------+-------------------+-------------------+
|              2.0 |    ...
Can you write Python code for it?

# Use the same settings as when calling e.g., `raw.filter()`
fir_coefs = mne.filter.create_filter(data=None,  # Data is only used for sanity checking, not strictly needed  # noqa
                                     sfreq=1000.,  # sfreq of your data in Hz
                                     l_freq=None,
                                     h_freq=40.,  # assuming a lowpass of 40 Hz
                                     method='fir',
                                     fir_window='hamming',
                                     fir_design='firwin',
                                     verbose=True)

# See the printed log for the transition bandwidth and filter length
# Alternatively, get the filter length through:
filter_length = fir_coefs.shape[0]


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
Both the MNE-Python 0.13 and MNE-C filhters have excellent frequency
attenuation, but it comes at a cost of potential
ringing (long-lasting ripples) in the time domain. Ringing can occur with
steep filters, especially on signals with frequency content around the
transition band. Our Morlet wavelet signal has power in our transition band,
and the time-domain ringing is thus more pronounced for the steep-slope,
long-duration filter than the shorter, shallower-slope filter:
Can you write Python code for it?

axes = plt.subplots(1, 2)[1]

def plot_signal(x, offset):
    t = np.arange(len(x)) / sfreq
    axes[0].plot(t, x + offset)
    axes[0].set(xlabel='Time (sec)', xlim=t[[0, -1]])
    X = fftpack.fft(x)
    freqs = fftpack.fftfreq(len(x), 1. / sfreq)
    mask = freqs >= 0
    X = X[mask]
    freqs = freqs[mask]
    axes[1].plot(freqs, 20 * np.log10(np.maximum(np.abs(X), 1e-16)))
    axes[1].set(xlim=flim)

yticks = np.arange(7) / -30.
yticklabels = ['Original', 'Noisy', 'FIR-firwin (0.16)', 'FIR-firwin2 (0.14)',
               'FIR-steep (0.13)', 'FIR-steep (MNE-C)', 'Minimum-phase']
plot_signal(x_orig, offset=yticks[0])
plot_signal(x, offset=yticks[1])
plot_signal(x_v16, offset=yticks[2])
plot_signal(x_v14, offset=yticks[3])
plot_signal(x_v13, offset=yticks[4])
plot_signal(x_mne_c, offset=yticks[5])
plot_signal(x_min, offset=yticks[6])
axes[0].set(xlim=tlim, title='FIR, Lowpass=%d Hz' % f_p, xticks=tticks,
            ylim=[-0.200, 0.025], yticks=yticks, yticklabels=yticklabels,)
for text in axes[0].get_yticklabels():
    text.set(rotation=45, size=8)
axes[1].set(xlim=flim, ylim=(-60, 10), xlabel='Frequency (Hz)',
            ylabel='Magnitude (dB)')
mne.viz.tight_layout()
plt.show()


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
Filter it with a different design mode fir_design="firwin2", and also
compensate for the constant filter delay. This method does not produce
quite as sharp a transition compared to fir_design="firwin", despite
being twice as long:
Can you write Python code for it?

transition_band = 0.25 * f_p
f_s = f_p + transition_band
filter_dur = 6.6 / transition_band  # sec
n = int(sfreq * filter_dur)
freq = [0., f_p, f_s, sfreq / 2.]
gain = [1., 1., 0., 0.]
# This would be equivalent:
# h = signal.firwin2(n, freq, gain, nyq=sfreq / 2.)
h = mne.filter.create_filter(x, sfreq, l_freq=None, h_freq=f_p,
                             fir_design='firwin2')
x_v14 = np.convolve(h, x)[len(h) // 2:]

plot_filter(h, sfreq, freq, gain, 'MNE-Python 0.14 default', flim=flim)


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
IIR filters
MNE-Python also offers IIR filtering functionality that is based on the
methods from :mod:scipy.signal. Specifically, we use the general-purpose
functions :func:scipy.signal.iirfilter and :func:scipy.signal.iirdesign,
which provide unified interfaces to IIR filter design.
Designing IIR filters
Let's continue with our design of a 40 Hz low-pass filter, and look at
some trade-offs of different IIR filters.
Often the default IIR filter is a Butterworth filter_, which is designed
to have a maximally flat pass-band. Let's look at a few orders of filter,
i.e., a few different number of coefficients used and therefore steepness
of the filter:

Note

Notice that the group delay (which is related to the phase) of
          the IIR filters below are not constant. In the FIR case, we can
          design so-called linear-phase filters that have a constant group
          delay, and thus compensate for the delay (making the filter
          acausal) if necessary. This cannot be done with IIR filters, as
          they have a non-linear phase (non-constant group delay). As the
          filter order increases, the phase distortion near and in the
          transition band worsens. However, if acausal (forward-backward)
          filtering can be used, e.g. with :func:`scipy.signal.filtfilt`,
          these phase issues can theoretically be mitigated.

Can you write Python code for it?

sos = signal.iirfilter(2, f_p / nyq, btype='low', ftype='butter', output='sos')
plot_filter(dict(sos=sos), sfreq, freq, gain, 'Butterworth order=2', flim=flim)

# Eventually this will just be from scipy signal.sosfiltfilt, but 0.18 is
# not widely adopted yet (as of June 2016), so we use our wrapper...
sosfiltfilt = mne.fixes.get_sosfiltfilt()
x_shallow = sosfiltfilt(sos, x)


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
In response, Maess et al. 2016 [11]_ note that these simulations do not
address cases of pre-stimulus activity that is shared across conditions, as
applying baseline correction will effectively copy the topology outside the
baseline period. We can see this if we give our signal x with some
consistent pre-stimulus activity, which makes everything look bad.

Note

An important thing to keep in mind with these plots is that they
          are for a single simulated sensor. In multielectrode recordings
          the topology (i.e., spatial pattiern) of the pre-stimulus activity
          will leak into the post-stimulus period. This will likely create a
          spatially varying distortion of the time-domain signals, as the
          averaged pre-stimulus spatial pattern gets subtracted from the
          sensor time courses.

Putting some activity in the baseline period:
Can you write Python code for it?

n_pre = (t < 0).sum()
sig_pre = 1 - np.cos(2 * np.pi * np.arange(n_pre) / (0.5 * n_pre))
x[:n_pre] += sig_pre
baseline_plot(x)


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
Now we have very sharp frequency suppression, but our filter rings for the
entire second. So this naïve method is probably not a good way to build
our low-pass filter.
Fortunately, there are multiple established methods to design FIR filters
based on desired response characteristics. These include:
1. The Remez_ algorithm (:func:`scipy.signal.remez`, `MATLAB firpm`_)
2. Windowed FIR design (:func:`scipy.signal.firwin2`, `MATLAB fir2`_
   and :func:`scipy.signal.firwin`)
3. Least squares designs (:func:`scipy.signal.firls`, `MATLAB firls`_)
4. Frequency-domain design (construct filter in Fourier
   domain and use an :func:`IFFT <scipy.fftpack.ifft>` to invert it)

Note

Remez and least squares designs have advantages when there are
          "do not care" regions in our frequency response. However, we want
          well controlled responses in all frequency regions.
          Frequency-domain construction is good when an arbitrary response
          is desired, but generally less clean (due to sampling issues) than
          a windowed approach for more straightfroward filter applications.
          Since our filters (low-pass, high-pass, band-pass, band-stop)
          are fairly simple and we require precise control of all frequency
          regions, here we will use and explore primarily windowed FIR
          design.

If we relax our frequency-domain filter requirements a little bit, we can
use these functions to construct a lowpass filter that instead has a
transition band, or a region between the pass frequency $f_p$
and stop frequency $f_s$, e.g.:
Can you write Python code for it?

trans_bandwidth = 10  # 10 Hz transition band
f_s = f_p + trans_bandwidth  # = 50 Hz

freq = [0., f_p, f_s, nyq]
gain = [1., 1., 0., 0.]
ax = plt.subplots(1, figsize=third_height)[1]
title = '%s Hz lowpass with a %s Hz transition' % (f_p, trans_bandwidth)
plot_ideal_filter(freq, gain, ax, title=title, flim=flim)


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
Similarly, in a P300 paradigm reported by Kappenman & Luck 2010 [12]_,
they found that applying a 1 Hz high-pass decreased the probaility of
finding a significant difference in the N100 response, likely because
the P300 response was smeared (and inverted) in time by the high-pass
filter such that it tended to cancel out the increased N100. However,
they nonetheless note that some high-passing can still be useful to deal
with drifts in the data.
Even though these papers generally advise a 0.1 HZ or lower frequency for
a high-pass, it is important to keep in mind (as most authors note) that
filtering choices should depend on the frequency content of both the
signal(s) of interest and the noise to be suppressed. For example, in
some of the MNE-Python examples involving ch_sample_data,
high-pass values of around 1 Hz are used when looking at auditory
or visual N100 responses, because we analyze standard (not deviant) trials
and thus expect that contamination by later or slower components will
be limited.
Baseline problems (or solutions?)
In an evolving discussion, Tanner et al. 2015 [8] suggest using baseline
correction to remove slow drifts in data. However, Maess et al. 2016 [9]
suggest that baseline correction, which is a form of high-passing, does
not offer substantial advantages over standard high-pass filtering.
Tanner et al. [10]_ rebutted that baseline correction can correct for
problems with filtering.
To see what they mean, consider again our old simulated signal x from
before:
Can you write Python code for it?

def baseline_plot(x):
    all_axes = plt.subplots(3, 2)[1]
    for ri, (axes, freq) in enumerate(zip(all_axes, [0.1, 0.3, 0.5])):
        for ci, ax in enumerate(axes):
            if ci == 0:
                iir_hp = signal.iirfilter(4, freq / sfreq, btype='highpass',
                                          output='sos')
                x_hp = sosfiltfilt(iir_hp, x, padlen=0)
            else:
                x_hp -= x_hp[t < 0].mean()
            ax.plot(t, x, color='0.5')
            ax.plot(t, x_hp, color='k', linestyle='--')
            if ri == 0:
                ax.set(title=('No ' if ci == 0 else '') +
                       'Baseline Correction')
            ax.set(xticks=tticks, ylim=ylim, xlim=xlim, xlabel=xlabel)
            ax.set_ylabel('%0.1f Hz' % freq, rotation=0,
                          horizontalalignment='right')
        mne.viz.adjust_axes(axes)
    mne.viz.tight_layout()
    plt.suptitle(title)
    plt.show()

baseline_plot(x)


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
Since our lowpass is around 40 Hz with a 10 Hz transition, we can actually
use a shorter filter (5 cycles at 10 Hz = 0.5 sec) and still get okay
stop-band attenuation:
Can you write Python code for it?

n = int(round(sfreq * 0.5)) + 1
h = signal.firwin2(n, freq, gain, nyq=nyq)
plot_filter(h, sfreq, freq, gain, 'Windowed 10-Hz transition (0.5 sec)',
            flim=flim)


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
So far we have only discussed acausal filtering, which means that each
sample at each time point $t$ is filtered using samples that come
after ($t + \Delta t$) and before ($t - \Delta t$) $t$.
In this sense, each sample is influenced by samples that come both before
and after it. This is useful in many cases, espcially because it does not
delay the timing of events.
However, sometimes it can be beneficial to use causal filtering,
whereby each sample $t$ is filtered only using time points that came
after it.
Note that the delay is variable (whereas for linear/zero-phase filters it
is constant) but small in the pass-band. Unlike zero-phase filters, which
require time-shifting backward the output of a linear-phase filtering stage
(and thus becoming acausal), minimum-phase filters do not require any
compensation to achieve small delays in the passband. Note that as an
artifact of the minimum phase filter construction step, the filter does
not end up being as steep as the linear/zero-phase version.
We can construct a minimum-phase filter from our existing linear-phase
filter with the minimum_phase function (that will be in SciPy 0.19's
:mod:scipy.signal), and note that the falloff is not as steep:
Can you write Python code for it?

h_min = mne.fixes.minimum_phase(h)
plot_filter(h_min, sfreq, freq, gain, 'Minimum-phase', flim=flim)


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
Some pitfalls of filtering
Multiple recent papers have noted potential risks of drawing
errant inferences due to misapplication of filters.
Low-pass problems
Filters in general, especially those that are acausal (zero-phase), can make
activity appear to occur earlier or later than it truly did. As
mentioned in VanRullen 2011 [3], investigations of commonly (at the time)
used low-pass filters created artifacts when they were applied to smulated
data. However, such deleterious effects were minimal in many real-world
examples in Rousselet 2012 [5].
Perhaps more revealing, it was noted in Widmann & Schröger 2012 [6] that
the problematic low-pass filters from VanRullen 2011 [3]:

Used a least-squares design (like :func:scipy.signal.firls) that
      included "do-not-care" transition regions, which can lead to
      uncontrolled behavior.
Had a filter length that was independent of the transition bandwidth,
      which can cause excessive ringing and signal distortion.

High-pass problems
When it comes to high-pass filtering, using corner frequencies above 0.1 Hz
were found in Acunzo et al. 2012 [4]_ to:
"...generate a systematic bias easily leading to misinterpretations of
   neural activity.”
In a related paper, Widmann et al. 2015 [7] also came to suggest a 0.1 Hz
highpass. And more evidence followed in Tanner et al. 2015 [8] of such
distortions. Using data from language ERP studies of semantic and syntactic
processing (i.e., N400 and P600), using a high-pass above 0.3 Hz caused
significant effects to be introduced implausibly early when compared to the
unfiltered data. From this, the authors suggested the optimal high-pass
value for language processing to be 0.1 Hz.
We can recreate a problematic simulation from Tanner et al. 2015 [8]_:
"The simulated component is a single-cycle cosine wave with an amplitude
   of 5µV, onset of 500 ms poststimulus, and duration of 800 ms. The
   simulated component was embedded in 20 s of zero values to avoid
   filtering edge effects... Distortions [were] caused by 2 Hz...
Can you write Python code for it?

x = np.zeros(int(2 * sfreq))
t = np.arange(0, len(x)) / sfreq - 0.2
onset = np.where(t >= 0.5)[0][0]
cos_t = np.arange(0, int(sfreq * 0.8)) / sfreq
sig = 2.5 - 2.5 * np.cos(2 * np.pi * (1. / 0.8) * cos_t)
x[onset:onset + len(sig)] = sig

iir_lp_30 = signal.iirfilter(2, 30. / sfreq, btype='lowpass')
iir_hp_p1 = signal.iirfilter(2, 0.1 / sfreq, btype='highpass')
iir_lp_2 = signal.iirfilter(2, 2. / sfreq, btype='lowpass')
iir_hp_2 = signal.iirfilter(2, 2. / sfreq, btype='highpass')
x_lp_30 = signal.filtfilt(iir_lp_30[0], iir_lp_30[1], x, padlen=0)
x_hp_p1 = signal.filtfilt(iir_hp_p1[0], iir_hp_p1[1], x, padlen=0)
x_lp_2 = signal.filtfilt(iir_lp_2[0], iir_lp_2[1], x, padlen=0)
x_hp_2 = signal.filtfilt(iir_hp_2[0], iir_hp_2[1], x, padlen=0)

xlim = t[[0, -1]]
ylim = [-2, 6]
xlabel = 'Time (sec)'
ylabel = r'Amplitude ($\mu$V)'
tticks = [0, 0.5, 1.3, t[-1]]
axes = plt.subplots(2, 2)[1].ravel()
for ax, x_f, title in zip(axes, [x_lp_2, x_lp_30, x_hp_2, x_hp_p1],
                          ['LP$_2$', 'LP$_{30}$', 'HP$_2$', 'LP$_{0.1}$']):
    ax.plot(t, x, color='0.5')
    ax.plot(t, x_f, color='k', linestyle='--')
    ax.set(ylim=ylim, xlim=xlim, xticks=tticks,
           title=title, xlabel=xlabel, ylabel=ylabel)
mne.viz.adjust_axes(axes)
mne.viz.tight_layout()
plt.show()


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
The falloff of this filter is not very steep.

Note

Here we have made use of second-order sections (SOS)
          by using :func:`scipy.signal.sosfilt` and, under the
          hood, :func:`scipy.signal.zpk2sos` when passing the
          ``output='sos'`` keyword argument to
          :func:`scipy.signal.iirfilter`. The filter definitions
          given in tut_filtering_basics_ use the polynomial
          numerator/denominator (sometimes called "tf") form ``(b, a)``,
          which are theoretically equivalent to the SOS form used here.
          In practice, however, the SOS form can give much better results
          due to issues with numerical precision (see
          :func:`scipy.signal.sosfilt` for an example), so SOS should be
          used when possible to do IIR filtering.

Let's increase the order, and note that now we have better attenuation,
with a longer impulse response:
Can you write Python code for it?

sos = signal.iirfilter(8, f_p / nyq, btype='low', ftype='butter', output='sos')
plot_filter(dict(sos=sos), sfreq, freq, gain, 'Butterworth order=8', flim=flim)
x_steep = sosfiltfilt(sos, x)


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
There are other types of IIR filters that we can use. For a complete list,
check out the documentation for :func:scipy.signal.iirdesign. Let's
try a Chebychev (type I) filter, which trades off ripple in the pass-band
to get better attenuation in the stop-band:
Can you write Python code for it?

sos = signal.iirfilter(8, f_p / nyq, btype='low', ftype='cheby1', output='sos',
                       rp=1)  # dB of acceptable pass-band ripple
plot_filter(dict(sos=sos), sfreq, freq, gain,
            'Chebychev-1 order=8, ripple=1 dB', flim=flim)


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
This filter hypothetically achieves zero ripple in the frequency domain,
perfect attenuation, and perfect steepness. However, due to the discontunity
in the frequency response, the filter would require infinite ringing in the
time domain (i.e., infinite order) to be realized. Another way to think of
this is that a rectangular window in frequency is actually sinc_ function
in time, which requires an infinite number of samples, and thus infinite
time, to represent. So although this filter has ideal frequency suppression,
it has poor time-domain characteristics.
Let's try to naïvely make a brick-wall filter of length 0.1 sec, and look
at the filter itself in the time domain and the frequency domain:
Can you write Python code for it?

n = int(round(0.1 * sfreq)) + 1
t = np.arange(-n // 2, n // 2) / sfreq  # center our sinc
h = np.sinc(2 * f_p * t) / (4 * np.pi)
plot_filter(h, sfreq, freq, gain, 'Sinc (0.1 sec)', flim=flim)


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
This is actually set to become the default type of filter used in MNE-Python
in 0.14 (see tut_filtering_in_python).
Let's also filter with the MNE-Python 0.13 default, which is a
long-duration, steep cutoff FIR that gets applied twice:
Can you write Python code for it?

transition_band = 0.5  # Hz
f_s = f_p + transition_band
filter_dur = 10.  # sec
n = int(sfreq * filter_dur)
freq = [0., f_p, f_s, sfreq / 2.]
gain = [1., 1., 0., 0.]
# This would be equivalent
# h = signal.firwin2(n, freq, gain, nyq=sfreq / 2.)
h = mne.filter.create_filter(x, sfreq, l_freq=None, h_freq=f_p,
                             h_trans_bandwidth=transition_band,
                             filter_length='%ss' % filter_dur,
                             fir_design='firwin2')
x_v13 = np.convolve(np.convolve(h, x)[::-1], h)[::-1][len(h) - 1:-len(h) - 1]

plot_filter(h, sfreq, freq, gain, 'MNE-Python 0.13 default', flim=flim)


I am working on the file "0.17/_downloads/26e7a9a235c1f1a45a51c99f55fafe0d/plot_background_filtering.ipynb".
The first task is:
This is not so good! Making the filter 10 times longer (1 sec) gets us a
bit better stop-band suppression, but still has a lot of ringing in
the time domain. Note the x-axis is an order of magnitude longer here,
and the filter has a correspondingly much longer group delay (again equal
to half the filter length, or 0.5 seconds):
Can you write Python code for it?

n = int(round(1. * sfreq)) + 1
t = np.arange(-n // 2, n // 2) / sfreq
h = np.sinc(2 * f_p * t) / (4 * np.pi)
plot_filter(h, sfreq, freq, gain, 'Sinc (1.0 sec)', flim=flim)


I am working on the file "0.17/_downloads/275d6fecfc61c14ad9e91bb36b7359e0/plot_stats_cluster_erp.ipynb".
The first task is:
Absent specific hypotheses, we can also conduct an exploratory
mass-univariate analysis at all sensors and time points. This requires
correcting for multiple tests.
MNE offers various methods for this; amongst them, cluster-based permutation
methods allow deriving power from the spatio-temoral correlation structure
of the data. Here, we use TFCE.
Can you write Python code for it?

# Calculate statistical thresholds
con = find_ch_connectivity(epochs.info, "eeg")

# Extract data: transpose because the cluster test requires channels to be last
# In this case, inference is done over items. In the same manner, we could
# also conduct the test over, e.g., subjects.
X = [long_words.get_data().transpose(0, 2, 1),
     short_words.get_data().transpose(0, 2, 1)]
tfce = dict(start=.2, step=.2)

t_obs, clusters, cluster_pv, h0 = spatio_temporal_cluster_test(
    X, tfce, n_permutations=100)  # a more standard number would be 1000+
significant_points = cluster_pv.reshape(t_obs.shape).T < .05
print(str(significant_points.sum()) + " points selected by TFCE ...")


I am working on the file "0.17/_downloads/275d6fecfc61c14ad9e91bb36b7359e0/plot_stats_cluster_erp.ipynb".
The first task is:
If we have a specific point in space and time we wish to test, it can be
convenient to convert the data into Pandas Dataframe format. In this case,
the :class:mne.Epochs object has a convenient
:meth:mne.Epochs.to_data_frame method, which returns a dataframe.
This dataframe can then be queried for specific time windows and sensors.
The extracted data can be submitted to standard statistical tests. Here,
we conduct t-tests on the difference between long and short words.
Can you write Python code for it?

time_windows = ((.2, .25), (.35, .45))
elecs = ["Fz", "Cz", "Pz"]

# display the EEG data in Pandas format (first 5 rows)
print(epochs.to_data_frame()[elecs].head())

report = "{elec}, time: {tmin}-{tmax} s; t({df})={t_val:.3f}, p={p:.3f}"
print("\nTargeted statistical test results:")
for (tmin, tmax) in time_windows:
    long_df = long_words.copy().crop(tmin, tmax).to_data_frame()
    short_df = short_words.copy().crop(tmin, tmax).to_data_frame()
    for elec in elecs:
        # extract data
        A = long_df[elec].groupby("condition").mean()
        B = short_df[elec].groupby("condition").mean()

        # conduct t test
        t, p = ttest_ind(A, B)

        # display results
        format_dict = dict(elec=elec, tmin=tmin, tmax=tmax,
                           df=len(epochs.events) - 2, t_val=t, p=p)
        print(report.format(**format_dict))


I am working on the file "0.17/_downloads/275d6fecfc61c14ad9e91bb36b7359e0/plot_stats_cluster_erp.ipynb".
The first task is:
The results of these mass univariate analyses can be visualised by plotting
:class:mne.Evoked objects as images (via :class:mne.Evoked.plot_image)
and masking points for significance.
Here, we group channels by Regions of Interest to facilitate localising
effects on the head.
Can you write Python code for it?

# We need an evoked object to plot the image to be masked
evoked = mne.combine_evoked([long_words.average(), -short_words.average()],
                            weights='equal')  # calculate difference wave
time_unit = dict(time_unit="s")
evoked.plot_joint(title="Long vs. short words", ts_args=time_unit,
                  topomap_args=time_unit)  # show difference wave

# Create ROIs by checking channel labels
selections = make_1020_channel_selections(evoked.info, midline="12z")

# Visualize the results
fig, axes = plt.subplots(nrows=3, figsize=(8, 8))
axes = {sel: ax for sel, ax in zip(selections, axes.ravel())}
evoked.plot_image(axes=axes, group_by=selections, colorbar=False, show=False,
                  mask=significant_points, show_names="all", titles=None,
                  **time_unit)
plt.colorbar(axes["Left"].images[-1], ax=list(axes.values()), shrink=.3,
             label="uV")

plt.show()


I am working on the file "0.17/_downloads/275d6fecfc61c14ad9e91bb36b7359e0/plot_stats_cluster_erp.ipynb".
The first task is:
Visualising statistical significance thresholds on EEG data
MNE-Python provides a range of tools for statistical hypothesis testing
and the visualisation of the results. Here, we show a few options for
exploratory and confirmatory tests - e.g., targeted t-tests, cluster-based
permutation approaches (here with Threshold-Free Cluster Enhancement);
and how to visualise the results.
The underlying data comes from [1]; we contrast long vs. short words.
TFCE is described in [2].
References
.. [1] Dufau, S., Grainger, J., Midgley, KJ., Holcomb, PJ. A thousand
   words are worth a picture: Snapshots of printed-word processing in an
   event-related potential megastudy. Psychological Science, 2015
.. [2] Smith and Nichols 2009, "Threshold-free cluster enhancement:
   addressing problems of smoothing, threshold dependence, and
   localisation in cluster inference", NeuroImage 44 (2009) 83-98.
Can you write Python code for it?

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

import mne
from mne.channels import find_ch_connectivity, make_1020_channel_selections
from mne.stats import spatio_temporal_cluster_test

np.random.seed(0)

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

# Split up the data by the median length in letters via the attached metadata
median_value = str(epochs.metadata[name].median())
long_words = epochs[name + " > " + median_value]
short_words = epochs[name + " < " + median_value]


I am working on the file "0.17/_downloads/285b08fd9daa300c4b586365a3234831/plot_read_evoked.ipynb".
The first task is:
Reading and writing an evoked file
This script shows how to read and write evoked datasets.
Can you write Python code for it?

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

from mne import read_evokeds
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

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

# Reading
condition = 'Left Auditory'
evoked = read_evokeds(fname, condition=condition, baseline=(None, 0),
                      proj=True)


I am working on the file "0.17/_downloads/285b08fd9daa300c4b586365a3234831/plot_read_evoked.ipynb".
The first task is:
Show result as a butterfly plot:
By using exclude=[] bad channels are not excluded and are shown in red
Can you write Python code for it?

evoked.plot(exclude=[], time_unit='s')

# Show result as a 2D image (x: time, y: channels, color: amplitude)
evoked.plot_image(exclude=[], time_unit='s')


I am working on the file "0.17/_downloads/2aba6a5c9f79fe16cdce1a232bc5e327/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Brainstorm Elekta phantom dataset tutorial
Here we compute the evoked from raw for the Brainstorm Elekta phantom
tutorial dataset. For comparison, see [1]_ and:
http://neuroimage.usc.edu/brainstorm/Tutorials/PhantomElekta

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

# sphinx_gallery_thumbnail_number = 9

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

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

import mne
from mne import find_events, fit_dipole
from mne.datasets.brainstorm import bst_phantom_elekta
from mne.io import read_raw_fif

from mayavi import mlab
print(__doc__)


I am working on the file "0.17/_downloads/2aba6a5c9f79fe16cdce1a232bc5e327/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Data channel array consisted of 204 MEG planor gradiometers,
102 axial magnetometers, and 3 stimulus channels. Let's get the events
for the phantom, where each dipole (1-32) gets its own event:
Can you write Python code for it?

events = find_events(raw, 'STI201')
raw.plot(events=events)
raw.info['bads'] = ['MEG2421']


I am working on the file "0.17/_downloads/2aba6a5c9f79fe16cdce1a232bc5e327/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Do a quick visualization of how much variance we explained, putting the
data and residuals on the same scale (here the "time points" are the
32 dipole peak values that we fit):
Can you write Python code for it?

fig, axes = plt.subplots(2, 1)
evoked.plot(axes=axes)
for ax in axes:
    ax.texts = []
    for line in ax.lines:
        line.set_color('#98df81')
residual.plot(axes=axes)


I am working on the file "0.17/_downloads/2aba6a5c9f79fe16cdce1a232bc5e327/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Let's do some dipole fits. We first compute the noise covariance,
then do the fits for each event_id taking the time instant that maximizes
the global field power.
Can you write Python code for it?

# here we can get away with using method='oas' for speed (faster than "shrunk")
# but in general "shrunk" is usually better
cov = mne.compute_covariance(
    epochs, tmax=0, method='oas', rank=None)
mne.viz.plot_evoked_white(epochs['1'].average(), cov)

data = []
t_peak = 0.036  # true for Elekta phantom
for ii in event_id:
    evoked = epochs[str(ii)].average().crop(t_peak, t_peak)
    data.append(evoked.data[:, 0])
evoked = mne.EvokedArray(np.array(data).T, evoked.info, tmin=0.)
del epochs, raw
dip, residual = fit_dipole(evoked, cov, sphere, n_jobs=1)


I am working on the file "0.17/_downloads/2aba6a5c9f79fe16cdce1a232bc5e327/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Let's plot the positions and the orientations of the actual and the estimated
dipoles
Can you write Python code for it?

def plot_pos_ori(pos, ori, color=(0., 0., 0.), opacity=1.):
    x, y, z = pos.T
    u, v, w = ori.T
    mlab.points3d(x, y, z, scale_factor=0.005, opacity=opacity, color=color)
    q = mlab.quiver3d(x, y, z, u, v, w,
                      scale_factor=0.03, opacity=opacity,
                      color=color, mode='arrow')
    q.glyph.glyph_source.glyph_source.shaft_radius = 0.02
    q.glyph.glyph_source.glyph_source.tip_length = 0.1
    q.glyph.glyph_source.glyph_source.tip_radius = 0.05

mne.viz.plot_alignment(evoked.info, bem=sphere, surfaces='inner_skull',
                       coord_frame='head', meg='helmet', show_axes=True)

# Plot the position and the orientation of the actual dipole
plot_pos_ori(actual_pos, actual_ori, color=(0., 0., 0.), opacity=0.5)
# Plot the position and the orientation of the estimated dipole
plot_pos_ori(dip.pos, dip.ori, color=(0.2, 1., 0.5))
mlab.view(70, 80, distance=0.5)


I am working on the file "0.17/_downloads/2aba6a5c9f79fe16cdce1a232bc5e327/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Let's use a sphere head geometry model and let's see the coordinate
alignment and the sphere location. The phantom is properly modeled by
a single-shell sphere with origin (0., 0., 0.).
Can you write Python code for it?

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

mne.viz.plot_alignment(raw.info, subject='sample', show_axes=True,
                       bem=sphere, dig=True, surfaces='inner_skull')


I am working on the file "0.17/_downloads/2aba6a5c9f79fe16cdce1a232bc5e327/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Now we can compare to the actual locations, taking the difference in mm:
Can you write Python code for it?

actual_pos, actual_ori = mne.dipole.get_phantom_dipoles()
actual_amp = 100.  # nAm

fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, ncols=1, figsize=(6, 7))

diffs = 1000 * np.sqrt(np.sum((dip.pos - actual_pos) ** 2, axis=-1))
print('mean(position error) = %0.1f mm' % (np.mean(diffs),))
ax1.bar(event_id, diffs)
ax1.set_xlabel('Dipole index')
ax1.set_ylabel('Loc. error (mm)')

angles = np.rad2deg(np.arccos(np.abs(np.sum(dip.ori * actual_ori, axis=1))))
print(u'mean(angle error) = %0.1f°' % (np.mean(angles),))
ax2.bar(event_id, angles)
ax2.set_xlabel('Dipole index')
ax2.set_ylabel(u'Angle error (°)')

amps = actual_amp - dip.amplitude / 1e-9
print('mean(abs amplitude error) = %0.1f nAm' % (np.mean(np.abs(amps)),))
ax3.bar(event_id, amps)
ax3.set_xlabel('Dipole index')
ax3.set_ylabel('Amplitude error (nAm)')

fig.tight_layout()
plt.show()


I am working on the file "0.17/_downloads/2aba6a5c9f79fe16cdce1a232bc5e327/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
Now we epoch our data, average it, and look at the first dipole response.
The first peak appears around 3 ms. Because we low-passed at 40 Hz,
we can also decimate our data to save memory.
Can you write Python code for it?

tmin, tmax = -0.1, 0.1
event_id = list(range(1, 33))
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, baseline=(None, -0.01),
                    decim=3, preload=True)
epochs['1'].average().plot(time_unit='s')


I am working on the file "0.17/_downloads/2aba6a5c9f79fe16cdce1a232bc5e327/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
The data were collected with an Elekta Neuromag VectorView system at 1000 Hz
and low-pass filtered at 330 Hz. Here the medium-amplitude (200 nAm) data
are read to construct instances of :class:mne.io.Raw.
Can you write Python code for it?

data_path = bst_phantom_elekta.data_path(verbose=True)

raw_fname = op.join(data_path, 'kojak_all_200nAm_pp_no_chpi_no_ms_raw.fif')
raw = read_raw_fif(raw_fname)


I am working on the file "0.17/_downloads/2aba6a5c9f79fe16cdce1a232bc5e327/plot_brainstorm_phantom_elekta.ipynb".
The first task is:
We know our phantom produces sinusoidal bursts below 25 Hz, so let's filter.
Can you write Python code for it?

raw.filter(None, 40., fir_design='firwin')
raw.plot(events=events)


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

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

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

print(__doc__)

data_path = sample.data_path()


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

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

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

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

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

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


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


I am working on the file "0.17/_downloads/2e5e89949bd57aecc1ef4e79435a8149/plot_temporal_whitening.ipynb".
The first task is:
Plot the different time series and PSDs
Can you write Python code for it?

plt.close('all')
plt.figure()
plt.plot(d[:100], label='signal')
plt.plot(d_[:100], label='regenerated signal')
plt.legend()

plt.figure()
plt.psd(d, Fs=raw.info['sfreq'], NFFT=2048)
plt.psd(innovation, Fs=raw.info['sfreq'], NFFT=2048)
plt.psd(d_, Fs=raw.info['sfreq'], NFFT=2048, linestyle='--')
plt.legend(('Signal', 'Innovation', 'Regenerated signal'))
plt.show()


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

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

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

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


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

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

from matplotlib import pyplot as plt

import mne
from mne.datasets import sample


I am working on the file "0.17/_downloads/36757d92ff90d872eb3ba9854678a45f/plot_ica_comparison.ipynb".
The first task is:
Compare the different ICA algorithms in MNE
Different ICA algorithms are fit to raw MEG data, and the corresponding maps
are displayed.
Can you write Python code for it?

# Authors: Pierre Ablin <pierreablin@gmail.com>
#
# License: BSD (3-clause)

from time import time

import mne
from mne.preprocessing import ICA
from mne.datasets import sample

print(__doc__)


I am working on the file "0.17/_downloads/36757d92ff90d872eb3ba9854678a45f/plot_ica_comparison.ipynb".
The first task is:
Define a function that runs ICA on the raw MEG data and plots the components
Can you write Python code for it?

def run_ica(method):
    ica = ICA(n_components=20, method=method, random_state=0)
    t0 = time()
    ica.fit(raw, picks=picks, reject=reject)
    fit_time = time() - t0
    title = ('ICA decomposition using %s (took %.1fs)' % (method, fit_time))
    ica.plot_components(title=title)


I am working on the file "0.17/_downloads/36757d92ff90d872eb3ba9854678a45f/plot_ica_comparison.ipynb".
The first task is:
Extended Infomax
Can you write Python code for it?


I am working on the file "0.17/_downloads/36757d92ff90d872eb3ba9854678a45f/plot_ica_comparison.ipynb".
The first task is:
FastICA
Can you write Python code for it?


I am working on the file "0.17/_downloads/36757d92ff90d872eb3ba9854678a45f/plot_ica_comparison.ipynb".
The first task is:
Infomax
Can you write Python code for it?


I am working on the file "0.17/_downloads/36757d92ff90d872eb3ba9854678a45f/plot_ica_comparison.ipynb".
The first task is:
Read and preprocess the data. Preprocessing consists of:

MEG channel selection
1-30 Hz band-pass filter
Can you write Python code for it?

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

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

picks = mne.pick_types(raw.info)
reject = dict(mag=5e-12, grad=4000e-13)
raw.filter(1, 30, fir_design='firwin')


I am working on the file "0.17/_downloads/3ade035c928216ab770a554e9a0c0cef/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
It's a good idea to spatially smooth the data, and for visualization
purposes, let's morph these to fsaverage, which is a grade 5 source space
with vertices 0:10242 for each hemisphere. Usually you'd have to morph
each subject's data separately (and you might want to use morph_data
instead), but here since all estimates are on 'sample' we can use one
morph matrix for all the heavy lifting.
Can you write Python code for it?

# Read the source space we are morphing to
src = mne.read_source_spaces(src_fname)
fsave_vertices = [s['vertno'] for s in src]
morph_mat = mne.compute_source_morph(
    src=inverse_operator['src'], subject_to='fsaverage',
    spacing=fsave_vertices, subjects_dir=subjects_dir).morph_mat

n_vertices_fsave = morph_mat.shape[0]

#    We have to change the shape for the dot() to work properly
X = X.reshape(n_vertices_sample, n_times * n_subjects * 2)
print('Morphing data.')
X = morph_mat.dot(X)  # morph_mat is a sparse matrix
X = X.reshape(n_vertices_fsave, n_times, n_subjects, 2)


I am working on the file "0.17/_downloads/3ade035c928216ab770a554e9a0c0cef/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Permutation t-test on source data with spatio-temporal clustering
Tests if the evoked response is significantly different between
two conditions across subjects. Here just for demonstration purposes
we simulate data from multiple subjects using one subject's data.
The multiple comparisons problem is addressed with a cluster-level
permutation test across space and time.
Can you write Python code for it?

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

import os.path as op

import numpy as np
from numpy.random import randn
from scipy import stats as stats

import mne
from mne.epochs import equalize_epoch_counts
from mne.stats import (spatio_temporal_cluster_1samp_test,
                       summarize_clusters_stc)
from mne.minimum_norm import apply_inverse, read_inverse_operator
from mne.datasets import sample

print(__doc__)


I am working on the file "0.17/_downloads/3ade035c928216ab770a554e9a0c0cef/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Read epochs for all channels, removing a bad one
Can you write Python code for it?

raw.info['bads'] += ['MEG 2443']
picks = mne.pick_types(raw.info, meg=True, eog=True, exclude='bads')
event_id = 1  # L auditory
reject = dict(grad=1000e-13, mag=4000e-15, eog=150e-6)
epochs1 = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                     baseline=(None, 0), reject=reject, preload=True)

event_id = 3  # L visual
epochs2 = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                     baseline=(None, 0), reject=reject, preload=True)

#    Equalize trial counts to eliminate bias (which would otherwise be
#    introduced by the abs() performed below)
equalize_epoch_counts([epochs1, epochs2])


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

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
subjects_dir = data_path + '/subjects'
src_fname = subjects_dir + '/fsaverage/bem/fsaverage-ico-5-src.fif'

tmin = -0.2
tmax = 0.3  # Use a lower tmax to reduce multiple comparisons

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


I am working on the file "0.17/_downloads/3ade035c928216ab770a554e9a0c0cef/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Transform to common cortical space
Normally you would read in estimates across several subjects and morph
them to the same cortical space (e.g. fsaverage). For example purposes,
we will simulate this by just having each "subject" have the same
response (just noisy in source space) here.

Note

Note that for 7 subjects with a two-sided statistical test, the minimum
    significance under a permutation test is only p = 1/(2 ** 6) = 0.015,
    which is large.

Can you write Python code for it?

n_vertices_sample, n_times = condition1.data.shape
n_subjects = 7
print('Simulating data for %d subjects.' % n_subjects)

#    Let's make sure our results replicate, so set the seed.
np.random.seed(0)
X = randn(n_vertices_sample, n_times, n_subjects, 2) * 10
X[:, :, :, 0] += condition1.data[:, :, np.newaxis]
X[:, :, :, 1] += condition2.data[:, :, np.newaxis]


I am working on the file "0.17/_downloads/3ade035c928216ab770a554e9a0c0cef/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Transform to source space
Can you write Python code for it?

fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE, sLORETA, or eLORETA)
inverse_operator = read_inverse_operator(fname_inv)
sample_vertices = [s['vertno'] for s in inverse_operator['src']]

#    Let's average and compute inverse, resampling to speed things up
evoked1 = epochs1.average()
evoked1.resample(50, npad='auto')
condition1 = apply_inverse(evoked1, inverse_operator, lambda2, method)
evoked2 = epochs2.average()
evoked2.resample(50, npad='auto')
condition2 = apply_inverse(evoked2, inverse_operator, lambda2, method)

#    Let's only deal with t > 0, cropping to reduce multiple comparisons
condition1.crop(0, None)
condition2.crop(0, None)
tmin = condition1.tmin
tstep = condition1.tstep


I am working on the file "0.17/_downloads/3ade035c928216ab770a554e9a0c0cef/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Visualize the clusters
Can you write Python code for it?

print('Visualizing clusters.')

#    Now let's build a convenient representation of each cluster, where each
#    cluster becomes a "time point" in the SourceEstimate
stc_all_cluster_vis = summarize_clusters_stc(clu, tstep=tstep,
                                             vertices=fsave_vertices,
                                             subject='fsaverage')

#    Let's actually plot the first "time point" in the SourceEstimate, which
#    shows all the clusters, weighted by duration
subjects_dir = op.join(data_path, 'subjects')
# blue blobs are for condition A < condition B, red for A > B
brain = stc_all_cluster_vis.plot(
    hemi='both', views='lateral', subjects_dir=subjects_dir,
    time_label='Duration significant (ms)', size=(800, 800),
    smoothing_steps=5, clim=dict(kind='value', pos_lims=[0, 1, 40]))
# brain.save_image('clusters.png')


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

snr = 3.0
noise_cov = mne.read_cov(fname_cov)
inverse_operator = read_inverse_operator(fname_inv)

stcs = apply_inverse_epochs(epochs, inverse_operator,
                            lambda2=1.0 / snr ** 2, verbose=False,
                            method="dSPM", pick_ori="normal")


I am working on the file "0.17/_downloads/3c22b754d3ee35b041302de37d5f9515/plot_decoding_spatio_temporal_source.ipynb".
The first task is:
Decoding in sensor space using a logistic regression
Can you write Python code for it?

# Retrieve source space data into an array
X = np.array([stc.lh_data for stc in stcs])  # only keep left hemisphere
y = epochs.events[:, 2]

# prepare a series of classifier applied at each time sample
clf = make_pipeline(StandardScaler(),  # z-score normalization
                    SelectKBest(f_classif, k=500),  # select features for speed
                    LinearModel(LogisticRegression(C=1, solver='liblinear')))
time_decod = SlidingEstimator(clf, scoring='roc_auc')

# Run cross-validated decoding analyses:
scores = cross_val_multiscore(time_decod, X, y, cv=5, n_jobs=1)

# Plot average decoding scores of 5 splits
fig, ax = plt.subplots(1)
ax.plot(epochs.times, scores.mean(0), label='score')
ax.axhline(.5, color='k', linestyle='--', label='chance')
ax.axvline(0, color='k')
plt.legend()


I am working on the file "0.17/_downloads/3c22b754d3ee35b041302de37d5f9515/plot_decoding_spatio_temporal_source.ipynb".
The first task is:
Decoding source space data
Decoding to MEG data in source space on the left cortical surface. Here
univariate feature selection is employed for speed purposes to confine the
classification to a small number of potentially relevant features. The
classifier then is trained to selected features of epochs in source space.
Can you write Python code for it?

# sphinx_gallery_thumbnail_number = 2

# Author: Denis A. Engemann <denis.engemann@gmail.com>
#         Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#         Jean-Remi King <jeanremi.king@gmail.com>
#         Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression

import mne
from mne.minimum_norm import apply_inverse_epochs, read_inverse_operator
from mne.decoding import (cross_val_multiscore, LinearModel, SlidingEstimator,
                          get_coef)

print(__doc__)

data_path = mne.datasets.sample.data_path()
fname_fwd = data_path + 'MEG/sample/sample_audvis-meg-oct-6-fwd.fif'
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
subjects_dir = data_path + '/subjects'


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

raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
fname_cov = data_path + '/MEG/sample/sample_audvis-cov.fif'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'

tmin, tmax = -0.2, 0.8
event_id = dict(aud_r=2, vis_r=4)  # load contra-lateral conditions

# Setup for reading the raw data
raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.filter(None, 10., fir_design='firwin')
events = mne.read_events(event_fname)

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

# Read epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    picks=picks, baseline=(None, 0), preload=True,
                    reject=dict(grad=4000e-13, eog=150e-6),
                    decim=5)  # decimate to save memory and increase speed


I am working on the file "0.17/_downloads/3c22b754d3ee35b041302de37d5f9515/plot_decoding_spatio_temporal_source.ipynb".
The first task is:
To investigate weights, we need to retrieve the patterns of a fitted model
Can you write Python code for it?

# The fitting needs not be cross validated because the weights are based on
# the training sets
time_decod.fit(X, y)

# Retrieve patterns after inversing the z-score normalization step:
patterns = get_coef(time_decod, 'patterns_', inverse_transform=True)

stc = stcs[0]  # for convenience, lookup parameters from first stc
vertices = [stc.lh_vertno, np.array([], int)]  # empty array for right hemi
stc_feat = mne.SourceEstimate(np.abs(patterns), vertices=vertices,
                              tmin=stc.tmin, tstep=stc.tstep, subject='sample')

brain = stc_feat.plot(views=['lat'], transparent=True,
                      initial_time=0.1, time_unit='s',
                      subjects_dir=subjects_dir)


I am working on the file "0.17/_downloads/3d91fc276019c34c190d40f0bfd39940/plot_visualize_epochs.ipynb".
The first task is:
The numbers at the top refer to the event id of the epoch. The number at the
bottom is the running numbering for the epochs.
Since we did no artifact correction or rejection, there are epochs
contaminated with blinks and saccades. For instance, epoch number 1 seems to
be contaminated by a blink (scroll to the bottom to view the EOG channel).
This epoch can be marked for rejection by clicking on top of the browser
window. The epoch should turn red when you click it. This means that it will
be dropped as the browser window is closed.
It is possible to plot event markers on epoched data by passing events
keyword to the epochs plotter. The events are plotted as vertical lines and
they follow the same coloring scheme as :func:mne.viz.plot_events. The
events plotter gives you all the events with a rough idea of the timing.
Since the colors are the same, the event plotter can also function as a
legend for the epochs plotter events. It is also possible to pass your own
colors via event_colors keyword. Here we can plot the reaction times
between seeing the smiley face and the button press (event 32).
When events are passed, the epoch numbering at the bottom is switched off by
default to avoid overlaps. You can turn it back on via settings dialog by
pressing o key. You should check out help at the lower left corner of the
window for more information about the interactive features.
Can you write Python code for it?

events = mne.pick_events(events, include=[5, 32])
mne.viz.plot_events(events)
epochs['smiley'].plot(events=events)


I am working on the file "0.17/_downloads/3d91fc276019c34c190d40f0bfd39940/plot_visualize_epochs.ipynb".
The first task is:
Visualize Epochs data
Can you write Python code for it?

# sphinx_gallery_thumbnail_number = 7

import os.path as op

import mne

data_path = op.join(mne.datasets.sample.data_path(), 'MEG', 'sample')
raw = mne.io.read_raw_fif(
    op.join(data_path, 'sample_audvis_raw.fif'), preload=True)
raw.load_data().filter(None, 9, fir_design='firwin')
raw.set_eeg_reference('average', projection=True)  # set EEG average reference
event_id = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
            'visual/right': 4, 'smiley': 5, 'button': 32}
events = mne.read_events(op.join(data_path, 'sample_audvis_raw-eve.fif'))
epochs = mne.Epochs(raw, events, event_id=event_id, tmin=-0.2, tmax=.5)


I am working on the file "0.17/_downloads/3d91fc276019c34c190d40f0bfd39940/plot_visualize_epochs.ipynb".
The first task is:
You also have functions for plotting channelwise information arranged into a
shape of the channel array. The image plotting uses automatic scaling by
default, but noisy channels and different channel types can cause the scaling
to be a bit off. Here we define the limits by hand.
Can you write Python code for it?

epochs.plot_topo_image(vmin=-250, vmax=250, title='ERF images', sigma=2.,
                       fig_facecolor='w', font_color='k')


I am working on the file "0.17/_downloads/3ebd331f774b241a9eda870b8410800d/plot_info.ipynb".
The first task is:
:class:mne.Info behaves as a nested Python dictionary:
Can you write Python code for it?

# Read the info object from an example recording
info = mne.io.read_info(
    op.join(mne.datasets.sample.data_path(), 'MEG', 'sample',
            'sample_audvis_raw.fif'), verbose=False)


I am working on the file "0.17/_downloads/3ebd331f774b241a9eda870b8410800d/plot_info.ipynb".
The first task is:
Channel types of a collection of channels
Can you write Python code for it?

meg_channels = mne.pick_types(info, meg=True)[:10]
channel_types = [mne.io.pick.channel_type(info, ch) for ch in meg_channels]
print('First 10 MEG channels are of type:\n', channel_types)


I am working on the file "0.17/_downloads/3ebd331f774b241a9eda870b8410800d/plot_info.ipynb".
The first task is:
Dropping channels from an info structure
It is possible to limit the info structure to only include a subset of
channels with the :func:mne.pick_info function:
Can you write Python code for it?

# Only keep EEG channels
eeg_indices = mne.pick_types(info, meg=False, eeg=True)
reduced_info = mne.pick_info(info, eeg_indices)

print(reduced_info)


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

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


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

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


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

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


I am working on the file "0.17/_downloads/3ebd331f774b241a9eda870b8410800d/plot_info.ipynb".
The first task is:
MEG gradiometers and EEG channels
Can you write Python code for it?

channel_indices = mne.pick_types(info, meg='grad', eeg=True)


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


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

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


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

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


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

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

import numpy as np
import matplotlib.pyplot as plt

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

print(__doc__)

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

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

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

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

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

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

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

# 8.5% of original source space vertices were omitted during forward
# calculation, suppress the warning here with verbose='error'
func_labels, _ = mne.stc_to_label(stc_mean_label, src=src, smooth=True,
                                  subjects_dir=subjects_dir,...


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

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


I am working on the file "0.17/_downloads/4457f1e38b5fa0853b9fa024b11fe018/plot_artifacts_detection.ipynb".
The first task is:
Introduction to artifacts and artifact detection
Since MNE supports the data of many different acquisition systems, the
particular artifacts in your data might behave very differently from the
artifacts you can observe in our tutorials and examples.
Therefore you should be aware of the different approaches and of
the variability of artifact rejection (automatic/manual) procedures described
onwards. At the end consider always to visually inspect your data
after artifact rejection or correction.
Background: what is an artifact?
Artifacts are signal interference that can be
endogenous (biological) and exogenous (environmental).
Typical biological artifacts are head movements, eye blinks
or eye movements, heart beats. The most common environmental
artifact is due to the power line, the so-called line noise.
How to handle artifacts?
MNE deals with artifacts by first identifying them, and subsequently removing
them. Detection of artifacts can be done visually, or using automatic routines
(or a combination of both). After you know what the artifacts are, you need
remove them. This can be done by:
- *ignoring* the piece of corrupted data
- *fixing* the corrupted data

For the artifact detection the functions MNE provides depend on whether
your data is continuous (Raw) or epoch-based (Epochs) and depending on
whether your data is stored on disk or already in memory.
Detecting the artifacts without reading the complete data into memory allows
you to work with datasets that are too large to fit in memory all at once.
Detecting the artifacts in continuous data allows you to apply filters
(e.g. a band-pass filter to zoom in on the muscle artifacts on the temporal
channels) without having to worry about edge effects due to the filter
(i.e. filter ringing). Having the data in memory after segmenting/epoching is
however a very efficient way of browsing through the data which helps
in visualizing. So to conclude, there is not a single most optimal manner
to detect the artifacts: it just depends on the data properties and...
Can you write Python code for it?

import numpy as np

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

# getting some data ready
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'

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


I am working on the file "0.17/_downloads/4457f1e38b5fa0853b9fa024b11fe018/plot_artifacts_detection.ipynb".
The first task is:
Low frequency drifts and line noise
Can you write Python code for it?

(raw.copy().pick_types(meg='mag')
           .del_proj(0)
           .plot(duration=60, n_channels=100, remove_dc=False))


I am working on the file "0.17/_downloads/4457f677e595ddd6eaad6bb91f5bea1a/plot_source_space_time_frequency.ipynb".
The first task is:
Compute induced power in the source space with dSPM
Returns STC files ie source estimates of induced power
for different bands in the source space. The inverse method
is linear based on dSPM inverse operator.
Can you write Python code for it?

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

import matplotlib.pyplot as plt

import mne
from mne import io
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, source_band_induced_power

print(__doc__)


I am working on the file "0.17/_downloads/4457f677e595ddd6eaad6bb91f5bea1a/plot_source_space_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'
tmin, tmax, event_id = -0.2, 0.5, 1

# 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 gradiometers
picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=True,
                       stim=False, include=include, exclude='bads')

# Load condition 1
event_id = 1
events = events[:10]  # take 10 events to keep the computation time low
# Use linear detrend to reduce any edge artifacts
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6),
                    preload=True, detrend=1)

# Compute a source estimate per frequency band
bands = dict(alpha=[9, 11], beta=[18, 22])

stcs = source_band_induced_power(epochs, inverse_operator, bands, n_cycles=2,
                                 use_fft=False, n_jobs=1)

for b, stc in stcs.items():
    stc.save('induced_power_%s' % b)


I am working on the file "0.17/_downloads/4457f677e595ddd6eaad6bb91f5bea1a/plot_source_space_time_frequency.ipynb".
The first task is:
plot mean power
Can you write Python code for it?

plt.plot(stcs['alpha'].times, stcs['alpha'].data.mean(axis=0), label='Alpha')
plt.plot(stcs['beta'].times, stcs['beta'].data.mean(axis=0), label='Beta')
plt.xlabel('Time (ms)')
plt.ylabel('Power')
plt.legend()
plt.title('Mean source induced power')
plt.show()


I am working on the file "0.17/_downloads/463a9f516ed3ca72fbb7a63001ffa664/plot_time_frequency_simulated.ipynb".
The first task is:
(1) Least smoothing (most variance/background fluctuations).
Can you write Python code for it?

n_cycles = freqs / 2.
time_bandwidth = 2.0  # Least possible frequency-smoothing (1 taper)
power = tfr_multitaper(epochs, freqs=freqs, n_cycles=n_cycles,
                       time_bandwidth=time_bandwidth, return_itc=False)
# Plot results. Baseline correct based on first 100 ms.
power.plot([0], baseline=(0., 0.1), mode='mean', vmin=vmin, vmax=vmax,
           title='Sim: Least smoothing, most variance')


I am working on the file "0.17/_downloads/463a9f516ed3ca72fbb7a63001ffa664/plot_time_frequency_simulated.ipynb".
The first task is:
(2) Less frequency smoothing, more time smoothing.
Can you write Python code for it?

n_cycles = freqs  # Increase time-window length to 1 second.
time_bandwidth = 4.0  # Same frequency-smoothing as (1) 3 tapers.
power = tfr_multitaper(epochs, freqs=freqs, n_cycles=n_cycles,
                       time_bandwidth=time_bandwidth, return_itc=False)
# Plot results. Baseline correct based on first 100 ms.
power.plot([0], baseline=(0., 0.1), mode='mean', vmin=vmin, vmax=vmax,
           title='Sim: Less frequency smoothing, more time smoothing')


I am working on the file "0.17/_downloads/463a9f516ed3ca72fbb7a63001ffa664/plot_time_frequency_simulated.ipynb".
The first task is:
======================================================================
Time-frequency on simulated data (Multitaper vs. Morlet vs. Stockwell)
======================================================================
This example demonstrates the different time-frequency estimation methods
on simulated data. It shows the time-frequency resolution trade-off
and the problem of estimation variance. In addition it highlights
alternative functions for generating TFRs without averaging across
trials, or by operating on numpy arrays.
Can you write Python code for it?

# Authors: Hari Bharadwaj <hari@nmr.mgh.harvard.edu>
#          Denis Engemann <denis.engemann@gmail.com>
#          Chris Holdgraf <choldgraf@berkeley.edu>
#
# License: BSD (3-clause)

import numpy as np
from matplotlib import pyplot as plt

from mne import create_info, EpochsArray
from mne.baseline import rescale
from mne.time_frequency import (tfr_multitaper, tfr_stockwell, tfr_morlet,
                                tfr_array_morlet)

print(__doc__)


I am working on the file "0.17/_downloads/463a9f516ed3ca72fbb7a63001ffa664/plot_time_frequency_simulated.ipynb".
The first task is:
Calculate a time-frequency representation (TFR)
Below we'll demonstrate the output of several TFR functions in MNE:

:func:mne.time_frequency.tfr_multitaper
:func:mne.time_frequency.tfr_stockwell
:func:mne.time_frequency.tfr_morlet

Multitaper transform
First we'll use the multitaper method for calculating the TFR.
This creates several orthogonal tapering windows in the TFR estimation,
which reduces variance. We'll also show some of the parameters that can be
tweaked (e.g., time_bandwidth) that will result in different multitaper
properties, and thus a different TFR. You can trade time resolution or
frequency resolution or both in order to get a reduction in variance.
Can you write Python code for it?

freqs = np.arange(5., 100., 3.)
vmin, vmax = -3., 3.  # Define our color limits.


I am working on the file "0.17/_downloads/463a9f516ed3ca72fbb7a63001ffa664/plot_time_frequency_simulated.ipynb".
The first task is:
Calculating a TFR without averaging over epochs
It is also possible to calculate a TFR without averaging across trials.
We can do this by using average=False. In this case, an instance of
:class:mne.time_frequency.EpochsTFR is returned.
Can you write Python code for it?

n_cycles = freqs / 2.
power = tfr_morlet(epochs, freqs=freqs,
                   n_cycles=n_cycles, return_itc=False, average=False)
print(type(power))
avgpower = power.average()
avgpower.plot([0], baseline=(0., 0.1), mode='mean', vmin=vmin, vmax=vmax,
              title='Using Morlet wavelets and EpochsTFR', show=False)


I am working on the file "0.17/_downloads/463a9f516ed3ca72fbb7a63001ffa664/plot_time_frequency_simulated.ipynb".
The first task is:
Morlet Wavelets
Finally, show the TFR using morlet wavelets, which are a sinusoidal wave
with a gaussian envelope. We can control the balance between spectral and
temporal resolution with the n_cycles parameter, which defines the
number of cycles to include in the window.
Can you write Python code for it?

fig, axs = plt.subplots(1, 3, figsize=(15, 5), sharey=True)
all_n_cycles = [1, 3, freqs / 2.]
for n_cycles, ax in zip(all_n_cycles, axs):
    power = tfr_morlet(epochs, freqs=freqs,
                       n_cycles=n_cycles, return_itc=False)
    power.plot([0], baseline=(0., 0.1), mode='mean', vmin=vmin, vmax=vmax,
               axes=ax, show=False, colorbar=False)
    n_cycles = 'scaled by freqs' if not isinstance(n_cycles, int) else n_cycles
    ax.set_title('Sim: Using Morlet wavelet, n_cycles = %s' % n_cycles)
plt.tight_layout()


I am working on the file "0.17/_downloads/463a9f516ed3ca72fbb7a63001ffa664/plot_time_frequency_simulated.ipynb".
The first task is:
Operating on arrays
MNE also has versions of the functions above which operate on numpy arrays
instead of MNE objects. They expect inputs of the shape
(n_epochs, n_channels, n_times). They will also return a numpy array
of shape (n_epochs, n_channels, n_freqs, n_times).
Can you write Python code for it?

power = tfr_array_morlet(epochs.get_data(), sfreq=epochs.info['sfreq'],
                         freqs=freqs, n_cycles=n_cycles,
                         output='avg_power')
# Baseline the output
rescale(power, epochs.times, (0., 0.1), mode='mean', copy=False)
fig, ax = plt.subplots()
mesh = ax.pcolormesh(epochs.times * 1000, freqs, power[0],
                     cmap='RdBu_r', vmin=vmin, vmax=vmax)
ax.set_title('TFR calculated on a numpy array')
ax.set(ylim=freqs[[0, -1]], xlabel='Time (ms)')
fig.colorbar(mesh)
plt.tight_layout()

plt.show()


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

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

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

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

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


I am working on the file "0.17/_downloads/469b6692cc10fb0680563c52afebc05c/plot_channel_epochs_image.ipynb".
The first task is:
Show event related fields images
Can you write Python code for it?

# and order with spectral reordering
# If you don't have scikit-learn installed set order_func to None
from sklearn.cluster.spectral import spectral_embedding  # noqa
from sklearn.metrics.pairwise import rbf_kernel   # noqa

def order_func(times, data):
    this_data = data[:, (times > 0.0) & (times < 0.350)]
    this_data /= np.sqrt(np.sum(this_data ** 2, axis=1))[:, np.newaxis]
    return np.argsort(spectral_embedding(rbf_kernel(this_data, gamma=1.),
                      n_components=1, random_state=0).ravel())

good_pick = 97  # channel with a clear evoked response
bad_pick = 98  # channel with no evoked response

# We'll also plot a sample time onset for each trial
plt_times = np.linspace(0, .2, len(epochs))

plt.close('all')
mne.viz.plot_epochs_image(epochs, [good_pick, bad_pick], sigma=.5,
                          order=order_func, vmin=-250, vmax=250,
                          overlay_times=plt_times, show=True)


I am working on the file "0.17/_downloads/469b6692cc10fb0680563c52afebc05c/plot_channel_epochs_image.ipynb".
The first task is:
Visualize channel over epochs as an image
This will produce what is sometimes called an event related
potential / field (ERP/ERF) image.
Two images are produced, one with a good channel and one with a channel
that does not show any evoked field.
It is also demonstrated how to reorder the epochs using a 1D spectral
embedding as described in:
Graph-based variability estimation in single-trial event-related neural
responses A. Gramfort, R. Keriven, M. Clerc, 2010,
Biomedical Engineering, IEEE Trans. on, vol. 57 (5), 1051-1061
https://hal.inria.fr/inria-00497023
Can you write Python code for it?

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

import numpy as np
import matplotlib.pyplot as plt

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

print(__doc__)

data_path = sample.data_path()


I am working on the file "0.17/_downloads/47de0e2137654670a631ea71dfab4b62/plot_lcmv_beamformer_volume.ipynb".
The first task is:
Compute covariance matrices, fit and apply  spatial filter.
Can you write Python code for it?

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

# Compute weights of free orientation (vector) beamformer with weight
# normalization (neural activity index, NAI). Providing a noise covariance
# matrix enables whitening of the data and forward solution. Source orientation
# is optimized by setting pick_ori to 'max-power'.
# weight_norm can also be set to 'unit-noise-gain'. Source orientation can also
# be 'normal' (but only when using a surface-based source space) or None,
# which computes a vector beamfomer. Note, however, that not all combinations
# of orientation selection and weight normalization are implemented yet.
filters = make_lcmv(evoked.info, forward, data_cov, reg=0.05,
                    noise_cov=noise_cov, pick_ori='max-power',
                    weight_norm='nai', rank=None)
print(filters)

# You can save these with:
# filters.save('filters-lcmv.h5')

# Apply this spatial filter to the evoked data.
stc = apply_lcmv(evoked, filters, max_ori_out='signed')


I am working on the file "0.17/_downloads/47de0e2137654670a631ea71dfab4b62/plot_lcmv_beamformer_volume.ipynb".
The first task is:
Plot source space activity:
Can you write Python code for it?

# You can save result in stc files with:
# stc.save('lcmv-vol')

clim = dict(kind='value', pos_lims=[0.3, 0.6, 0.9])
stc.plot(src=forward['src'], subject='sample', subjects_dir=subjects_dir,
         clim=clim)


I am working on the file "0.17/_downloads/4c66a907fef8e4e049497d46de605e3a/plot_define_target_events.ipynb".
The first task is:
Find stimulus event followed by quick button presses
Can you write Python code for it?

reference_id = 5  # presentation of a smiley face
target_id = 32  # button press
sfreq = raw.info['sfreq']  # sampling rate
tmin = 0.1  # trials leading to very early responses will be rejected
tmax = 0.59  # ignore face stimuli followed by button press later than 590 ms
new_id = 42  # the new event id for a hit. If None, reference_id is used.
fill_na = 99  # the fill value for misses

events_, lag = define_target_events(events, reference_id, target_id,
                                    sfreq, tmin, tmax, new_id, fill_na)

print(events_)  # The 99 indicates missing or too late button presses

# besides the events also the lag between target and reference is returned
# this could e.g. be used as parametric regressor in subsequent analyses.

print(lag[lag != fill_na])  # lag in milliseconds

# #############################################################################
# Construct epochs

tmin_ = -0.2
tmax_ = 0.4
event_id = dict(early=new_id, late=fill_na)

epochs = mne.Epochs(raw, events_, event_id, tmin_,
                    tmax_, picks=picks, baseline=(None, 0),
                    reject=dict(mag=4e-12))

# average epochs and get an Evoked dataset.

early, late = [epochs[k].average() for k in event_id]


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

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

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

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

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


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

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

raw_band = raw.copy()
raw_band.filter(12, 18, l_trans_bandwidth=2., h_trans_bandwidth=2.,
                fir_design='firwin')
raw_hilb = raw_band.copy()
hilb_picks = mne.pick_types(raw_band.info, meg=False, eeg=True)
raw_hilb.apply_hilbert(hilb_picks)
print(raw_hilb[0][0].dtype)


I am working on the file "0.17/_downloads/4db67f73b2950e88bd1e641ba8cf44c0/plot_modifying_data_inplace.ipynb".
The first task is:
Load an example dataset, the preload flag loads the data into memory now
Can you write Python code for it?

data_path = op.join(mne.datasets.sample.data_path(), 'MEG',
                    'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(data_path, preload=True)
raw = raw.crop(0, 10)
print(raw)


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

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


I am working on the file "0.17/_downloads/50f27a42fcbd35f08d90ddc7386b7140/plot_compute_raw_data_spectrum.ipynb".
The first task is:
Compute the power spectral density of raw data
This script shows how to compute the power spectral density (PSD)
of measurements on a raw dataset. It also show the effect of applying SSP
to the data to reduce ECG and EOG artifacts.
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#          Eric Larson <larson.eric.d@gmail.com>
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne import io, read_proj, read_selection
from mne.datasets import sample
from mne.time_frequency import psd_multitaper

print(__doc__)


I am working on the file "0.17/_downloads/50f27a42fcbd35f08d90ddc7386b7140/plot_compute_raw_data_spectrum.ipynb".
The first task is:
Plot a cleaned PSD
Next we'll focus the visualization on a subset of channels.
This can be useful for identifying particularly noisy channels or
investigating how the power spectrum changes across channels.
We'll visualize how this PSD changes after applying some standard
filtering techniques. We'll first apply the SSP projections, which is
accomplished with the proj=True kwarg. We'll then perform a notch filter
to remove particular frequency bands.
Can you write Python code for it?

# Pick MEG magnetometers in the Left-temporal region
selection = read_selection('Left-temporal')
picks = mne.pick_types(raw.info, meg='mag', eeg=False, eog=False,
                       stim=False, exclude='bads', selection=selection)

# Let's just look at the first few channels for demonstration purposes
picks = picks[:4]

plt.figure()
ax = plt.axes()
raw.plot_psd(tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, n_fft=n_fft,
             n_jobs=1, proj=False, ax=ax, color=(0, 0, 1),  picks=picks,
             show=False, average=True)

raw.plot_psd(tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, n_fft=n_fft,
             n_jobs=1, proj=True, ax=ax, color=(0, 1, 0), picks=picks,
             show=False, average=True)

# And now do the same with SSP + notch filtering
# Pick all channels for notch since the SSP projection mixes channels together
raw.notch_filter(np.arange(60, 241, 60), n_jobs=1, fir_design='firwin')
raw.plot_psd(tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, n_fft=n_fft,
             n_jobs=1, proj=True, ax=ax, color=(1, 0, 0), picks=picks,
             show=False, average=True)

ax.set_title('Four left-temporal magnetometers')
plt.legend(ax.lines[::3], ['Without SSP', 'With SSP', 'SSP + Notch'])


I am working on the file "0.17/_downloads/50f27a42fcbd35f08d90ddc7386b7140/plot_compute_raw_data_spectrum.ipynb".
The first task is:
Plot the raw PSD
First we'll visualize the raw PSD of our data. We'll do this on all of the
channels first. Note that there are several parameters to the
:meth:mne.io.Raw.plot_psd method, some of which will be explained below.
Can you write Python code for it?

raw.plot_psd(area_mode='range', tmax=10.0, show=False, average=True)


I am working on the file "0.17/_downloads/5617c8669823fc31e46a191429c04b8f/plot_python_intro.ipynb".
The first task is:
Introduction to Python
Python <https://www.python.org/>_ is a modern general-purpose object-oriented
high-level programming language. First make sure you have a working Python
environment and dependencies (see install_python_and_mne_python). If you
are completely new to Python, don't worry, it's just like any other programming
language, only easier. Here are a few great resources to get you started:

SciPy lectures <http://scipy-lectures.github.io>_
Learn X in Y minutes: Python <https://learnxinyminutes.com/docs/python/>_
NumPy for MATLAB users <https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html>_

We highly recommend watching the SciPy videos and reading through these sites
to get a sense of how scientific computing is done in Python.
Here are few important points to familiarize yourself with Python. First,
everything is dynamically typed. There is no need to declare and initialize
data structures or variables separately.
Can you write Python code for it?

a = 3
print(type(a))
b = [1, 2.5, 'This is a string']
print(type(b))
c = 'Hello world!'
print(type(c))


I am working on the file "0.17/_downloads/5617c8669823fc31e46a191429c04b8f/plot_python_intro.ipynb".
The first task is:
Second, if you have a MATLAB background remember that indexing in Python
starts from zero (and is done with square brackets):
Can you write Python code for it?

a = [1, 2, 3, 4]
print('This is the zeroth value in the list: {}'.format(a[0]))


I am working on the file "0.17/_downloads/566cfb4f28beeb6e54665d64bb3ce99c/plot_metadata_epochs.ipynb".
The first task is:

Note

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

Can you write Python code for it?

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


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

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

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

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


I am working on the file "0.17/_downloads/566cfb4f28beeb6e54665d64bb3ce99c/plot_metadata_epochs.ipynb".
The first task is:
Next we'll choose a subset of words to keep.
Can you write Python code for it?

words = ['film', 'cent', 'shot', 'cold', 'main']
epochs['WORD in {}'.format(words)].plot_image(show=False)


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

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

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

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


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

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

# License: BSD (3-clause)

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

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

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


I am working on the file "0.17/_downloads/5834d0f519577e60275c6ef3c9fb0dbc/plot_read_inverse.ipynb".
The first task is:
Reading an inverse operator
The inverse operator's source space is shown in 3D.
Can you write Python code for it?

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

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

print(__doc__)

data_path = sample.data_path()
fname = data_path
fname += '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'

inv = read_inverse_operator(fname)

print("Method: %s" % inv['methods'])
print("fMRI prior: %s" % inv['fmri_prior'])
print("Number of sources: %s" % inv['nsource'])
print("Number of channels: %s" % inv['nchan'])