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

times = 1e3 * epochs_condition_1.times  # change unit to ms
evoked_condition_1 = epochs_condition_1.average()
evoked_condition_2 = epochs_condition_2.average()

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

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

plt.imshow(T_obs,
           extent=[times[0], times[-1], freqs[0], freqs[-1]],
           aspect='auto', origin='lower', cmap='gray')
plt.imshow(T_obs_plot,
           extent=[times[0], times[-1], freqs[0], freqs[-1]],
           aspect='auto', origin='lower', cmap='RdBu_r')

plt.xlabel('Time (ms)')
plt.ylabel('Frequency (Hz)')
plt.title('Induced power (%s)' % ch_name)

ax2 = plt.subplot(2, 1, 2)
evoked_contrast = mne.combine_evoked([evoked_condition_1, evoked_condition_2],
                                     weights=[1, -1])
evoked_contrast.plot(axes=ax2, time_unit='s')

plt.show()


I am working on the file "0.20/_downloads/12e915738bb5b40ffcb1157f1c2dee72/plot_receptive_field.ipynb".
The first task is:
Fit a model to recover this receptive field
Finally, we'll use the :class:mne.decoding.ReceptiveField class to recover
the linear receptive field of this signal. Note that properties of the
receptive field (e.g. smoothness) will depend on the autocorrelation in the
inputs and outputs.
Can you write Python code for it?

# Create training and testing data
train, test = np.arange(n_epochs - 1), n_epochs - 1
X_train, X_test, y_train, y_test = X[train], X[test], y[train], y[test]
X_train, X_test, y_train, y_test = [np.rollaxis(ii, -1, 0) for ii in
                                    (X_train, X_test, y_train, y_test)]
# Model the simulated data as a function of the spectrogram input
alphas = np.logspace(-3, 3, 7)
scores = np.zeros_like(alphas)
models = []
for ii, alpha in enumerate(alphas):
    rf = ReceptiveField(tmin, tmax, sfreq, freqs, estimator=alpha)
    rf.fit(X_train, y_train)

    # Now make predictions about the model output, given input stimuli.
    scores[ii] = rf.score(X_test, y_test)
    models.append(rf)

times = rf.delays_ / float(rf.sfreq)

# Choose the model that performed best on the held out data
ix_best_alpha = np.argmax(scores)
best_mod = models[ix_best_alpha]
coefs = best_mod.coef_[0]
best_pred = best_mod.predict(X_test)[:, 0]

# Plot the original STRF, and the one that we recovered with modeling.
_, (ax1, ax2) = plt.subplots(1, 2, figsize=(6, 3), sharey=True, sharex=True)
ax1.pcolormesh(delays_sec, freqs, weights, **kwargs)
ax2.pcolormesh(times, rf.feature_names, coefs, **kwargs)
ax1.set_title('Original STRF')
ax2.set_title('Best Reconstructed STRF')
plt.setp([iax.get_xticklabels() for iax in [ax1, ax2]], rotation=45)
plt.autoscale(tight=True)
mne.viz.tight_layout()

# Plot the actual response and the predicted response on a held out stimulus
time_pred = np.arange(best_pred.shape[0]) / sfreq
fig, ax = plt.subplots()
ax.plot(time_pred, y_test, color='k', alpha=.2, lw=4)
ax.plot(time_pred, best_pred, color='r', lw=1)
ax.set(title='Original and predicted activity', xlabel='Time (s)')
ax.legend(['Original', 'Predicted'])
plt.autoscale(tight=True)
mne.viz.tight_layout()


I am working on the file "0.20/_downloads/12e915738bb5b40ffcb1157f1c2dee72/plot_receptive_field.ipynb".
The first task is:
Load audio data
We'll read in the audio data from [3]_ in order to simulate a response.
In addition, we'll downsample the data along the time dimension in order to
speed up computation. Note that depending on the input values, this may
not be desired. For example if your input stimulus varies more quickly than
1/2 the sampling rate to which we are downsampling.
Can you write Python code for it?

# Read in audio that's been recorded in epochs.
path_audio = mne.datasets.mtrf.data_path()
data = loadmat(path_audio + '/speech_data.mat')
audio = data['spectrogram'].T
sfreq = float(data['Fs'][0, 0])
n_decim = 2
audio = mne.filter.resample(audio, down=n_decim, npad='auto')
sfreq /= n_decim


I am working on the file "0.20/_downloads/12e915738bb5b40ffcb1157f1c2dee72/plot_receptive_field.ipynb".
The first task is:
Simulate a neural response
Using this receptive field, we'll create an artificial neural response to
a stimulus.
To do this, we'll create a time-delayed version of the receptive field, and
then calculate the dot product between this and the stimulus. Note that this
is effectively doing a convolution between the stimulus and the receptive
field. See here <https://en.wikipedia.org/wiki/Convolution>_ for more
information.
Can you write Python code for it?

# Reshape audio to split into epochs, then make epochs the first dimension.
n_epochs, n_seconds = 16, 5
audio = audio[:, :int(n_seconds * sfreq * n_epochs)]
X = audio.reshape([n_freqs, n_epochs, -1]).swapaxes(0, 1)
n_times = X.shape[-1]

# Delay the spectrogram according to delays so it can be combined w/ the STRF
# Lags will now be in axis 1, then we reshape to vectorize
delays = np.arange(np.round(tmin * sfreq),
                   np.round(tmax * sfreq) + 1).astype(int)

# Iterate through indices and append
X_del = np.zeros((len(delays),) + X.shape)
for ii, ix_delay in enumerate(delays):
    # These arrays will take/put particular indices in the data
    take = [slice(None)] * X.ndim
    put = [slice(None)] * X.ndim
    if ix_delay > 0:
        take[-1] = slice(None, -ix_delay)
        put[-1] = slice(ix_delay, None)
    elif ix_delay < 0:
        take[-1] = slice(-ix_delay, None)
        put[-1] = slice(None, ix_delay)
    X_del[ii][tuple(put)] = X[tuple(take)]

# Now set the delayed axis to the 2nd dimension
X_del = np.rollaxis(X_del, 0, 3)
X_del = X_del.reshape([n_epochs, -1, n_times])
n_features = X_del.shape[1]
weights_sim = weights.ravel()

# Simulate a neural response to the sound, given this STRF
y = np.zeros((n_epochs, n_times))
for ii, iep in enumerate(X_del):
    # Simulate this epoch and add random noise
    noise_amp = .002
    y[ii] = np.dot(weights_sim, iep) + noise_amp * rng.randn(n_times)

# Plot the first 2 trials of audio and the simulated electrode activity
X_plt = scale(np.hstack(X[:2]).T).T
y_plt = scale(np.hstack(y[:2]))
time = np.arange(X_plt.shape[-1]) / sfreq
_, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 6), sharex=True)
ax1.pcolormesh(time, freqs, X_plt, vmin=0, vmax=4, cmap='Reds')
ax1.set_title('Input auditory features')
ax1.set(ylim=[freqs.min(), freqs.max()], ylabel='Frequency (Hz)')
ax2.plot(time, y_plt)
ax2.set(xlim=[time.min(), time.max()], title='Simulated response',
        xlabel='Time (s)', ylabel='Activity (a.u.)')
mne.viz.tight_layout()


I am working on the file "0.20/_downloads/12e915738bb5b40ffcb1157f1c2dee72/plot_receptive_field.ipynb".
The first task is:
Using different regularization types
In addition to the standard ridge regularization, the
:class:mne.decoding.TimeDelayingRidge class also exposes
Laplacian <https://en.wikipedia.org/wiki/Laplacian_matrix>_ regularization
term as:
\begin{align}\left[\begin{matrix}
        1 & -1 &   &   & & \
       -1 &  2 & -1 &   & & \
          & -1 & 2 & -1 & & \
          & & \ddots & \ddots & \ddots & \
          & & & -1 & 2 & -1 \
          & & &    & -1 & 1\end{matrix}\right]\end{align}
