I am working on the file "0.23/_downloads/fb92190904499e5a95e92ab70177abf7/60_make_fixed_length_epochs.ipynb".
The first task is:
If desired, separate correlation matrices for each epoch can be obtained.
For envelope correlations, this is done by passing combine=None to the
envelope correlations function.
Can you write Python code for it?

corr_matrix = mne.connectivity.envelope_correlation(alpha_data, combine=None)


I am working on the file "0.23/_downloads/fb92190904499e5a95e92ab70177abf7/60_make_fixed_length_epochs.ipynb".
The first task is:
Now we can plot correlation matrices. We'll compare the first and last
30-second epochs of the recording:
Can you write Python code for it?

first_30 = corr_matrix[0]
last_30 = corr_matrix[-1]
corr_matrices = [first_30, last_30]
color_lims = np.percentile(np.array(corr_matrices), [5, 95])
titles = ['First 30 Seconds', 'Last 30 Seconds']

fig, axes = plt.subplots(nrows=1, ncols=2)
fig.suptitle('Correlation Matrices from First 30 Seconds and Last 30 Seconds')
for ci, corr_matrix in enumerate(corr_matrices):
    ax = axes[ci]
    mpbl = ax.imshow(corr_matrix, clim=color_lims)
    ax.set_xlabel(titles[ci])
fig.subplots_adjust(right=0.8)
cax = fig.add_axes([0.85, 0.2, 0.025, 0.6])
cbar = fig.colorbar(ax.images[0], cax=cax)
cbar.set_label('Correlation Coefficient')


I am working on the file "0.23/_downloads/fb92190904499e5a95e92ab70177abf7/60_make_fixed_length_epochs.ipynb".
The first task is:
To create fixed length epochs, we simply call the function and provide it
with the appropriate parameters indicating the desired duration of epochs in
seconds, whether or not to preload data, whether or not to reject epochs that
overlap with raw data segments annotated as bad, whether or not to include
projectors, and finally whether or not to be verbose. Here, we choose a long
epoch duration (30 seconds). To conserve memory, we set preload to
False.
Can you write Python code for it?

epochs = mne.make_fixed_length_epochs(raw, duration=30, preload=False)


I am working on the file "0.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_auditory.ipynb".
The first task is:
Deviant condition.
Can you write Python code for it?

stc_deviant = mne.minimum_norm.apply_inverse(evoked_dev, inv, lambda2, 'dSPM')
brain = stc_deviant.plot(subjects_dir=subjects_dir, subject=subject,
                         surface='inflated', time_viewer=False, hemi='lh',
                         initial_time=0.1, time_unit='s')
del stc_deviant, brain


I am working on the file "0.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_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.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_auditory.ipynb".
The first task is:
Epoching and averaging.
First some parameters are defined and events extracted from the stimulus
channel (UPPT001). The rejection thresholds are defined as peak-to-peak
values and are in T / m for gradiometers, T for magnetometers and
V for EOG and EEG channels.
Can you write Python code for it?

tmin, tmax = -0.1, 0.5
event_id = dict(standard=1, deviant=2)
reject = dict(mag=4e-12, eog=250e-6)
# find events
events = mne.find_events(raw, stim_channel='UPPT001')


I am working on the file "0.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_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.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_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.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_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.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_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 into memory.
Can you write Python code for it?

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


I am working on the file "0.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_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.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_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.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_auditory.ipynb".
The first task is:
The data array consists of 274 MEG axial gradiometers, 26 MEG reference
sensors and 2 EEG electrodes (Cz and Pz). In addition:

1 stim channel for marking presentation times for the stimuli
1 audio channel for the sent signal
1 response channel for recording the button presses
1 ECG bipolar
2 EOG bipolar (vertical and horizontal)
12 head tracking channels
20 unused channels

The head tracking channels and the unused channels are marked as misc
channels. Here we define the EOG and ECG channels.
Can you write Python code for it?

raw.set_channel_types({'HEOG': 'eog', 'VEOG': 'eog', 'ECG': 'ecg'})
if not use_precomputed:
    # Leave out the two EEG channels for easier computation of forward.
    raw.pick(['meg', 'stim', 'misc', 'eog', 'ecg']).load_data()


I am working on the file "0.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_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.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_auditory.ipynb".
The first task is:
The sources are computed using dSPM method and plotted on an inflated brain
surface. For interactive controls over the image, use keyword
time_viewer=True.
Standard condition.
Can you write Python code for it?

stc_standard = mne.minimum_norm.apply_inverse(evoked_std, inv, lambda2, 'dSPM')
brain = stc_standard.plot(subjects_dir=subjects_dir, subject=subject,
                          surface='inflated', time_viewer=False, hemi='lh',
                          initial_time=0.1, time_unit='s')
del stc_standard, brain


I am working on the file "0.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_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 use_precomputed 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.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_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.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_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.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_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.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_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.23/_downloads/fcc5782db3e2930fc79f31bc745495ed/60_ctf_bst_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.24/_downloads/00ac060e49528fd74fda09b97366af98/3d_to_2d.ipynb".
The first task is:
How to convert 3D electrode positions to a 2D image.
Sometimes we want to convert a 3D representation of electrodes into a 2D
image. For example, if we are using electrocorticography it is common to
create scatterplots on top of a brain, with each point representing an
electrode.
In this example, we'll show two ways of doing this in MNE-Python. First,
if we have the 3D locations of each electrode then we can use Mayavi to
take a snapshot of a view of the brain. If we do not have these 3D locations,
and only have a 2D image of the electrodes on the brain, we can use the
:class:mne.viz.ClickableImage class to choose our own electrode positions
on the image.
Can you write Python code for it?

# Authors: Christopher Holdgraf <choldgraf@berkeley.edu>
#          Alex Rockhill        <aprockhill@mailbox.org>
#
# License: BSD-3-Clause

from mne.io.fiff.raw import read_raw_fif
import numpy as np
from matplotlib import pyplot as plt
from os import path as op

import mne
from mne.viz import ClickableImage  # noqa: F401
from mne.viz import (plot_alignment, snapshot_brain_montage, set_3d_view)

misc_path = mne.datasets.misc.data_path()
ecog_data_fname = op.join(misc_path, 'ecog', 'sample_ecog_ieeg.fif')
subjects_dir = op.join(misc_path, 'ecog')

# We've already clicked and exported
layout_path = op.join(op.dirname(mne.__file__), 'data', 'image')
layout_name = 'custom_layout.lout'


I am working on the file "0.24/_downloads/00e78bba5d10188fcf003ef05e32a6f7/decoding_time_generalization_conditions.ipynb".
The first task is:
Decoding sensor space data with generalization across time and conditions
This example runs the analysis described in :footcite:KingDehaene2014. It
illustrates how one can
fit a linear classifier to identify a discriminatory topography at a given time
instant and subsequently assess whether this linear model can accurately
predict all of the time samples of a second set of conditions.
Can you write Python code for it?

# Authors: Jean-Remi King <jeanremi.king@gmail.com>
#          Alexandre Gramfort <alexandre.gramfort@inria.fr>
#          Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD-3-Clause

import matplotlib.pyplot as plt

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

import mne
from mne.datasets import sample
from mne.decoding import GeneralizingEstimator

print(__doc__)

# Preprocess data
data_path = sample.data_path()
# Load and filter data, set up epochs
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
events_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
raw = mne.io.read_raw_fif(raw_fname, preload=True)
picks = mne.pick_types(raw.info, meg=True, exclude='bads')  # Pick MEG channels
raw.filter(1., 30., fir_design='firwin')  # Band pass filtering signals
events = mne.read_events(events_fname)
event_id = {'Auditory/Left': 1, 'Auditory/Right': 2,
            'Visual/Left': 3, 'Visual/Right': 4}
tmin = -0.050
tmax = 0.400
# decimate to make the example faster to run, but then use verbose='error' in
# the Epochs constructor to suppress warning about decimation causing aliasing
decim = 2
epochs = mne.Epochs(raw, events, event_id=event_id, tmin=tmin, tmax=tmax,
                    proj=True, picks=picks, baseline=None, preload=True,
                    reject=dict(mag=5e-12), decim=decim, verbose='error')


I am working on the file "0.24/_downloads/00e78bba5d10188fcf003ef05e32a6f7/decoding_time_generalization_conditions.ipynb".
The first task is:
Score on the epochs where the stimulus was presented to the right.
Can you write Python code for it?

scores = time_gen.score(X=epochs['Right'].get_data(),
                        y=epochs['Right'].events[:, 2] > 2)


I am working on the file "0.24/_downloads/00e78bba5d10188fcf003ef05e32a6f7/decoding_time_generalization_conditions.ipynb".
The first task is:
We will train the classifier on all left visual vs auditory trials
and test on all right visual vs auditory trials.
Can you write Python code for it?

clf = make_pipeline(StandardScaler(), LogisticRegression(solver='lbfgs'))
time_gen = GeneralizingEstimator(clf, scoring='roc_auc', n_jobs=1,
                                 verbose=True)

# Fit classifiers on the epochs where the stimulus was presented to the left.
# Note that the experimental condition y indicates auditory or visual
time_gen.fit(X=epochs['Left'].get_data(),
             y=epochs['Left'].events[:, 2] > 2)


I am working on the file "0.24/_downloads/029173f022506572bcefa009b440732f/evoked_arrowmap.ipynb".
The first task is:
Plot gradiometer data as an arrowmap along with the topoplot at the time
of the maximum sensor space activity:
Can you write Python code for it?

plot_arrowmap(evoked_grad.data[:, max_time_idx], info_from=evoked_grad.info,
              info_to=evoked_mag.info)


