I am working on the file "0.23/_downloads/ab9aa98c1c3d10ded0b9447abaef0b61/30_ecog.ipynb".
The first task is:
Working with ECoG data
MNE supports working with more than just MEG and EEG data. Here we show some
of the functions that can be used to facilitate working with
electrocorticography (ECoG) data.
This example shows how to use:

ECoG data (available here <https://openneuro.org/datasets/ds003029>_)
  from an epilepsy patient during a seizure
channel locations in FreeSurfer's fsaverage MRI space
projection onto a pial surface

For a complementary example that involves sEEG data, channel locations in
MNI space, or projection into a volume, see tut_working_with_seeg.
Can you write Python code for it?

# Authors: Eric Larson <larson.eric.d@gmail.com>
#          Chris Holdgraf <choldgraf@gmail.com>
#          Adam Li <adam2392@gmail.com>
#          Alex Rockhill <aprockhill@mailbox.org>
#          Liberty Hamilton <libertyhamilton@gmail.com>
#
# License: BSD (3-clause)

import os.path as op

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap
from mne_bids import BIDSPath, read_raw_bids

import mne
from mne.viz import plot_alignment, snapshot_brain_montage

print(__doc__)

# paths to mne datasets - sample ECoG and FreeSurfer subject
bids_root = mne.datasets.epilepsy_ecog.data_path()
sample_path = mne.datasets.sample.data_path()
subjects_dir = op.join(sample_path, 'subjects')


I am working on the file "0.23/_downloads/aec45e1f20057e833cee12bb6bd292dc/10_evoked_overview.ipynb".
The first task is:
Above, when we created an :class:~mne.Evoked object by averaging epochs,
baseline correction was applied by default when we extracted epochs from the
~mne.io.Raw object (the default baseline period is (None, 0),
which assured zero mean for times before the stimulus event). In contrast, if
we plot the first :class:~mne.Evoked object in the list that was loaded
from disk, we'll see that the data have not been baseline-corrected:
Can you write Python code for it?


I am working on the file "0.23/_downloads/aec45e1f20057e833cee12bb6bd292dc/10_evoked_overview.ipynb".
The first task is:
Basic visualization of Evoked objects
We can visualize the average evoked response for left-auditory stimuli using
the :meth:~mne.Evoked.plot method, which yields a butterfly plot of each
channel type:
Can you write Python code for it?


I am working on the file "0.23/_downloads/aec45e1f20057e833cee12bb6bd292dc/10_evoked_overview.ipynb".
The first task is:
Like the plot() methods for :meth:Raw <mne.io.Raw.plot> and
:meth:Epochs <mne.Epochs.plot> objects,
:meth:evoked.plot() <mne.Evoked.plot> has many parameters for customizing
the plot output, such as color-coding channel traces by scalp location, or
plotting the :term:global field power alongside the channel traces.
See tut-visualize-evoked for more information about visualizing
:class:~mne.Evoked objects.
Subselecting Evoked data
.. sidebar:: Evokeds are not memory-mapped
:class:~mne.Evoked objects use a :attr:~mne.Evoked.data attribute
  rather than a :meth:~mne.Epochs.get_data method; this reflects the fact
  that the data in :class:~mne.Evoked objects are always loaded into
  memory, never memory-mapped_ from their location on disk (because they
  are typically much smaller than :class:~mne.io.Raw or
  :class:~mne.Epochs objects).
Unlike :class:~mne.io.Raw and :class:~mne.Epochs objects,
:class:~mne.Evoked objects do not support selection by square-bracket
indexing. Instead, data can be subselected by indexing the
:attr:~mne.Evoked.data attribute:
Can you write Python code for it?

print(evoked.data[:2, :3])  # first 2 channels, first 3 timepoints


I am working on the file "0.23/_downloads/aec45e1f20057e833cee12bb6bd292dc/10_evoked_overview.ipynb".
The first task is:
Note that the nave attribute of the resulting ~mne.Evoked object will
reflect the effective number of averages, and depends on both the nave
attributes of the contributing ~mne.Evoked objects and the weights at
which they are combined. Keeping track of effective nave is important for
inverse imaging, because nave is used to scale the noise covariance
estimate (which in turn affects the magnitude of estimated source activity).
See minimum_norm_estimates for more information (especially the
whitening_and_scaling section). Note that mne.grand_average does
not adjust nave to reflect effective number of averaged epochs; rather
it simply sets nave to the number of evokeds that were averaged
together. For this reason, it is best to use mne.combine_evoked rather than
mne.grand_average if you intend to perform inverse imaging on the resulting
:class:~mne.Evoked object.
Other uses of Evoked objects
Although the most common use of :class:~mne.Evoked objects is to store
averages of epoched data, there are a couple other uses worth noting here.
First, the method :meth:epochs.standard_error() <mne.Epochs.standard_error>
will create an :class:~mne.Evoked object (just like
:meth:epochs.average() <mne.Epochs.average> does), but the data in the
:class:~mne.Evoked object will be the standard error across epochs instead
of the average. To indicate this difference, :class:~mne.Evoked objects
have a :attr:~mne.Evoked.kind attribute that takes values 'average' or
'standard error' as appropriate.
Another use of :class:~mne.Evoked objects is to represent a single trial
or epoch of data, usually when looping through epochs. This can be easily
accomplished with the :meth:epochs.iter_evoked() <mne.Epochs.iter_evoked>
method, and can be useful for applications where you want to do something
that is only possible for :class:~mne.Evoked objects. For example, here
we use the :meth:~mne.Evoked.get_peak method (which isn't available for
:class:~mne.Epochs objects) to get the peak response in each trial:
Can you write Python code for it?

for ix, trial in enumerate(epochs[:3].iter_evoked()):
    channel, latency, value = trial.get_peak(ch_type='eeg',
                                             return_amplitude=True)
    latency = int(round(latency * 1e3))  # convert to milliseconds
    value = int(round(value * 1e6))      # convert to µV
    print('Trial {}: peak of {} µV at {} ms in channel {}'
          .format(ix, value, latency, channel))


I am working on the file "0.23/_downloads/aec45e1f20057e833cee12bb6bd292dc/10_evoked_overview.ipynb".
The first task is:
Notice that :func:mne.read_evokeds returned a :class:list of
:class:~mne.Evoked objects, and each one has an evoked.comment
attribute describing the experimental condition that was averaged to
generate the estimate:
Can you write Python code for it?

for evok in evokeds_list:
    print(evok.comment)


I am working on the file "0.23/_downloads/aec45e1f20057e833cee12bb6bd292dc/10_evoked_overview.ipynb".
The first task is:
Similarities among the core data structures
:class:~mne.Evoked objects have many similarities with :class:~mne.io.Raw
and :class:~mne.Epochs objects, including:

They can be loaded from and saved to disk in .fif format, and their
  data can be exported to a :class:NumPy array <numpy.ndarray> (but through
  the :attr:~mne.Evoked.data attribute, not through a get_data()
  method). :class:Pandas DataFrame <pandas.DataFrame> export is also
  available through the :meth:~mne.Evoked.to_data_frame method.

You can change the name or type of a channel using
  :meth:evoked.rename_channels() <mne.Evoked.rename_channels> or
  :meth:evoked.set_channel_types() <mne.Evoked.set_channel_types>.
  Both methods take :class:dictionaries <dict> where the keys are existing
  channel names, and the values are the new name (or type) for that channel.
  Existing channels that are not in the dictionary will be unchanged.

:term:SSP projector <projector> manipulation is possible through
  :meth:~mne.Evoked.add_proj, :meth:~mne.Evoked.del_proj, and
  :meth:~mne.Evoked.plot_projs_topomap methods, and the
  :attr:~mne.Evoked.proj attribute. See tut-artifact-ssp for more
  information on SSP.

Like :class:~mne.io.Raw and :class:~mne.Epochs objects,
  :class:~mne.Evoked objects have :meth:~mne.Evoked.copy,
  :meth:~mne.Evoked.crop, :meth:~mne.Evoked.time_as_index,
  :meth:~mne.Evoked.filter, and :meth:~mne.Evoked.resample methods.

Like :class:~mne.io.Raw and :class:~mne.Epochs objects,
  :class:~mne.Evoked objects have evoked.times,
  :attr:evoked.ch_names <mne.Evoked.ch_names>, and :class:info <mne.Info>
  attributes.

Loading and saving Evoked data
Single :class:~mne.Evoked objects can be saved to disk with the
:meth:evoked.save() <mne.Evoked.save> method. One difference between
:class:~mne.Evoked objects and the other data structures is that multiple
:class:~mne.Evoked objects can be saved into a single .fif file, using
:func:mne.write_evokeds. The example data...
Can you write Python code for it?

sample_data_evk_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis-ave.fif')
evokeds_list = mne.read_evokeds(sample_data_evk_file, verbose=False)
print(evokeds_list)
print(type(evokeds_list))


I am working on the file "0.23/_downloads/aec45e1f20057e833cee12bb6bd292dc/10_evoked_overview.ipynb".
The first task is:
The Evoked data structure: evoked/averaged data
This tutorial covers the basics of creating and working with :term:evoked
data. It introduces the :class:~mne.Evoked data structure in detail,
including how to load, query, subselect, export, and plot data from an
:class:~mne.Evoked object. For info on creating an :class:~mne.Evoked
object from (possibly simulated) data in a :class:NumPy array
<numpy.ndarray>, see tut_creating_data_structures.
As usual we'll start by importing the modules we need:
Can you write Python code for it?


I am working on the file "0.23/_downloads/aec45e1f20057e833cee12bb6bd292dc/10_evoked_overview.ipynb".
The first task is:
This approach will weight each epoch equally and create a single
:class:~mne.Evoked object. Notice that the printed representation includes
(average, N=145), indicating that the :class:~mne.Evoked object was
created by averaging across 145 epochs. In this case, the event types were
fairly close in number:
Can you write Python code for it?

left_aud = epochs['auditory/left'].average()
right_aud = epochs['auditory/right'].average()
print([evok.nave for evok in (left_aud, right_aud)])


I am working on the file "0.23/_downloads/b11aa17d34c637b8e89ed78c8bdf13e4/eeglab_head_sphere.ipynb".
The first task is:
Calculate sphere origin and radius
EEGLAB plots head outline at the level where the head circumference is
measured
in the 10-20 system (a line going through Fpz, T8/T4, Oz and T7/T3 channels).
MNE-Python places the head outline lower on the z dimension, at the level of
the anatomical landmarks :term:LPA, RPA, and NAS <fiducial>.
Therefore to use the EEGLAB layout we
have to move the origin of the reference sphere (a sphere that is used as a
reference when projecting channel locations to a 2d plane) a few centimeters
up.
Instead of approximating this position by eye, as we did in the sensor
locations tutorial <tut-sensor-locations>, here we will calculate it using
the position of Fpz, T8, Oz and T7 channels available in our montage.
Can you write Python code for it?

# first we obtain the 3d positions of selected channels
chs = ['Oz', 'Fpz', 'T7', 'T8']
pos = np.stack([biosemi_montage.get_positions()['ch_pos'][ch] for ch in chs])

# now we calculate the radius from T7 and T8 x position
# (we could use Oz and Fpz y positions as well)
radius = np.abs(pos[[2, 3], 0]).mean()

# then we obtain the x, y, z sphere center this way:
# x: x position of the Oz channel (should be very close to 0)
# y: y position of the T8 channel (should be very close to 0 too)
# z: average z position of Oz, Fpz, T7 and T8 (their z position should be the
#    the same, so we could also use just one of these channels), it should be
#    positive and somewhere around `0.03` (3 cm)
x = pos[0, 0]
y = pos[-1, 1]
z = pos[:, -1].mean()

# lets print the values we got:
print([f'{v:0.5f}' for v in [x, y, z, radius]])


I am working on the file "0.23/_downloads/b11aa17d34c637b8e89ed78c8bdf13e4/eeglab_head_sphere.ipynb".
The first task is:
How to plot topomaps the way EEGLAB does
If you have previous EEGLAB experience you may have noticed that topomaps
(topoplots) generated using MNE-Python look a little different from those
created in EEGLAB. If you prefer the EEGLAB style this example will show you
how to calculate head sphere origin and radius to obtain EEGLAB-like channel
layout in MNE.
Can you write Python code for it?

# Authors: Mikołaj Magnuski <mmagnuski@swps.edu.pl>
#
# License: BSD (3-clause)
import numpy as np
from matplotlib import pyplot as plt

import mne

print(__doc__)


I am working on the file "0.23/_downloads/b11aa17d34c637b8e89ed78c8bdf13e4/eeglab_head_sphere.ipynb".
The first task is:
Topomaps (topoplots)
As the last step we do the same, but plotting the topomaps. These will not
be particularly interesting as they will show random data but hopefully you
will see the difference.
Can you write Python code for it?

fig, ax = plt.subplots(ncols=2, figsize=(8, 4), gridspec_kw=dict(top=0.9),
                       sharex=True, sharey=True)

mne.viz.plot_topomap(fake_evoked.data[:, 0], fake_evoked.info, axes=ax[0],
                     show=False)
mne.viz.plot_topomap(fake_evoked.data[:, 0], fake_evoked.info, axes=ax[1],
                     show=False, sphere=(x, y, z, radius))

# add titles
ax[0].set_title('MNE', fontweight='bold')
ax[1].set_title('EEGLAB', fontweight='bold')


I am working on the file "0.23/_downloads/b2637a9801fb152d611a08a816cc5583/sensor_regression.ipynb".
The first task is:
Because the :func:~mne.stats.linear_regression function also estimates
p values, we can --
after applying FDR correction for multiple comparisons -- also visualise the
statistical significance of the regression of word concreteness.
The :func:mne.viz.plot_evoked_image function takes a mask parameter.
If we supply it with a boolean mask of the positions where we can reject
the null hypothesis, points that are not significant will be shown
transparently, and if desired, in a different colour palette and surrounded
by dark contour lines.
Can you write Python code for it?

reject_H0, fdr_pvals = fdr_correction(res["Concreteness"].p_val.data)
evoked = res["Concreteness"].beta
evoked.plot_image(mask=reject_H0, time_unit='s')


I am working on the file "0.23/_downloads/b36af73820a7a52a4df3c42b66aef8a5/source_power_spectrum_opm.ipynb".
The first task is:
Alignment and forward
Can you write Python code for it?

# Here we use a reduced size source space (oct5) just for speed
src = mne.setup_source_space(
    subject, 'oct5', add_dist=False, subjects_dir=subjects_dir)
# This line removes source-to-source distances that we will not need.
# We only do it here to save a bit of memory, in general this is not required.
del src[0]['dist'], src[1]['dist']
bem = mne.read_bem_solution(bem_fname)
fwd = dict()

# check alignment and generate forward for VectorView
kwargs = dict(azimuth=0, elevation=90, distance=0.6, focalpoint=(0., 0., 0.))
fig = mne.viz.plot_alignment(
    raws['vv'].info, trans=vv_trans_fname, subject=subject,
    subjects_dir=subjects_dir, dig=True, coord_frame='mri',
    surfaces=('head', 'white'))
mne.viz.set_3d_view(figure=fig, **kwargs)
fwd['vv'] = mne.make_forward_solution(
    raws['vv'].info, vv_trans_fname, src, bem, eeg=False, verbose=True)


I am working on the file "0.23/_downloads/b36af73820a7a52a4df3c42b66aef8a5/source_power_spectrum_opm.ipynb".
The first task is:
And for OPM:
Can you write Python code for it?

with mne.use_coil_def(opm_coil_def_fname):
    fig = mne.viz.plot_alignment(
        raws['opm'].info, trans=opm_trans_fname, subject=subject,
        subjects_dir=subjects_dir, dig=False, coord_frame='mri',
        surfaces=('head', 'white'))
    mne.viz.set_3d_view(figure=fig, **kwargs)
    fwd['opm'] = mne.make_forward_solution(
        raws['opm'].info, opm_trans_fname, src, bem, eeg=False, verbose=True)

del src, bem


I am working on the file "0.23/_downloads/b36af73820a7a52a4df3c42b66aef8a5/source_power_spectrum_opm.ipynb".
The first task is:
Beta
Here we also show OPM data, which shows a profile similar to the VectorView
data beneath the sensors. VectorView first:
Can you write Python code for it?

fig_beta, brain_beta = plot_band('vv', 'beta')


I am working on the file "0.23/_downloads/b36af73820a7a52a4df3c42b66aef8a5/source_power_spectrum_opm.ipynb".
The first task is:
Compute and apply inverse to PSD estimated using multitaper + Welch.
Group into frequency bands, then normalize each source point and sensor
independently. This makes the value of each sensor point and source location
in each frequency band the percentage of the PSD accounted for by that band.
Can you write Python code for it?

freq_bands = dict(
    delta=(2, 4), theta=(5, 7), alpha=(8, 12), beta=(15, 29), gamma=(30, 45))
topos = dict(vv=dict(), opm=dict())
stcs = dict(vv=dict(), opm=dict())

snr = 3.
lambda2 = 1. / snr ** 2
for kind in kinds:
    noise_cov = mne.compute_raw_covariance(raw_erms[kind])
    inverse_operator = mne.minimum_norm.make_inverse_operator(
        raws[kind].info, forward=fwd[kind], noise_cov=noise_cov, verbose=True)
    stc_psd, sensor_psd = mne.minimum_norm.compute_source_psd(
        raws[kind], inverse_operator, lambda2=lambda2,
        n_fft=n_fft, dB=False, return_sensor=True, verbose=True)
    topo_norm = sensor_psd.data.sum(axis=1, keepdims=True)
    stc_norm = stc_psd.sum()  # same operation on MNE object, sum across freqs
    # Normalize each source point by the total power across freqs
    for band, limits in freq_bands.items():
        data = sensor_psd.copy().crop(*limits).data.sum(axis=1, keepdims=True)
        topos[kind][band] = mne.EvokedArray(
            100 * data / topo_norm, sensor_psd.info)
        stcs[kind][band] = \
            100 * stc_psd.copy().crop(*limits).sum() / stc_norm.data
    del inverse_operator
del fwd, raws, raw_erms


I am working on the file "0.23/_downloads/b36af73820a7a52a4df3c42b66aef8a5/source_power_spectrum_opm.ipynb".
The first task is:
Compute source power spectral density (PSD) of VectorView and OPM data
Here we compute the resting state from raw for data recorded using
a Neuromag VectorView system and a custom OPM system.
The pipeline is meant to mostly follow the Brainstorm :footcite:TadelEtAl2011
OMEGA resting tutorial pipeline <bst_omega_>_.
The steps we use are:

Filtering: downsample heavily.
Artifact detection: use SSP for EOG and ECG.
Source localization: dSPM, depth weighting, cortically constrained.
Frequency: power spectral density (Welch), 4 sec window, 50% overlap.
Standardize: normalize by relative power for each source.

Preprocessing
Can you write Python code for it?

# Authors: Denis Engemann <denis.engemann@gmail.com>
#          Luke Bloy <luke.bloy@gmail.com>
#          Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)

import os.path as op

from mne.filter import next_fast_len

import mne

print(__doc__)

data_path = mne.datasets.opm.data_path()
subject = 'OPM_sample'

subjects_dir = op.join(data_path, 'subjects')
bem_dir = op.join(subjects_dir, subject, 'bem')
bem_fname = op.join(subjects_dir, subject, 'bem',
                    subject + '-5120-5120-5120-bem-sol.fif')
src_fname = op.join(bem_dir, '%s-oct6-src.fif' % subject)
vv_fname = data_path + '/MEG/SQUID/SQUID_resting_state.fif'
vv_erm_fname = data_path + '/MEG/SQUID/SQUID_empty_room.fif'
vv_trans_fname = data_path + '/MEG/SQUID/SQUID-trans.fif'
opm_fname = data_path + '/MEG/OPM/OPM_resting_state_raw.fif'
opm_erm_fname = data_path + '/MEG/OPM/OPM_empty_room_raw.fif'
opm_trans_fname = None
opm_coil_def_fname = op.join(data_path, 'MEG', 'OPM', 'coil_def.dat')


I am working on the file "0.23/_downloads/b36af73820a7a52a4df3c42b66aef8a5/source_power_spectrum_opm.ipynb".
The first task is:
Do some minimal artifact rejection just for VectorView data
Can you write Python code for it?

titles = dict(vv='VectorView', opm='OPM')
ssp_ecg, _ = mne.preprocessing.compute_proj_ecg(
    raws['vv'], tmin=-0.1, tmax=0.1, n_grad=1, n_mag=1)
raws['vv'].add_proj(ssp_ecg, remove_existing=True)
# due to how compute_proj_eog works, it keeps the old projectors, so
# the output contains both projector types (and also the original empty-room
# projectors)
ssp_ecg_eog, _ = mne.preprocessing.compute_proj_eog(
    raws['vv'], n_grad=1, n_mag=1, ch_name='MEG0112')
raws['vv'].add_proj(ssp_ecg_eog, remove_existing=True)
raw_erms['vv'].add_proj(ssp_ecg_eog)
fig = mne.viz.plot_projs_topomap(raws['vv'].info['projs'][-4:],
                                 info=raws['vv'].info)
fig.suptitle(titles['vv'])
fig.subplots_adjust(0.05, 0.05, 0.95, 0.85)


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

kinds = ('vv', 'opm')
n_fft = next_fast_len(int(round(4 * new_sfreq)))
print('Using n_fft=%d (%0.1f sec)' % (n_fft, n_fft / raws['vv'].info['sfreq']))
for kind in kinds:
    fig = raws[kind].plot_psd(n_fft=n_fft, proj=True)
    fig.suptitle(titles[kind])
    fig.subplots_adjust(0.1, 0.1, 0.95, 0.85)


I am working on the file "0.23/_downloads/b36af73820a7a52a4df3c42b66aef8a5/source_power_spectrum_opm.ipynb".
The first task is:
Gamma
Can you write Python code for it?

fig_gamma, brain_gamma = plot_band('vv', 'gamma')


I am working on the file "0.23/_downloads/b36af73820a7a52a4df3c42b66aef8a5/source_power_spectrum_opm.ipynb".
The first task is:
Load data, resample. We will store the raw objects in dicts with entries
"vv" and "opm" to simplify housekeeping and simplify looping later.
Can you write Python code for it?

raws = dict()
raw_erms = dict()
new_sfreq = 90.  # Nyquist frequency (45 Hz) < line noise freq (50 Hz)
raws['vv'] = mne.io.read_raw_fif(vv_fname, verbose='error')  # ignore naming
raws['vv'].load_data().resample(new_sfreq)
raws['vv'].info['bads'] = ['MEG2233', 'MEG1842']
raw_erms['vv'] = mne.io.read_raw_fif(vv_erm_fname, verbose='error')
raw_erms['vv'].load_data().resample(new_sfreq)
raw_erms['vv'].info['bads'] = ['MEG2233', 'MEG1842']

raws['opm'] = mne.io.read_raw_fif(opm_fname)
raws['opm'].load_data().resample(new_sfreq)
raw_erms['opm'] = mne.io.read_raw_fif(opm_erm_fname)
raw_erms['opm'].load_data().resample(new_sfreq)
# Make sure our assumptions later hold
assert raws['opm'].info['sfreq'] == raws['vv'].info['sfreq']


I am working on the file "0.23/_downloads/b6ccbb801939862ed915d2c7295ac245/sensor_permutation_test.ipynb".
The first task is:
Permutation T-test on sensor data
One tests if the signal significantly deviates from 0
during a fixed time window of interest. Here computation
is performed on MNE sample dataset between 40 and 60 ms.
Can you write Python code for it?

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

import numpy as np

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

print(__doc__)


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

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

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

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

temporal_mask = np.logical_and(0.04 <= times, times <= 0.06)
data = np.mean(data[:, :, temporal_mask], axis=2)

n_permutations = 50000
T0, p_values, H0 = permutation_t_test(data, n_permutations, n_jobs=1)

significant_sensors = picks[p_values <= 0.05]
significant_sensors_names = [raw.ch_names[k] for k in significant_sensors]

print("Number of significant sensors : %d" % len(significant_sensors))
print("Sensors names : %s" % significant_sensors_names)


I am working on the file "0.23/_downloads/b7659d33d6ffe8531d004e9d6051f16f/forward_sensitivity_maps.ipynb".
The first task is:
Compute sensitivity maps
Can you write Python code for it?

grad_map = mne.sensitivity_map(fwd, ch_type='grad', mode='fixed')
mag_map = mne.sensitivity_map(fwd, ch_type='mag', mode='fixed')
eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed')


I am working on the file "0.23/_downloads/b7659d33d6ffe8531d004e9d6051f16f/forward_sensitivity_maps.ipynb".
The first task is:
Sensitivity is likely to co-vary with the distance between sources to
sensors. To determine the strength of this relationship, we can compute the
correlation between source depth and sensitivity values.
Can you write Python code for it?

corr = np.corrcoef(depths, grad_map.data[:, 0])[0, 1]
print('Correlation between source depth and gradiomter sensitivity values: %f.'
      % corr)


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

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

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

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

brain_sens = grad_map.plot(
    subjects_dir=subjects_dir, clim=dict(lims=[0, 50, 100]), figure=1)
brain_sens.add_text(0.1, 0.9, 'Gradiometer sensitivity', 'title', font_size=16)


I am working on the file "0.23/_downloads/b89584de6ec99a847868d7b80a32cf50/80_dics.ipynb".
The first task is:
Before we simulate the sensor-level data, let's define a signal-to-noise
ratio. You are encouraged to play with this parameter and see the effect of
noise on our results.
Can you write Python code for it?

snr = 1.  # Signal-to-noise ratio. Decrease to add more noise.


I am working on the file "0.23/_downloads/b89584de6ec99a847868d7b80a32cf50/80_dics.ipynb".
The first task is:
Data simulation
The following function generates a timeseries that contains an oscillator,
whose frequency fluctuates a little over time, but stays close to 10 Hz.
We'll use this function to generate our two signals.
Can you write Python code for it?

sfreq = 50.  # Sampling frequency of the generated signal
n_samp = int(round(10. * sfreq))
times = np.arange(n_samp) / sfreq  # 10 seconds of signal
n_times = len(times)

def coh_signal_gen():
    """Generate an oscillating signal.

    Returns
    -------
    signal : ndarray
        The generated signal.
    """
    t_rand = 0.001  # Variation in the instantaneous frequency of the signal
    std = 0.1  # Std-dev of the random fluctuations added to the signal
    base_freq = 10.  # Base frequency of the oscillators in Hertz
    n_times = len(times)

    # Generate an oscillator with varying frequency and phase lag.
    signal = np.sin(2.0 * np.pi *
                    (base_freq * np.arange(n_times) / sfreq +
                     np.cumsum(t_rand * rand.randn(n_times))))

    # Add some random fluctuations to the signal.
    signal += std * rand.randn(n_times)

    # Scale the signal to be in the right order of magnitude (~100 nAm)
    # for MEG data.
    signal *= 100e-9

    return signal


I am working on the file "0.23/_downloads/b89584de6ec99a847868d7b80a32cf50/80_dics.ipynb".
The first task is:
Let's simulate two timeseries and plot some basic information about them.
Can you write Python code for it?

signal1 = coh_signal_gen()
signal2 = coh_signal_gen()

fig, axes = plt.subplots(2, 2, figsize=(8, 4))

# Plot the timeseries
ax = axes[0][0]
ax.plot(times, 1e9 * signal1, lw=0.5)
ax.set(xlabel='Time (s)', xlim=times[[0, -1]], ylabel='Amplitude (Am)',
       title='Signal 1')
ax = axes[0][1]
ax.plot(times, 1e9 * signal2, lw=0.5)
ax.set(xlabel='Time (s)', xlim=times[[0, -1]], title='Signal 2')

# Power spectrum of the first timeseries
f, p = welch(signal1, fs=sfreq, nperseg=128, nfft=256)
ax = axes[1][0]
# Only plot the first 100 frequencies
ax.plot(f[:100], 20 * np.log10(p[:100]), lw=1.)
ax.set(xlabel='Frequency (Hz)', xlim=f[[0, 99]],
       ylabel='Power (dB)', title='Power spectrum of signal 1')

# Compute the coherence between the two timeseries
f, coh = coherence(signal1, signal2, fs=sfreq, nperseg=100, noverlap=64)
ax = axes[1][1]
ax.plot(f[:50], coh[:50], lw=1.)
ax.set(xlabel='Frequency (Hz)', xlim=f[[0, 49]], ylabel='Coherence',
       title='Coherence between the timeseries')
fig.tight_layout()


I am working on the file "0.23/_downloads/b89584de6ec99a847868d7b80a32cf50/80_dics.ipynb".
The first task is:
Now we put the signals at two locations on the cortex. We construct a
:class:mne.SourceEstimate object to store them in.
The timeseries will have a part where the signal is active and a part where
it is not. The techniques we'll be using in this tutorial depend on being
able to contrast data that contains the signal of interest versus data that
does not (i.e. it contains only noise).
Can you write Python code for it?

# The locations on the cortex where the signal will originate from. These
# locations are indicated as vertex numbers.
vertices = [[146374], [33830]]

# Construct SourceEstimates that describe the signals at the cortical level.
data = np.vstack((signal1, signal2))
stc_signal = mne.SourceEstimate(
    data, vertices, tmin=0, tstep=1. / sfreq, subject='sample')
stc_noise = stc_signal * 0.


I am working on the file "0.23/_downloads/b89584de6ec99a847868d7b80a32cf50/80_dics.ipynb".
The first task is:
Plot the DICS power maps for both approaches, starting with the first:
Can you write Python code for it?

def plot_approach(power, n):
    """Plot the results on a brain."""
    title = 'DICS power map, approach %d' % n
    brain = power_approach1.plot(
        'sample', subjects_dir=subjects_dir, hemi='both',
        size=600, time_label=title, title=title)
    # Indicate the true locations of the source activity on the plot.
    brain.add_foci(vertices[0][0], coords_as_verts=True, hemi='lh', color='b')
    brain.add_foci(vertices[1][0], coords_as_verts=True, hemi='rh', color='b')
    # Rotate the view and add a title.
    brain.show_view(view={'azimuth': 0, 'elevation': 0, 'distance': 550,
                          'focalpoint': [0, 0, 0]})
    return brain

brain1 = plot_approach(power_approach1, 1)


I am working on the file "0.23/_downloads/b89584de6ec99a847868d7b80a32cf50/80_dics.ipynb".
The first task is:
Setup
We first import the required packages to run this tutorial and define a list
of filenames for various things we'll be using.
Can you write Python code for it?

import os.path as op
import numpy as np
from scipy.signal import welch, coherence, unit_impulse
from matplotlib import pyplot as plt

import mne
from mne.simulation import simulate_raw, add_noise
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
from mne.time_frequency import csd_morlet
from mne.beamformer import make_dics, apply_dics_csd

# We use the MEG and MRI setup from the MNE-sample dataset
data_path = sample.data_path(download=False)
subjects_dir = op.join(data_path, 'subjects')

# Filenames for various files we'll be using
meg_path = op.join(data_path, 'MEG', 'sample')
raw_fname = op.join(meg_path, 'sample_audvis_raw.fif')
fwd_fname = op.join(meg_path, 'sample_audvis-meg-eeg-oct-6-fwd.fif')
cov_fname = op.join(meg_path, 'sample_audvis-cov.fif')
fwd = mne.read_forward_solution(fwd_fname)

# Seed for the random number generator
rand = np.random.RandomState(42)


I am working on the file "0.23/_downloads/b89584de6ec99a847868d7b80a32cf50/80_dics.ipynb".
The first task is:
We will now compute the cortical power map at 10 Hz. using a DICS beamformer.
A beamformer will construct for each vertex a spatial filter that aims to
pass activity originating from the vertex, while dampening activity from
other sources as much as possible.
The :func:mne.beamformer.make_dics function has many switches that offer
precise control
over the way the filter weights are computed. Currently, there is no clear
consensus regarding the best approach. This is why we will demonstrate two
approaches here:

The approach as described in :footcite:vanVlietEtAl2018, which first
    normalizes the forward solution and computes a vector beamformer.
The scalar beamforming approach based on
    :footcite:SekiharaNagarajan2008, which uses weight normalization
    instead of normalizing the forward solution.
Can you write Python code for it?

# Estimate the cross-spectral density (CSD) matrix on the trial containing the
# signal.
csd_signal = csd_morlet(epochs['signal'], frequencies=[10])

# Compute the spatial filters for each vertex, using two approaches.
filters_approach1 = make_dics(
    info, fwd, csd_signal, reg=0.05, pick_ori='max-power', depth=1.,
    inversion='single', weight_norm=None, real_filter=True)
print(filters_approach1)

filters_approach2 = make_dics(
    info, fwd, csd_signal, reg=0.05, pick_ori='max-power', depth=None,
    inversion='matrix', weight_norm='unit-noise-gain', real_filter=True)
print(filters_approach2)

# You can save these to disk with:
# filters_approach1.save('filters_1-dics.h5')

# Compute the DICS power map by applying the spatial filters to the CSD matrix.
power_approach1, f = apply_dics_csd(csd_signal, filters_approach1)
power_approach2, f = apply_dics_csd(csd_signal, filters_approach2)


I am working on the file "0.23/_downloads/b96d98f7c704193a3ede176aaf9433d2/85_brainstorm_phantom_ctf.ipynb".
The first task is:
Brainstorm CTF phantom dataset tutorial
Here we compute the evoked from raw for the Brainstorm CTF phantom
tutorial dataset. For comparison, see :footcite:TadelEtAl2011 and:
https://neuroimage.usc.edu/brainstorm/Tutorials/PhantomCtf

References
.. footbibliography::
Can you write Python code for it?

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

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

import mne
from mne import fit_dipole
from mne.datasets.brainstorm import bst_phantom_ctf
from mne.io import read_raw_ctf

print(__doc__)


I am working on the file "0.23/_downloads/b96d98f7c704193a3ede176aaf9433d2/85_brainstorm_phantom_ctf.ipynb".
The first task is:
But here we can get slightly better noise suppression, lower localization
bias, and a better dipole goodness of fit with spatio-temporal (tSSS)
Maxwell filtering:
Can you write Python code for it?

raw.apply_gradient_compensation(0)  # must un-do software compensation first
mf_kwargs = dict(origin=(0., 0., 0.), st_duration=10.)
raw = mne.preprocessing.maxwell_filter(raw, **mf_kwargs)
raw.plot()


I am working on the file "0.23/_downloads/b96d98f7c704193a3ede176aaf9433d2/85_brainstorm_phantom_ctf.ipynb".
The first task is:
Compare the actual position with the estimated one.
Can you write Python code for it?

expected_pos = np.array([18., 0., 49.])
diff = np.sqrt(np.sum((dip.pos[0] * 1000 - expected_pos) ** 2))
print('Actual pos:     %s mm' % np.array_str(expected_pos, precision=1))
print('Estimated pos:  %s mm' % np.array_str(dip.pos[0] * 1000, precision=1))
print('Difference:     %0.1f mm' % diff)
print('Amplitude:      %0.1f nAm' % (1e9 * dip.amplitude[0]))
print('GOF:            %0.1f %%' % dip.gof[0])


I am working on the file "0.23/_downloads/b96d98f7c704193a3ede176aaf9433d2/85_brainstorm_phantom_ctf.ipynb".
The first task is:
Let's create some events using this signal by thresholding the sinusoid.
Can you write Python code for it?

events = np.where(np.diff(sinusoid > 0.5) > 0)[1] + raw.first_samp
events = np.vstack((events, np.zeros_like(events), np.ones_like(events))).T


I am working on the file "0.23/_downloads/b96d98f7c704193a3ede176aaf9433d2/85_brainstorm_phantom_ctf.ipynb".
The first task is:
Let's use a sphere head geometry model <eeg_sphere_model>
and let's see the coordinate alignment and the sphere location.
Can you write Python code for it?

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

mne.viz.plot_alignment(raw.info, subject='sample',
                       meg='helmet', bem=sphere, dig=True,
                       surfaces=['brain'])
del raw, epochs


I am working on the file "0.23/_downloads/b96d98f7c704193a3ede176aaf9433d2/85_brainstorm_phantom_ctf.ipynb".
The first task is:
The sinusoidal signal is generated on channel HDAC006, so we can use
that to obtain precise timing.
Can you write Python code for it?

sinusoid, times = raw[raw.ch_names.index('HDAC006-4408')]
plt.figure()
plt.plot(times[times < 1.], sinusoid.T[times < 1.])


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

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

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


I am working on the file "0.23/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
Aside from the fact that the data for the (much fewer) slow responses looks
noisier – which is entirely to be expected – not much of an ERP difference
can be seen.
Applying the knowledge: visualizing the ERN component
In the following analysis, we will use the same dataset as above, but
we'll time-lock our epochs to the response events, not to the stimulus
onset. Comparing ERPs associated with correct and incorrect behavioral
responses, we should be able to see the error-related negativity (ERN) in
the difference wave.
Since we want to time-lock our analysis to responses, for the automated
metadata generation we'll consider events occurring up to 1500 ms before
the response trigger.
We only wish to consider the last stimulus and response in each time
window: Remember that we're dealing with rapid stimulus presentations in
this paradigm; taking the last response – at time point zero – and the last
stimulus – the one closest to the response – ensures we actually create
the right stimulus-response pairings. We can achieve this by passing the
keep_last parameter, which works exactly like keep_first we got to
know above, only that it keeps the last occurrences of the specified
events and stores them in columns whose names start with last_.
Can you write Python code for it?

metadata_tmin, metadata_tmax = -1.5, 0
row_events = ['response/left', 'response/right']
keep_last = ['stimulus', 'response']

metadata, events, event_id = mne.epochs.make_metadata(
    events=all_events, event_id=all_event_id,
    tmin=metadata_tmin, tmax=metadata_tmax, sfreq=raw.info['sfreq'],
    row_events=row_events,
    keep_last=keep_last)


I am working on the file "0.23/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
Auto-generating Epochs metadata
This tutorial shows how to auto-generate metadata for ~mne.Epochs, based on
events via mne.epochs.make_metadata.
We are going to use data from the erp-core-dataset (derived from
:footcite:Kappenman2021). This is EEG data from a single participant
performing an active visual task (Eriksen flanker task).

Note

If you wish to skip the introductory parts of this tutorial, you may jump
   straight to `tut-autogenerate-metadata-ern` after completing the data
   import and event creation in the
   `tut-autogenerate-metadata-preparation` section.

This tutorial is loosely divided into two parts:

We will first focus on producing ERP time-locked to the visual
   stimulation, conditional on response correctness and response time in
   order to familiarize ourselves with the ~mne.epochs.make_metadata
   function.
After that, we will calculate ERPs time-locked to the responses – again,
   conditional on response correctness – to visualize the error-related
   negativity (ERN), i.e. the ERP component associated with incorrect
   behavioral responses.

Preparation
Let's start by reading, filtering, and producing a simple visualization of the
raw data. The data is pretty clean and contains very few blinks, so there's no
need to apply sophisticated preprocessing and data cleaning procedures.
We will also convert the ~mne.Annotations contained in this dataset to events
by calling mne.events_from_annotations.
Can you write Python code for it?

from pathlib import Path
import matplotlib.pyplot as plt
import mne

data_dir = Path(mne.datasets.erp_core.data_path())
infile = data_dir / 'ERP-CORE_Subject-001_Task-Flankers_eeg.fif'

raw = mne.io.read_raw(infile, preload=True)
raw.filter(l_freq=0.1, h_freq=40)
raw.plot(start=60)

# extract events
all_events, all_event_id = mne.events_from_annotations(raw)


I am working on the file "0.23/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
Creating Epochs with metadata, and visualizing ERPs
It's finally time to create our epochs! We set the metadata directly on
instantiation via the metadata parameter. Also it is important to
remember to pass events and event_id as returned from
~mne.epochs.make_metadata, as we only created metadata for a subset of
our original events by passing row_events. Otherwise, the length
of the metadata and the number of epochs would not match and MNE-Python
would raise an error.
Can you write Python code for it?

epochs_tmin, epochs_tmax = -0.1, 0.4  # epochs range: [-0.1, 0.4] s
reject = {'eeg': 250e-6}  # exclude epochs with strong artifacts
epochs = mne.Epochs(raw=raw, tmin=epochs_tmin, tmax=epochs_tmax,
                    events=events, event_id=event_id, metadata=metadata,
                    reject=reject, preload=True)


I am working on the file "0.23/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
Creating metadata from events
The basics of make_metadata
Now it's time to think about the time windows to use for epoching and
metadata generation. It is important to understand that these time windows
need not be the same! That is, the automatically generated metadata might
include information about events from only a fraction of the epochs duration;
or it might include events that occurred well outside a given epoch.
Let us look at a concrete example. In the Flankers task of the ERP CORE
dataset, participants were required to respond to visual stimuli by pressing
a button. We're interested in looking at the visual evoked responses (ERPs)
of trials with correct responses. Assume that based on literature
studies, we decide that responses later than 1500 ms after stimulus onset are
to be considered invalid, because they don't capture the neuronal processes
of interest here. We can approach this  in the following way with the help of
mne.epochs.make_metadata:
Can you write Python code for it?

# metadata for each epoch shall include events from the range: [0.0, 1.5] s,
# i.e. starting with stimulus onset and expanding beyond the end of the epoch
metadata_tmin, metadata_tmax = 0.0, 1.5

# auto-create metadata
# this also returns a new events array and an event_id dictionary. we'll see
# later why this is important
metadata, events, event_id = mne.epochs.make_metadata(
    events=all_events, event_id=all_event_id,
    tmin=metadata_tmin, tmax=metadata_tmax, sfreq=raw.info['sfreq'])

# let's look at what we got!
metadata


I am working on the file "0.23/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
Lastly, let's visualize the ERPs evoked by the visual stimulation, once for
all trials with correct responses, and once for all trials with correct
responses and a response time greater than 0.5 seconds
(i.e., slow responses).
Can you write Python code for it?

vis_erp = epochs['response_correct'].average()
vis_erp_slow = epochs['(not response_correct) & '
                      '(response > 0.3)'].average()

fig, ax = plt.subplots(2, figsize=(6, 6))
vis_erp.plot(gfp=True, spatial_colors=True, axes=ax[0])
vis_erp_slow.plot(gfp=True, spatial_colors=True, axes=ax[1])
ax[0].set_title('Visual ERPs – All Correct Responses')
ax[1].set_title('Visual ERPs – Slow Correct Responses')
fig.tight_layout()
fig


I am working on the file "0.23/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
Now it's already time to epoch the data! When deciding upon the epochs
duration for this specific analysis, we need to ensure we see quite a bit of
signal from before and after the motor response. We also must be aware of
the fact that motor-/muscle-related signals will most likely be present
before the response button trigger pulse appears in our data, so the time
period close to the response event should not be used for baseline
correction. But at the same time, we don't want to use a baseline
period that extends too far away from the button event. The following values
seem to work quite well.
Can you write Python code for it?

epochs_tmin, epochs_tmax = -0.6, 0.4
baseline = (-0.4, -0.2)
reject = {'eeg': 250e-6}
epochs = mne.Epochs(raw=raw, tmin=epochs_tmin, tmax=epochs_tmax,
                    baseline=baseline, reject=reject,
                    events=events, event_id=event_id, metadata=metadata,
                    preload=True)


I am working on the file "0.23/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
This can easily lead to confusion during later stages of processing, so let's
create a column for the first stimulus – which will always be the time-locked
stimulus, as our time interval starts at 0 seconds. We can pass a list of
strings to keep_first.
Can you write Python code for it?

keep_first = ['stimulus', 'response']
metadata, events, event_id = mne.epochs.make_metadata(
    events=all_events, event_id=all_event_id,
    tmin=metadata_tmin, tmax=metadata_tmax, sfreq=raw.info['sfreq'],
    row_events=row_events,
    keep_first=keep_first)

# all times of the time-locked events should be zero
assert all(metadata['stimulus'] == 0)

# the values in the new "first_stimulus" and "first_response" columns indicate
# which events were selected via "keep_first"
metadata[['first_stimulus', 'first_response']]


I am working on the file "0.23/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
We can see a strong negative deflection immediately after incorrect
responses, compared to correct responses. The topoplot, too, leaves no doubt:
what we're looking at is, in fact, the ERN.
Some researchers suggest to construct the difference wave between ERPs for
correct and incorrect responses, as it more clearly reveals signal
differences, while ideally also improving the signal-to-noise ratio (under
the assumption that the noise level in "correct" and "incorrect" trials is
similar). Let's do just that and put it into a publication-ready
visualization.
Can you write Python code for it?

# difference wave: incorrect minus correct responses
resp_erp_diff = mne.combine_evoked([resp_erp_incorrect, resp_erp_correct],
                                   weights=[1, -1])

fig, ax = plt.subplots()
resp_erp_diff.plot(picks='FCz', axes=ax, selectable=False, show=False)

# make ERP trace bolder
ax.lines[0].set_linewidth(1.5)

# add lines through origin
ax.axhline(0, ls='dotted', lw=0.75, color='gray')
ax.axvline(0, ls=(0, (10, 10)), lw=0.75, color='gray',
           label='response trigger')

# mark trough
trough_time_idx = resp_erp_diff.copy().pick('FCz').data.argmin()
trough_time = resp_erp_diff.times[trough_time_idx]
ax.axvline(trough_time, ls=(0, (10, 10)), lw=0.75, color='red',
           label='max. negativity')

# legend, axis labels, title
ax.legend(loc='lower left')
ax.set_xlabel('Time (s)', fontweight='bold')
ax.set_ylabel('Amplitude (µV)', fontweight='bold')
ax.set_title('Channel: FCz')
fig.suptitle('ERN (Difference Wave)', fontweight='bold')

fig


I am working on the file "0.23/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
We're facing a similar issue with the stimulus events, and now there are not
only two, but four different types: stimulus/compatible/target_left,
stimulus/compatible/target_right, stimulus/incompatible/target_left,
and stimulus/incompatible/target_right. Even more, because in the present
paradigm stimuli were presented in rapid succession, sometimes multiple
stimulus events occurred within the 1.5 second time window we're using to
generate our metadata. See for example:
Can you write Python code for it?

metadata.loc[metadata['stimulus/compatible/target_left'].notna() &
             metadata['stimulus/compatible/target_right'].notna(),
             :]


I am working on the file "0.23/_downloads/bcaf3ed1f43ea7377c6c0b00137d728f/custom_inverse_solver.ipynb".
The first task is:
Apply your custom solver
Can you write Python code for it?

# loose, depth = 0.2, 0.8  # corresponds to loose orientation
loose, depth = 1., 0.  # corresponds to free orientation
stc = apply_solver(solver, evoked, forward, noise_cov, loose, depth)


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

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

    This function does all the necessary computation:

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

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

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

    all_ch_names = evoked.ch_names

    # Handle...


I am working on the file "0.23/_downloads/bcaf3ed1f43ea7377c6c0b00137d728f/custom_inverse_solver.ipynb".
The first task is:
Define your solver
Can you write Python code for it?

def solver(M, G, n_orient):
    """Run L2 penalized regression and keep 10 strongest locations.

    Parameters
    ----------
    M : array, shape (n_channels, n_times)
        The whitened data.
    G : array, shape (n_channels, n_dipoles)
        The gain matrix a.k.a. the forward operator. The number of locations
        is n_dipoles / n_orient. n_orient will be 1 for a fixed orientation
        constraint or 3 when using a free orientation model.
    n_orient : int
        Can be 1 or 3 depending if one works with fixed or free orientations.
        If n_orient is 3, then ``G[:, 2::3]`` corresponds to the dipoles that
        are normal to the cortex.

    Returns
    -------
    X : array, (n_active_dipoles, n_times)
        The time series of the dipoles in the active set.
    active_set : array (n_dipoles)
        Array of bool. Entry j is True if dipole j is in the active set.
        We have ``X_full[active_set] == X`` where X_full is the full X matrix
        such that ``M = G X_full``.
    """
    inner = np.dot(G, G.T)
    trace = np.trace(inner)
    K = linalg.solve(inner + 4e-6 * trace * np.eye(G.shape[0]), G).T
    K /= np.linalg.norm(K, axis=1)[:, None]
    X = np.dot(K, M)

    indices = np.argsort(np.sum(X ** 2, axis=1))[-10:]
    active_set = np.zeros(G.shape[1], dtype=bool)
    for idx in indices:
        idx -= idx % n_orient
        active_set[idx:idx + n_orient] = True
    X = X[active_set]
    return X, active_set


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
.. sidebar:: Head coordinate frame
 The head coordinate frame in MNE is the "Neuromag" head coordinate
 frame. The origin is given by the intersection between a line connecting
 the LPA and RPA and the line orthogonal to it that runs through the
 nasion. It is also in RAS orientation, meaning that +X runs through
 the RPA, +Y goes through the nasion, and +Z is orthogonal to these
 pointing upward. See `coordinate_systems` for more information.

Notice that in "head" coordinate frame the nasion has values of 0 for the
x and z directions (which makes sense given that the nasion is used
to define the y axis in that system).
To convert from head coordinate frame to voxels, we first apply the head →
MRI (surface RAS) transform
from a :file:trans file (typically created with the MNE-Python
coregistration GUI), then convert meters → millimeters, and finally apply the
inverse of Torig to get to voxels.
Under the hood, functions like :func:mne.setup_source_space,
:func:mne.setup_volume_source_space, and :func:mne.compute_source_morph
make extensive use of these coordinate frames.
Can you write Python code for it?

trans = mne.read_trans(
    os.path.join(data_path, 'MEG', 'sample', 'sample_audvis_raw-trans.fif'))

# first we transform from head to MRI, and *then* convert to millimeters
nasion_dig_mri = apply_trans(trans, nasion_head['r']) * 1000

# ...then we can use Torig to convert MRI to voxels:
nasion_dig_vox = np.round(
    apply_trans(np.linalg.inv(Torig), nasion_dig_mri)).astype(int)
imshow_mri(data, t1, nasion_dig_vox, dict(MRI=nasion_dig_mri),
           'Nasion transformed from digitization')


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:

Warning

Some source space vertices can be removed during forward computation.
   See `tut-forward` for more information.

FreeSurfer's MNI affine transformation
In addition to surface-based approaches, FreeSurfer also provides a simple
affine coregistration of each subject's data to the fsaverage subject.
Let's pick a point for sample and plot it on the brain:
Can you write Python code for it?

brain = mne.viz.Brain('sample', 'lh', 'white', subjects_dir=subjects_dir,
                      background='w')
xyz = np.array([[-55, -10, 35]])
brain.add_foci(xyz, hemi='lh', color='k')
brain.show_view('lat')


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
And because fsaverage is special in that it's already in MNI space
(its MRI-to-MNI transform is identity), it should land in the equivalent
anatomical location:
Can you write Python code for it?

brain = mne.viz.Brain('fsaverage', 'lh', 'white', subjects_dir=subjects_dir,
                      background='w')
brain.add_foci(xyz_mni, hemi='lh', color='k')
brain.show_view('lat')


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
How MNE uses FreeSurfer's outputs
This tutorial explains how MRI coordinate frames are handled in MNE-Python,
and how MNE-Python integrates with FreeSurfer for handling MRI data and
source space data in general.
As usual we'll start by importing the necessary packages; for this tutorial
that includes :mod:nibabel to handle loading the MRI images (MNE-Python also
uses :mod:nibabel under the hood). We'll also use a special :mod:Matplotlib
<matplotlib.patheffects> function for adding outlines to text, so that text is
readable on top of an MRI image.
Can you write Python code for it?

import os

import numpy as np
import nibabel
import matplotlib.pyplot as plt
import matplotlib.patheffects as path_effects

import mne
from mne.transforms import apply_trans
from mne.io.constants import FIFF


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
If you have a point (x, y, z) in scanner-native RAS space and you want
the corresponding voxel number, you can get it using the inverse of the
affine. This involves some rounding, so it's possible to end up off by one
voxel if you're not careful:
Can you write Python code for it?

ras_coords_mm = np.array([1, -17, -18])
inv_affine = np.linalg.inv(t1.affine)
i_, j_, k_ = np.round(apply_trans(inv_affine, ras_coords_mm)).astype(int)
print('Our real-world coordinates correspond to voxel ({}, {}, {})'
      .format(i_, j_, k_))


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
Knowing these relationships and being mindful about transformations, we
can get from a point in any given space to any other space. Let's start out
by plotting the Nasion on a saggital MRI slice:
Can you write Python code for it?

fiducials = mne.coreg.get_mni_fiducials(subject, subjects_dir=subjects_dir)
nasion_mri = [d for d in fiducials if d['ident'] == FIFF.FIFFV_POINT_NASION][0]
print(nasion_mri)  # note it's in Freesurfer MRI coords


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
Let's actually plot it:
Can you write Python code for it?

renderer = mne.viz.backends.renderer.create_3d_figure(
    size=(600, 600), bgcolor='w', scene=False)
gray = (0.5, 0.5, 0.5)
renderer.mesh(*rr_mm.T, triangles=tris, color=gray)
view_kwargs = dict(elevation=90, azimuth=0)
mne.viz.set_3d_view(
    figure=renderer.figure, distance=350, focalpoint=(0., 0., 40.),
    **view_kwargs)
renderer.show()


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
Let's look a bit more closely at the spherical alignment by overlaying the
two spherical meshes as wireframes and zooming way in (the purple points are
separated by about 1 mm):
Can you write Python code for it?

cyan = '#66CCEE'
purple = '#AA3377'
renderer = mne.viz.backends.renderer.create_3d_figure(
    size=(800, 800), scene=False, **renderer_kwargs)
fnames = [os.path.join(subjects_dir, subj, 'surf', 'rh.sphere')
          for subj in ('sample', 'fsaverage')]
colors = [cyan, purple]
for name, color in zip(fnames, colors):
    this_rr, this_tri = mne.read_surface(name)
    renderer.mesh(*this_rr.T, triangles=this_tri, color=color,
                  representation='wireframe')
mne.viz.set_3d_view(figure=renderer.figure, distance=20, **view_kwargs)
renderer.show()


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
Let's write a short function to visualize where our voxel lies in an
image, and annotate it in RAS space (rounded to the nearest millimeter):
Can you write Python code for it?

def imshow_mri(data, img, vox, xyz, suptitle):
    """Show an MRI slice with a voxel annotated."""
    i, j, k = vox
    fig, ax = plt.subplots(1, figsize=(6, 6))
    codes = nibabel.orientations.aff2axcodes(img.affine)
    # Figure out the title based on the code of this axis
    ori_slice = dict(P='Coronal', A='Coronal',
                     I='Axial', S='Axial',
                     L='Sagittal', R='Saggital')
    ori_names = dict(P='posterior', A='anterior',
                     I='inferior', S='superior',
                     L='left', R='right')
    title = ori_slice[codes[0]]
    ax.imshow(data[i], vmin=10, vmax=120, cmap='gray', origin='lower')
    ax.axvline(k, color='y')
    ax.axhline(j, color='y')
    for kind, coords in xyz.items():
        annotation = ('{}: {}, {}, {} mm'
                      .format(kind, *np.round(coords).astype(int)))
        text = ax.text(k, j, annotation, va='baseline', ha='right',
                       color=(1, 1, 0.7))
        text.set_path_effects([
            path_effects.Stroke(linewidth=2, foreground='black'),
            path_effects.Normal()])
    # reorient view so that RAS is always rightward and upward
    x_order = -1 if codes[2] in 'LIP' else 1
    y_order = -1 if codes[1] in 'LIP' else 1
    ax.set(xlim=[0, data.shape[2] - 1][::x_order],
           ylim=[0, data.shape[1] - 1][::y_order],
           xlabel=f'k ({ori_names[codes[2]]}+)',
           ylabel=f'j ({ori_names[codes[1]]}+)',
           title=f'{title} view: i={i} ({ori_names[codes[0]]}+)')
    fig.suptitle(suptitle)
    fig.subplots_adjust(0.1, 0.1, 0.95, 0.85)
    return fig

imshow_mri(data, t1, vox, {'Scanner RAS': xyz_ras}, 'MRI slice')


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
Notice that the axes in the
:meth:~nibabel.spatialimages.SpatialImage.orthoview figure are labeled
L-R, S-I, and P-A. These reflect the standard RAS (right-anterior-superior)
coordinate system that is widely used in MRI imaging. If you are unfamiliar
with RAS coordinates, see the excellent nibabel tutorial
:doc:nibabel:coordinate_systems.
Nibabel already takes care of some coordinate frame transformations under the
hood, so let's do it manually so we understand what is happening. First let's
get our data as a 3D array and note that it's already a standard size:
Can you write Python code for it?

data = np.asarray(t1.dataobj)
print(data.shape)


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
Using FreeSurfer's surface reconstructions
An important part of what FreeSurfer does is provide cortical surface
reconstructions. For example, let's load and view the white surface
of the brain. This is a 3D mesh defined by a set of vertices (conventionally
called rr) with shape (n_vertices, 3) and a set of triangles
(tris) with shape (n_tris, 3) defining which vertices in rr form
each triangular facet of the mesh.
Can you write Python code for it?

fname = os.path.join(subjects_dir, subject, 'surf', 'rh.white')
rr_mm, tris = mne.read_surface(fname)
print(f'rr_mm.shape == {rr_mm.shape}')
print(f'tris.shape == {tris.shape}')
print(f'rr_mm.max() = {rr_mm.max()}')  # just to show that we are in mm


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
We can also plot the mesh on top of an MRI slice. The mesh surfaces are
defined in millimeters in the MRI (FreeSurfer surface RAS) coordinate frame,
so we can convert them to voxels by applying the inverse of the Torig
transform:
Can you write Python code for it?

rr_vox = apply_trans(np.linalg.inv(Torig), rr_mm)
fig = imshow_mri(data, t1, vox, {'Scanner RAS': xyz_ras}, 'MRI slice')
# Based on how imshow_mri works, the "X" here is the last dim of the MRI vol,
# the "Y" is the middle dim, and the "Z" is the first dim, so now that our
# points are in the correct coordinate frame, we need to ask matplotlib to
# do a tricontour slice like:
fig.axes[0].tricontour(rr_vox[:, 2], rr_vox[:, 1], tris, rr_vox[:, 0],
                       levels=[vox[0]], colors='r', linewidths=1.0,
                       zorder=1)


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
We can also take the digitization point from the MEG data, which is in the
"head" coordinate frame.
Let's look at the nasion in the head coordinate frame:
Can you write Python code for it?

info = mne.io.read_info(
    os.path.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif'))
nasion_head = [d for d in info['dig'] if
               d['kind'] == FIFF.FIFFV_POINT_CARDINAL and
               d['ident'] == FIFF.FIFFV_POINT_NASION][0]
print(nasion_head)  # note it's in "head" coordinates


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
We can take this point and transform it to MNI space:
Can you write Python code for it?

mri_mni_trans = mne.read_talxfm(subject, subjects_dir)
print(mri_mni_trans)
xyz_mni = apply_trans(mri_mni_trans, xyz / 1000.) * 1000.
print(np.round(xyz_mni, 1))


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
When we print the nasion, it displays as a DigPoint and shows its
coordinates in millimeters, but beware that the underlying data is
actually stored in meters <units>,
so before transforming and plotting we'll convert to millimeters:
Can you write Python code for it?

nasion_mri = nasion_mri['r'] * 1000  # meters → millimeters
nasion_vox = np.round(
    apply_trans(np.linalg.inv(Torig), nasion_mri)).astype(int)
imshow_mri(data, t1, nasion_vox, dict(MRI=nasion_mri),
           'Nasion estimated from MRI transform')


I am working on the file "0.23/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
You can see that the fsaverage (purple) mesh is uniformly spaced, and the
mesh for subject "sample" (in cyan) has been deformed along the spherical
surface by
FreeSurfer. This deformation is designed to optimize the sulcal-gyral
alignment.
Surface decimation
These surfaces have a lot of vertices, and in general we only need to use
a subset of these vertices for creating source spaces. A uniform sampling can
easily be achieved by subsampling in the spherical space. To do this, we
use a recursively subdivided icosahedron or octahedron. For example, let's
load a standard oct-6 source space, and at the same zoom level as before
visualize how it subsampled the dense mesh:
Can you write Python code for it?

src = mne.read_source_spaces(os.path.join(subjects_dir, 'sample', 'bem',
                                          'sample-oct-6-src.fif'))
print(src)

blue = '#4477AA'
renderer = mne.viz.backends.renderer.create_3d_figure(
    size=(800, 800), scene=False, **renderer_kwargs)
rr_sph, _ = mne.read_surface(fnames[0])
for tris, color in [(src[1]['tris'], cyan), (src[1]['use_tris'], blue)]:
    renderer.mesh(*rr_sph.T, triangles=tris, color=color,
                  representation='wireframe')
mne.viz.set_3d_view(figure=renderer.figure, distance=20, **view_kwargs)
renderer.show()


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

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

import os.path as op

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.connectivity import envelope_correlation
from mne.minimum_norm import make_inverse_operator, apply_inverse_epochs
from mne.preprocessing import compute_proj_ecg, compute_proj_eog

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


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

labels = mne.read_labels_from_annot(subject, 'aparc_sub',
                                    subjects_dir=subjects_dir)
epochs.apply_hilbert()  # faster to apply in sensor space
stcs = apply_inverse_epochs(epochs, inv, lambda2=1. / 9., pick_ori='normal',
                            return_generator=True)
label_ts = mne.extract_label_time_course(
    stcs, labels, inv['src'], return_generator=True)
corr = envelope_correlation(label_ts, verbose=True)

# let's plot this matrix
fig, ax = plt.subplots(figsize=(4, 4))
ax.imshow(corr, cmap='viridis', clim=np.percentile(corr, [5, 95]))
fig.tight_layout()


I am working on the file "0.23/_downloads/c129e399417e02679103f64ce31da37e/mne_inverse_envelope_correlation.ipynb".
The first task is:
Now we band-pass filter our data and create epochs.
Can you write Python code for it?

raw.filter(14, 30)
events = mne.make_fixed_length_events(raw, duration=5.)
epochs = mne.Epochs(raw, events=events, tmin=0, tmax=5.,
                    baseline=None, reject=dict(mag=8e-13), preload=True)
del raw


I am working on the file "0.23/_downloads/c1dad3cf15579a4724c19d6df916b111/mixed_norm_inverse.ipynb".
The first task is:
Compute sparse inverse solution with mixed norm: MxNE and irMxNE
Runs an (ir)MxNE (L1/L2 :footcite:GramfortEtAl2012 or L0.5/L2
:footcite:StrohmeierEtAl2014 mixed norm) inverse solver.
L0.5/L2 is done with irMxNE which allows for sparser source estimates with less
amplitude bias due to the non-convexity of the L0.5/L2 mixed norm penalty.
Can you write Python code for it?

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

import numpy as np

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

print(__doc__)

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

# Read noise covariance matrix
cov = mne.read_cov(cov_fname)
# Handling average file
condition = 'Left Auditory'
evoked = mne.read_evokeds(ave_fname, condition=condition, baseline=(None, 0))
evoked.crop(tmin=0, tmax=0.3)
# Handling forward solution
forward = mne.read_forward_solution(fwd_fname)


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

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


I am working on the file "0.23/_downloads/c1dad3cf15579a4724c19d6df916b111/mixed_norm_inverse.ipynb".
The first task is:
Morph onto fsaverage brain and view
Can you write Python code for it?

morph = mne.compute_source_morph(stc, subject_from='sample',
                                 subject_to='fsaverage', spacing=None,
                                 sparse=True, subjects_dir=subjects_dir)
stc_fsaverage = morph.apply(stc)
src_fsaverage_fname = subjects_dir + '/fsaverage/bem/fsaverage-ico-5-src.fif'
src_fsaverage = mne.read_source_spaces(src_fsaverage_fname)

plot_sparse_source_estimates(src_fsaverage, stc_fsaverage, bgcolor=(1, 1, 1),
                             fig_name="Morphed %s (cond %s)" % (solver,
                             condition), opacity=0.1)


I am working on the file "0.23/_downloads/c1dad3cf15579a4724c19d6df916b111/mixed_norm_inverse.ipynb".
The first task is:
Plot dipole activations
Can you write Python code for it?

plot_dipole_amplitudes(dipoles)

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

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


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

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


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

alpha = 55  # regularization parameter between 0 and 100 (100 is high)
loose, depth = 0.2, 0.9  # loose orientation & depth weighting
n_mxne_iter = 10  # if > 1 use L0.5/L2 reweighted mixed norm solver
# if n_mxne_iter > 1 dSPM weighting can be avoided.

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

# Compute (ir)MxNE inverse solution with dipole output
dipoles, residual = mixed_norm(
    evoked, forward, cov, alpha, loose=loose, depth=depth, maxit=3000,
    tol=1e-4, active_set_size=10, debias=True, weights=stc_dspm,
    weights_min=8., n_mxne_iter=n_mxne_iter, return_residual=True,
    return_as_dipoles=True, verbose=True)

t = 0.083
tidx = evoked.time_as_index(t)
for di, dip in enumerate(dipoles, 1):
    print(f'Dipole #{di} GOF at {1000 * t:0.1f} ms: '
          f'{float(dip.gof[tidx]):0.1f}%')


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

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


I am working on the file "0.23/_downloads/c37ac181bfe2eb2f1fa69c3fab30417d/mne_cov_power.ipynb".
The first task is:
And visualize power is relative to the baseline:
Can you write Python code for it?

stc_data /= stc_base
brain = stc_data.plot(subject='sample', subjects_dir=subjects_dir,
                      clim=dict(kind='percent', lims=(50, 90, 98)))


I am working on the file "0.23/_downloads/c37ac181bfe2eb2f1fa69c3fab30417d/mne_cov_power.ipynb".
The first task is:
Compute source power estimate by projecting the covariance with MNE
We can apply the MNE inverse operator to a covariance matrix to obtain
an estimate of source power. This is computationally more efficient than first
estimating the source timecourses and then computing their power. This
code is based on the code from :footcite:Sabbagh2020 and has been useful to
correct for individual field spread using source localization in the context of
predictive modeling.
References
.. footbibliography::
Can you write Python code for it?

# Author: Denis A. Engemann <denis-alexander.engemann@inria.fr>
#         Luke Bloy <luke.bloy@gmail.com>
#
# License: BSD (3-clause)

import os.path as op
import numpy as np

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

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read_raw_fif(raw_fname)


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

raw.info['bads'] = ['MEG 2443', 'EEG 053']
raw.load_data().filter(4, 12)
events = mne.find_events(raw, stim_channel='STI 014')
event_id = dict(aud_l=1, aud_r=2, vis_l=3, vis_r=4)
tmin, tmax = -0.2, 0.5
baseline = (None, 0)  # means from the first instant to t = 0
reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)
epochs = mne.Epochs(raw.copy().filter(4, 12), events, event_id, tmin, tmax,
                    proj=True, picks=('meg', 'eog'), baseline=None,
                    reject=reject, preload=True)
del raw


I am working on the file "0.23/_downloads/c37ac181bfe2eb2f1fa69c3fab30417d/mne_cov_power.ipynb".
The first task is:
We can also look at the covariances using topomaps, here we just show the
baseline and data covariances, followed by the data covariance whitened
by the baseline covariance:
Can you write Python code for it?

evoked = epochs.average().pick('meg')
evoked.drop_channels(evoked.info['bads'])
evoked.plot(time_unit='s')
evoked.plot_topomap(times=np.linspace(0.05, 0.15, 5), ch_type='mag')
noise_cov.plot_topomap(evoked.info, 'grad', title='Noise')
data_cov.plot_topomap(evoked.info, 'grad', title='Data')
data_cov.plot_topomap(evoked.info, 'grad', noise_cov=noise_cov,
                      title='Whitened data')


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


I am working on the file "0.23/_downloads/c4c1adf6983ad491e45e3941a0c10d6e/time_frequency_mixed_norm_inverse.ipynb".
The first task is:
Plot dipole activations
Can you write Python code for it?


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

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

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

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

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

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


I am working on the file "0.23/_downloads/c4c1adf6983ad491e45e3941a0c10d6e/time_frequency_mixed_norm_inverse.ipynb".
The first task is:
Show the evoked response and the residual for gradiometers
Can you write Python code for it?

ylim = dict(grad=[-120, 120])
evoked.pick_types(meg='grad', exclude='bads')
evoked.plot(titles=dict(grad='Evoked Response: Gradiometers'), ylim=ylim,
            proj=True, time_unit='s')

residual.pick_types(meg='grad', exclude='bads')
residual.plot(titles=dict(grad='Residuals: Gradiometers'), ylim=ylim,
              proj=True, time_unit='s')


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

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

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


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

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

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


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

fig = mne.viz.create_3d_figure(size=(600, 400))

# Plot the cortex
mne.viz.plot_alignment(
    subject=subject, subjects_dir=subjects_dir, trans=trans,
    surfaces='white', coord_frame='head', fig=fig)

# Show the dipoles as arrows pointing along the surface normal
mne.viz.plot_dipole_locations(
    dipoles=dipoles, trans=trans, mode='arrow', subject=subject,
    subjects_dir=subjects_dir, coord_frame='head', scale=7e-4, fig=fig)

mne.viz.set_3d_view(figure=fig, azimuth=180, distance=0.1)


I am working on the file "0.23/_downloads/c69e0120935518121b8298ecac72eed8/35_dipole_orientations.ipynb".
The first task is:
Restricting the dipole orientations in this manner leads to the following
source estimate for the sample data:
Can you write Python code for it?

# Compute the source estimate for the 'left - auditory' condition in the sample
# dataset.
inv = make_inverse_operator(left_auditory.info, fwd, noise_cov, fixed=True)
stc = apply_inverse(left_auditory, inv, pick_ori=None)

# Visualize it at the moment of peak activity.
_, time_max = stc.get_peak(hemi='lh')
brain_fixed = stc.plot(surface='white', subjects_dir=subjects_dir,
                       initial_time=time_max, time_unit='s', size=(600, 400))
mne.viz.set_3d_view(figure=brain_fixed, focalpoint=(0., 0., 50))


I am working on the file "0.23/_downloads/c69e0120935518121b8298ecac72eed8/35_dipole_orientations.ipynb".
The first task is:
The direction of the estimated current is now restricted to two directions:
inward and outward. In the plot, blue areas indicate current flowing inwards
and red areas indicate current flowing outwards. Given the curvature of the
cortex, groups of dipoles tend to point in the same direction: the direction
of the electromagnetic field picked up by the sensors.
Loose dipole orientations
Forcing the source dipoles to be strictly orthogonal to the cortex makes the
source estimate sensitive to the spacing of the dipoles along the cortex,
since the curvature of the cortex changes within each ~10 square mm patch.
Furthermore, misalignment of the MEG/EEG and MRI coordinate frames is more
critical when the source dipole orientations are strictly constrained
:footcite:LinEtAl2006. To lift the restriction on the orientation of the
dipoles, the inverse operator has the ability to place not one, but three
dipoles at each location defined by the source space. These three dipoles are
placed orthogonally to form a Cartesian coordinate system. Let's visualize
this:
Can you write Python code for it?

fig = mne.viz.create_3d_figure(size=(600, 400))

# Plot the cortex
mne.viz.plot_alignment(
    subject=subject, subjects_dir=subjects_dir, trans=trans,
    surfaces='white', coord_frame='head', fig=fig)

# Show the three dipoles defined at each location in the source space
mne.viz.plot_alignment(
    subject=subject, subjects_dir=subjects_dir, trans=trans, fwd=fwd,
    surfaces='white', coord_frame='head', fig=fig)

mne.viz.set_3d_view(figure=fig, azimuth=180, distance=0.1)


I am working on the file "0.23/_downloads/c69e0120935518121b8298ecac72eed8/35_dipole_orientations.ipynb".
The first task is:
The role of dipole orientations in distributed source localization
When performing source localization in a distributed manner
(MNE/dSPM/sLORETA/eLORETA),
the source space is defined as a grid of dipoles that spans a large portion of
the cortex. These dipoles have both a position and an orientation. In this
tutorial, we will look at the various options available to restrict the
orientation of the dipoles and the impact on the resulting source estimate.
See inverse_orientation_constraints for related information.
Loading data
Load everything we need to perform source localization on the sample dataset.
Can you write Python code for it?

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

data_path = sample.data_path()
evokeds = mne.read_evokeds(data_path + '/MEG/sample/sample_audvis-ave.fif')
left_auditory = evokeds[0].apply_baseline()
fwd = mne.read_forward_solution(
    data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif')
mne.convert_forward_solution(fwd, surf_ori=True, copy=False)
noise_cov = mne.read_cov(data_path + '/MEG/sample/sample_audvis-cov.fif')
subject = 'sample'
subjects_dir = data_path + '/subjects'
trans_fname = data_path + '/MEG/sample/sample_audvis_raw-trans.fif'


I am working on the file "0.23/_downloads/c69e0120935518121b8298ecac72eed8/35_dipole_orientations.ipynb".
The first task is:
The source space
Let's start by examining the source space as constructed by the
:func:mne.setup_source_space function. Dipoles are placed along fixed
intervals on the cortex, determined by the spacing parameter. The source
space does not define the orientation for these dipoles.
Can you write Python code for it?

lh = fwd['src'][0]  # Visualize the left hemisphere
verts = lh['rr']  # The vertices of the source space
tris = lh['tris']  # Groups of three vertices that form triangles
dip_pos = lh['rr'][lh['vertno']]  # The position of the dipoles
dip_ori = lh['nn'][lh['vertno']]
dip_len = len(dip_pos)
dip_times = [0]
white = (1.0, 1.0, 1.0)  # RGB values for a white color

actual_amp = np.ones(dip_len)  # misc amp to create Dipole instance
actual_gof = np.ones(dip_len)  # misc GOF to create Dipole instance
dipoles = mne.Dipole(dip_times, dip_pos, actual_amp, dip_ori, actual_gof)
trans = mne.read_trans(trans_fname)

fig = mne.viz.create_3d_figure(size=(600, 400), bgcolor=white)
coord_frame = 'mri'

# Plot the cortex
mne.viz.plot_alignment(
    subject=subject, subjects_dir=subjects_dir, trans=trans, surfaces='white',
    coord_frame=coord_frame, fig=fig)

# Mark the position of the dipoles with small red dots
mne.viz.plot_dipole_locations(
    dipoles=dipoles, trans=trans, mode='sphere', subject=subject,
    subjects_dir=subjects_dir, coord_frame=coord_frame, scale=7e-4, fig=fig)

mne.viz.set_3d_view(figure=fig, azimuth=180, distance=0.25)


I am working on the file "0.23/_downloads/c69e0120935518121b8298ecac72eed8/35_dipole_orientations.ipynb".
The first task is:
When computing the source estimate, the activity at each of the three dipoles
is collapsed into the XYZ components of a single vector, which leads to the
following source estimate for the sample data:
Can you write Python code for it?

# Make an inverse operator with loose dipole orientations
inv = make_inverse_operator(left_auditory.info, fwd, noise_cov, fixed=False,
                            loose=1.0)

# Compute the source estimate, indicate that we want a vector solution
stc = apply_inverse(left_auditory, inv, pick_ori='vector')

# Visualize it at the moment of peak activity.
_, time_max = stc.magnitude().get_peak(hemi='lh')
brain_mag = stc.plot(subjects_dir=subjects_dir, initial_time=time_max,
                     time_unit='s', size=(600, 400), overlay_alpha=0)
mne.viz.set_3d_view(figure=brain_mag, focalpoint=(0., 0., 50))


I am working on the file "0.23/_downloads/c6baf7c1a2f53fda44e93271b91f45b8/50_beamformer_lcmv.ipynb".
The first task is:
Introduction to beamformers
A beamformer is a spatial filter that reconstructs source activity by
scanning through a grid of pre-defined source points and estimating activity
at each of those source points independently. A set of weights is
constructed for each defined source location which defines the contribution
of each sensor to this source.
Beamformers are often used for their focal reconstructions and their ability
to reconstruct deeper sources. They can also suppress external noise sources.
The beamforming method applied in this tutorial is the linearly constrained
minimum variance (LCMV) beamformer :footcite:VanVeenEtAl1997 operates on
time series.
Frequency-resolved data can be reconstructed with the dynamic imaging of
coherent sources (DICS) beamforming method :footcite:GrossEtAl2001.
As we will see in the following, the spatial filter is computed from two
ingredients: the forward model solution and the covariance matrix of the
data.
Data processing
We will use the sample data set for this tutorial and reconstruct source
activity on the trials with left auditory stimulation.
Can you write Python code for it?

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

# Read the raw data
raw = mne.io.read_raw_fif(raw_fname)
raw.info['bads'] = ['MEG 2443']  # bad MEG channel

# Set up the epoching
event_id = 1  # those are the trials with left-ear auditory stimuli
tmin, tmax = -0.2, 0.5
events = mne.find_events(raw)

# pick relevant channels
raw.pick(['meg', 'eog'])  # pick channels of interest

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

# for speed purposes, cut to a window of interest
evoked = epochs.average().crop(0.05, 0.15)

# Visualize averaged sensor space data
evoked.plot_joint()

del raw  # save memory


I am working on the file "0.23/_downloads/c6baf7c1a2f53fda44e93271b91f45b8/50_beamformer_lcmv.ipynb".
The first task is:
It is also possible to compute a vector beamformer, which gives back three
estimates per voxel, corresponding to the three direction components of the
source. This can be achieved by setting
pick_ori='vector' and will yield a :class:volume vector source estimate
<mne.VolVectorSourceEstimate>. So we will compute another set of filters
using the vector beamformer approach:
Can you write Python code for it?

filters_vec = make_lcmv(evoked.info, forward, data_cov, reg=0.05,
                        noise_cov=noise_cov, pick_ori='vector',
                        weight_norm='unit-noise-gain', rank=None)
# save a bit of memory
src = forward['src']
del forward


I am working on the file "0.23/_downloads/c6baf7c1a2f53fda44e93271b91f45b8/50_beamformer_lcmv.ipynb".
The first task is:
Morph the output to fsaverage
We can also use volumetric morphing to get the data to fsaverage space. This
is for example necessary when comparing activity across subjects. Here, we
will use the scalar beamformer example.
We pass a :class:mne.SourceMorph as the src argument to
mne.VolSourceEstimate.plot. To save some computational load when applying
the morph, we will crop the stc:
Can you write Python code for it?

fetch_fsaverage(subjects_dir)  # ensure fsaverage src exists
fname_fs_src = subjects_dir + '/fsaverage/bem/fsaverage-vol-5-src.fif'

src_fs = mne.read_source_spaces(fname_fs_src)
morph = mne.compute_source_morph(
    src, subject_from='sample', src_to=src_fs, subjects_dir=subjects_dir,
    niter_sdr=[10, 10, 5], niter_affine=[10, 10, 5],  # just for speed
    verbose=True)
stc_fs = morph.apply(stc)
del stc

stc_fs.plot(
    src=src_fs, mode='stat_map', initial_time=0.085, subjects_dir=subjects_dir,
    clim=dict(kind='value', pos_lims=lims), verbose=True)


I am working on the file "0.23/_downloads/c6baf7c1a2f53fda44e93271b91f45b8/50_beamformer_lcmv.ipynb".
The first task is:
On MNI glass brain (orthoview; 2D)
Can you write Python code for it?

stc.plot(mode='glass_brain', clim=dict(kind='value', lims=lims), **kwargs)


I am working on the file "0.23/_downloads/c6baf7c1a2f53fda44e93271b91f45b8/50_beamformer_lcmv.ipynb".
The first task is:
On MRI slices (orthoview; 2D)
Can you write Python code for it?

stc.plot(mode='stat_map', clim=dict(kind='value', pos_lims=lims), **kwargs)


I am working on the file "0.23/_downloads/c6baf7c1a2f53fda44e93271b91f45b8/50_beamformer_lcmv.ipynb".
The first task is:
Visualize the reconstructed source activity
We can visualize the source estimate in different ways, e.g. as a volume
rendering, an overlay onto the MRI, or as an overlay onto a glass brain.
The plots for the scalar beamformer show brain activity in the right temporal
lobe around 100 ms post stimulus. This is expected given the left-ear
auditory stimulation of the experiment.
Can you write Python code for it?

lims = [0.3, 0.45, 0.6]
kwargs = dict(src=src, subject='sample', subjects_dir=subjects_dir,
              initial_time=0.087, verbose=True)


I am working on the file "0.23/_downloads/c6baf7c1a2f53fda44e93271b91f45b8/50_beamformer_lcmv.ipynb".
The first task is:
Volumetric rendering (3D) with vectors
These plots can also be shown using a volumetric rendering via
:meth:~mne.VolVectorSourceEstimate.plot_3d. Let's try visualizing the
vector beamformer case. Here we get three source time courses out per voxel
(one for each component of the dipole moment: x, y, and z), which appear
as small vectors in the visualization (in the 2D plotters, only the
magnitude can be shown):
Can you write Python code for it?

brain = stc_vec.plot_3d(
    clim=dict(kind='value', lims=lims), hemi='both',
    views=['coronal', 'sagittal', 'axial'], size=(800, 300),
    view_layout='horizontal', show_traces=0.3,
    brain_kwargs=dict(silhouette=True), **kwargs)


I am working on the file "0.23/_downloads/c6baf7c1a2f53fda44e93271b91f45b8/50_beamformer_lcmv.ipynb".
The first task is:
When looking at the covariance matrix plots, we can see that our data is
slightly rank-deficient as the rank is not equal to the number of channels.
Thus, we will have to regularize the covariance matrix before inverting it
in the beamformer calculation. This can be achieved by setting the parameter
reg=0.05 when calculating the spatial filter with
:func:~mne.beamformer.make_lcmv. This corresponds to loading the diagonal
of the covariance matrix with 5% of the sensor power.
The forward model
The forward model is the other important ingredient for the computation of a
spatial filter. Here, we will load the forward model from disk; more
information on how to create a forward model can be found in this tutorial:
tut-forward.
Note that beamformers are usually computed in a :class:volume source space
<mne.VolSourceEstimate>, because estimating only cortical surface
activation can misrepresent the data.
Can you write Python code for it?

# Read forward model

fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-vol-7-fwd.fif'
forward = mne.read_forward_solution(fwd_fname)


I am working on the file "0.23/_downloads/c7633c38a703b9d0a626a5a4fa161026/psf_ctf_label_leakage.ipynb".
The first task is:
Load forward solution and inverse operator
We need a matching forward solution and inverse operator to compute
resolution matrices for different methods.
Can you write Python code for it?

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-fixed-inv.fif'
forward = mne.read_forward_solution(fname_fwd)
# Convert forward solution to fixed source orientations
mne.convert_forward_solution(
    forward, surf_ori=True, force_fixed=True, copy=False)
inverse_operator = read_inverse_operator(fname_inv)

# Compute resolution matrices for MNE
rm_mne = make_inverse_resolution_matrix(forward, inverse_operator,
                                        method='MNE', lambda2=1. / 3.**2)
src = inverse_operator['src']
del forward, inverse_operator  # save memory