This imposes a smoothness constraint of nearby time samples and/or features.
Quoting [3]_:
Tikhonov [identity] regularization (Equation 5) reduces overfitting by
   smoothing the TRF estimate in a way that is insensitive to
   the amplitude of the signal of interest. However, the Laplacian
   approach (Equation 6) reduces off-sample error whilst preserving
   signal amplitude (Lalor et al., 2006). As a result, this approach
   usually leads to an improved estimate of the system’s response (as
   indexed by MSE) compared to Tikhonov regularization.
Can you write Python code for it?

scores_lap = np.zeros_like(alphas)
models_lap = []
for ii, alpha in enumerate(alphas):
    estimator = TimeDelayingRidge(tmin, tmax, sfreq, reg_type='laplacian',
                                  alpha=alpha)
    rf = ReceptiveField(tmin, tmax, sfreq, freqs, estimator=estimator)
    rf.fit(X_train, y_train)

    # Now make predictions about the model output, given input stimuli.
    scores_lap[ii] = rf.score(X_test, y_test)
    models_lap.append(rf)

ix_best_alpha_lap = np.argmax(scores_lap)


I am working on the file "0.20/_downloads/12e915738bb5b40ffcb1157f1c2dee72/plot_receptive_field.ipynb".
The first task is:
Visualize the effects of regularization
Above we fit a :class:mne.decoding.ReceptiveField model for one of many
values for the ridge regularization parameter. Here we will plot the model
score as well as the model coefficients for each value, in order to
visualize how coefficients change with different levels of regularization.
These issues as well as the STRF pipeline are described in detail
in [1], [2], and [4]_.
Can you write Python code for it?

# Plot model score for each ridge parameter
fig = plt.figure(figsize=(10, 4))
ax = plt.subplot2grid([2, len(alphas)], [1, 0], 1, len(alphas))
ax.plot(np.arange(len(alphas)), scores, marker='o', color='r')
ax.annotate('Best parameter', (ix_best_alpha, scores[ix_best_alpha]),
            (ix_best_alpha, scores[ix_best_alpha] - .1),
            arrowprops={'arrowstyle': '->'})
plt.xticks(np.arange(len(alphas)), ["%.0e" % ii for ii in alphas])
ax.set(xlabel="Ridge regularization value", ylabel="Score ($R^2$)",
       xlim=[-.4, len(alphas) - .6])
mne.viz.tight_layout()

# Plot the STRF of each ridge parameter
for ii, (rf, i_alpha) in enumerate(zip(models, alphas)):
    ax = plt.subplot2grid([2, len(alphas)], [0, ii], 1, 1)
    ax.pcolormesh(times, rf.feature_names, rf.coef_[0], **kwargs)
    plt.xticks([], [])
    plt.yticks([], [])
    plt.autoscale(tight=True)
fig.suptitle('Model coefficients / scores for many ridge parameters', y=1)
mne.viz.tight_layout()


I am working on the file "0.20/_downloads/131324ab94fb4e4c09fa41f4692da130/plot_custom_inverse_solver.ipynb".
The first task is:
Auxiliary function to run the solver
Can you write Python code for it?

def apply_solver(solver, evoked, forward, noise_cov, loose=0.2, depth=0.8):
    """Call a custom solver on evoked data.

    This function does all the necessary computation:

    - to select the channels in the forward given the available ones in
      the data
    - to take into account the noise covariance and do the spatial whitening
    - to apply loose orientation constraint as MNE solvers
    - to apply a weigthing of the columns of the forward operator as in the
      weighted Minimum Norm formulation in order to limit the problem
      of depth bias.

    Parameters
    ----------
    solver : callable
        The solver takes 3 parameters: data M, gain matrix G, number of
        dipoles orientations per location (1 or 3). A solver shall return
        2 variables: X which contains the time series of the active dipoles
        and an active set which is a boolean mask to specify what dipoles are
        present in X.
    evoked : instance of mne.Evoked
        The evoked data
    forward : instance of Forward
        The forward solution.
    noise_cov : instance of Covariance
        The noise covariance.
    loose : float in [0, 1] | 'auto'
        Value that weights the source variances of the dipole components
        that are parallel (tangential) to the cortical surface. If loose
        is 0 then the solution is computed with fixed orientation.
        If loose is 1, it corresponds to free orientations.
        The default value ('auto') is set to 0.2 for surface-oriented source
        space and set to 1.0 for volumic or discrete source space.
    depth : None | float in [0, 1]
        Depth weighting coefficients. If None, no depth weighting is performed.

    Returns
    -------
    stc : instance of SourceEstimate
        The source estimates.
    """
    # Import the necessary private functions
    from mne.inverse_sparse.mxne_inverse import \
        (_prepare_gain, is_fixed_orient,
         _reapply_source_weighting, _make_sparse_stc)

    all_ch_names = evoked.ch_names

    # Handle...


I am working on the file "0.20/_downloads/131324ab94fb4e4c09fa41f4692da130/plot_custom_inverse_solver.ipynb".
The first task is:
Source localization with a custom inverse solver
The objective of this example is to show how to plug a custom inverse solver
in MNE in order to facilate empirical comparison with the methods MNE already
implements (wMNE, dSPM, sLORETA, eLORETA, LCMV, DICS, (TF-)MxNE etc.).
This script is educational and shall be used for methods
evaluations and new developments. It is not meant to be an example
of good practice to analyse your data.
The example makes use of 2 functions apply_solver and solver
so changes can be limited to the solver function (which only takes three
parameters: the whitened data, the gain matrix and the number of orientations)
in order to try out another inverse algorithm.
Can you write Python code for it?

import numpy as np
from scipy import linalg
import mne
from mne.datasets import sample
from mne.viz import plot_sparse_source_estimates

data_path = sample.data_path()
fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
ave_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
cov_fname = data_path + '/MEG/sample/sample_audvis-shrunk-cov.fif'
subjects_dir = data_path + '/subjects'
condition = 'Left Auditory'

# Read noise covariance matrix
noise_cov = mne.read_cov(cov_fname)
# Handling average file
evoked = mne.read_evokeds(ave_fname, condition=condition, baseline=(None, 0))
evoked.crop(tmin=0.04, tmax=0.18)

evoked = evoked.pick_types(eeg=False, meg=True)
# Handling forward solution
forward = mne.read_forward_solution(fwd_fname)


I am working on the file "0.20/_downloads/142c866d928b3d3a3a76c80e0ef4ea81/plot_rereference_eeg.ipynb".
The first task is:
Re-referencing the EEG signal
This example shows how to load raw data and apply some EEG referencing schemes.
Can you write Python code for it?

# Authors: Marijn van Vliet <w.m.vanvliet@gmail.com>
#          Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)

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

print(__doc__)

# Setup for reading the raw data
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
event_id, tmin, tmax = 1, -0.2, 0.5

# Read the raw data
raw = mne.io.read_raw_fif(raw_fname, preload=True)
events = mne.read_events(event_fname)

# The EEG channels will be plotted to visualize the difference in referencing
# schemes.
picks = mne.pick_types(raw.info, meg=False, eeg=True, eog=True, exclude='bads')


I am working on the file "0.20/_downloads/142c866d928b3d3a3a76c80e0ef4ea81/plot_rereference_eeg.ipynb".
The first task is:
We will now apply different EEG referencing schemes and plot the resulting
evoked potentials. Note that when we construct epochs with mne.Epochs, we
supply the proj=True argument. This means that any available projectors
are applied automatically. Specifically, if there is an average reference
projector set by raw.set_eeg_reference('average', projection=True), MNE
applies this projector when creating epochs.
Can you write Python code for it?

reject = dict(eog=150e-6)
epochs_params = dict(events=events, event_id=event_id, tmin=tmin, tmax=tmax,
                     picks=picks, reject=reject, proj=True)

fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, ncols=1, sharex=True)

# We first want to plot the data without any added reference (i.e., using only
# the reference that was applied during recording of the data).
# However, this particular data already has an average reference projection
# applied that we now need to remove again using :func:`mne.set_eeg_reference`
raw, _ = mne.set_eeg_reference(raw, [])  # use [] to remove average projection
evoked_no_ref = mne.Epochs(raw, **epochs_params).average()

evoked_no_ref.plot(axes=ax1, titles=dict(eeg='Original reference'), show=False,
                   time_unit='s')