I am working on the file "0.24/_downloads/029173f022506572bcefa009b440732f/evoked_arrowmap.ipynb".
The first task is:
Plot magnetometer data as an arrowmap along with the topoplot at the time
of the maximum sensor space activity:
Can you write Python code for it?

max_time_idx = np.abs(evoked_mag.data).mean(axis=0).argmax()
plot_arrowmap(evoked_mag.data[:, max_time_idx], evoked_mag.info)

# Since planar gradiometers takes gradients along latitude and longitude,
# they need to be projected to the flatten manifold span by magnetometer
# or radial gradiometers before taking the gradients in the 2D Cartesian
# coordinate system for visualization on the 2D topoplot. You can use the
# ``info_from`` and ``info_to`` parameters to interpolate from
# gradiometer data to magnetometer data.


I am working on the file "0.24/_downloads/029173f022506572bcefa009b440732f/evoked_arrowmap.ipynb".
The first task is:
Plotting topographic arrowmaps of evoked data
Load evoked data and plot arrowmaps along with the topomap for selected time
points. An arrowmap is based upon the Hosaka-Cohen transformation and
represents an estimation of the current flow underneath the MEG sensors.
They are a poor man's MNE.
See :footcite:CohenHosaka1976 for details.
References
.. footbibliography::
Can you write Python code for it?

# Authors: Sheraz Khan <sheraz@khansheraz.com>
#
# License: BSD-3-Clause

import numpy as np
import mne
from mne.datasets import sample
from mne.datasets.brainstorm import bst_raw
from mne import read_evokeds
from mne.viz import plot_arrowmap

print(__doc__)

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

# load evoked data
condition = 'Left Auditory'
evoked = read_evokeds(fname, condition=condition, baseline=(None, 0))
evoked_mag = evoked.copy().pick_types(meg='mag')
evoked_grad = evoked.copy().pick_types(meg='grad')


I am working on the file "0.24/_downloads/029173f022506572bcefa009b440732f/evoked_arrowmap.ipynb".
The first task is:
Since Vectorview 102 system perform sparse spatial sampling of the magnetic
field, data from the Vectorview (info_from) can be projected to the high
density CTF 272 system (info_to) for visualization
Plot gradiometer data as an arrowmap along with the topoplot at the time
of the maximum sensor space activity:
Can you write Python code for it?

path = bst_raw.data_path()
raw_fname = path + ('/MEG/bst_raw/'
                    'subj001_somatosensory_20111109_01_AUX-f.ds')
raw_ctf = mne.io.read_raw_ctf(raw_fname)
raw_ctf_info = mne.pick_info(
    raw_ctf.info, mne.pick_types(raw_ctf.info, meg=True, ref_meg=False))
plot_arrowmap(evoked_grad.data[:, max_time_idx], info_from=evoked_grad.info,
              info_to=raw_ctf_info, scale=6e-10)


I am working on the file "0.24/_downloads/06371e7a69d2c0314dea0a4363315ef2/css.ipynb".
The first task is:
Load sample subject data
Can you write Python code for it?

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-cov.fif'
trans_fname = data_path + '/MEG/sample/sample_audvis_raw-trans.fif'
bem_fname = subjects_dir + '/sample' + '/bem' + '/sample-5120-bem-sol.fif'

raw = mne.io.read_raw_fif(data_path + '/MEG/sample/sample_audvis_raw.fif')
fwd = mne.read_forward_solution(fwd_fname)
fwd = mne.convert_forward_solution(fwd, force_fixed=True, surf_ori=True)
fwd = mne.pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads'])
cov = mne.read_cov(cov_fname)


I am working on the file "0.24/_downloads/06371e7a69d2c0314dea0a4363315ef2/css.ipynb".
The first task is:
Process with CSS and plot PSD of EEG data before and after processing
Can you write Python code for it?

evoked_subcortical = mne.preprocessing.cortical_signal_suppression(evoked,
                                                                   n_proj=6)
chs = mne.pick_types(evoked.info, meg=False, eeg=True)

psd = np.mean(np.abs(np.fft.rfft(evoked.data))**2, axis=0)
psd_proc = np.mean(np.abs(np.fft.rfft(evoked_subcortical.data))**2, axis=0)
freq = np.arange(0, stop=int(evoked.info['sfreq'] / 2),
                 step=evoked.info['sfreq'] / (2 * len(psd)))

fig, ax = plt.subplots()
ax.plot(freq, psd, label='raw')
ax.plot(freq, psd_proc, label='processed')
ax.text(.2, .7, 'cortical', transform=ax.transAxes)
ax.text(.8, .25, 'subcortical', transform=ax.transAxes)
ax.set(ylabel='EEG Power spectral density', xlabel='Frequency (Hz)')
ax.legend()

# References
# ^^^^^^^^^^
#
# .. footbibliography::


I am working on the file "0.24/_downloads/06371e7a69d2c0314dea0a4363315ef2/css.ipynb".
The first task is:
Simulate one cortical dipole (40 Hz) and one subcortical (239 Hz)
Can you write Python code for it?

def cortical_waveform(times):
    """Create a cortical waveform."""
    return 10e-9 * np.cos(times * 2 * np.pi * 40)

def subcortical_waveform(times):
    """Create a subcortical waveform."""
    return 10e-9 * np.cos(times * 2 * np.pi * 239)

times = np.linspace(0, 0.5, int(0.5 * raw.info['sfreq']))
stc = simulate_sparse_stc(fwd['src'], n_dipoles=2, times=times,
                          location='center', subjects_dir=subjects_dir,
                          labels=[postcenlab, hiplab],
                          data_fun=cortical_waveform)
stc.data[np.where(np.isin(stc.vertices[0], hiplab.vertices))[0], :] = \
    subcortical_waveform(times)
evoked = simulate_evoked(fwd, stc, raw.info, cov, nave=15)


I am working on the file "0.24/_downloads/066ec12646ce0d0818ad9b78bc602218/fdr_stats_evoked.ipynb".
The first task is:
FDR correction on T-test on sensor data
One tests if the evoked response significantly deviates from 0.
Multiple comparison problem is addressed with
False Discovery Rate (FDR) correction.
Can you write Python code for it?

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

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

import mne
from mne import io
from mne.datasets import sample
from mne.stats import bonferroni_correction, fdr_correction

print(__doc__)


I am working on the file "0.24/_downloads/08101c5685595d96337d701dc0603996/40_mne_fixed_free.ipynb".
The first task is:
And finally eLORETA:
Can you write Python code for it?

stc = apply_inverse(evoked, inv, lambda2, 'eLORETA', verbose=True,
                    method_params=dict(eps=1e-4))  # larger eps just for speed
brain = stc.plot(figure=8, **kwargs)
brain.add_text(0.1, 0.9, 'eLORETA', 'title', font_size=14)


stc = abs(apply_inverse(evoked, inv, lambda2, 'eLORETA', verbose=True))
brain = stc.plot(figure=4, **kwargs)
brain.add_text(0.1, 0.9, 'eLORETA', 'title', font_size=14)
del inv


I am working on the file "0.24/_downloads/08101c5685595d96337d701dc0603996/40_mne_fixed_free.ipynb".
The first task is:
And sLORETA:
Can you write Python code for it?

stc = abs(apply_inverse(evoked, inv, lambda2, 'sLORETA', verbose=True))
brain = stc.plot(figure=3, **kwargs)
brain.add_text(0.1, 0.9, 'sLORETA', 'title', font_size=14)


I am working on the file "0.24/_downloads/08101c5685595d96337d701dc0603996/40_mne_fixed_free.ipynb".
The first task is:
Fixed orientation
First let's create a fixed-orientation inverse, with the default weighting.
Can you write Python code for it?

inv = make_inverse_operator(evoked.info, fwd, cov, loose=0., depth=0.8,
                            verbose=True)


I am working on the file "0.24/_downloads/08101c5685595d96337d701dc0603996/40_mne_fixed_free.ipynb".
The first task is:
Let's look at the current estimates using MNE. We'll take the absolute
value of the source estimates to simplify the visualization.
Can you write Python code for it?

snr = 3.0
lambda2 = 1.0 / snr ** 2
kwargs = dict(initial_time=0.08, hemi='lh', subjects_dir=subjects_dir,
              size=(600, 600), clim=dict(kind='percent', lims=[90, 95, 99]),
              smoothing_steps=7)

stc = abs(apply_inverse(evoked, inv, lambda2, 'MNE', verbose=True))
brain = stc.plot(figure=1, **kwargs)
brain.add_text(0.1, 0.9, 'MNE', 'title', font_size=14)


I am working on the file "0.24/_downloads/08101c5685595d96337d701dc0603996/40_mne_fixed_free.ipynb".
The first task is:
sLORETA:
Can you write Python code for it?

stc = apply_inverse(evoked, inv, lambda2, 'sLORETA', verbose=True)
brain = stc.plot(figure=7, **kwargs)
brain.add_text(0.1, 0.9, 'sLORETA', 'title', font_size=14)


I am working on the file "0.24/_downloads/09a8b0bb7a57481cdd1f7832f0291ee6/brain.ipynb".
The first task is:
Add source information
Plot source information.
Can you write Python code for it?

brain_kwargs = dict(alpha=0.1, background='white', cortex='low_contrast')
brain = mne.viz.Brain('sample', subjects_dir=subjects_dir, **brain_kwargs)

stc = mne.read_source_estimate(op.join(sample_dir, 'sample_audvis-meg'))
stc.crop(0.09, 0.1)

kwargs = dict(fmin=stc.data.min(), fmax=stc.data.max(), alpha=0.25,
              smoothing_steps='nearest', time=stc.times)
brain.add_data(stc.lh_data, hemi='lh', vertices=stc.lh_vertno, **kwargs)
brain.add_data(stc.rh_data, hemi='rh', vertices=stc.rh_vertno, **kwargs)


I am working on the file "0.24/_downloads/09a8b0bb7a57481cdd1f7832f0291ee6/brain.ipynb".
The first task is:
Highlight a region on the brain
It can be useful to highlight a region of the brain for analyses.
To highlight a region on the brain you can use the add_label method.
Labels are stored in the Freesurfer label directory from the recon-all
for that subject. Labels can also be made following the
Freesurfer instructions
<https://surfer.nmr.mgh.harvard.edu/fswiki/mri_vol2label>_
Here we will show Brodmann Area 44.

Note

The MNE sample dataset contains only a subselection of the
          Freesurfer labels created during the ``recon-all``.

Can you write Python code for it?

brain = mne.viz.Brain('sample', subjects_dir=subjects_dir, **brain_kwargs)
brain.add_label('BA44', hemi='lh', color='green', borders=True)
brain.show_view(azimuth=190, elevation=70, distance=350, focalpoint=(0, 0, 20))


I am working on the file "0.24/_downloads/09a8b0bb7a57481cdd1f7832f0291ee6/brain.ipynb".
The first task is:
Modify the view of the brain
You can adjust the view of the brain using show_view method.
Can you write Python code for it?

brain = mne.viz.Brain('sample', subjects_dir=subjects_dir, **brain_kwargs)
brain.show_view(azimuth=190, elevation=70, distance=350, focalpoint=(0, 0, 20))


I am working on the file "0.24/_downloads/09a8b0bb7a57481cdd1f7832f0291ee6/brain.ipynb".
The first task is:
Plot a brain
In this example we use the sample data which is data from a subject
being presented auditory and visual stimuli to display the functionality
of :class:mne.viz.Brain for plotting data on a brain.
Can you write Python code for it?

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

import mne
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
sample_dir = op.join(data_path, 'MEG', 'sample')


I am working on the file "0.24/_downloads/09a8b0bb7a57481cdd1f7832f0291ee6/brain.ipynb".
The first task is:
Plotting with mne.viz.Brain
In this example, we'll show how to use :class:mne.viz.Brain.
Can you write Python code for it?

# Author: Alex Rockhill <aprockhill@mailbox.org>
#
# License: BSD-3-Clause


I am working on the file "0.24/_downloads/0a1bad60270bfbdeeea274fcca0015d2/multidict_reweighted_tfmxne.ipynb".
The first task is:
Compute iterative reweighted TF-MxNE with multiscale time-frequency dictionary
The iterative reweighted TF-MxNE solver is a distributed inverse method
based on the TF-MxNE solver, which promotes focal (sparse) sources
:footcite:StrohmeierEtAl2015. The benefits of this approach are that:

it is spatio-temporal without assuming stationarity (source properties
  can vary over time),
activations are localized in space, time, and frequency in one step,
the solver uses non-convex penalties in the TF domain, which results in a
  solution less biased towards zero than when simple TF-MxNE is used,
using a multiscale dictionary allows to capture short transient
  activations along with slower brain waves :footcite:BekhtiEtAl2016.
Can you write Python code for it?

# Author: Mathurin Massias <mathurin.massias@gmail.com>
#         Yousra Bekhti <yousra.bekhti@gmail.com>
#         Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#         Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD-3-Clause

import os.path as op

import mne
from mne.datasets import somato
from mne.inverse_sparse import tf_mixed_norm, make_stc_from_dipoles
from mne.viz import plot_sparse_source_estimates

print(__doc__)


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

stc = make_stc_from_dipoles(dipoles, forward['src'])
plot_sparse_source_estimates(
    forward['src'], stc, bgcolor=(1, 1, 1), opacity=0.1,
    fig_name=f"irTF-MxNE (cond {evoked.comment})")


I am working on the file "0.24/_downloads/0a1bad60270bfbdeeea274fcca0015d2/multidict_reweighted_tfmxne.ipynb".
The first task is:
Load somatosensory MEG data
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))
fwd_fname = op.join(data_path, 'derivatives', 'sub-{}'.format(subject),
                    'sub-{}_task-{}-fwd.fif'.format(subject, task))

# Read evoked
raw = mne.io.read_raw_fif(raw_fname)
raw.pick_types(meg=True, eog=True, stim=True)
events = mne.find_events(raw, stim_channel='STI 014')

reject = dict(grad=4000e-13, eog=350e-6)
event_id, tmin, tmax = dict(unknown=1), -0.5, 0.5
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, reject=reject,
                    baseline=(None, 0))
evoked = epochs.average()

evoked.crop(tmin=0.0, tmax=0.2)

# Compute noise covariance matrix
cov = mne.compute_covariance(epochs, rank='info', tmax=0.)
del epochs, raw

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


I am working on the file "0.24/_downloads/0ae9af7fe8e152942071a6b23acc0958/40_sensor_locations.ipynb".
The first task is:
.. sidebar:: Computing sensor locations
If you are interested in how standard (idealized) EEG sensor positions
are computed on a spherical head model, make sure to check out the
`eeg_positions`_ repository.

These built-in EEG montages can be loaded with
mne.channels.make_standard_montage (note that you need to provide the
filename without its extension):
Can you write Python code for it?

ten_twenty_montage = mne.channels.make_standard_montage('standard_1020')
print(ten_twenty_montage)


I am working on the file "0.24/_downloads/0ae9af7fe8e152942071a6b23acc0958/40_sensor_locations.ipynb".
The first task is:
Alternatively, you can calculate the sphere origin from Oz, Fpz, T3/T7 or
T4/T8 channels. This is easier once the montage has been applied to the data
and channel positions are in the head space (see
this example <ex-topomap-eeglab-style>).
Reading sensor digitization files
In the sample data, the sensor positions are already available in the
info attribute of the ~mne.io.Raw object (see the documentation of the
reading functions and ~mne.io.Raw.set_montage for details on how that
works). Therefore, we can plot sensor locations directly from the
~mne.io.Raw object using ~mne.io.Raw.plot_sensors, which provides similar
functionality to montage.plot() <mne.channels.DigMontage.plot>. In
addition, ~mne.io.Raw.plot_sensors supports channel selection by type,
color-coding channels in various ways (by default, channels listed in
raw.info['bads'] will be plotted in red), and drawing in an existing
Matplotlib Axes object (so the channel positions can easily be added as a
subplot in a multi-panel figure):
Can you write Python code for it?

fig = plt.figure()
ax2d = fig.add_subplot(121)
ax3d = fig.add_subplot(122, projection='3d')
raw.plot_sensors(ch_type='eeg', axes=ax2d)
raw.plot_sensors(ch_type='eeg', axes=ax3d, kind='3d')
ax3d.view_init(azim=70, elev=15)


I am working on the file "0.24/_downloads/0ae9af7fe8e152942071a6b23acc0958/40_sensor_locations.ipynb".
The first task is:
By default, a sphere with origin at (0, 0, 0) (x, y, z coordinates) and
radius of 0.095 meters (9.5 cm) is used. You can use a different sphere
radius by passing a single value as the  sphere argument in any function
that plots channels in 2D (like ~mne.channels.DigMontage.plot that we use
here, but also for example mne.viz.plot_topomap):
Can you write Python code for it?


I am working on the file "0.24/_downloads/0ae9af7fe8e152942071a6b23acc0958/40_sensor_locations.ipynb".
The first task is:
Controlling channel projection (MNE vs EEGLAB)
Channel positions in 2D space are obtained by projecting their actual 3D
positions onto a sphere, then projecting the sphere onto a plane. Because the
'standard_1020' montage contains realistic (as opposed to idealized
spherical) channel positions, we will use a different montage to demonstrate
how channels are projected to 2D:
Can you write Python code for it?

biosemi_montage = mne.channels.make_standard_montage('biosemi64')
biosemi_montage.plot(show_names=False)


I am working on the file "0.24/_downloads/0ae9af7fe8e152942071a6b23acc0958/40_sensor_locations.ipynb".
The first task is:
If you have a ~mne.io.Raw object that contains sensor positions, you can
create a ~mne.channels.Layout object with either
mne.channels.make_eeg_layout or mne.channels.find_layout.
Can you write Python code for it?

layout_from_raw = mne.channels.make_eeg_layout(raw.info)
# same result as mne.channels.find_layout(raw.info, ch_type='eeg')
layout_from_raw.plot()


I am working on the file "0.24/_downloads/0ae9af7fe8e152942071a6b23acc0958/40_sensor_locations.ipynb".
The first task is:
Montage <mne.channels.DigMontage> objects have a
~mne.channels.DigMontage.plot method for visualizing the sensor locations
in 2D or 3D:
Can you write Python code for it?

fig = ten_twenty_montage.plot(kind='3d')
fig.gca().view_init(azim=70, elev=15)  # set view angle
ten_twenty_montage.plot(kind='topomap', show_names=False)


I am working on the file "0.24/_downloads/0ae9af7fe8e152942071a6b23acc0958/40_sensor_locations.ipynb".
The first task is:
Once loaded, a montage can be applied to data with the
~mne.io.Raw.set_montage method, for example
raw.set_montage <mne.io.Raw.set_montage>. It is also possible to skip the
loading step by passing the filename string directly to the
~mne.io.Raw.set_montage method. This will not work with our sample
data, because its channel names do not match the channel names in the
standard 10–20 montage. Therefore, we do not run the following commands here:
Can you write Python code for it?

# these will be equivalent:
# raw_1020 = raw.copy().set_montage(ten_twenty_montage)
# raw_1020 = raw.copy().set_montage('standard_1020')