# Now we want to plot the data with an average reference, so let's add the
# projection we removed earlier back to the data. Note that we can use
# "set_eeg_reference" as a method on the ``raw`` object as well.
raw.set_eeg_reference('average', projection=True)
evoked_car = mne.Epochs(raw, **epochs_params).average()

evoked_car.plot(axes=ax2, titles=dict(eeg='Average reference'), show=False,
                time_unit='s')

# Re-reference from an average reference to the mean of channels EEG 001 and
# EEG 002.
raw.set_eeg_reference(['EEG 001', 'EEG 002'])
evoked_custom = mne.Epochs(raw, **epochs_params).average()

evoked_custom.plot(axes=ax3, titles=dict(eeg='Custom reference'),
                   time_unit='s')


I am working on the file "0.20/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
Adding custom plots to a report
The python interface has greater flexibility compared to the command
line interface <gen_mne_report>. For example, custom plots can be added via
the :meth:~mne.Report.add_figs_to_section method:
Can you write Python code for it?

# generate a custom plot:
fname_evoked = os.path.join(path, 'MEG', 'sample', 'sample_audvis-ave.fif')
evoked = mne.read_evokeds(fname_evoked,
                          condition='Left Auditory',
                          baseline=(None, 0),
                          verbose=True)
fig = evoked.plot(show=False)

# add the custom plot to the report:
report.add_figs_to_section(fig, captions='Left Auditory', section='evoked')
report.save('report_custom.html')


I am working on the file "0.20/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
Getting started with mne.Report
This tutorial covers making interactive HTML summaries with
:class:mne.Report.
   :depth: 2
As usual we'll start by importing the modules we need and loading some
example data <sample-dataset>:
Can you write Python code for it?


I am working on the file "0.20/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
If you want to actually view the noise covariance in the report, make sure
it is captured by the pattern passed to :meth:~mne.Report.parse_folder, and
also include a source for an :class:~mne.Info object (any of the
:class:~mne.io.Raw, :class:~mne.Epochs or :class:~mne.Evoked
:file:.fif files that contain subject data also contain the measurement
information and should work):
Can you write Python code for it?

pattern = 'sample_audvis-cov.fif'
info_fname = os.path.join(path, 'MEG', 'sample', 'sample_audvis-ave.fif')
report = mne.Report(info_fname=info_fname, verbose=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_cov.html')


I am working on the file "0.20/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
Managing report sections
The MNE report command internally manages the sections so that plots
belonging to the same section are rendered consecutively. Within a section,
the plots are ordered in the same order that they were added using the
:meth:~mne.Report.add_figs_to_section command. Each section is identified
by a toggle button in the top navigation bar of the report which can be used
to show or hide the contents of the section. To toggle the show/hide state of
all sections in the HTML report, press :kbd:t.

Note

Although we've been generating separate reports in each example, you could
   easily create a single report for all :file:`.fif` files (raw, evoked,
   covariance, etc) by passing ``pattern='*.fif'``.

Editing a saved report
Saving to HTML is a write-only operation, meaning that we cannot read an
.html file back as a :class:~mne.Report object. In order to be able
to edit a report once it's no longer in-memory in an active Python session,
save it as an HDF5 file instead of HTML:
Can you write Python code for it?

report.save('report.h5', overwrite=True)
report_from_disk = mne.open_report('report.h5')
print(report_from_disk)


I am working on the file "0.20/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
Now let's look at how :class:~mne.Report handles :class:~mne.Evoked data
(we'll skip the MRIs to save computation time):
Can you write Python code for it?

pattern = 'sample_audvis-no-filter-ave.fif'
report = mne.Report(verbose=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_evoked.html')


I am working on the file "0.20/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
This report yields a textual summary of the :class:~mne.io.Raw files
selected by the pattern. For a slightly more useful report, we'll ask for the
power spectral density of the :class:~mne.io.Raw files, by passing
raw_psd=True to the :class:~mne.Report constructor. Let's also refine
our pattern to select only the filtered raw recording (omitting the
unfiltered data and the empty-room noise recordings):
Can you write Python code for it?

pattern = 'sample_audvis_filt-0-40_raw.fif'
report = mne.Report(verbose=True, raw_psd=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_raw_psd.html')


I am working on the file "0.20/_downloads/1458a29737cd3695e2bfc763012d8259/plot_report.ipynb".
The first task is:
To render whitened :class:~mne.Evoked files with baseline correction, add
the noise covariance file. This will display ERP/F plots for both the
original and whitened :class:~mne.Evoked objects, but scalp topomaps only
for the original.
Can you write Python code for it?

cov_fname = os.path.join(path, 'MEG', 'sample', 'sample_audvis-cov.fif')
report = mne.Report(cov_fname=cov_fname, verbose=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_evoked_whitened.html')


I am working on the file "0.20/_downloads/162648d33d7b9ea4f5ce1e8bb494a02d/plot_mne_inverse_label_connectivity.ipynb".
The first task is:
Compute inverse solutions and their connectivity
Next, we need to compute the inverse solution for this data. This will return
the sources / source activity that we'll use in computing connectivity. We'll
compute the connectivity in the alpha band of these sources. We can specify
particular frequencies to include in the connectivity with the fmin and
fmax flags. Notice from the status messages how mne-python:

reads an epoch from the raw file
applies SSP and baseline correction
computes the inverse to obtain a source estimate
averages the source estimate to obtain a time series for each label
includes the label time series in the connectivity computation
moves to the next epoch.

This behaviour is because we are using generators. Since we only need to
operate on the data one epoch at a time, using a generator allows us to
compute connectivity in a computationally efficient manner where the amount
of memory (RAM) needed is independent from the number of epochs.
Can you write Python code for it?

# Compute inverse solution and for each epoch. By using "return_generator=True"
# stcs will be a generator object instead of a list.
snr = 1.0  # use lower SNR for single epochs
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)
stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method,
                            pick_ori="normal", return_generator=True)

# Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi
labels = mne.read_labels_from_annot('sample', parc='aparc',
                                    subjects_dir=subjects_dir)
label_colors = [label.color for label in labels]

# Average the source estimates within each label using sign-flips to reduce
# signal cancellations, also here we return a generator
src = inverse_operator['src']
label_ts = mne.extract_label_time_course(stcs, labels, src, mode='mean_flip',
                                         return_generator=True)

fmin = 8.
fmax = 13.
sfreq = raw.info['sfreq']  # the sampling frequency
con_methods = ['pli', 'wpli2_debiased', 'ciplv']
con, freqs, times, n_epochs, n_tapers = spectral_connectivity(
    label_ts, method=con_methods, mode='multitaper', sfreq=sfreq, fmin=fmin,
    fmax=fmax, faverage=True, mt_adaptive=True, n_jobs=1)

# con is a 3D array, get the connectivity for the first (and only) freq. band
# for each method
con_res = dict()
for method, c in zip(con_methods, con):
    con_res[method] = c[:, :, 0]


I am working on the file "0.20/_downloads/162648d33d7b9ea4f5ce1e8bb494a02d/plot_mne_inverse_label_connectivity.ipynb".
The first task is:
Save the figure (optional)
By default matplotlib does not save using the facecolor, even though this was
set when the figure was generated. If not set via savefig, the labels, title,
and legend will be cut off from the output png file.
Can you write Python code for it?

# fname_fig = data_path + '/MEG/sample/plot_inverse_connect.png'
# fig.savefig(fname_fig, facecolor='black')


I am working on the file "0.20/_downloads/17295dea468fcedae97ed8a6f9afc520/plot_decoding_csp_timefreq.ipynb".
The first task is:
Decoding in time-frequency space data using the Common Spatial Pattern (CSP)
The time-frequency decomposition is estimated by iterating over raw data that
has been band-passed at different frequencies. This is used to compute a
covariance matrix over each epoch or a rolling time-window and extract the CSP
filtered signals. A linear discriminant classifier is then applied to these
signals.
Can you write Python code for it?

# Authors: Laura Gwilliams <laura.gwilliams@nyu.edu>
#          Jean-Remi King <jeanremi.king@gmail.com>
#          Alex Barachant <alexandre.barachant@gmail.com>
#          Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

from mne import Epochs, create_info, events_from_annotations
from mne.io import concatenate_raws, read_raw_edf
from mne.datasets import eegbci
from mne.decoding import CSP
from mne.time_frequency import AverageTFR

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import LabelEncoder


I am working on the file "0.20/_downloads/17295dea468fcedae97ed8a6f9afc520/plot_decoding_csp_timefreq.ipynb".
The first task is:
Loop through frequencies and time, apply classifier and save scores
Can you write Python code for it?

# init scores
tf_scores = np.zeros((n_freqs - 1, n_windows))

# Loop through each frequency range of interest
for freq, (fmin, fmax) in enumerate(freq_ranges):

    # Infer window size based on the frequency being used
    w_size = n_cycles / ((fmax + fmin) / 2.)  # in seconds

    # Apply band-pass filter to isolate the specified frequencies
    raw_filter = raw.copy().filter(fmin, fmax, n_jobs=1, fir_design='firwin',
                                   skip_by_annotation='edge')

    # Extract epochs from filtered data, padded by window size
    epochs = Epochs(raw_filter, events, event_id, tmin - w_size, tmax + w_size,
                    proj=False, baseline=None, preload=True)
    epochs.drop_bad()
    y = le.fit_transform(epochs.events[:, 2])

    # Roll covariance, csp and lda over time
    for t, w_time in enumerate(centered_w_times):

        # Center the min and max of the window
        w_tmin = w_time - w_size / 2.
        w_tmax = w_time + w_size / 2.

        # Crop data into time-window of interest
        X = epochs.copy().crop(w_tmin, w_tmax).get_data()

        # Save mean scores over folds for each frequency and time window
        tf_scores[freq, t] = np.mean(cross_val_score(estimator=clf, X=X, y=y,
                                                     scoring='roc_auc', cv=cv,
                                                     n_jobs=1), axis=0)


I am working on the file "0.20/_downloads/17295dea468fcedae97ed8a6f9afc520/plot_decoding_csp_timefreq.ipynb".
The first task is:
Loop through frequencies, apply classifier and save scores
Can you write Python code for it?

# init scores
freq_scores = np.zeros((n_freqs - 1,))

# Loop through each frequency range of interest
for freq, (fmin, fmax) in enumerate(freq_ranges):

    # Infer window size based on the frequency being used
    w_size = n_cycles / ((fmax + fmin) / 2.)  # in seconds

    # Apply band-pass filter to isolate the specified frequencies
    raw_filter = raw.copy().filter(fmin, fmax, n_jobs=1, fir_design='firwin',
                                   skip_by_annotation='edge')

    # Extract epochs from filtered data, padded by window size
    epochs = Epochs(raw_filter, events, event_id, tmin - w_size, tmax + w_size,
                    proj=False, baseline=None, preload=True)
    epochs.drop_bad()
    y = le.fit_transform(epochs.events[:, 2])

    X = epochs.get_data()

    # Save mean scores over folds for each frequency and time window
    freq_scores[freq] = np.mean(cross_val_score(estimator=clf, X=X, y=y,
                                                scoring='roc_auc', cv=cv,
                                                n_jobs=1), axis=0)


I am working on the file "0.20/_downloads/17295dea468fcedae97ed8a6f9afc520/plot_decoding_csp_timefreq.ipynb".
The first task is:
Plot frequency results
Can you write Python code for it?

plt.bar(freqs[:-1], freq_scores, width=np.diff(freqs)[0],
        align='edge', edgecolor='black')
plt.xticks(freqs)
plt.ylim([0, 1])
plt.axhline(len(epochs['feet']) / len(epochs), color='k', linestyle='--',
            label='chance level')
plt.legend()
plt.xlabel('Frequency (Hz)')
plt.ylabel('Decoding Scores')
plt.title('Frequency Decoding Scores')


I am working on the file "0.20/_downloads/17295dea468fcedae97ed8a6f9afc520/plot_decoding_csp_timefreq.ipynb".
The first task is:
Plot time-frequency results
Can you write Python code for it?

# Set up time frequency object
av_tfr = AverageTFR(create_info(['freq'], sfreq), tf_scores[np.newaxis, :],
                    centered_w_times, freqs[1:], 1)

chance = np.mean(y)  # set chance level to white in the plot
av_tfr.plot([0], vmin=chance, title="Time-Frequency Decoding Scores",
            cmap=plt.cm.Reds)


I am working on the file "0.20/_downloads/17295dea468fcedae97ed8a6f9afc520/plot_decoding_csp_timefreq.ipynb".
The first task is:
Set parameters and read data
Can you write Python code for it?

event_id = dict(hands=2, feet=3)  # motor imagery: hands vs feet
subject = 1
runs = [6, 10, 14]
raw_fnames = eegbci.load_data(subject, runs)
raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames])

# Extract information from the raw file
sfreq = raw.info['sfreq']
events, _ = events_from_annotations(raw, event_id=dict(T1=2, T2=3))
raw.pick_types(meg=False, eeg=True, stim=False, eog=False, exclude='bads')

# Assemble the classifier using scikit-learn pipeline
clf = make_pipeline(CSP(n_components=4, reg=None, log=True, norm_trace=False),
                    LinearDiscriminantAnalysis())
n_splits = 5  # how many folds to use for cross-validation
cv = StratifiedKFold(n_splits=n_splits, shuffle=True)

# Classification & Time-frequency parameters
tmin, tmax = -.200, 2.000
n_cycles = 10.  # how many complete cycles: used to define window size
min_freq = 5.
max_freq = 25.
n_freqs = 8  # how many frequency bins to use

# Assemble list of frequency range tuples
freqs = np.linspace(min_freq, max_freq, n_freqs)  # assemble frequencies
freq_ranges = list(zip(freqs[:-1], freqs[1:]))  # make freqs list of tuples

# Infer window spacing from the max freq and number of cycles to avoid gaps
window_spacing = (n_cycles / np.max(freqs) / 2.)
centered_w_times = np.arange(tmin, tmax, window_spacing)[1:]
n_windows = len(centered_w_times)

# Instantiate label encoder
le = LabelEncoder()


I am working on the file "0.20/_downloads/1935e973eb220e31cb4a6a6541231eb1/plot_background_statistics.ipynb".
The first task is:
"Hat" variance adjustment
The "hat" technique regularizes the variance values used in the t-test
calculation [1]_ to compensate for implausibly small variances.
Can you write Python code for it?

ts.append(ttest_1samp_no_p(X, sigma=sigma))
ps.append(stats.distributions.t.sf(np.abs(ts[-1]), len(X) - 1) * 2)
titles.append(r'$\mathrm{t_{hat}}$')
mccs.append(False)
plot_t_p(ts[-1], ps[-1], titles[-1], mccs[-1])


I am working on the file "0.20/_downloads/1935e973eb220e31cb4a6a6541231eb1/plot_background_statistics.ipynb".
The first task is:
"Hat" variance adjustment
This method can also be used in this context to correct for small
variances [1]_:
Can you write Python code for it?

titles.append(r'$\mathbf{C_{hat}}$')
stat_fun_hat = partial(ttest_1samp_no_p, sigma=sigma)
t_hat, clusters, p_values, H0 = permutation_cluster_1samp_test(
    X, n_jobs=1, threshold=threshold, connectivity=None,
    n_permutations=n_permutations, stat_fun=stat_fun_hat, buffer_size=None)
p_hat = np.ones((width, width))
for cl, p in zip(clusters, p_values):
    p_hat[cl] = p
ts.append(t_hat)
ps.append(p_hat)
mccs.append(True)
plot_t_p(ts[-1], ps[-1], titles[-1], mccs[-1])


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

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

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

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


I am working on the file "0.20/_downloads/1935e973eb220e31cb4a6a6541231eb1/plot_background_statistics.ipynb".
The first task is:
Multiple comparisons
So far, we have done no correction for multiple comparisons. This is
potentially problematic for these data because there are
$40 \cdot 40 = 1600$ tests being performed. If we use a threshold
p < 0.05 for each individual test, we would expect many voxels to be declared
significant even if there were no true effect. In other words, we would make
many type I errors (adapted from here <errors_>_):
.. rst-class:: skinnytable
+----------+--------+------------------+------------------+
  |                   |          Null hypothesis            |
  |                   +------------------+------------------+
  |                   |       True       |       False      |
  +==========+========+==================+==================+
  |          |        | Type I error     | Correct          |
  |          | Yes    |   False positive |   True positive  |
  + Reject   +--------+------------------+------------------+
  |          |        | Correct          | Type II error    |
  |          | No     |   True Negative  |   False negative |
  +----------+--------+------------------+------------------+
To see why, consider a standard $\alpha = 0.05$.
For a single test, our probability of making a type I error is 0.05.
The probability of making at least one type I error in
$N_{\mathrm{test}}$ independent tests is then given by
$1 - (1 - \alpha)^{N_{\mathrm{test}}}$:
Can you write Python code for it?

N = np.arange(1, 80)
alpha = 0.05
p_type_I = 1 - (1 - alpha) ** N
fig, ax = plt.subplots(figsize=(4, 3))
ax.scatter(N, p_type_I, 3)
ax.set(xlim=N[[0, -1]], ylim=[0, 1], xlabel=r'$N_{\mathrm{test}}$',
       ylabel=u'Probability of at least\none type I error')
ax.grid(True)
fig.tight_layout()
fig.show()


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

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

from functools import partial

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

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

print(__doc__)


I am working on the file "0.20/_downloads/1935e973eb220e31cb4a6a6541231eb1/plot_background_statistics.ipynb".
The first task is:
The data averaged over all subjects looks like this:
Can you write Python code for it?

fig, ax = plt.subplots()
ax.imshow(X.mean(0), cmap='inferno')
ax.set(xticks=[], yticks=[], title="Data averaged over subjects")


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

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


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

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

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

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

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


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

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


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

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


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

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

import matplotlib.pyplot as plt

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

print(__doc__)


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

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


I am working on the file "0.20/_downloads/1947e3859a9ecfd32afbd0018a48f74d/plot_cluster_stats_evoked.ipynb".
The first task is:
Read epochs for the channel of interest
Can you write Python code for it?

picks = mne.pick_types(raw.info, meg=False, eog=True, include=include,
                       exclude='bads')
event_id = 1
reject = dict(grad=4000e-13, eog=150e-6)
epochs1 = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                     baseline=(None, 0), reject=reject)
condition1 = epochs1.get_data()  # as 3D matrix