I am working on the file "0.24/_downloads/0ae9af7fe8e152942071a6b23acc0958/40_sensor_locations.ipynb".
The first task is:
The file formats (and therefore file extensions) of the built-in layout and
montage files vary considerably (because manufacturers like to use different
conventions). However, the montage and layout loading functions in MNE-Python
take the filename without its extension so you do not have to keep track of
which file format is used by which manufacturer.
To load a layout file, use the mne.channels.read_layout function and
provide the filename without its file extension. You can then visualize the
layout using its ~mne.channels.Layout.plot method or equivalently passing
the layout to mne.viz.plot_layout:
Can you write Python code for it?

biosemi_layout = mne.channels.read_layout('biosemi')
biosemi_layout.plot()  # same result as mne.viz.plot_layout(biosemi_layout)


I am working on the file "0.24/_downloads/0ae9af7fe8e152942071a6b23acc0958/40_sensor_locations.ipynb".
The first task is:
To change not only the radius, but also the sphere origin, pass a
(x, y, z, radius) tuple as the sphere argument:
Can you write Python code for it?

biosemi_montage.plot(show_names=False, sphere=(0.03, 0.02, 0.01, 0.075))


I am working on the file "0.24/_downloads/0ae9af7fe8e152942071a6b23acc0958/40_sensor_locations.ipynb".
The first task is:
Working with sensor locations
This tutorial describes how to read and plot sensor locations, and how
MNE-Python handles physical locations of sensors.
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?

import os
import numpy as np
import matplotlib.pyplot as plt
# the following import is required for matplotlib < 3.2:
from mpl_toolkits.mplot3d import Axes3D  # noqa
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, preload=True, verbose=False)


I am working on the file "0.24/_downloads/0bf55d4c93021947144bdb72823131e5/read_neo_format.ipynb".
The first task is:
How to use data in neural ensemble (NEO) format
This example shows how to create an MNE-Python ~mne.io.Raw object from data
in the neural ensemble <http://neuralensemble.org/neo/>__ format. For general
information on creating MNE-Python's data objects from NumPy arrays, see
tut-creating-data-structures.
Can you write Python code for it?


I am working on the file "0.24/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb".
The first task is:
From here on, standard inverse imaging methods can be used!
Infant MRI surrogates
We don't have a sample infant dataset for MNE, so let's fake a 10-20 one:
Can you write Python code for it?

ch_names = \
    'Fz Cz Pz Oz Fp1 Fp2 F3 F4 F7 F8 C3 C4 T7 T8 P3 P4 P7 P8 O1 O2'.split()
data = np.random.RandomState(0).randn(len(ch_names), 1000)
info = mne.create_info(ch_names, 1000., 'eeg')
raw = mne.io.RawArray(data, info)


I am working on the file "0.24/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb".
The first task is:
Get an infant MRI template
To use an infant head model for M/EEG data, you can use
:func:mne.datasets.fetch_infant_template to download an infant template:
Can you write Python code for it?

subject = mne.datasets.fetch_infant_template('6mo', subjects_dir, verbose=True)


I am working on the file "0.24/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb".
The first task is:
It comes with several helpful built-in files, including a 10-20 montage
in the MRI coordinate frame, which can be used to compute the
MRI<->head transform trans:
Can you write Python code for it?

fname_1020 = op.join(subjects_dir, subject, 'montages', '10-20-montage.fif')
mon = mne.channels.read_dig_fif(fname_1020)
mon.rename_channels(
    {f'EEG{ii:03d}': ch_name for ii, ch_name in enumerate(ch_names, 1)})
trans = mne.channels.compute_native_head_t(mon)
raw.set_montage(mon)
print(trans)


I am working on the file "0.24/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb".
The first task is:
Setup source space and compute forward
Can you write Python code for it?

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


I am working on the file "0.24/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb".
The first task is:
There are also BEM and source spaces:
Can you write Python code for it?

bem_dir = op.join(subjects_dir, subject, 'bem')
fname_src = op.join(bem_dir, f'{subject}-oct-6-src.fif')
src = mne.read_source_spaces(fname_src)
print(src)
fname_bem = op.join(bem_dir, f'{subject}-5120-5120-5120-bem-sol.fif')
bem = mne.read_bem_solution(fname_bem)


I am working on the file "0.24/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb".
The first task is:
You can ensure everything is as expected by plotting the result:
Can you write Python code for it?

fig = mne.viz.plot_alignment(
    raw.info, subject=subject, subjects_dir=subjects_dir, trans=trans,
    src=src, bem=bem, coord_frame='mri', mri_fiducials=True, show_axes=True,
    surfaces=('white', 'outer_skin', 'inner_skull', 'outer_skull'))
mne.viz.set_3d_view(fig, 25, 70, focalpoint=[0, -0.005, 0.01])


I am working on the file "0.24/_downloads/13f9133d0e7c13dded3c5dd2cf828dd3/gamma_map_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.24/_downloads/13f9133d0e7c13dded3c5dd2cf828dd3/gamma_map_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.24/_downloads/13f9133d0e7c13dded3c5dd2cf828dd3/gamma_map_inverse.ipynb".
The first task is:
View in 2D and 3D ("glass" brain like 3D plot)
Show the sources as spheres scaled by their strength
Can you write Python code for it?

scale_factors = np.max(np.abs(stc.data), axis=1)
scale_factors = 0.5 * (1 + scale_factors / np.max(scale_factors))

plot_sparse_source_estimates(
    forward['src'], stc, bgcolor=(1, 1, 1),
    modes=['sphere'], opacity=0.1, scale_factors=(scale_factors, None),
    fig_name="Gamma-MAP")


I am working on the file "0.24/_downloads/141ddce18e923e8220337b357ba3dc45/ssd_spatial_filters.ipynb".
The first task is:
Compute Spectro-Spatial Decomposition (SSD) spatial filters
In this example, we will compute spatial filters for retaining
oscillatory brain activity and down-weighting 1/f background signals
as proposed by :footcite:NikulinEtAl2011.
The idea is to learn spatial filters that separate oscillatory dynamics
from surrounding non-oscillatory noise based on the covariance in the
frequency band of interest and the noise covariance based on surrounding
frequencies.
Can you write Python code for it?

# Author: Denis A. Engemann <denis.engemann@gmail.com>
#         Victoria Peterson <victoriapeterson09@gmail.com>
# License: BSD-3-Clause

import matplotlib.pyplot as plt
import mne
from mne import Epochs
from mne.datasets.fieldtrip_cmc import data_path
from mne.decoding import SSD


I am working on the file "0.24/_downloads/141ddce18e923e8220337b357ba3dc45/ssd_spatial_filters.ipynb".
The first task is:
Define parameters
Can you write Python code for it?

fname = data_path() + '/SubjectCMC.ds'

# Prepare data
raw = mne.io.read_raw_ctf(fname)
raw.crop(50., 110.).load_data()  # crop for memory purposes
raw.resample(sfreq=250)

raw.pick_types(meg=True, eeg=False, ref_meg=False)

freqs_sig = 9, 12
freqs_noise = 8, 13

ssd = SSD(info=raw.info,
          reg='oas',
          sort_by_spectral_ratio=False,  # False for purpose of example.
          filt_params_signal=dict(l_freq=freqs_sig[0], h_freq=freqs_sig[1],
                                  l_trans_bandwidth=1, h_trans_bandwidth=1),
          filt_params_noise=dict(l_freq=freqs_noise[0], h_freq=freqs_noise[1],
                                 l_trans_bandwidth=1, h_trans_bandwidth=1))
ssd.fit(X=raw.get_data())


I am working on the file "0.24/_downloads/141ddce18e923e8220337b357ba3dc45/ssd_spatial_filters.ipynb".
The first task is:
Epoched data
Although we suggest to use this method before epoching, there might be some
situations in which data can only be treated by chunks.
Can you write Python code for it?

# Build epochs as sliding windows over the continuous raw file.
events = mne.make_fixed_length_events(raw, id=1, duration=5.0, overlap=0.0)

# Epoch length is 5 seconds.
epochs = Epochs(raw, events, tmin=0., tmax=5,
                baseline=None, preload=True)

ssd_epochs = SSD(info=epochs.info,
                 reg='oas',
                 filt_params_signal=dict(l_freq=freqs_sig[0],
                                         h_freq=freqs_sig[1],
                                         l_trans_bandwidth=1,
                                         h_trans_bandwidth=1),
                 filt_params_noise=dict(l_freq=freqs_noise[0],
                                        h_freq=freqs_noise[1],
                                        l_trans_bandwidth=1,
                                        h_trans_bandwidth=1))
ssd_epochs.fit(X=epochs.get_data())

# Plot topographies.
pattern_epochs = mne.EvokedArray(data=ssd_epochs.patterns_[:4].T,
                                 info=ssd_epochs.info)
pattern_epochs.plot_topomap(units=dict(mag='A.U.'), time_format='')


I am working on the file "0.24/_downloads/141ddce18e923e8220337b357ba3dc45/ssd_spatial_filters.ipynb".
The first task is:
Let's investigate spatial filter with max power ratio.
We will first inspect the topographies.
According to Nikulin et al. 2011 this is done by either inverting the filters
(W^{-1}) or by multiplying the noise cov with the filters Eq. (22) (C_n W)^t.
We rely on the inversion approach here.
Can you write Python code for it?

pattern = mne.EvokedArray(data=ssd.patterns_[:4].T,
                          info=ssd.info)
pattern.plot_topomap(units=dict(mag='A.U.'), time_format='')

# The topographies suggest that we picked up a parietal alpha generator.