event_id = 2
epochs2 = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                     baseline=(None, 0), reject=reject)
condition2 = epochs2.get_data()  # as 3D matrix

condition1 = condition1[:, 0, :]  # take only one channel to get a 2D array
condition2 = condition2[:, 0, :]  # take only one channel to get a 2D array


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

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

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

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


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
Brainstorm auditory tutorial dataset
Here we compute the evoked from raw for the auditory Brainstorm
tutorial dataset. For comparison, see [1] and the associated
brainstorm site <https://neuroimage.usc.edu/brainstorm/Tutorials/Auditory>.
Experiment:
- One subject, 2 acquisition runs 6 minutes each.
- Each run contains 200 regular beeps and 40 easy deviant beeps.
- Random ISI: between 0.7s and 1.7s seconds, uniformly distributed.
- Button pressed when detecting a deviant with the right index finger.

The specifications of this dataset were discussed initially on the
FieldTrip bug tracker
<http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=2300>__.
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?

# Authors: Mainak Jas <mainak.jas@telecom-paristech.fr>
#          Eric Larson <larson.eric.d@gmail.com>
#          Jaakko Leppakangas <jaeilepp@student.jyu.fi>
#
# License: BSD (3-clause)

import os.path as op
import pandas as pd
import numpy as np

import mne
from mne import combine_evoked
from mne.minimum_norm import apply_inverse
from mne.datasets.brainstorm import bst_auditory
from mne.io import read_raw_ctf

print(__doc__)


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
Difference.
Can you write Python code for it?

stc_difference = apply_inverse(evoked_difference, inv, lambda2, 'dSPM')
brain = stc_difference.plot(subjects_dir=subjects_dir, subject=subject,
                            surface='inflated', time_viewer=False, hemi='lh',
                            initial_time=0.15, time_unit='s')


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
For noise reduction, a set of bad segments have been identified and stored
in csv files. The bad segments are later used to reject epochs that overlap
with them.
The file for the second run also contains some saccades. The saccades are
removed by using SSP. We use pandas to read the data from the csv files. You
can also view the files with your favorite text editor.
Can you write Python code for it?

annotations_df = pd.DataFrame()
offset = n_times_run1
for idx in [1, 2]:
    csv_fname = op.join(data_path, 'MEG', 'bst_auditory',
                        'events_bad_0%s.csv' % idx)
    df = pd.read_csv(csv_fname, header=None,
                     names=['onset', 'duration', 'id', 'label'])
    print('Events from run {0}:'.format(idx))
    print(df)

    df['onset'] += offset * (idx - 1)
    annotations_df = pd.concat([annotations_df, df], axis=0)

saccades_events = df[df['label'] == 'saccade'].values[:, :3].astype(int)

# Conversion from samples to times:
onsets = annotations_df['onset'].values / raw.info['sfreq']
durations = annotations_df['duration'].values / raw.info['sfreq']
descriptions = annotations_df['label'].values

annotations = mne.Annotations(onsets, durations, descriptions)
raw.set_annotations(annotations)
del onsets, durations, descriptions


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
Here we compute the saccade and EOG projectors for magnetometers and add
them to the raw data. The projectors are added to both runs.
Can you write Python code for it?

saccade_epochs = mne.Epochs(raw, saccades_events, 1, 0., 0.5, preload=True,
                            baseline=(None, None),
                            reject_by_annotation=False)

projs_saccade = mne.compute_proj_epochs(saccade_epochs, n_mag=1, n_eeg=0,
                                        desc_prefix='saccade')
if use_precomputed:
    proj_fname = op.join(data_path, 'MEG', 'bst_auditory',
                         'bst_auditory-eog-proj.fif')
    projs_eog = mne.read_proj(proj_fname)[0]
else:
    projs_eog, _ = mne.preprocessing.compute_proj_eog(raw.load_data(),
                                                      n_mag=1, n_eeg=0)
raw.add_proj(projs_saccade)
raw.add_proj(projs_eog)
del saccade_epochs, saccades_events, projs_eog, projs_saccade  # To save memory


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
Here we plot the ERF of standard and deviant conditions. In both conditions
we can see the P50 and N100 responses. The mismatch negativity is visible
only in the deviant condition around 100-200 ms. P200 is also visible around
170 ms in both conditions but much stronger in the standard condition. P300
is visible in deviant condition only (decision making in preparation of the
button press). You can view the topographies from a certain time span by
painting an area with clicking and holding the left mouse button.
Can you write Python code for it?

evoked_std.plot(window_title='Standard', gfp=True, time_unit='s')
evoked_dev.plot(window_title='Deviant', gfp=True, time_unit='s')


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
In the memory saving mode we use preload=False and use the memory
efficient IO which loads the data on demand. However, filtering and some
other functions require the data to be preloaded in the memory.
Can you write Python code for it?

preload = not use_precomputed
raw = read_raw_ctf(raw_fname1, preload=preload)
n_times_run1 = raw.n_times
mne.io.concatenate_raws([raw, read_raw_ctf(raw_fname2, preload=preload)])
raw_erm = read_raw_ctf(erm_fname, preload=preload)


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
Show activations as topography figures.
Can you write Python code for it?

times = np.arange(0.05, 0.301, 0.025)
evoked_std.plot_topomap(times=times, title='Standard', time_unit='s')
evoked_dev.plot_topomap(times=times, title='Deviant', time_unit='s')


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
Source estimation.
We compute the noise covariance matrix from the empty room measurement
and use it for the other runs.
Can you write Python code for it?

reject = dict(mag=4e-12)
cov = mne.compute_raw_covariance(raw_erm, reject=reject)
cov.plot(raw_erm.info)
del raw_erm


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
The averages for each conditions are computed.
Can you write Python code for it?