# Transform
ssd_sources = ssd.transform(X=raw.get_data())

# Get psd of SSD-filtered signals.
psd, freqs = mne.time_frequency.psd_array_welch(
    ssd_sources, sfreq=raw.info['sfreq'], n_fft=4096)

# Get spec_ratio information (already sorted).
# Note that this is not necessary if sort_by_spectral_ratio=True (default).
spec_ratio, sorter = ssd.get_spectral_ratio(ssd_sources)

# Plot spectral ratio (see Eq. 24 in Nikulin 2011).
fig, ax = plt.subplots(1)
ax.plot(spec_ratio, color='black')
ax.plot(spec_ratio[sorter], color='orange', label='sorted eigenvalues')
ax.set_xlabel("Eigenvalue Index")
ax.set_ylabel(r"Spectral Ratio $\frac{P_f}{P_{sf}}$")
ax.legend()
ax.axhline(1, linestyle='--')

# We can see that the initial sorting based on the eigenvalues
# was already quite good. However, when using few components only
# the sorting might make a difference.


I am working on the file "0.24/_downloads/1537c1215a3e40187a4513e0b5f1d03d/eeg_csd.ipynb".
The first task is:
Also look at the power spectral densities:
Can you write Python code for it?


I am working on the file "0.24/_downloads/1537c1215a3e40187a4513e0b5f1d03d/eeg_csd.ipynb".
The first task is:
CSD has parameters stiffness and lambda2 affecting smoothing and
spline flexibility, respectively. Let's see how they affect the solution:
Can you write Python code for it?

fig, ax = plt.subplots(4, 4)
fig.subplots_adjust(hspace=0.5)
fig.set_size_inches(10, 10)
for i, lambda2 in enumerate([0, 1e-7, 1e-5, 1e-3]):
    for j, m in enumerate([5, 4, 3, 2]):
        this_evoked_csd = mne.preprocessing.compute_current_source_density(
            evoked, stiffness=m, lambda2=lambda2)
        this_evoked_csd.plot_topomap(
            0.1, axes=ax[i, j], outlines='skirt', contours=4, time_unit='s',
            colorbar=False, show=False)
        ax[i, j].set_title('stiffness=%i\nλ²=%s' % (m, lambda2))


I am working on the file "0.24/_downloads/1537c1215a3e40187a4513e0b5f1d03d/eeg_csd.ipynb".
The first task is:
First let's look at how CSD affects scalp topography:
Can you write Python code for it?

times = np.array([-0.1, 0., 0.05, 0.1, 0.15])
evoked_csd = mne.preprocessing.compute_current_source_density(evoked)
evoked.plot_joint(title='Average Reference', show=False)
evoked_csd.plot_joint(title='Current Source Density')


I am working on the file "0.24/_downloads/1537c1215a3e40187a4513e0b5f1d03d/eeg_csd.ipynb".
The first task is:
Load sample subject data
Can you write Python code for it?

raw = mne.io.read_raw_fif(data_path + '/MEG/sample/sample_audvis_raw.fif')
raw = raw.pick_types(meg=False, eeg=True, eog=True, ecg=True, stim=True,
                     exclude=raw.info['bads']).load_data()
events = mne.find_events(raw)
raw.set_eeg_reference(projection=True).apply_proj()


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:

Note

Before applying ICA (or any artifact repair strategy), be sure to observe
    the artifacts in your data to make sure you choose the right repair tool.
    Sometimes the right tool is no tool at all — if the artifacts are small
    enough you may not even need to repair them to get good analysis results.
    See `tut-artifact-overview` for guidance on detecting and
    visualizing various types of artifact.

What is ICA?
Independent components analysis (ICA) is a technique for estimating
independent source signals from a set of recordings in which the source
signals were mixed together in unknown ratios. A common example of this is
the problem of blind source separation_: with 3 musical instruments playing
in the same room, and 3 microphones recording the performance (each picking
up all 3 instruments, but at varying levels), can you somehow "unmix" the
signals recorded by the 3 microphones so that you end up with a separate
"recording" isolating the sound of each instrument?
It is not hard to see how this analogy applies to EEG/MEG analysis: there are
many "microphones" (sensor channels) simultaneously recording many
"instruments" (blinks, heartbeats, activity in different areas of the brain,
muscular activity from jaw clenching or swallowing, etc). As long as these
various source signals are statistically independent_ and non-gaussian, it
is usually possible to separate the sources using ICA, and then re-construct
the sensor signals after excluding the sources that are unwanted.
ICA in MNE-Python
.. sidebar:: ICA and dimensionality reduction
If you want to perform ICA with *no* dimensionality reduction (other than
the number of Independent Components (ICs) given in ``n_components``, and
any subsequent exclusion of ICs you specify in ``ICA.exclude``), simply
pass ``n_components``.

However, if you *do* want to reduce dimensionality, consider this
example: if you have 300 sensor channels and you set ``n_components=50``
during instantiation and pass...
Can you write Python code for it?

# pick some channels that clearly show heartbeats and blinks
regexp = r'(MEG [12][45][123]1|EEG 00.)'
artifact_picks = mne.pick_channels_regexp(raw.ch_names, regexp=regexp)
raw.plot(order=artifact_picks, n_channels=len(artifact_picks),
         show_scrollbars=False)


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:

Note

`~mne.preprocessing.ICA.plot_components` (which plots the scalp
    field topographies for each component) has an optional ``inst`` parameter
    that takes an instance of `~mne.io.Raw` or `~mne.Epochs`.
    Passing ``inst`` makes the scalp topographies interactive: clicking one
    will bring up a diagnostic `~mne.preprocessing.ICA.plot_properties`
    window (see below) for that component.

In the plots above it's fairly obvious which ICs are capturing our EOG and
ECG artifacts, but there are additional ways visualize them anyway just to
be sure. First, we can plot an overlay of the original signal against the
reconstructed signal with the artifactual ICs excluded, using
~mne.preprocessing.ICA.plot_overlay:
Can you write Python code for it?

# blinks
ica.plot_overlay(raw, exclude=[0], picks='eeg')
# heartbeats
ica.plot_overlay(raw, exclude=[1], picks='mag')


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
An advantage of using this numerical representation of an IC to capture a
particular artifact pattern is that it can be saved and used as a template
for future template-matching tasks using ~mne.preprocessing.corrmap
without having to load or recompute the ICA solution that yielded the
template originally. Put another way, when the template is a NumPy array, the
~mne.preprocessing.ICA object containing the template does not need
to be in the list of ICAs provided to ~mne.preprocessing.corrmap.
.. LINKS
https://en.wikipedia.org/wiki/Signal_separation
   https://en.wikipedia.org/wiki/Independence_(probability_theory)
Compute ICA components on Epochs
ICA is now fit to epoched MEG data instead of the raw data.
We assume that the non-stationary EOG artifacts have already been removed.
The sources matching the ECG are automatically found and displayed.

Note

This example is computationally intensive, so it might take a few minutes
    to complete.

After reading the data, preprocessing consists of:

MEG channel selection
1-30 Hz band-pass filter
epoching -0.2 to 0.5 seconds with respect to events
rejection based on peak-to-peak amplitude

Note that we don't baseline correct the epochs here – we'll do this after
cleaning with ICA is completed. Baseline correction before ICA is not
recommended by the MNE-Python developers, as it doesn't guarantee optimal
results.
Can you write Python code for it?

filt_raw.pick_types(meg=True, eeg=False, exclude='bads', stim=True).load_data()
filt_raw.filter(1, 30, fir_design='firwin')

# peak-to-peak amplitude rejection parameters
reject = dict(mag=4e-12)
# create longer and more epochs for more artifact exposure
events = mne.find_events(filt_raw, stim_channel='STI 014')
# don't baseline correct epochs
epochs = mne.Epochs(filt_raw, events, event_id=None, tmin=-0.2, tmax=0.5,
                    reject=reject, baseline=None)


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
As a final note, it is possible to extract ICs numerically using the
~mne.preprocessing.ICA.get_components method of
~mne.preprocessing.ICA objects. This will return a :class:NumPy
array <numpy.ndarray> that can be passed to
~mne.preprocessing.corrmap instead of the :class:tuple of
(subject_index, component_index) we passed before, and will yield the
same result:
Can you write Python code for it?

template_eog_component = icas[0].get_components()[:, eog_inds[0]]
corrmap(icas, template=template_eog_component, threshold=0.9)
print(template_eog_component)


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Filtering to remove slow drifts
Before we run the ICA, an important step is filtering the data to remove
low-frequency drifts, which can negatively affect the quality of the ICA fit.
The slow drifts are problematic because they reduce the independence of the
assumed-to-be-independent sources (e.g., during a slow upward drift, the
neural, heartbeat, blink, and other muscular sources will all tend to have
higher values), making it harder for the algorithm to find an accurate
solution. A high-pass filter with 1 Hz cutoff frequency is recommended.
However, because filtering is a linear operation, the ICA solution found from
the filtered signal can be applied to the unfiltered signal (see
:footcite:WinklerEtAl2015 for
more information), so we'll keep a copy of the unfiltered
~mne.io.Raw object around so we can apply the ICA solution to it
later.
Can you write Python code for it?

filt_raw = raw.copy().filter(l_freq=1., h_freq=None)


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Fit ICA model using the FastICA algorithm, detect and plot components
explaining ECG artifacts.
Can you write Python code for it?

ica = ICA(n_components=15, method='fastica', max_iter="auto").fit(epochs)

ecg_epochs = create_ecg_epochs(filt_raw, tmin=-.5, tmax=.5)
ecg_inds, scores = ica.find_bads_ecg(ecg_epochs, threshold='auto')