evoked_std = epochs_standard.average()
evoked_dev = epochs_deviant.average()
del epochs_standard, epochs_deviant


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
The event timing is adjusted by comparing the trigger times on detected
sound onsets on channel UADC001-4408.
Can you write Python code for it?

sound_data = raw[raw.ch_names.index('UADC001-4408')][0][0]
onsets = np.where(np.abs(sound_data) > 2. * np.std(sound_data))[0]
min_diff = int(0.5 * raw.info['sfreq'])
diffs = np.concatenate([[min_diff + 1], np.diff(onsets)])
onsets = onsets[diffs > min_diff]
assert len(onsets) == len(events)
diffs = 1000. * (events[:, 0] - onsets) / raw.info['sfreq']
print('Trigger delay removed (μ ± σ): %0.1f ± %0.1f ms'
      % (np.mean(diffs), np.std(diffs)))
events[:, 0] = onsets
del sound_data, diffs


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
The transformation is read from a file:
Can you write Python code for it?

trans_fname = op.join(data_path, 'MEG', 'bst_auditory',
                      'bst_auditory-trans.fif')
trans = mne.read_trans(trans_fname)


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
To reduce memory consumption and running time, some of the steps are
precomputed. To run everything from scratch change this to False. With
use_precomputed = False running time of this script can be several
minutes even on a fast computer.
Can you write Python code for it?


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
To save time and memory, the forward solution is read from a file. Set
use_precomputed=False in the beginning of this script to build the
forward solution from scratch. The head surfaces for constructing a BEM
solution are read from a file. Since the data only contains MEG channels, we
only need the inner skull surface for making the forward solution. For more
information: CHDBBCEJ, :func:mne.setup_source_space,
bem-model, :func:mne.bem.make_watershed_bem.
Can you write Python code for it?

if use_precomputed:
    fwd_fname = op.join(data_path, 'MEG', 'bst_auditory',
                        'bst_auditory-meg-oct-6-fwd.fif')
    fwd = mne.read_forward_solution(fwd_fname)
else:
    src = mne.setup_source_space(subject, spacing='ico4',
                                 subjects_dir=subjects_dir, overwrite=True)
    model = mne.make_bem_model(subject=subject, ico=4, conductivity=[0.3],
                               subjects_dir=subjects_dir)
    bem = mne.make_bem_solution(model)
    fwd = mne.make_forward_solution(evoked_std.info, trans=trans, src=src,
                                    bem=bem)

inv = mne.minimum_norm.make_inverse_operator(evoked_std.info, fwd, cov)
snr = 3.0
lambda2 = 1.0 / snr ** 2
del fwd


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
Typical preprocessing step is the removal of power line artifact (50 Hz or
60 Hz). Here we lowpass filter the data at 40 Hz, which will remove all
line artifacts (and high frequency information). Normally this would be done
to raw data (with :func:mne.io.Raw.filter), but to reduce memory
consumption of this tutorial, we do it at evoked stage. (At the raw stage,
you could alternatively notch filter with :func:mne.io.Raw.notch_filter.)
Can you write Python code for it?

for evoked in (evoked_std, evoked_dev):
    evoked.filter(l_freq=None, h_freq=40., fir_design='firwin')


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
We also lowpass filter the data at 100 Hz to remove the hf components.
Can you write Python code for it?

if not use_precomputed:
    raw.filter(None, 100., h_trans_bandwidth=0.5, filter_length='10s',
               phase='zero-double', fir_design='firwin2')


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
We can see the MMN effect more clearly by looking at the difference between
the two conditions. P50 and N100 are no longer visible, but MMN/P200 and
P300 are emphasised.
Can you write Python code for it?

evoked_difference = combine_evoked([evoked_dev, -evoked_std], weights='equal')
evoked_difference.plot(window_title='Difference', gfp=True, time_unit='s')


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
We mark a set of bad channels that seem noisier than others. This can also
be done interactively with raw.plot by clicking the channel name
(or the line). The marked channels are added as bad when the browser window
is closed.
Can you write Python code for it?


I am working on the file "0.20/_downloads/1af5a35cbb809b9480120842884536c5/plot_brainstorm_auditory.ipynb".
The first task is:
We only use first 40 good epochs from each run. Since we first drop the bad
epochs, the indices of the epochs are no longer same as in the original
epochs collection. Investigation of the event timings reveals that first
epoch from the second run corresponds to index 182.
Can you write Python code for it?

epochs.drop_bad()
epochs_standard = mne.concatenate_epochs([epochs['standard'][range(40)],
                                          epochs['standard'][182:222]])
epochs_standard.load_data()  # Resampling to save memory.
epochs_standard.resample(600, npad='auto')
epochs_deviant = epochs['deviant'].load_data()
epochs_deviant.resample(600, npad='auto')
del epochs


I am working on the file "0.20/_downloads/1c42464343cb8d2a19e726a89ed2fd17/plot_simulated_raw_data_using_subject_anatomy.ipynb".
The first task is:
Extract epochs and compute evoked responsses
Can you write Python code for it?

epochs = mne.Epochs(raw_sim, events, event_id, tmin=-0.2, tmax=0.3,
                    baseline=(None, 0))
evoked_aud_left = epochs['auditory/left'].average()
evoked_vis_right = epochs['visual/right'].average()

# Visualize the evoked data
evoked_aud_left.plot(spatial_colors=True)
evoked_vis_right.plot(spatial_colors=True)


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

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

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

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


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

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

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

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

annot = 'aparc.a2009s'

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


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

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

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


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

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

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

raw_sim = mne.simulation.simulate_raw(info, source_simulator, forward=fwd)
raw_sim.set_eeg_reference(projection=True)

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

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


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

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

# License: BSD (3-clause)

import os.path as op

import numpy as np

import mne
from mne.datasets import sample

print(__doc__)

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

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

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

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

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

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

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

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


I am working on the file "0.20/_downloads/20f35983ef279d1b30aa970c81aafe26/plot_read_events.ipynb".
The first task is:
Events objects are essentially numpy arrays with three columns:
event_sample | previous_event_id | event_id
Can you write Python code for it?

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

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


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

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

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

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

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


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

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

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

print(__doc__)

data_path = sample.data_path()

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

subjects_dir = data_path + '/subjects'

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


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

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

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

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

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


I am working on the file "0.20/_downloads/2369809188e1e28fb4d0ad564cdfa36d/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@inria.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.20/_downloads/2369809188e1e28fb4d0ad564cdfa36d/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.20/_downloads/2369809188e1e28fb4d0ad564cdfa36d/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.20/_downloads/243172b1ef6a2d804d3245b8c0a927ef/plot_60_maxwell_filtering_sss.ipynb".
The first task is:
But this algorithm is not perfect. For example, it misses MEG 2313,
which has some flux jumps, because there are not enough flux jumps in the
recording. So it can still be useful to manually inspect and mark bad
channels:
Can you write Python code for it?

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


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

import os
import mne

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


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

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


I am working on the file "0.20/_downloads/2567f25ca4c6b483c12d38184d7fe9d7/plot_decoding_xdawn_eeg.ipynb".
The first task is:
Set parameters and read data
Can you write Python code for it?

raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
tmin, tmax = -0.1, 0.3
event_id = {'Auditory/Left': 1, 'Auditory/Right': 2,
            'Visual/Left': 3, 'Visual/Right': 4}
n_filter = 3

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

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

epochs = Epochs(raw, events, event_id, tmin, tmax, proj=False,
                picks=picks, baseline=None, preload=True,
                verbose=False)

# Create classification pipeline
clf = make_pipeline(Xdawn(n_components=n_filter),
                    Vectorizer(),
                    MinMaxScaler(),
                    LogisticRegression(penalty='l1', solver='liblinear',
                                       multi_class='auto'))

# Get the labels
labels = epochs.events[:, -1]

# Cross validator
cv = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)

# Do cross-validation
preds = np.empty(len(labels))
for train, test in cv.split(epochs, labels):
    clf.fit(epochs[train], labels[train])
    preds[test] = clf.predict(epochs[test])