ica.plot_components(ecg_inds)


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Fitting and plotting the ICA solution
.. sidebar:: Ignoring the time domain
The ICA algorithms implemented in MNE-Python find patterns across
channels, but ignore the time domain. This means you can compute ICA on
discontinuous `~mne.Epochs` or `~mne.Evoked` objects (not
just continuous `~mne.io.Raw` objects), or only use every Nth
sample by passing the ``decim`` parameter to ``ICA.fit()``.

.. note:: `~mne.Epochs` used for fitting ICA should not be
          baseline-corrected. Because cleaning the data via ICA may
          introduce DC offsets, we suggest to baseline correct your data
          **after** cleaning (and not before), should you require
          baseline correction.

Now we're ready to set up and fit the ICA. Since we know (from observing our
raw data) that the EOG and ECG artifacts are fairly strong, we would expect
those artifacts to be captured in the first few dimensions of the PCA
decomposition that happens before the ICA. Therefore, we probably don't need
a huge number of components to do a good job of isolating our artifacts
(though it is usually preferable to include more components for a more
accurate solution). As a first guess, we'll run ICA with n_components=15
(use only the first 15 PCA components to compute the ICA decomposition) — a
very small number given that our data has over 300 channels, but with the
advantage that it will run quickly and we will able to tell easily whether it
worked or not (because we already know what the EOG / ECG artifacts should
look like).
ICA fitting is not deterministic (e.g., the components may get a sign
flip on different runs, or may not always be returned in the same order), so
we'll also specify a random seed_ so that we get identical results each
time this tutorial is built by our web servers.
Can you write Python code for it?

ica = ICA(n_components=15, max_iter='auto', random_state=97)
ica.fit(filt_raw)
ica


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Here we can pretty clearly see that the first component (ICA000) captures
the EOG signal quite well, and the second component (ICA001) looks a lot
like a heartbeat <qrs_> (for more info on visually identifying Independent
Components, this EEGLAB tutorial is a good resource). We can also
visualize the scalp field distribution of each component using
~mne.preprocessing.ICA.plot_components. These are interpolated based
on the values in the ICA mixing matrix:
Can you write Python code for it?


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Much better! Now we've captured both ICs that are reflecting the heartbeat
artifact (and as a result, we got two diagnostic plots: one for each IC that
reflects the heartbeat). This demonstrates the value of checking the results
of automated approaches like ~mne.preprocessing.ICA.find_bads_ecg
before accepting them.
Can you write Python code for it?

# clean up memory before moving on
del raw, ica, new_ica


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Notice that subjects 2 and 3 each seem to have two ICs that reflect ocular
activity (components ICA000 and ICA002), but only one was caught by
~mne.preprocessing.corrmap. Let's try setting the threshold manually:
Can you write Python code for it?

corrmap(icas, template=(0, eog_inds[0]), threshold=0.9)


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Now let's run ~mne.preprocessing.corrmap:
Can you write Python code for it?

# use the first subject as template; use Fpz as proxy for EOG
raw = raws[0]
ica = icas[0]
eog_inds, eog_scores = ica.find_bads_eog(raw, ch_name='Fpz')
corrmap(icas, template=(0, eog_inds[0]))


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Now that the exclusions have been set, we can reconstruct the sensor signals
with artifacts removed using the ~mne.preprocessing.ICA.apply method
(remember, we're applying the ICA solution from the filtered data to the
original unfiltered signal). Plotting the original raw data alongside the
reconstructed data shows that the heartbeat and blink artifacts are repaired.
Can you write Python code for it?

# ica.apply() changes the Raw object in-place, so let's make a copy first:
reconst_raw = raw.copy()
ica.apply(reconst_raw)

raw.plot(order=artifact_picks, n_channels=len(artifact_picks),
         show_scrollbars=False)
reconst_raw.plot(order=artifact_picks, n_channels=len(artifact_picks),
                 show_scrollbars=False)
del reconst_raw


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Now we'll do the same for the heartbeat artifacts, using
~mne.preprocessing.create_ecg_epochs:
Can you write Python code for it?

ecg_evoked = create_ecg_epochs(raw).average()
ecg_evoked.apply_baseline(baseline=(None, -0.2))
ecg_evoked.plot_joint()


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Plot the properties of the ECG components:
Can you write Python code for it?


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Repairing artifacts with ICA
This tutorial covers the basics of independent components analysis (ICA) and
shows how ICA can be used for artifact repair; an extended example illustrates
repair of ocular and heartbeat artifacts. For conceptual background on ICA, see
this scikit-learn tutorial
<sphx_glr_auto_examples_decomposition_plot_ica_blind_source_separation.py>.
We begin as always by importing the necessary Python modules and loading some
example data <sample-dataset>. Because ICA can be computationally
intense, we'll also crop the data to 60 seconds; and to save ourselves from
repeatedly typing mne.preprocessing we'll directly import a few functions
and classes from that submodule:
Can you write Python code for it?

import os
import mne
from mne.preprocessing import (ICA, create_eog_epochs, create_ecg_epochs,
                               corrmap)

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_filt-0-40_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file)
# Here we'll crop to 60 seconds and drop gradiometer channels for speed
raw.crop(tmax=60.).pick_types(meg='mag', eeg=True, stim=True, eog=True)
raw.load_data()


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Selecting ICA components using template matching
When dealing with multiple subjects, it is also possible to manually select
an IC for exclusion on one subject, and then use that component as a
template for selecting which ICs to exclude from other subjects' data,
using mne.preprocessing.corrmap :footcite:CamposViolaEtAl2009.
The idea behind ~mne.preprocessing.corrmap is that the artifact patterns
are similar
enough across subjects that corresponding ICs can be identified by
correlating the ICs from each ICA solution with a common template, and
picking the ICs with the highest correlation strength.
~mne.preprocessing.corrmap takes a list of ICA solutions, and a
template parameter that specifies which ICA object and which component
within it to use as a template.
Since our sample dataset only contains data from one subject, we'll use a
different dataset with multiple subjects: the EEGBCI dataset
:footcite:SchalkEtAl2004,GoldbergerEtAl2000. The
dataset has 109 subjects, we'll just download one run (a left/right hand
movement task) from each of the first 4 subjects:
Can you write Python code for it?


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Some optional parameters that we could have passed to the
~mne.preprocessing.ICA.fit method include decim (to use only
every Nth sample in computing the ICs, which can yield a considerable
speed-up) and reject (for providing a rejection dictionary for maximum
acceptable peak-to-peak amplitudes for each channel type, just like we used
when creating epoched data in the tut-overview tutorial).
Now we can examine the ICs to see what they captured.
~mne.preprocessing.ICA.plot_sources will show the time series of the
ICs. Note that in our call to ~mne.preprocessing.ICA.plot_sources we
can use the original, unfiltered ~mne.io.Raw object:
Can you write Python code for it?


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
The first figure shows the template map, while the second figure shows all
the maps that were considered a "match" for the template (including the
template itself). There is one match for each subject, but it's a good idea
to also double-check the ICA sources for each subject:
Can you write Python code for it?

for index, (ica, raw) in enumerate(zip(icas, raws)):
    fig = ica.plot_sources(raw, show_scrollbars=False)
    fig.subplots_adjust(top=0.9)  # make space for title
    fig.suptitle('Subject {}'.format(index))


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
Using an EOG channel to select ICA components
It may have seemed easy to review the plots and manually select which ICs to
exclude, but when processing dozens or hundreds of subjects this can become
a tedious, rate-limiting step in the analysis pipeline. One alternative is to
use dedicated EOG or ECG sensors as a "pattern" to check the ICs against, and
automatically mark for exclusion any ICs that match the EOG/ECG pattern. Here
we'll use ~mne.preprocessing.ICA.find_bads_eog to automatically find
the ICs that best match the EOG signal, then use
~mne.preprocessing.ICA.plot_scores along with our other plotting
functions to see which ICs it picked. We'll start by resetting
ica.exclude back to an empty list:
Can you write Python code for it?

ica.exclude = []
# find which ICs match the EOG pattern
eog_indices, eog_scores = ica.find_bads_eog(raw)
ica.exclude = eog_indices

# barplot of ICA component "EOG match" scores
ica.plot_scores(eog_scores)

# plot diagnostics
ica.plot_properties(raw, picks=eog_indices)

# plot ICs applied to raw data, with EOG matches highlighted
ica.plot_sources(raw, show_scrollbars=False)

# plot ICs applied to the averaged EOG epochs, with EOG matches highlighted
ica.plot_sources(eog_evoked)


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
We can also plot some diagnostics of each IC using
~mne.preprocessing.ICA.plot_properties:
Can you write Python code for it?


I am working on the file "0.24/_downloads/1a105d401683707ed0696f30397d6253/40_artifact_correction_ica.ipynb".
The first task is:
We can get a summary of how the ocular artifact manifests across each channel
type using ~mne.preprocessing.create_eog_epochs like we did in the
tut-artifact-overview tutorial:
Can you write Python code for it?

eog_evoked = create_eog_epochs(raw).average()
eog_evoked.apply_baseline(baseline=(None, -0.2))
eog_evoked.plot_joint()


I am working on the file "0.24/_downloads/1abc74aa28d845859c3852be5f0bdd21/30_forward.ipynb".
The first task is:

Warning

Forward computation can remove vertices that are too close to (or outside)
   the inner skull surface. For example, here we have gone from 516 to 474
   vertices in use. For many functions, such as
   :func:`mne.compute_source_morph`, it is important to pass ``fwd['src']``
   or ``inv['src']`` so that this removal is adequately accounted for.

Can you write Python code for it?