# Classification report
target_names = ['aud_l', 'aud_r', 'vis_l', 'vis_r']
report = classification_report(labels, preds, target_names=target_names)
print(report)

# Normalized confusion matrix
cm = confusion_matrix(labels, preds)
cm_normalized = cm.astype(float) / cm.sum(axis=1)[:, np.newaxis]

# Plot confusion matrix
fig, ax = plt.subplots(1)
im = ax.imshow(cm_normalized, interpolation='nearest', cmap=plt.cm.Blues)
ax.set(title='Normalized Confusion matrix')
fig.colorbar(im)
tick_marks = np.arange(len(target_names))
plt.xticks(tick_marks, target_names, rotation=45)
plt.yticks(tick_marks, target_names)
fig.tight_layout()
ax.set(ylabel='True label', xlabel='Predicted label')


I am working on the file "0.20/_downloads/2567f25ca4c6b483c12d38184d7fe9d7/plot_decoding_xdawn_eeg.ipynb".
The first task is:
The patterns_ attribute of a fitted Xdawn instance (here from the last
cross-validation fold) can be used for visualization.
Can you write Python code for it?

fig, axes = plt.subplots(nrows=len(event_id), ncols=n_filter,
                         figsize=(n_filter, len(event_id) * 2))
fitted_xdawn = clf.steps[0][1]
tmp_info = epochs.info.copy()
tmp_info['sfreq'] = 1.
for ii, cur_class in enumerate(sorted(event_id)):
    cur_patterns = fitted_xdawn.patterns_[cur_class]
    pattern_evoked = EvokedArray(cur_patterns[:n_filter].T, tmp_info, tmin=0)
    pattern_evoked.plot_topomap(
        times=np.arange(n_filter),
        time_format='Component %d' if ii == 0 else '', colorbar=False,
        show_names=False, axes=axes[ii], show=False)
    axes[ii, 0].set(ylabel=cur_class)
fig.tight_layout(h_pad=1.0, w_pad=1.0, pad=0.1)


I am working on the file "0.20/_downloads/2567f25ca4c6b483c12d38184d7fe9d7/plot_decoding_xdawn_eeg.ipynb".
The first task is:
XDAWN Decoding From EEG data
ERP decoding with Xdawn ([1], [2]). For each event type, a set of
spatial Xdawn filters are trained and applied on the signal. Channels are
concatenated and rescaled to create features vectors that will be fed into
a logistic regression.
Can you write Python code for it?

# Authors: Alexandre Barachant <alexandre.barachant@gmail.com>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.preprocessing import MinMaxScaler

from mne import io, pick_types, read_events, Epochs, EvokedArray
from mne.datasets import sample
from mne.preprocessing import Xdawn
from mne.decoding import Vectorizer

print(__doc__)

data_path = sample.data_path()


I am working on the file "0.20/_downloads/2677ee623a2aeff54fe63131444b1844/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']

# Create epochs, here for gradiometers + EOG only for simplicity
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    picks=('grad', 'eog'), baseline=(None, 0), preload=True,
                    reject=dict(grad=4000e-13, eog=150e-6))


I am working on the file "0.20/_downloads/2677ee623a2aeff54fe63131444b1844/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.manifold 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.20/_downloads/2677ee623a2aeff54fe63131444b1844/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 [1]_.
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@inria.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.20/_downloads/270188718f88ff03a28e3be5f47294ee/plot_decoding_unsupervised_spatial_filter.ipynb".
The first task is:
Transform data with ICA computed on the raw epochs (no averaging)
Can you write Python code for it?

ica = UnsupervisedSpatialFilter(FastICA(30), average=False)
ica_data = ica.fit_transform(X)
ev1 = mne.EvokedArray(np.mean(ica_data, axis=0),
                      mne.create_info(30, epochs.info['sfreq'],
                                      ch_types='eeg'), tmin=tmin)
ev1.plot(show=False, window_title='ICA', time_unit='s')

plt.show()


I am working on the file "0.20/_downloads/2784a8d5822ed9797c0330f973573c10/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.20/_downloads/2784a8d5822ed9797c0330f973573c10/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"]
index = ['condition', 'epoch', 'time']

# display the EEG data in Pandas format (first 5 rows)
print(epochs.to_data_frame(index=index)[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(index=index)
    short_df = short_words.copy().crop(tmin, tmax).to_data_frame(index=index)
    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.20/_downloads/285b673bc4afbda20046e6f8ff40b632/plot_sensor_noise_level.ipynb".
The first task is:
Show noise levels from empty room data
This shows how to use :meth:mne.io.Raw.plot_psd to examine noise levels
of systems. See [1]_ for an example.
References
.. [1] Khan S, Cohen D (2013). Note: Magnetic noise from the inner wall of
   a magnetically shielded room. Review of Scientific Instruments 84:56101.
   https://doi.org/10.1063/1.4802845
Can you write Python code for it?

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

import os.path as op
import mne

data_path = mne.datasets.sample.data_path()

raw_erm = mne.io.read_raw_fif(op.join(data_path, 'MEG', 'sample',
                                      'ernoise_raw.fif'), preload=True)


I am working on the file "0.20/_downloads/285b673bc4afbda20046e6f8ff40b632/plot_sensor_noise_level.ipynb".
The first task is:
We can plot the absolute noise levels:
Can you write Python code for it?

raw_erm.plot_psd(tmax=10., average=True, spatial_colors=False,
                 dB=False, xscale='log')


I am working on the file "0.20/_downloads/2b710ad55cbf958235c0d74bf0b0d4ae/plot_evoked_ers_source_power.ipynb".
The first task is:
Compute covariances
ERS activity starts at 0.5 seconds after stimulus onset.
Can you write Python code for it?

active_win = (0.5, 1.5)
baseline_win = (-1, 0)

baseline_cov = compute_covariance(epochs, tmin=baseline_win[0],
                                  tmax=baseline_win[1], method='shrunk',
                                  rank=None)
active_cov = compute_covariance(epochs, tmin=active_win[0], tmax=active_win[1],
                                method='shrunk', rank=None)

# Weighted averaging is already in the addition of covariance objects.
common_cov = baseline_cov + active_cov


I am working on the file "0.20/_downloads/2b710ad55cbf958235c0d74bf0b0d4ae/plot_evoked_ers_source_power.ipynb".
The first task is:
Compute evoked ERS source power using DICS, LCMV beamformer, and dSPM
Here we examine 3 ways of localizing event-related synchronization (ERS) of
beta band activity in this dataset: somato-dataset using
:term:DICS, :term:LCMV beamformer, and :term:dSPM applied to active and
baseline covariance matrices.
Can you write Python code for it?

# Authors: Luke Bloy <luke.bloy@gmail.com>
#          Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)
import os.path as op

import numpy as np
import mne
from mne.cov import compute_covariance
from mne.datasets import somato
from mne.time_frequency import csd_morlet
from mne.beamformer import (make_dics, apply_dics_csd, make_lcmv,
                            apply_lcmv_cov)
from mne.minimum_norm import (make_inverse_operator, apply_inverse_cov)

print(__doc__)


I am working on the file "0.20/_downloads/2b710ad55cbf958235c0d74bf0b0d4ae/plot_evoked_ers_source_power.ipynb".
The first task is:
Plot source estimates
Can you write Python code for it?

for method, stc in zip(['DICS', 'LCMV', 'dSPM'],
                       [stc_dics, stc_lcmv, stc_dspm]):
    title = '%s source power in the 12-30 Hz frequency band' % method
    brain = stc.plot(hemi='rh', subjects_dir=subjects_dir,
                     subject=subject, time_label=title)


I am working on the file "0.20/_downloads/2b710ad55cbf958235c0d74bf0b0d4ae/plot_evoked_ers_source_power.ipynb".
The first task is:
Reading the raw data and creating epochs:
Can you write Python code for it?

data_path = somato.data_path()
subject = '01'
task = 'somato'
raw_fname = op.join(data_path, 'sub-{}'.format(subject), 'meg',
                    'sub-{}_task-{}_meg.fif'.format(subject, task))

raw = mne.io.read_raw_fif(raw_fname)

# We are interested in the beta band (12-30 Hz)
raw.load_data().filter(12, 30)

# The DICS beamformer currently only supports a single sensor type.
# We'll use the gradiometers in this example.
picks = mne.pick_types(raw.info, meg='grad', exclude='bads')

# Read epochs
events = mne.find_events(raw)
epochs = mne.Epochs(raw, events, event_id=1, tmin=-1.5, tmax=2, picks=picks,
                    preload=True)

# Read forward operator and point to freesurfer subject directory
fname_fwd = op.join(data_path, 'derivatives', 'sub-{}'.format(subject),
                    'sub-{}_task-{}-fwd.fif'.format(subject, task))
subjects_dir = op.join(data_path, 'derivatives', 'freesurfer', 'subjects')

fwd = mne.read_forward_solution(fname_fwd)


I am working on the file "0.20/_downloads/2b9ae87368ee06cd9589fd87e1be1d30/plot_time_frequency_mixed_norm_inverse.ipynb".
The first task is:
Compute MxNE with time-frequency sparse prior
The TF-MxNE solver is a distributed inverse method (like dSPM or sLORETA)
that promotes focal (sparse) sources (such as dipole fitting techniques)
[1] [2]. The benefit of this approach is that:

it is spatio-temporal without assuming stationarity (sources properties
    can vary over time)
activations are localized in space, time and frequency in one step.
with a built-in filtering process based on a short time Fourier
    transform (STFT), data does not need to be low passed (just high pass
    to make the signals zero mean).
the solver solves a convex optimization problem, hence cannot be
    trapped in local minima.

References
.. [1] A. Gramfort, D. Strohmeier, J. Haueisen, M. Hämäläinen, M. Kowalski
   "Time-Frequency Mixed-Norm Estimates: Sparse M/EEG imaging with
   non-stationary source activations",
   Neuroimage, Volume 70, pp. 410-422, 15 April 2013.
   DOI: 10.1016/j.neuroimage.2012.12.051
.. [2] A. Gramfort, D. Strohmeier, J. Haueisen, M. Hämäläinen, M. Kowalski
   "Functional Brain Imaging with M/EEG Using Structured Sparsity in
   Time-Frequency Dictionaries",
   Proceedings Information Processing in Medical Imaging
   Lecture Notes in Computer Science, Volume 6801/2011, pp. 600-611, 2011.
   DOI: 10.1007/978-3-642-22092-0_49
Can you write Python code for it?

# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#         Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: BSD (3-clause)

import numpy as np

import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
from mne.inverse_sparse import tf_mixed_norm, make_stc_from_dipoles
from mne.viz import (plot_sparse_source_estimates,
                     plot_dipole_locations, plot_dipole_amplitudes)

print(__doc__)

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
ave_fname = data_path + '/MEG/sample/sample_audvis-no-filter-ave.fif'
cov_fname = data_path + '/MEG/sample/sample_audvis-shrunk-cov.fif'

# Read noise covariance matrix
cov = mne.read_cov(cov_fname)

# Handling average file
condition = 'Left visual'
evoked = mne.read_evokeds(ave_fname, condition=condition, baseline=(None, 0))
evoked = mne.pick_channels_evoked(evoked)
# We make the window slightly larger than what you'll eventually be interested
# in ([-0.05, 0.3]) to avoid edge effects.
evoked.crop(tmin=-0.1, tmax=0.4)

# Handling forward solution
forward = mne.read_forward_solution(fwd_fname)


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

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


I am working on the file "0.20/_downloads/2b9ae87368ee06cd9589fd87e1be1d30/plot_time_frequency_mixed_norm_inverse.ipynb".
The first task is:
Plot dipole activations
Can you write Python code for it?

plot_dipole_amplitudes(dipoles)

# Plot dipole location of the strongest dipole with MRI slices
idx = np.argmax([np.max(np.abs(dip.amplitude)) for dip in dipoles])
plot_dipole_locations(dipoles[idx], forward['mri_head_t'], 'sample',
                      subjects_dir=subjects_dir, mode='orthoview',
                      idx='amplitude')

# # Plot dipole locations of all dipoles with MRI slices
# for dip in dipoles:
#     plot_dipole_locations(dip, forward['mri_head_t'], 'sample',
#                           subjects_dir=subjects_dir, mode='orthoview',
#                           idx='amplitude')


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

# alpha parameter is between 0 and 100 (100 gives 0 active source)
alpha = 40.  # general regularization parameter
# l1_ratio parameter between 0 and 1 promotes temporal smoothness
# (0 means no temporal regularization)
l1_ratio = 0.03  # temporal regularization parameter

loose, depth = 0.2, 0.9  # loose orientation & depth weighting

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

# Compute TF-MxNE inverse solution with dipole output
dipoles, residual = tf_mixed_norm(
    evoked, forward, cov, alpha=alpha, l1_ratio=l1_ratio, loose=loose,
    depth=depth, maxit=200, tol=1e-6, weights=stc_dspm, weights_min=8.,
    debias=True, wsize=16, tstep=4, window=0.05, return_as_dipoles=True,
    return_residual=True)

# Crop to remove edges
for dip in dipoles:
    dip.crop(tmin=-0.05, tmax=0.3)
evoked.crop(tmin=-0.05, tmax=0.3)
residual.crop(tmin=-0.05, tmax=0.3)


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

plot_sparse_source_estimates(forward['src'], stc, bgcolor=(1, 1, 1),
                             opacity=0.1, fig_name="TF-MxNE (cond %s)"
                             % condition, modes=['sphere'], scale_factors=[1.])

time_label = 'TF-MxNE time=%0.2f ms'
clim = dict(kind='value', lims=[10e-9, 15e-9, 20e-9])
brain = stc.plot('sample', 'inflated', 'rh', views='medial',
                 clim=clim, time_label=time_label, smoothing_steps=5,
                 subjects_dir=subjects_dir, initial_time=150, time_unit='ms')
brain.add_label("V1", color="yellow", scalar_thresh=.5, borders=True)
brain.add_label("V2", color="red", scalar_thresh=.5, borders=True)


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

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

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

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

print(__doc__)


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

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


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

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

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

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


I am working on the file "0.20/_downloads/2e7ef25ccf0fd2af7902f12debe11fc1/plot_stats_cluster_1samp_test_time_frequency.ipynb".
The first task is:
Non-parametric 1 sample cluster statistic on single trial power
This script shows how to estimate significant clusters
in time-frequency power estimates. It uses a non-parametric
statistical procedure based on permutations and cluster
level statistics.
The procedure consists of:

extracting epochs
compute single trial power estimates
baseline line correct the power estimates (power ratios)
compute stats to see if ratio deviates from 1.
Can you write Python code for it?

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

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.time_frequency import tfr_morlet
from mne.stats import permutation_cluster_1samp_test
from mne.datasets import sample

print(__doc__)


I am working on the file "0.20/_downloads/2e7ef25ccf0fd2af7902f12debe11fc1/plot_stats_cluster_1samp_test_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'
tmin, tmax, event_id = -0.3, 0.6, 1

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

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

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

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

# Take only one channel
ch_name = 'MEG 1332'
epochs.pick_channels([ch_name])

evoked = epochs.average()

# Factor to down-sample the temporal dimension of the TFR computed by
# tfr_morlet. Decimation occurs after frequency decomposition and can
# be used to reduce memory usage (and possibly computational time of downstream
# operations such as nonparametric statistics) if you don't need high
# spectrotemporal resolution.
decim = 5
freqs = np.arange(8, 40, 2)  # define frequencies of interest
sfreq = raw.info['sfreq']  # sampling in Hz
tfr_epochs = tfr_morlet(epochs, freqs, n_cycles=4., decim=decim,
                        average=False, return_itc=False, n_jobs=1)

# Baseline power
tfr_epochs.apply_baseline(mode='logratio', baseline=(-.100, 0))

# Crop in time to keep only what is between 0 and 400 ms
evoked.crop(0., 0.4)
tfr_epochs.crop(0., 0.4)

epochs_power = tfr_epochs.data[:, 0, :, :]  # take the 1 channel