print(f'Before: {src}')
print(f'After:  {fwd["src"]}')


I am working on the file "0.24/_downloads/1abc74aa28d845859c3852be5f0bdd21/30_forward.ipynb".
The first task is:

Note

Some sources may appear to be outside the BEM inner skull contour.
          This is because the ``slices`` are decimated for plotting here.
          Each slice in the figure actually represents several MRI slices,
          but only the MRI voxels and BEM boundaries for a single (midpoint
          of the given slice range) slice are shown, whereas the source space
          points plotted on that midpoint slice consist of all points
          for which that slice (out of all slices shown) was the closest.

Now let's see how to view all sources in 3D.
Can you write Python code for it?

fig = mne.viz.plot_alignment(subject=subject, subjects_dir=subjects_dir,
                             surfaces='white', coord_frame='mri',
                             src=src)
mne.viz.set_3d_view(fig, azimuth=173.78, elevation=101.75,
                    distance=0.30, focalpoint=(-0.03, -0.01, 0.03))


I am working on the file "0.24/_downloads/1abc74aa28d845859c3852be5f0bdd21/30_forward.ipynb".
The first task is:
Compute Source Space
The source space defines the position and orientation of the candidate source
locations. There are two types of source spaces:

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

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

Surface-based source space is computed using
:func:mne.setup_source_space, while volumetric source space is computed
using :func:mne.setup_volume_source_space.
We will now compute a surface-based source space with an 'oct4'
resolution. See setting_up_source_space for details on source space
definition and spacing parameter.

Warning

``'oct4'`` is used here just for speed, for real analyses the recommended
    spacing is ``'oct6'``.

Can you write Python code for it?

src = mne.setup_source_space(subject, spacing='oct4', add_dist='patch',
                             subjects_dir=subjects_dir)
print(src)


I am working on the file "0.24/_downloads/1abc74aa28d845859c3852be5f0bdd21/30_forward.ipynb".
The first task is:
The surface based source space src contains two parts, one for the left
hemisphere (258 locations) and one for the right hemisphere (258
locations). Sources can be visualized on top of the BEM surfaces in purple.
Can you write Python code for it?


I am working on the file "0.24/_downloads/1abc74aa28d845859c3852be5f0bdd21/30_forward.ipynb".
The first task is:
We can explore the content of fwd to access the numpy array that contains
the gain matrix.
Can you write Python code for it?

leadfield = fwd['sol']['data']
print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape)


I am working on the file "0.24/_downloads/1b3716673f2aeae3f2b0c6c336812aba/80_fix_bem_in_blender.ipynb".
The first task is:
Back in Python, you can read the fixed .obj files and save them as
FreeSurfer .surf files. For the :func:mne.make_bem_model function to find
them, they need to be saved using their original names in the surf
folder, e.g. bem/inner_skull.surf. Be sure to first backup the original
surfaces in case you make a mistake!
Can you write Python code for it?

# Read the fixed surface
coords, faces = mne.read_surface(op.join(conv_dir, 'inner_skull_fixed.obj'))

# Backup the original surface
shutil.copy(op.join(bem_dir, 'inner_skull.surf'),
            op.join(bem_dir, 'inner_skull_orig.surf'))

# Overwrite the original surface with the fixed version
# In real study you should provide the correct metadata using ``volume_info=``
# This could be accomplished for example with:
#
# _, _, vol_info = mne.read_surface(op.join(bem_dir, 'inner_skull.surf'),
#                                   read_metadata=True)
# mne.write_surface(op.join(bem_dir, 'inner_skull.surf'), coords, faces,
#                   volume_info=vol_info, overwrite=True)


I am working on the file "0.24/_downloads/1b3716673f2aeae3f2b0c6c336812aba/80_fix_bem_in_blender.ipynb".
The first task is:
Editing BEM surfaces in Blender
Sometimes when creating a BEM model the surfaces need manual correction because
of a series of problems that can arise (e.g. intersection between surfaces).
Here, we will see how this can be achieved by exporting the surfaces to the 3D
modeling program Blender <https://blender.org>_, editing them, and
re-importing them.
This tutorial is based on https://github.com/ezemikulan/blender_freesurfer by
Ezequiel Mikulan.
   :depth: 2
Can you write Python code for it?

# Authors: Marijn van Vliet <w.m.vanvliet@gmail.com>
#          Ezequiel Mikulan <e.mikulan@gmail.com>
#          Manorama Kadwani <manorama.kadwani@gmail.com>
#
# License: BSD-3-Clause

import os
import os.path as op
import shutil
import mne

data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
bem_dir = op.join(subjects_dir, 'sample', 'bem', 'flash')


I am working on the file "0.24/_downloads/1b3716673f2aeae3f2b0c6c336812aba/80_fix_bem_in_blender.ipynb".
The first task is:
Editing the head surfaces
Sometimes the head surfaces are faulty and require manual editing. We use
:func:mne.write_head_bem to convert the fixed surfaces to .fif files.
Low-resolution head
For EEG forward modeling, it is possible that outer_skin.surf would be
manually edited. In that case, remember to save the fixed version of
-head.fif from the edited surface file for coregistration.
Can you write Python code for it?

# Load the fixed surface
coords, faces = mne.read_surface(op.join(bem_dir, 'outer_skin.surf'))

# Make sure we are in the correct directory
head_dir = op.dirname(bem_dir)

# Remember to backup the original head file in advance!
# Overwrite the original head file
#
# mne.write_head_bem(op.join(head_dir, 'sample-head.fif'), coords, faces,
#                    overwrite=True)


I am working on the file "0.24/_downloads/1b3716673f2aeae3f2b0c6c336812aba/80_fix_bem_in_blender.ipynb".
The first task is:
Exporting surfaces to Blender
In this tutorial, we are working with the MNE-Sample set, for which the
surfaces have no issues. To demonstrate how to fix problematic surfaces, we
are going to manually place one of the inner-skull vertices outside the
outer-skill mesh.
We then convert the surfaces to .obj
<https://en.wikipedia.org/wiki/Wavefront_.obj_file>_ files and create a new
folder called conv inside the FreeSurfer subject folder to keep them in.
Can you write Python code for it?

# Put the converted surfaces in a separate 'conv' folder
conv_dir = op.join(subjects_dir, 'sample', 'conv')
os.makedirs(conv_dir, exist_ok=True)

# Load the inner skull surface and create a problem
# The metadata is empty in this example. In real study, we want to write the
# original metadata to the fixed surface file. Set read_metadata=True to do so.
coords, faces = mne.read_surface(op.join(bem_dir, 'inner_skull.surf'))
coords[0] *= 1.1  # Move the first vertex outside the skull

# Write the inner skull surface as an .obj file that can be imported by
# Blender.
mne.write_surface(op.join(conv_dir, 'inner_skull.obj'), coords, faces,
                  overwrite=True)

# Also convert the outer skull surface.
coords, faces = mne.read_surface(op.join(bem_dir, 'outer_skull.surf'))
mne.write_surface(op.join(conv_dir, 'outer_skull.obj'), coords, faces,
                  overwrite=True)


I am working on the file "0.24/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
Also by default, :func:~mne.set_config will set values in both the JSON
file and in :data:os.environ; to set a config variable only in the JSON
file use set_env=False. Here we'll use :func:print statement to confirm
that an environment variable is being created and deleted (we could have used
the Python assert statement <assert> instead, but it doesn't print any
output when it succeeds so it's a little less obvious):
Can you write Python code for it?

mne.set_config('foo', 'bar', set_env=False)
print('foo' in os.environ.keys())
mne.set_config('foo', 'bar')
print('foo' in os.environ.keys())
mne.set_config('foo', None)  # unsetting a key deletes var from environment
print('foo' in os.environ.keys())


I am working on the file "0.24/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
Configuring MNE-Python
This tutorial covers how to configure MNE-Python to suit your local system and
your analysis preferences.
We begin by importing the necessary Python modules:
Can you write Python code for it?


I am working on the file "0.24/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
If you're unsure whether a config variable has been set, there is a
convenient way to check it and provide a fallback in case it doesn't exist:
:func:~mne.get_config has a default parameter.
Can you write Python code for it?


I am working on the file "0.24/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
It is possible to add config variables that are not part of the recognized
list, by passing any arbitrary key to :func:~mne.set_config. This will
yield a warning, however, which is a nice check in cases where you meant to
set a valid key but simply misspelled it:
Can you write Python code for it?


I am working on the file "0.24/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
Let's delete that config variable we just created. To unset a config
variable, use :func:~mne.set_config with value=None. Since we're still
dealing with an unrecognized key (as far as MNE-Python is concerned) we'll
still get a warning, but the key will be unset:
Can you write Python code for it?

mne.set_config('MNEE_USE_CUUDAA', None)
assert 'MNEE_USE_CUUDAA' not in mne.get_config('')


I am working on the file "0.24/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
No messages were generated, because none of the messages were of severity
"warning" or worse. Next, we'll load the same file with log level info
(the default level):
Can you write Python code for it?

raw = mne.io.read_raw_kit(kit_data_path, verbose='info')


I am working on the file "0.24/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
Note that the string values read from the JSON file are not parsed in any
way, so :func:~mne.get_config returns a string even for true/false config
values, rather than a Python boolean <bltin-boolean-values>.
Similarly, :func:~mne.set_config will only set string values (or None
values, to unset a variable):
Can you write Python code for it?

try:
    mne.set_config('MNE_USE_CUDA', True)
except TypeError as err:
    print(err)


I am working on the file "0.24/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
The logging levels that can be set as config variables are debug,
info, warning, error, and critical. Around 90% of the log
messages in MNE-Python are info messages, so for most users the choice is
between info (tell me what is happening) and warning (tell me only if
something worrisome happens). The debug logging level is intended for
MNE-Python developers.
In an earlier section <config-get-set> we saw how
:func:mne.set_config is used to change the logging level for the current
Python session and all future sessions. To change the logging level only for
the current Python session, you can use :func:mne.set_log_level instead.
The :func:~mne.set_log_level function takes the same five string options
that are used for the MNE_LOGGING_LEVEL config variable; additionally, it
can accept :class:int or :class:bool values that are equivalent to those
strings. The equivalencies are given in this table:
+----------+---------+---------+
| String   | Integer | Boolean |
+==========+=========+=========+
| DEBUG    | 10      |         |
+----------+---------+---------+
| INFO     | 20      | True    |
+----------+---------+---------+
| WARNING  | 30      | False   |
+----------+---------+---------+
| ERROR    | 40      |         |
+----------+---------+---------+
| CRITICAL | 50      |         |
+----------+---------+---------+
With many MNE-Python functions it is possible to change the logging level
temporarily for just that function call, by using the verbose parameter.
To illustrate this, we'll load some sample data with different logging levels
set. First, with log level warning:
Can you write Python code for it?

kit_data_path = os.path.join(os.path.abspath(os.path.dirname(mne.__file__)),
                             'io', 'kit', 'tests', 'data', 'test.sqd')
raw = mne.io.read_raw_kit(kit_data_path, verbose='warning')


I am working on the file "0.24/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
The second convenience mode will return a :class:tuple of all the keys that
MNE-Python recognizes and uses, regardless of whether they've been set on
your system. This is done by passing an empty string '' as the key:
Can you write Python code for it?


I am working on the file "0.24/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
There are also two convenience modes of :func:~mne.get_config. The first
will return a :class:dict containing all config variables (and their
values) that have been set on your system; this is done by passing
key=None (which is the default, so it can be omitted):
Can you write Python code for it?

print(mne.get_config())  # same as mne.get_config(key=None)


I am working on the file "0.24/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
This time, we got a few messages about extracting information from the file,
converting that information into the MNE-Python :class:~mne.Info format,
etc. Finally, if we request debug-level information, we get even more
detail:
Can you write Python code for it?

raw = mne.io.read_raw_kit(kit_data_path, verbose='debug')


I am working on the file "0.24/_downloads/1c191178a3423d922910711c4b574821/50_configure_mne.ipynb".
The first task is:
Where configurations are stored
MNE-Python stores configuration variables in a JSON_ file. By default, this
file is located in :file:{%USERPROFILE%}\\.mne\\mne-python.json on Windows
and :file:{$HOME}/.mne/mne-python.json on Linux or macOS. You can get the
full path to the config file with :func:mne.get_config_path.
Can you write Python code for it?


I am working on the file "0.24/_downloads/23237b92405a4b223d89222e217ffffd/morph_volume_stc.ipynb".
The first task is:
Morph volumetric source estimate
This example demonstrates how to morph an individual subject's
:class:mne.VolSourceEstimate to a common reference space. We achieve this
using :class:mne.SourceMorph. Data will be morphed based on
an affine transformation and a nonlinear registration method
known as Symmetric Diffeomorphic Registration (SDR) by
:footcite:AvantsEtAl2008.
Transformation is estimated from the subject's anatomical T1 weighted MRI
(brain) to FreeSurfer's 'fsaverage' T1 weighted MRI (brain)
<https://surfer.nmr.mgh.harvard.edu/fswiki/FsAverage>__.
Afterwards the transformation will be applied to the volumetric source
estimate. The result will be plotted, showing the fsaverage T1 weighted
anatomical MRI, overlaid with the morphed volumetric source estimate.
Can you write Python code for it?

# Author: Tommy Clausner <tommy.clausner@gmail.com>
#
# License: BSD-3-Clause

import os

import nibabel as nib
import mne
from mne.datasets import sample, fetch_fsaverage
from mne.minimum_norm import apply_inverse, read_inverse_operator
from nilearn.plotting import plot_glass_brain

print(__doc__)


I am working on the file "0.24/_downloads/23237b92405a4b223d89222e217ffffd/morph_volume_stc.ipynb".
The first task is:
Plot results
Can you write Python code for it?

# Load fsaverage anatomical image
t1_fsaverage = nib.load(fname_t1_fsaverage)

# Plot glass brain (change to plot_anat to display an overlaid anatomical T1)
display = plot_glass_brain(t1_fsaverage,
                           title='subject results to fsaverage',
                           draw_cross=False,
                           annotate=True)

# Add functional data as overlay
display.add_overlay(img_fsaverage, alpha=0.75)


I am working on the file "0.24/_downloads/26b665b81df8d69d2764306260a9ffa9/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,
                             out_type='mask')


I am working on the file "0.24/_downloads/26b665b81df8d69d2764306260a9ffa9/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.24/_downloads/26b665b81df8d69d2764306260a9ffa9/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.24/_downloads/272b39eb7cbe2bfe1e8c768341ec7c56/time_frequency_simulated.ipynb".
The first task is:
(1) Least smoothing (most variance/background fluctuations).
Can you write Python code for it?

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


I am working on the file "0.24/_downloads/272b39eb7cbe2bfe1e8c768341ec7c56/time_frequency_simulated.ipynb".
The first task is:
(3) Less time smoothing, more frequency smoothing.
Can you write Python code for it?

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


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

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

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

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


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

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


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

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

plt.show()


I am working on the file "0.24/_downloads/272b39eb7cbe2bfe1e8c768341ec7c56/time_frequency_simulated.ipynb".
The first task is:
Stockwell (S) transform
Stockwell uses a Gaussian window to balance temporal and spectral resolution.
Importantly, frequency bands are phase-normalized, hence strictly comparable
with regard to timing, and, the input signal can be recoverd from the
transform in a lossless way if we disregard numerical errors. In this case,
we control the spectral / temporal resolution by specifying different widths
of the gaussian window using the width parameter.
Can you write Python code for it?

fig, axs = plt.subplots(1, 3, figsize=(15, 5), sharey=True)
fmin, fmax = freqs[[0, -1]]
for width, ax in zip((0.2, .7, 3.0), axs):
    power = tfr_stockwell(epochs, fmin=fmin, fmax=fmax, width=width)
    power.plot([0], baseline=(0., 0.1), mode='mean', axes=ax, show=False,
               colorbar=False)
    ax.set_title('Sim: Using S transform, width = {:0.1f}'.format(width))
plt.tight_layout()


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:

Warning

The code above yields an **equal-weighted difference**. If you have
    imbalanced trial numbers, you might want to equalize the number of events
    per condition first by using `epochs.equalize_event_counts()
    <mne.Epochs.equalize_event_counts>` before averaging.

Grand averages
To compute grand averages across conditions (or subjects), you can pass a
list of ~mne.Evoked objects to mne.grand_average. The result is another
~mne.Evoked object.
Can you write Python code for it?

grand_average = mne.grand_average([l_aud, l_vis])
print(grand_average)


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
Another way in which epochs can be automatically dropped is if the event
around which the epoch is formed is too close to the start or end of the
~mne.io.Raw object (e.g., if the epoch's tmax would be past the end of
the file; this is the cause of the "TOO_SHORT" entry in the
~mne.Epochs.plot_drop_log plot above). Epochs may also be automatically
dropped if the ~mne.io.Raw object contains :term:annotations that begin
with either bad or edge ("edge" annotations are automatically
inserted when concatenating two separate ~mne.io.Raw objects together). See
tut-reject-data-spans for more information about annotation-based
epoch rejection.
Now that we've dropped the bad epochs, let's look at our evoked responses for
some conditions we care about. Here the ~mne.Epochs.average method will
create an ~mne.Evoked object, which we can then plot. Notice that we
select which condition we want to average using the square-bracket indexing
(like a :class:dictionary <dict>); that returns a smaller epochs object
containing just the epochs from that condition, to which we then apply the
~mne.Epochs.average method:
Can you write Python code for it?

l_aud = epochs['auditory/left'].average()
l_vis = epochs['visual/left'].average()


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
As demonstrated in the above example, the mean amplitude was higher and
positive in right compared to left hemisphere channels. It should be
reiterated that both that spatial and temporal window you use should be
determined in an independent manner (e.g., defined a priori from prior
research, a "localizer" or another independent condition) and not based
on the data you will use to test your hypotheses.
The above example can be modified to extract the the mean amplitude
from all channels and store the resulting output in
:class:pandas.DataFrame. This can be useful for statistical analyses
conducted in other programming languages.
Can you write Python code for it?

# Extract mean amplitude for all channels in l_vis (including `eog`)
l_vis_cropped = l_vis.copy().crop(tmin=good_tmin, tmax=good_tmax)
mean_amp_all = l_vis_cropped.data.mean(axis=1) * 1e6
mean_amp_all_df = pd.DataFrame({
    'ch_name': l_vis_cropped.info['ch_names'],
    'mean_amp': mean_amp_all
})
mean_amp_all_df['tmin'] = good_tmin
mean_amp_all_df['tmax'] = good_tmax
mean_amp_all_df['condition'] = 'Left/Visual'
print(mean_amp_all_df.head())
print(mean_amp_all_df.tail())


I am working on the file "0.24/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
Considerable customization of these plots is possible, see the docstring of
~mne.Evoked.plot_topomap for details.
There is also a built-in method for combining "butterfly" plots of the
signals with scalp topographies, called ~mne.Evoked.plot_joint. Like
~mne.Evoked.plot_topomap you can specify times for the scalp topographies
or you can let the method choose times automatically, as is done here:
Can you write Python code for it?