I am working on the file "0.23/_downloads/93beebed8738eca8bfe26d41a12f4260/10_stc_class.ipynb".
The first task is:
Load and inspect example data
This data set contains source estimation data from an audio visual task. It
has been mapped onto the inflated cortical surface representation obtained
from FreeSurfer <tut-freesurfer-mne>
using the dSPM method. It highlights a noticeable peak in the auditory
cortices.
Let's see how it looks like.
Can you write Python code for it?

stc = read_source_estimate(fname_stc, subject='sample')

# Define plotting parameters
surfer_kwargs = dict(
    hemi='lh', subjects_dir=subjects_dir,
    clim=dict(kind='value', lims=[8, 12, 15]), views='lateral',
    initial_time=0.09, time_unit='s', size=(800, 800),
    smoothing_steps=5)

# Plot surface
brain = stc.plot(**surfer_kwargs)

# Add title
brain.add_text(0.1, 0.9, 'SourceEstimate', 'title', font_size=16)


I am working on the file "0.23/_downloads/93beebed8738eca8bfe26d41a12f4260/10_stc_class.ipynb".
The first task is:
The :class:SourceEstimate <mne.SourceEstimate> data structure
Source estimates, commonly referred to as STC (Source Time Courses),
are obtained from source localization methods.
Source localization method solve the so-called 'inverse problem'.
MNE provides different methods for solving it:
dSPM, sLORETA, LCMV, MxNE etc.
Source localization consists in projecting the EEG/MEG sensor data into
a 3-dimensional 'source space' positioned in the individual subject's brain
anatomy. Hence the data is transformed such that the recorded time series at
each sensor location maps to time series at each spatial location of the
'source space' where is defined our source estimates.
An STC object contains the amplitudes of the sources over time.
It only stores the amplitudes of activations but
not the locations of the sources. To get access to the locations
you need to have the :class:source space <mne.SourceSpaces>
(often abbreviated src) used to compute the
:class:forward operator <mne.Forward> (often abbreviated fwd).
See tut-forward for more details on forward modeling, and
tut-inverse-methods
for an example of source localization with dSPM, sLORETA or eLORETA.
Source estimates come in different forms:
- :class:`mne.SourceEstimate`: For cortically constrained source spaces.

- :class:`mne.VolSourceEstimate`: For volumetric source spaces

- :class:`mne.VectorSourceEstimate`: For cortically constrained source
  spaces with vector-valued source activations (strength and orientation)

- :class:`mne.MixedSourceEstimate`: For source spaces formed of a
  combination of cortically constrained and volumetric sources.

Note

:class:`(Vector) <mne.VectorSourceEstimate>`
    :class:`SourceEstimate <mne.SourceEstimate>` are surface representations
    mostly used together with `FreeSurfer <tut-freesurfer-mne>`
    surface representations.

Let's get ourselves an idea of what a :class:mne.SourceEstimate really
is. We first set up the environment and load some data:
Can you write Python code for it?

import os

from mne import read_source_estimate
from mne.datasets import sample

print(__doc__)

# Paths to example data
sample_dir_raw = sample.data_path()
sample_dir = os.path.join(sample_dir_raw, 'MEG', 'sample')
subjects_dir = os.path.join(sample_dir_raw, 'subjects')

fname_stc = os.path.join(sample_dir, 'sample_audvis-meg')


I am working on the file "0.23/_downloads/9552276573be20bde95d1b4bc52b4768/20_event_arrays.ipynb".
The first task is:
Event dictionaries like this one are used when extracting epochs from
continuous data, and the resulting :class:~mne.Epochs object allows pooling
by requesting partial trial descriptors. For example, if we wanted to pool
all auditory trials, instead of merging Event IDs 1 and 2 using the
:func:~mne.merge_events function, we can make use of the fact that the keys
of event_dict contain multiple trial descriptors separated by /
characters: requesting 'auditory' trials will select all epochs with
Event IDs 1 and 2; requesting 'left' trials will select all epochs with
Event IDs 1 and 3. An example of this is shown in a later tutorial.
.. TODO replace above sentence when the relevant tut is ready:
   An example of this is shown later, in the epoch-pooling section of
   the epochs-intro-tutorial tutorial.
Plotting events
Another use of event dictionaries is when plotting events, which can serve as
a useful check that your event signals were properly sent to the STIM
channel(s) and that MNE-Python has successfully found them. The function
:func:mne.viz.plot_events will plot each event versus its sample number
(or, if you provide the sampling frequency, it will plot them versus time in
seconds). It can also account for the offset between sample number and sample
index in Neuromag systems, with the first_samp parameter. If an event
dictionary is provided, it will be used to generate a legend:
Can you write Python code for it?

fig = mne.viz.plot_events(events, sfreq=raw.info['sfreq'],
                          first_samp=raw.first_samp, event_id=event_dict)
fig.subplots_adjust(right=0.7)  # make room for legend


I am working on the file "0.23/_downloads/9552276573be20bde95d1b4bc52b4768/20_event_arrays.ipynb".
The first task is:
It is also possible to combine two Event IDs using :func:mne.merge_events;
the following example will combine Event IDs 1, 2 and 3 into a single event
labelled 1:
Can you write Python code for it?

merged_events = mne.merge_events(events, [1, 2, 3], 1)
print(np.unique(merged_events[:, -1]))


I am working on the file "0.23/_downloads/9552276573be20bde95d1b4bc52b4768/20_event_arrays.ipynb".
The first task is:
Making equally-spaced Events arrays
For some experiments (such as those intending to analyze resting-state
activity) there may not be any experimental events included in the raw
recording. In such cases, an Events array of equally-spaced events can be
generated using :func:mne.make_fixed_length_events:
Can you write Python code for it?

new_events = mne.make_fixed_length_events(raw, start=5, stop=50, duration=2.)


I am working on the file "0.23/_downloads/9552276573be20bde95d1b4bc52b4768/20_event_arrays.ipynb".
The first task is:
Plotting events and raw data together
Events can also be plotted alongside the :class:~mne.io.Raw object they
were extracted from, by passing the Event array as the events parameter
of :meth:raw.plot <mne.io.Raw.plot>:
Can you write Python code for it?

raw.plot(events=events, start=5, duration=10, color='gray',
         event_color={1: 'r', 2: 'g', 3: 'b', 4: 'm', 5: 'y', 32: 'k'})


I am working on the file "0.23/_downloads/9552276573be20bde95d1b4bc52b4768/20_event_arrays.ipynb".
The first task is:
The tutorial tut-events-vs-annotations describes in detail the
different ways of obtaining an :term:Events array <events> from a
:class:~mne.io.Raw object (see the section
overview-tut-events-section for details). Since the sample
dataset <sample-dataset> includes experimental events recorded on
:term:stim channel STI 014, we'll start this tutorial by parsing the
events from that channel using :func:mne.find_events:
Can you write Python code for it?

events = mne.find_events(raw, stim_channel='STI 014')


I am working on the file "0.23/_downloads/9552276573be20bde95d1b4bc52b4768/20_event_arrays.ipynb".
The first task is:
Working with events
This tutorial describes event representation and how event arrays are used to
subselect data.
As usual we'll start by importing the modules we need, loading some
example data <sample-dataset>, and cropping the :class:~mne.io.Raw
object to just 60 seconds before loading it into RAM to save memory:
Can you write Python code for it?

import os
import numpy as np
import mne

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


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
:class:~mne.Epochs objects are a data structure for representing and
analyzing equal-duration chunks of the EEG/MEG signal. :class:~mne.Epochs
are most often used to represent data that is time-locked to repeated
experimental events (such as stimulus onsets or subject button presses), but
can also be used for storing sequential or overlapping frames of a continuous
signal (e.g., for analysis of resting-state activity; see
fixed-length-events). Inside an :class:~mne.Epochs object, the data
are stored in an :class:array <numpy.ndarray> of shape (n_epochs,
n_channels, n_times).
:class:~mne.Epochs objects have many similarities with :class:~mne.io.Raw
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> through the
  :meth:~mne.Epochs.get_data method or to a :class:Pandas DataFrame
  <pandas.DataFrame> through the :meth:~mne.Epochs.to_data_frame method.

Both :class:~mne.Epochs and :class:~mne.io.Raw objects support channel
  selection by index or name, including :meth:~mne.Epochs.pick,
  :meth:~mne.Epochs.pick_channels and :meth:~mne.Epochs.pick_types
  methods.

:term:SSP projector <projector> manipulation is possible through
  :meth:~mne.Epochs.add_proj, :meth:~mne.Epochs.del_proj, and
  :meth:~mne.Epochs.plot_projs_topomap methods.

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

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

Both :class:~mne.Epochs and :class:~mne.io.Raw objects have built-in
  plotting methods :meth:~mne.Epochs.plot, :meth:~mne.Epochs.plot_psd,
  and :meth:~mne.Epochs.plot_psd_topomap.

Creating Epoched data from a Raw object
The example dataset we've been using...
Can you write Python code for it?

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


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:

Note

If you forget to provide the event dictionary to the :class:`~mne.Epochs`
    constructor, you can add it later by assigning to the ``event_id``
    attribute::

        epochs.event_id = event_dict

Basic visualization of Epochs objects
The :class:~mne.Epochs object can be visualized (and browsed interactively)
using its :meth:~mne.Epochs.plot method:
Can you write Python code for it?


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:

Note

We could also have loaded the events from file, using
    :func:`mne.read_events`::

        sample_data_events_file = os.path.join(sample_data_folder,
                                               'MEG', 'sample',
                                               'sample_audvis_raw-eve.fif')
        events_from_file = mne.read_events(sample_data_events_file)

    See `tut-section-events-io` for more details.

The :class:~mne.io.Raw object and the events array are the bare minimum
needed to create an :class:~mne.Epochs object, which we create with the
:class:mne.Epochs class constructor. However, you will almost surely want
to change some of the other default parameters. Here we'll change tmin
and tmax (the time relative to each event at which to start and end each
epoch). Note also that the :class:~mne.Epochs constructor accepts
parameters reject and flat for rejecting individual epochs based on
signal amplitude. See the tut-reject-epochs-section section for
examples.
Can you write Python code for it?

epochs = mne.Epochs(raw, events, tmin=-0.3, tmax=0.7)


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
As we saw in the tut-events-vs-annotations tutorial, we can extract an
events array from :class:~mne.io.Raw objects using :func:mne.find_events:
Can you write Python code for it?


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
Changing channel name and type
You can change the name or type of a channel using
:meth:~mne.Epochs.rename_channels or :meth:~mne.Epochs.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.
Can you write Python code for it?

epochs.rename_channels({'EOG 061': 'BlinkChannel'})

epochs.set_channel_types({'EEG 060': 'ecg'})
print(list(zip(epochs.ch_names, epochs.get_channel_types()))[-4:])

# let's set them back to the correct values before moving on
epochs.rename_channels({'BlinkChannel': 'EOG 061'})
epochs.set_channel_types({'EEG 060': 'eeg'})


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
Cropping removed part of the baseline. When printing the
cropped :class:~mne.Epochs, MNE-Python will inform you about the time
period that was originally used to perform baseline correction by displaying
the string "baseline period cropped after baseline correction":
Can you write Python code for it?


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
However, if you wanted to expand the time domain of an :class:~mne.Epochs
object, you would need to go back to the :class:~mne.io.Raw data and
recreate the :class:~mne.Epochs with different values for tmin and/or
tmax.
It is also possible to change the "zero point" that defines the time values
in an :class:~mne.Epochs object, with the :meth:~mne.Epochs.shift_time
method. :meth:~mne.Epochs.shift_time allows shifting times relative to the
current values, or specifying a fixed time to set as the new time value of
the first sample (deriving the new time values of subsequent samples based on
the :class:~mne.Epochs object's sampling frequency).
Can you write Python code for it?

# shift times so that first sample of each epoch is at time zero
later_epochs = epochs.copy().shift_time(tshift=0., relative=False)
print(later_epochs.times[:3])

# shift times by a relative amount
later_epochs.shift_time(tshift=-7, relative=True)
print(later_epochs.times[:3])

del shorter_epochs, later_epochs


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
If you want to iterate over :class:~mne.Epochs objects, you can use an
integer index as the iterator:
Can you write Python code for it?

for index in range(3):
    print(type(epochs[index]))


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
Note that although time shifting respects the sampling frequency (the spacing
between samples), it does not enforce the assumption that there is a sample
occurring at exactly time=0.
Extracting data in other forms
The :meth:~mne.Epochs.get_data method returns the epoched data as a
:class:NumPy array <numpy.ndarray>, of shape (n_epochs, n_channels,
n_times); an optional picks parameter selects a subset of channels by
index, name, or type:
Can you write Python code for it?

eog_data = epochs.get_data(picks='EOG 061')
meg_data = epochs.get_data(picks=['mag', 'grad'])
channel_4_6_8 = epochs.get_data(picks=slice(4, 9, 2))

for name, arr in dict(EOG=eog_data, MEG=meg_data, Slice=channel_4_6_8).items():
    print('{} contains {} channels'.format(name, arr.shape[1]))


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
Note that if your analysis requires repeatedly extracting single epochs from
an :class:~mne.Epochs object, epochs.get_data(item=2) will be much
faster than epochs[2].get_data(), because it avoids the step of
subsetting the :class:~mne.Epochs object first.
You can also export :class:~mne.Epochs data to :class:Pandas DataFrames
<pandas.DataFrame>. Here, the :class:~pandas.DataFrame index will be
constructed by converting the time of each sample into milliseconds and
rounding it to the nearest integer, and combining it with the event types and
epoch numbers to form a hierarchical :class:~pandas.MultiIndex. Each
channel will appear in a separate column. Then you can use any of Pandas'
tools for grouping and aggregating data; for example, here we select any
epochs numbered 10 or less from the auditory/left condition, and extract
times between 100 and 107 ms on channels EEG 056 through EEG 058
(note that slice indexing within Pandas' :obj:~pandas.DataFrame.loc is
inclusive of the endpoint):
Can you write Python code for it?

df = epochs.to_data_frame(index=['condition', 'epoch', 'time'])
df.sort_index(inplace=True)
print(df.loc[('auditory/left', slice(0, 10), slice(100, 107)),
             'EEG 056':'EEG 058'])

del df


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
Notice that the Event IDs are in quotes; since we didn't provide an event
dictionary, the :class:mne.Epochs constructor created one automatically and
used the string representation of the integer Event IDs as the dictionary
keys. This is more clear when viewing the event_id attribute:
Can you write Python code for it?


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
Notice that the individual epochs are sequentially numbered along the bottom
axis and are separated by vertical dashed lines.
Epoch plots are interactive (similar to :meth:raw.plot()
<mne.io.Raw.plot>) and have many of the same interactive controls as
:class:~mne.io.Raw plots. Horizontal and vertical scrollbars allow browsing
through epochs or channels (respectively), and pressing :kbd:? when the
plot is focused will show a help screen with all the available controls. See
tut-visualize-epochs for more details (as well as other ways of
visualizing epoched data).
Subselecting epochs
Now that we have our :class:~mne.Epochs object with our descriptive event
labels added, we can subselect epochs easily using square brackets. For
example, we can load all the "catch trials" where the stimulus was a face:
Can you write Python code for it?


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
Notice that the output now mentions "1 bad epoch dropped". In the tutorial
section tut-reject-epochs-section we saw how you can specify channel
amplitude criteria for rejecting epochs, but here we haven't specified any
such criteria. In this case, it turns out that the last event was too close
the end of the (cropped) raw file to accommodate our requested tmax of
0.7 seconds, so the final epoch was dropped because it was too short. Here
are the drop_log entries for the last 4 epochs (empty lists indicate
epochs that were not dropped):
Can you write Python code for it?


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
See the tut-epochs-dataframe tutorial for many more examples of the
:meth:~mne.Epochs.to_data_frame method.
Loading and saving Epochs objects to disk
:class:~mne.Epochs objects can be loaded and saved in the .fif format
just like :class:~mne.io.Raw objects, using the :func:mne.read_epochs
function and the :meth:~mne.Epochs.save method. Functions are also
available for loading data that was epoched outside of MNE-Python, such as
:func:mne.read_epochs_eeglab and :func:mne.read_epochs_kit.
Can you write Python code for it?

epochs.save('saved-audiovisual-epo.fif', overwrite=True)
epochs_from_file = mne.read_epochs('saved-audiovisual-epo.fif', preload=False)


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
Selecting epochs by index
:class:~mne.Epochs objects can also be indexed with integers, :term:slices
<slice>, or lists of integers. This method of selection ignores event
labels, so if you want the first 10 epochs of a particular type, you can
select the type first, then use integers or slices:
Can you write Python code for it?

print(epochs[:10])    # epochs 0-9
print(epochs[1:8:2])  # epochs 1, 3, 5, 7

print(epochs['buttonpress'][:4])            # first 4 "buttonpress" epochs
print(epochs['buttonpress'][[0, 1, 2, 3]])  # same as previous line


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
Selection in the time domain
To change the temporal extent of the :class:~mne.Epochs, you can use the
:meth:~mne.Epochs.crop method:
Can you write Python code for it?

shorter_epochs = epochs.copy().crop(tmin=-0.1, tmax=0.1, include_tmax=True)

for name, obj in dict(Original=epochs, Cropped=shorter_epochs).items():
    print('{} epochs has {} time samples'
          .format(name, obj.get_data().shape[-1]))


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
The Epochs data structure: discontinuous data
This tutorial covers the basics of creating and working with :term:epoched
<epochs> data. It introduces the :class:~mne.Epochs data structure in
detail, including how to load, query, subselect, export, and plot data from an
:class:~mne.Epochs object. For more information about visualizing
:class:~mne.Epochs objects, see tut-visualize-epochs. For info on
creating an :class:~mne.Epochs 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/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
The MNE-Python naming convention for epochs files is that the file basename
(the part before the .fif or .fif.gz extension) should end with
-epo or _epo, and a warning will be issued if the filename you
provide does not adhere to that convention.
As a final note, be aware that the class of the epochs object is different
when epochs are loaded from disk rather than generated from a
:class:~mne.io.Raw object:
Can you write Python code for it?


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
We can also pool across conditions easily, thanks to how MNE-Python handles
the / character in epoch labels (using what is sometimes called
"tag-based indexing"):
Can you write Python code for it?

# pool across left + right
print(epochs['auditory'])
assert len(epochs['auditory']) == (len(epochs['auditory/left']) +
                                   len(epochs['auditory/right']))
# pool across auditory + visual
print(epochs['left'])
assert len(epochs['left']) == (len(epochs['auditory/left']) +
                               len(epochs['visual/left']))


I am working on the file "0.23/_downloads/9619fd95b952a0c715b83d0e6b37c416/10_epochs_overview.ipynb".
The first task is:
You can also pool conditions by passing multiple tags as a list. Note that
MNE-Python will not complain if you ask for tags not present in the object,
as long as it can find some match: the below example is parsed as
(inclusive) 'right' or 'bottom', and you can see from the output
that it selects only auditory/right and visual/right.
Can you write Python code for it?


I am working on the file "0.23/_downloads/98d9662291626be9c938eee7a8fcc9bd/sensor_noise_level.ipynb".
The first task is:
Show noise levels from empty room data
This shows how to use :meth:mne.io.Raw.plot_psd to examine noise levels
of systems. See :footcite:KhanCohen2013 for an example.
Can you write Python code for it?

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

import os.path as op
import mne

data_path = mne.datasets.sample.data_path()

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


I am working on the file "0.23/_downloads/98d9662291626be9c938eee7a8fcc9bd/sensor_noise_level.ipynb".
The first task is:
We can plot the absolute noise levels:
Can you write Python code for it?

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


I am working on the file "0.23/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb".
The first task is:
Additional examples of plotting scalp topographies can be found in
ex-evoked-topomap.
Arrow maps
Scalp topographies at a given time point can be augmented with arrows to show
the estimated magnitude and direction of the magnetic field, using the
function mne.viz.plot_arrowmap:
Can you write Python code for it?

mags = evks['aud/left'].copy().pick_types(meg='mag')
mne.viz.plot_arrowmap(mags.data[:, 175], mags.info, extrapolate='local')


I am working on the file "0.23/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb".
The first task is:
By default, MEG sensors will be used to estimate the field on the helmet
surface, while EEG sensors will be used to estimate the field on the scalp.
Once the maps are computed, you can plot them with evoked.plot_field()
<mne.Evoked.plot_field>:
Can you write Python code for it?

maps = mne.make_field_map(evks['aud/left'], trans=sample_data_trans_file,
                          subject='sample', subjects_dir=subjects_dir)
evks['aud/left'].plot_field(maps, time=0.1)


I am working on the file "0.23/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb".
The first task is:
For larger numbers of sensors, the method evoked.plot_topo()
<mne.Evoked.plot_topo> and the function mne.viz.plot_evoked_topo
can both be used. The ~mne.Evoked.plot_topo method will plot only a
single condition, while the ~mne.viz.plot_evoked_topo function can
plot one or more conditions on the same axes, if passed a list of
~mne.Evoked objects. The legend entries will be automatically drawn
from the ~mne.Evoked objects' comment attribute:
Can you write Python code for it?


I am working on the file "0.23/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb".
The first task is:
Image plots
Like ~mne.Epochs, ~mne.Evoked objects also have a
~mne.Evoked.plot_image method, but unlike epochs.plot_image()
<mne.Epochs.plot_image>, evoked.plot_image() <mne.Evoked.plot_image>
shows one channel per row instead of one epoch per row. Again, a
picks parameter is available, as well as several other customization
options; see ~mne.Evoked.plot_image for details.
Can you write Python code for it?


I am working on the file "0.23/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb".
The first task is:
Instead of creating the ~mne.Evoked object from an ~mne.Epochs object,
we'll load an existing ~mne.Evoked object from disk. Remember, the
:file:.fif format can store multiple ~mne.Evoked objects, so we'll end up
with a list of ~mne.Evoked objects after loading. Recall also from the
tut-section-load-evk section of the introductory Evoked tutorial
<tut-evoked-class> that the sample ~mne.Evoked objects have not been
baseline-corrected and have unapplied projectors, so we'll take care of that
when loading:
Can you write Python code for it?

sample_data_folder = mne.datasets.sample.data_path()
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, baseline=(None, 0),
                                proj=True, verbose=False)

# Show the condition names, and reassure ourselves that baseline correction has
# been applied.
for e in evokeds_list:
    print(f'Condition: {e.comment}, baseline: {e.baseline}')


I am working on the file "0.23/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb".
The first task is:
Like ~mne.Evoked.plot_topomap you can specify the times at which
you want the scalp topographies calculated, and you can customize the plot in
various other ways as well. See mne.Evoked.plot_joint for details.
Comparing Evoked objects
To compare ~mne.Evoked objects from different experimental
conditions, the function mne.viz.plot_compare_evokeds can take a
:class:list or :class:dict of ~mne.Evoked objects and plot them
all on the same axes. Like most MNE-Python visualization functions, it has a
picks parameter for selecting channels, but by default will generate one
figure for each channel type, and combine information across channels of the
same type by calculating the :term:global field power. Information
may be combined across channels in other ways too; support for combining via
mean, median, or standard deviation are built-in, and custom callable
functions may also be used, as shown here:
Can you write Python code for it?

def custom_func(x):
    return x.max(axis=1)

for combine in ('mean', 'median', 'gfp', custom_func):
    mne.viz.plot_compare_evokeds(evks, picks='eeg', combine=combine)


I am working on the file "0.23/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb".
The first task is:
One nice feature of ~mne.viz.plot_compare_evokeds is that when
passing evokeds in a dictionary, it allows specifying plot styles based on
/-separated substrings of the dictionary keys (similar to epoch
selection; see tut-section-subselect-epochs). Here, we specify colors
for "aud" and "vis" conditions, and linestyles for "left" and "right"
conditions, and the traces and legend are styled accordingly.
Can you write Python code for it?

mne.viz.plot_compare_evokeds(evks, picks='MEG 1811', colors=dict(aud=0, vis=1),
                             linestyles=dict(left='solid', right='dashed'))


I am working on the file "0.23/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb".
The first task is:
Plotting scalp topographies
In an interactive session, the butterfly plots seen above can be
click-dragged to select a time region, which will pop up a map of the average
field distribution over the scalp for the selected time span. You can also
generate scalp topographies at specific times or time spans using the
~mne.Evoked.plot_topomap method:
Can you write Python code for it?

times = np.linspace(0.05, 0.13, 5)
evks['aud/left'].plot_topomap(ch_type='mag', times=times, colorbar=True)

fig = evks['aud/left'].plot_topomap(ch_type='mag', times=0.09, average=0.1)
fig.text(0.5, 0.05, 'average from 40-140 ms', ha='center')


I am working on the file "0.23/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb".
The first task is:
Plotting signal traces
.. sidebar:: Butterfly plots
Plots of superimposed sensor timeseries are called "butterfly plots"
   because the positive- and negative-going traces can resemble butterfly
   wings.
The most basic plot of ~mne.Evoked objects is a butterfly plot of
each channel type, generated by the evoked.plot() <mne.Evoked.plot>
method. By default, channels marked as "bad" are suppressed, but you can
control this by passing an empty :class:list to the exclude parameter
(default is exclude='bads'):
Can you write Python code for it?


I am working on the file "0.23/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb".
The first task is:
Topographical subplots
For sensor-level analyses it can be useful to plot the response at each
sensor in a topographical layout. The ~mne.viz.plot_compare_evokeds
function can do this if you pass axes='topo', but it can be quite slow
if the number of sensors is too large, so here we'll plot only the EEG
channels:
Can you write Python code for it?

mne.viz.plot_compare_evokeds(evks, picks='eeg', colors=dict(aud=0, vis=1),
                             linestyles=dict(left='solid', right='dashed'),
                             axes='topo', styles=dict(aud=dict(linewidth=1),
                                                      vis=dict(linewidth=1)))


I am working on the file "0.23/_downloads/99798f35196ac117a93fa936a5c48a93/20_visualize_evoked.ipynb".
The first task is:
Visualizing Evoked data
This tutorial shows the different visualization methods for
~mne.Evoked objects.
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/99a2efbcf51159fbb58f12830f81525d/compute_csd.ipynb".
The first task is:
By default, CSD matrices are computed using all MEG/EEG channels. When
interpreting a CSD matrix with mixed sensor types, be aware that the
measurement units, and thus the scalings, differ across sensors. In this
example, for speed and clarity, we select a single channel type:
gradiometers.
Can you write Python code for it?

picks = mne.pick_types(raw.info, meg='grad')

# Make some epochs, based on events with trigger code 1
epochs = mne.Epochs(raw, events, event_id=1, tmin=-0.2, tmax=1,
                    picks=picks, baseline=(None, 0),
                    reject=dict(grad=4000e-13), preload=True)


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

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

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

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

print(__doc__)


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

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


I am working on the file "0.23/_downloads/99a2efbcf51159fbb58f12830f81525d/compute_csd.ipynb".
The first task is:
In the following example, the computation of the CSD matrices can be
performed using multiple cores. Set n_jobs to a value >1 to select the
number of cores to use.
Can you write Python code for it?


I am working on the file "0.23/_downloads/99a2efbcf51159fbb58f12830f81525d/compute_csd.ipynb".
The first task is:
Loading the sample dataset.
Can you write Python code for it?

data_path = sample.data_path()
fname_raw = data_path + '/MEG/sample/sample_audvis_raw.fif'
fname_event = data_path + '/MEG/sample/sample_audvis_raw-eve.fif'
raw = mne.io.read_raw_fif(fname_raw)
events = mne.read_events(fname_event)


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

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

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

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


I am working on the file "0.23/_downloads/99a2efbcf51159fbb58f12830f81525d/compute_csd.ipynb".
The first task is:
When computing the CSD with Morlet wavelets, you specify the exact
frequencies at which to compute it. For each frequency, a corresponding
wavelet will be constructed and convolved with the signal, resulting in a
time-frequency decomposition.
The CSD is constructed by computing the correlation between the
time-frequency representations between all sensor-to-sensor pairs. The
time-frequency decomposition originally has the same sampling rate as the
signal, in our case ~600Hz. This means the decomposition is over-specified in
time and we may not need to use all samples during our CSD computation, just
enough to get a reliable correlation statistic. By specifying decim=10,
we use every 10th sample, which will greatly speed up the computation and
will have a minimal effect on the CSD.
Can you write Python code for it?

frequencies = [16, 17, 18, 19, 20]
csd_wav = csd_morlet(epochs, frequencies, decim=10, n_jobs=n_jobs)


I am working on the file "0.23/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
:func:~mne.pick_channels_regexp can be especially useful for channels named
according to the 10-20 <ten-twenty_>_ system (e.g., to select all channels
ending in "z" to get the midline, or all channels beginning with "O" to get
the occipital channels). Note that :func:~mne.pick_channels_regexp uses the
Python standard module :mod:re to perform regular expression matching; see
the documentation of the :mod:re module for implementation details.

Warning

Both :func:`~mne.pick_channels` and :func:`~mne.pick_channels_regexp`
   operate on lists of channel names, so they are unaware of which channels
   (if any) have been marked as "bad" in ``info['bads']``. Use caution to
   avoid accidentally selecting bad channels.

Obtaining channel type information
Sometimes it can be useful to know channel type based on its index in the
data array. For this case, use :func:mne.channel_type, which takes
an :class:~mne.Info object and a single integer channel index:
Can you write Python code for it?


I am working on the file "0.23/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
Alternatively, you can get the indices of all channels of all channel types
present in the data, using :func:~mne.channel_indices_by_type,
which returns a :class:dict with channel types as keys, and lists of
channel indices as values:
Can you write Python code for it?

ch_idx_by_type = mne.channel_indices_by_type(info)
print(ch_idx_by_type.keys())
print(ch_idx_by_type['eog'])


I am working on the file "0.23/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
As seen in the introductory tutorial <tut-overview>, when a
:class:~mne.io.Raw object is loaded, an :class:~mne.Info object is
created automatically, and stored in the raw.info attribute:
Can you write Python code for it?


I am working on the file "0.23/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
As you can see, the :class:~mne.Info object keeps track of a lot of
information about:

the recording system (gantry angle, HPI details, sensor digitizations,
  channel names, ...)
the experiment (project name and ID, subject information, recording date,
  experimenter name or ID, ...)
the data (sampling frequency, applied filter frequencies, bad channels,
  projectors, ...)

The complete list of fields is given in :class:the API documentation
<mne.Info>.
Querying the Info object
The fields in a :class:~mne.Info object act like Python :class:dictionary
<dict> keys, using square brackets and strings to access the contents of a
field:
Can you write Python code for it?

print(info.keys())
print()  # insert a blank line
print(info['ch_names'])


I am working on the file "0.23/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
However, it is not strictly necessary to load the :class:~mne.io.Raw object
in order to view or edit the :class:~mne.Info object; you can extract all
the relevant information into a stand-alone :class:~mne.Info object using
:func:mne.io.read_info:
Can you write Python code for it?

info = mne.io.read_info(sample_data_raw_file)
print(info)


I am working on the file "0.23/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
Most of the fields contain :class:int, :class:float, or :class:list
data, but the chs field bears special mention: it contains a list of
dictionaries (one :class:dict per channel) containing everything there is
to know about a channel other than the data it recorded. Normally it is not
necessary to dig into the details of the chs field — various MNE-Python
functions can extract the information more cleanly than iterating over the
list of dicts yourself — but it can be helpful to know what is in there. Here
we show the keys for the first channel's :class:dict:
Can you write Python code for it?


I am working on the file "0.23/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
Note that the meg and fnirs parameters of :func:~mne.pick_types
accept strings as well as boolean values, to allow selecting only
magnetometer or gradiometer channels (via meg='mag' or meg='grad') or
to pick only oxyhemoglobin or deoxyhemoglobin channels (via fnirs='hbo'
or fnirs='hbr', respectively).
A third way to pick channels from an :class:~mne.Info object is to apply
regular expression_ matching to the channel names using
:func:mne.pick_channels_regexp. Here the ^ represents the beginning of
the string and . character matches any single character, so both EEG and
EOG channels will be selected:
Can you write Python code for it?


I am working on the file "0.23/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
Obtaining subsets of channels
It is often useful to convert between channel names and the integer indices
identifying rows of the data array where those channels' measurements are
stored. The :class:~mne.Info object is useful for this task; two
convenience functions that rely on the :class:mne.Info object for picking
channels are :func:mne.pick_channels and :func:mne.pick_types.
:func:~mne.pick_channels minimally takes a list of all channel names and a
list of channel names to include; it is also possible to provide an empty
list to include and specify which channels to exclude instead:
Can you write Python code for it?

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

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


I am working on the file "0.23/_downloads/9a8829bce25fe2d64489ddf54437cd3c/30_info.ipynb".
The first task is:
We can also get a nice HTML representation in IPython like:
Can you write Python code for it?


I am working on the file "0.23/_downloads/9bd293f49554a21d68d4f2a842cc6cc2/59_head_positions.ipynb".
The first task is:
Estimating continuous head position
First, let's extract the HPI coil amplitudes as a function of time:
Can you write Python code for it?


I am working on the file "0.23/_downloads/9bd293f49554a21d68d4f2a842cc6cc2/59_head_positions.ipynb".
The first task is:
Lastly, compute head positions from the coil locations:
Can you write Python code for it?

head_pos = mne.chpi.compute_head_pos(raw.info, chpi_locs, verbose=True)


I am working on the file "0.23/_downloads/9bd293f49554a21d68d4f2a842cc6cc2/59_head_positions.ipynb".
The first task is:
Note that these can then be written to disk or read from disk with
:func:mne.chpi.write_head_pos and :func:mne.chpi.read_head_pos,
respectively.
Visualizing continuous head position
We can plot as traces, which is especially useful for long recordings:
Can you write Python code for it?


I am working on the file "0.23/_downloads/9bd293f49554a21d68d4f2a842cc6cc2/59_head_positions.ipynb".
The first task is:
Or we can visualize them as a continuous field (with the vectors pointing
in the head-upward direction):
Can you write Python code for it?


I am working on the file "0.23/_downloads/9bd293f49554a21d68d4f2a842cc6cc2/59_head_positions.ipynb".
The first task is:
Second, let's compute time-varying HPI coil locations from these:
Can you write Python code for it?

chpi_locs = mne.chpi.compute_chpi_locs(raw.info, chpi_amplitudes)


I am working on the file "0.23/_downloads/9d142d98d094666b7fd2d94155f8b3ec/decoding_unsupervised_spatial_filter.ipynb".
The first task is:
Analysis of evoked response using ICA and PCA reduction techniques
This example computes PCA and ICA of evoked or epochs data. Then the
PCA / ICA components, a.k.a. spatial filters, are used to transform
the channel data to new sources / virtual channels. The output is
visualized on the average of all the epochs.
Can you write Python code for it?

# Authors: Jean-Remi King <jeanremi.king@gmail.com>
#          Asish Panda <asishrocks95@gmail.com>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.datasets import sample
from mne.decoding import UnsupervisedSpatialFilter

from sklearn.decomposition import PCA, FastICA

print(__doc__)

# Preprocess data
data_path = sample.data_path()

# Load and filter data, set up epochs
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
tmin, tmax = -0.1, 0.3
event_id = dict(aud_l=1, aud_r=2, vis_l=3, vis_r=4)

raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.filter(1, 20, fir_design='firwin')
events = mne.read_events(event_fname)

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

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

X = epochs.get_data()


I am working on the file "0.23/_downloads/9d142d98d094666b7fd2d94155f8b3ec/decoding_unsupervised_spatial_filter.ipynb".
The first task is:
Transform data with ICA computed on the raw epochs (no averaging)
Can you write Python code for it?

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

plt.show()


I am working on the file "0.23/_downloads/9d142d98d094666b7fd2d94155f8b3ec/decoding_unsupervised_spatial_filter.ipynb".
The first task is:
Transform data with PCA computed on the average ie evoked response
Can you write Python code for it?

pca = UnsupervisedSpatialFilter(PCA(30), average=False)
pca_data = pca.fit_transform(X)
ev = mne.EvokedArray(np.mean(pca_data, axis=0),
                     mne.create_info(30, epochs.info['sfreq'],
                                     ch_types='eeg'), tmin=tmin)
ev.plot(show=False, window_title="PCA", time_unit='s')


I am working on the file "0.23/_downloads/9e70404d3a55a6b6d1c1877784347c14/mixed_source_space_inverse.ipynb".
The first task is:
Compute MNE inverse solution on evoked data with a mixed source space
Create a mixed source space and compute an MNE inverse solution on an
evoked dataset.
Can you write Python code for it?

# Author: Annalisa Pascarella <a.pascarella@iac.cnr.it>
#
# License: BSD (3-clause)

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

from nilearn import plotting

import mne
from mne.minimum_norm import make_inverse_operator, apply_inverse

# Set dir
data_path = mne.datasets.sample.data_path()
subject = 'sample'
data_dir = op.join(data_path, 'MEG', subject)
subjects_dir = op.join(data_path, 'subjects')
bem_dir = op.join(subjects_dir, subject, 'bem')

# Set file names
fname_mixed_src = op.join(bem_dir, '%s-oct-6-mixed-src.fif' % subject)
fname_aseg = op.join(subjects_dir, subject, 'mri', 'aseg.mgz')

fname_model = op.join(bem_dir, '%s-5120-bem.fif' % subject)
fname_bem = op.join(bem_dir, '%s-5120-bem-sol.fif' % subject)

fname_evoked = data_dir + '/sample_audvis-ave.fif'
fname_trans = data_dir + '/sample_audvis_raw-trans.fif'
fname_fwd = data_dir + '/sample_audvis-meg-oct-6-mixed-fwd.fif'
fname_cov = data_dir + '/sample_audvis-shrunk-cov.fif'


I am working on the file "0.23/_downloads/9e70404d3a55a6b6d1c1877784347c14/mixed_source_space_inverse.ipynb".
The first task is:
Compute the fwd matrix
Can you write Python code for it?

fwd = mne.make_forward_solution(
    fname_evoked, fname_trans, src, fname_bem,
    mindist=5.0,  # ignore sources<=5mm from innerskull
    meg=True, eeg=False, n_jobs=1)
del src  # save memory

leadfield = fwd['sol']['data']
print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape)
print(f"The fwd source space contains {len(fwd['src'])} spaces and "
      f"{sum(s['nuse'] for s in fwd['src'])} vertices")

# Load data
condition = 'Left Auditory'
evoked = mne.read_evokeds(fname_evoked, condition=condition,
                          baseline=(None, 0))
noise_cov = mne.read_cov(fname_cov)


I am working on the file "0.23/_downloads/9e70404d3a55a6b6d1c1877784347c14/mixed_source_space_inverse.ipynb".
The first task is:
Get a surface-based source space, here with few source points for speed
in this demonstration, in general you should use oct6 spacing!
Can you write Python code for it?

src = mne.setup_source_space(subject, spacing='oct5',
                             add_dist=False, subjects_dir=subjects_dir)


I am working on the file "0.23/_downloads/9e70404d3a55a6b6d1c1877784347c14/mixed_source_space_inverse.ipynb".
The first task is:
Now we create a mixed src space by adding the volume regions specified in the
list labels_vol. First, read the aseg file and the source space bounds
using the inner skull surface (here using 10mm spacing to save time,
we recommend something smaller like 5.0 in actual analyses):
Can you write Python code for it?

vol_src = mne.setup_volume_source_space(
    subject, mri=fname_aseg, pos=10.0, bem=fname_model,
    volume_label=labels_vol, subjects_dir=subjects_dir,
    add_interpolator=False,  # just for speed, usually this should be True
    verbose=True)

# Generate the mixed source space
src += vol_src
print(f"The source space contains {len(src)} spaces and "
      f"{sum(s['nuse'] for s in src)} vertices")


I am working on the file "0.23/_downloads/9e70404d3a55a6b6d1c1877784347c14/mixed_source_space_inverse.ipynb".
The first task is:
Plot the volume
Can you write Python code for it?

fig = stc.volume().plot(initial_time=initial_time, src=src,
                        subjects_dir=subjects_dir)


I am working on the file "0.23/_downloads/9e70404d3a55a6b6d1c1877784347c14/mixed_source_space_inverse.ipynb".
The first task is:
Process labels
Average the source estimates within each label of the cortical parcellation
and each sub structure contained in the src space
Can you write Python code for it?

# Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi
labels_parc = mne.read_labels_from_annot(
    subject, parc=parc, subjects_dir=subjects_dir)

label_ts = mne.extract_label_time_course(
    [stc], labels_parc, src, mode='mean', allow_empty=True)

# plot the times series of 2 labels
fig, axes = plt.subplots(1)
axes.plot(1e3 * stc.times, label_ts[0][0, :], 'k', label='bankssts-lh')
axes.plot(1e3 * stc.times, label_ts[0][-1, :].T, 'r', label='Brain-stem')
axes.set(xlabel='Time (ms)', ylabel='MNE current (nAm)')
axes.legend()
mne.viz.tight_layout()


I am working on the file "0.23/_downloads/9e70404d3a55a6b6d1c1877784347c14/mixed_source_space_inverse.ipynb".
The first task is:
View the source space
Can you write Python code for it?


I am working on the file "0.23/_downloads/9e70404d3a55a6b6d1c1877784347c14/mixed_source_space_inverse.ipynb".
The first task is:
We could write the mixed source space with::

write_source_spaces(fname_mixed_src, src, overwrite=True)

We can also export source positions to NIfTI file and visualize it again:
Can you write Python code for it?

nii_fname = op.join(bem_dir, '%s-mixed-src.nii' % subject)
src.export_volume(nii_fname, mri_resolution=True, overwrite=True)
plotting.plot_img(nii_fname, cmap='nipy_spectral')


I am working on the file "0.23/_downloads/9f8cb3957705df93f5da4fe6dc1bc69b/fnirs_artifact_removal.ipynb".
The first task is:
Apply temporal derivative distribution repair
This approach corrects baseline shift and spike artifacts without the need
for any user-supplied parameters :footcite:FishburnEtAl2019.
Can you write Python code for it?

corrected_tddr = temporal_derivative_distribution_repair(corrupted_od)
corrected_tddr.plot(n_channels=15, duration=400, show_scrollbars=False)


I am working on the file "0.23/_downloads/9f8cb3957705df93f5da4fe6dc1bc69b/fnirs_artifact_removal.ipynb".
The first task is:
Import data
Here we will work with the fNIRS motor data <fnirs-motor-dataset>.
We resample the data to make indexing exact times more convenient.
We then convert the data to optical density to perform corrections on
and plot these signals.
Can you write Python code for it?

fnirs_data_folder = mne.datasets.fnirs_motor.data_path()
fnirs_cw_amplitude_dir = os.path.join(fnirs_data_folder, 'Participant-1')
raw_intensity = mne.io.read_raw_nirx(fnirs_cw_amplitude_dir, verbose=True)
raw_intensity.load_data().resample(3, npad="auto")
raw_od = optical_density(raw_intensity)
new_annotations = mne.Annotations([31, 187, 317], [8, 8, 8],
                                  ["Movement", "Movement", "Movement"])
raw_od.set_annotations(new_annotations)
raw_od.plot(n_channels=15, duration=400, show_scrollbars=False)


I am working on the file "0.23/_downloads/9f8cb3957705df93f5da4fe6dc1bc69b/fnirs_artifact_removal.ipynb".
The first task is:
Visualise NIRS artifact correction methods
Here we artificially introduce several fNIRS artifacts and observe
how artifact correction techniques attempt to correct the data.
Can you write Python code for it?

# Authors: Robert Luke <mail@robertluke.net>
#
# License: BSD (3-clause)

import os
import mne

from mne.preprocessing.nirs import (optical_density,
                                    temporal_derivative_distribution_repair)


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

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

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

print(__doc__)

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

fname_trans = data_path + '/MEG/sample/sample_audvis_raw-trans.fif'

inv_fname = data_path
inv_fname += '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'

inv = read_inverse_operator(inv_fname)

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

src = inv['src']  # get the source space

# Get access to the triangulation of the cortex

print("Number of vertices on the left hemisphere: %d" % len(src[0]['rr']))
print("Number of triangles on left hemisphere: %d" % len(src[0]['use_tris']))
print("Number of vertices on the right hemisphere: %d" % len(src[1]['rr']))
print("Number of triangles on right hemisphere: %d" % len(src[1]['use_tris']))


I am working on the file "0.23/_downloads/a179627fc73cce931ace004638e9685c/read_inverse.ipynb".
The first task is:
Show result on 3D source space
Can you write Python code for it?

fig = mne.viz.plot_alignment(subject='sample', subjects_dir=subjects_dir,
                             trans=fname_trans, surfaces='white', src=src)
set_3d_view(fig, focalpoint=(0., 0., 0.06))


I am working on the file "0.23/_downloads/a3f6a5e6550d5cc477c48007e697532b/ems_filtering.ipynb".
The first task is:
Compute effect-matched-spatial filtering (EMS)
This example computes the EMS to reconstruct the time course of the
experimental effect as described in :footcite:SchurgerEtAl2013.
This technique is used to create spatial filters based on the difference
between two conditions. By projecting the trial onto the corresponding spatial
filters, surrogate single trials are created in which multi-sensor activity is
reduced to one time series which exposes experimental effects, if present.
We will first plot a trials x times image of the single trials and order the
trials by condition. A second plot shows the average time series for each
condition. Finally a topographic plot is created which exhibits the temporal
evolution of the spatial filters.
Can you write Python code for it?

# Author: Denis Engemann <denis.engemann@gmail.com>
#         Jean-Remi King <jeanremi.king@gmail.com>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne import io, EvokedArray
from mne.datasets import sample
from mne.decoding import EMS, compute_ems
from sklearn.model_selection import StratifiedKFold

print(__doc__)

data_path = sample.data_path()

# Preprocess the data
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_ids = {'AudL': 1, 'VisL': 3}

# Read data and create epochs
raw = io.read_raw_fif(raw_fname, preload=True)
raw.filter(0.5, 45, fir_design='firwin')
events = mne.read_events(event_fname)

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

epochs = mne.Epochs(raw, events, event_ids, tmin=-0.2, tmax=0.5, picks=picks,
                    baseline=None, reject=dict(grad=4000e-13, eog=150e-6),
                    preload=True)
epochs.drop_bad()
epochs.pick_types(meg='grad')

# Setup the data to use it a scikit-learn way:
X = epochs.get_data()  # The MEG data
y = epochs.events[:, 2]  # The conditions indices
n_epochs, n_channels, n_times = X.shape

# Initialize EMS transformer
ems = EMS()

# Initialize the variables of interest
X_transform = np.zeros((n_epochs, n_times))  # Data after EMS transformation
filters = list()  # Spatial filters at each time point

# In the original paper, the cross-validation is a leave-one-out. However,
# we recommend using a Stratified KFold, because leave-one-out tends
# to overfit and cannot be used to estimate the variance of the
# prediction within a given fold.

for train, test in StratifiedKFold(n_splits=5).split(X, y):
    # In the original paper, the z-scoring is applied outside the CV.
    # However, we recommend to apply this preprocessing inside the CV.
    # Note that such scaling should be done separately for each channels if the
    # data...


I am working on the file "0.23/_downloads/a3f6a5e6550d5cc477c48007e697532b/ems_filtering.ipynb".
The first task is:
Note that a similar transformation can be applied with compute_ems
However, this function replicates Schurger et al's original paper, and thus
applies the normalization outside a leave-one-out cross-validation, which we
recommend not to do.
Can you write Python code for it?

epochs.equalize_event_counts(event_ids)
X_transform, filters, classes = compute_ems(epochs)


I am working on the file "0.23/_downloads/a3fade035778bc07f682b0807e91849e/decoding_csp_eeg.ipynb".
The first task is:
Classification with linear discrimant analysis
Can you write Python code for it?

# Define a monte-carlo cross-validation generator (reduce variance):
scores = []
epochs_data = epochs.get_data()
epochs_data_train = epochs_train.get_data()
cv = ShuffleSplit(10, test_size=0.2, random_state=42)
cv_split = cv.split(epochs_data_train)

# Assemble a classifier
lda = LinearDiscriminantAnalysis()
csp = CSP(n_components=4, reg=None, log=True, norm_trace=False)

# Use scikit-learn Pipeline with cross_val_score function
clf = Pipeline([('CSP', csp), ('LDA', lda)])
scores = cross_val_score(clf, epochs_data_train, labels, cv=cv, n_jobs=1)

# Printing the results
class_balance = np.mean(labels == labels[0])
class_balance = max(class_balance, 1. - class_balance)
print("Classification accuracy: %f / Chance level: %f" % (np.mean(scores),
                                                          class_balance))

# plot CSP patterns estimated on full data for visualization
csp.fit_transform(epochs_data, labels)

csp.plot_patterns(epochs.info, ch_type='eeg', units='Patterns (AU)', size=1.5)


I am working on the file "0.23/_downloads/a495a43b643e9ccca7a738dba79df263/find_ref_artifacts.ipynb".
The first task is:
Cleaned raw data PSD:
Can you write Python code for it?


I am working on the file "0.23/_downloads/a495a43b643e9ccca7a738dba79df263/find_ref_artifacts.ipynb".
The first task is:
Find MEG reference channel artifacts
Use ICA decompositions of MEG reference channels to remove intermittent noise.
Many MEG systems have an array of reference channels which are used to detect
external magnetic noise. However, standard techniques that use reference
channels to remove noise from standard channels often fail when noise is
intermittent. The technique described here (using ICA on the reference
channels) often succeeds where the standard techniques do not.
There are two algorithms to choose from: separate and together (default). In
the "separate" algorithm, two ICA decompositions are made: one on the reference
channels, and one on reference + standard channels. The reference + standard
channel components which correlate with the reference channel components are
removed.
In the "together" algorithm, a single ICA decomposition is made on reference +
standard channels, and those components whose weights are particularly heavy
on the reference channels are removed.
This technique is fully described and validated in :footcite:HannaEtAl2020
Can you write Python code for it?

# Authors: Jeff Hanna <jeff.hanna@gmail.com>
#
# License: BSD (3-clause)

import mne
from mne import io
from mne.datasets import refmeg_noise
from mne.preprocessing import ICA
import numpy as np

print(__doc__)

data_path = refmeg_noise.data_path()


I am working on the file "0.23/_downloads/a495a43b643e9ccca7a738dba79df263/find_ref_artifacts.ipynb".
The first task is:
Note that even though standard noise removal has already
been applied to these data, much of the noise in the reference channels
(bottom of the plot) can still be seen in the standard channels.
Can you write Python code for it?

select_picks = np.concatenate(
    (mne.pick_types(raw.info, meg=True)[-32:],
     mne.pick_types(raw.info, meg=False, ref_meg=True)))
plot_kwargs = dict(
    duration=100, order=select_picks, n_channels=len(select_picks),
    scalings={"mag": 8e-13, "ref_meg": 2e-11})
raw.plot(**plot_kwargs)


I am working on the file "0.23/_downloads/a495a43b643e9ccca7a738dba79df263/find_ref_artifacts.ipynb".
The first task is:
Read raw data, cropping to 5 minutes to save memory
Can you write Python code for it?

raw_fname = data_path + '/sample_reference_MEG_noise-raw.fif'
raw = io.read_raw_fif(raw_fname).crop(300, 600).load_data()


I am working on the file "0.23/_downloads/a495a43b643e9ccca7a738dba79df263/find_ref_artifacts.ipynb".
The first task is:
Run the "together" algorithm.
Can you write Python code for it?

raw_tog = raw.copy()
ica_kwargs = dict(
    method='picard',
    fit_params=dict(tol=1e-4),  # use a high tol here for speed
)
all_picks = mne.pick_types(raw_tog.info, meg=True, ref_meg=True)
ica_tog = ICA(n_components=60, max_iter='auto', allow_ref_meg=True,
              **ica_kwargs)
ica_tog.fit(raw_tog, picks=all_picks)
# low threshold (2.0) here because of cropped data, entire recording can use
# a higher threshold (2.5)
bad_comps, scores = ica_tog.find_bads_ref(raw_tog, threshold=2.0)

# Plot scores with bad components marked.
ica_tog.plot_scores(scores, bad_comps)

# Examine the properties of removed components. It's clear from the time
# courses and topographies that these components represent external,
# intermittent noise.
ica_tog.plot_properties(raw_tog, picks=bad_comps)

# Remove the components.
raw_tog = ica_tog.apply(raw_tog, exclude=bad_comps)


I am working on the file "0.23/_downloads/a495a43b643e9ccca7a738dba79df263/find_ref_artifacts.ipynb".
The first task is:
The PSD of these data show the noise as clear peaks.
Can you write Python code for it?


I am working on the file "0.23/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Data preprocessing
Due to a generally high SNR in SSVEP/vSSR, typical preprocessing steps
are considered optional. This doesn't mean, that a proper cleaning would not
increase your signal quality!

Raw data have FCz reference, so we will apply common-average rereferencing.

We  will apply a 0.1 highpass filter.

Lastly, we will cut the data in 20 s epochs corresponding to the trials.
Can you write Python code for it?

# Load raw data
data_path = mne.datasets.ssvep.data_path()
bids_fname = data_path + '/sub-02/ses-01/eeg/sub-02_ses-01_task-ssvep_eeg.vhdr'

raw = mne.io.read_raw_brainvision(bids_fname, preload=True, verbose=False)
raw.info['line_freq'] = 50.

# Set montage
montage = mne.channels.make_standard_montage('easycap-M1')
raw.set_montage(montage, verbose=False)

# Set common average reference
raw.set_eeg_reference('average', projection=False, verbose=False)

# Apply bandpass filter
raw.filter(l_freq=0.1, h_freq=None, fir_design='firwin', verbose=False)

# Construct epochs
event_id = {
    '12hz': 255,
    '15hz': 155
}
events, _ = mne.events_from_annotations(raw, verbose=False)
raw.info["events"] = events
tmin, tmax = -1., 20.  # in s
baseline = None
epochs = mne.Epochs(
    raw, events=events,
    event_id=[event_id['12hz'], event_id['15hz']], tmin=tmin,
    tmax=tmax, baseline=baseline, verbose=False)


I am working on the file "0.23/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Debriefing
So that's it, we hope you enjoyed our little tour through this example
dataset.
As you could see, frequency-tagging is a very powerful tool that can yield
very high signal to noise ratios and effect sizes that enable you to detect
brain responses even within a single participant and single trials of only
a few seconds duration.
Bonus exercises
For the overly motivated amongst you, let's see what else we can show with
these data.
Using the PSD function as implemented in MNE makes it very easy to change
the amount of data that is actually used in the spectrum
estimation.
Here we employ this to show you some features of frequency
tagging data that you might or might not have already intuitively expected:
Effect of trial duration on SNR
First we will simulate shorter trials by taking only the first x s of our 20s
trials (2, 4, 6, 8, ..., 20 s), and compute the SNR using a FFT window
that covers the entire epoch:
Can you write Python code for it?

stim_bandwidth = .5

# shorten data and welch window
window_lengths = [i for i in range(2, 21, 2)]
window_snrs = [[]] * len(window_lengths)
for i_win, win in enumerate(window_lengths):
    # compute spectrogram
    windowed_psd, windowed_freqs = mne.time_frequency.psd_welch(
        epochs[str(event_id['12hz'])],
        n_fft=int(sfreq * win),
        n_overlap=0, n_per_seg=None,
        tmin=0, tmax=win,
        window='boxcar',
        fmin=fmin, fmax=fmax, verbose=False)
    # define a bandwidth of 1 Hz around stimfreq for SNR computation
    bin_width = windowed_freqs[1] - windowed_freqs[0]
    skip_neighbor_freqs = \
        round((stim_bandwidth / 2) / bin_width - bin_width / 2. - .5) if (
            bin_width < stim_bandwidth) else 0
    n_neighbor_freqs = \
        int((sum((windowed_freqs <= 13) & (windowed_freqs >= 11)
                 ) - 1 - 2 * skip_neighbor_freqs) / 2)
    # compute snr
    windowed_snrs = \
        snr_spectrum(
            windowed_psd,
            noise_n_neighbor_freqs=n_neighbor_freqs if (
                n_neighbor_freqs > 0
            ) else 1,
            noise_skip_neighbor_freqs=skip_neighbor_freqs)
    window_snrs[i_win] = \
        windowed_snrs[
        :, picks_roi_vis,
        np.argmin(
            abs(windowed_freqs - 12.))].mean(axis=1)

fig, ax = plt.subplots(1)
ax.boxplot(window_snrs, labels=window_lengths, vert=True)
ax.set(title='Effect of trial duration on 12 Hz SNR',
       ylabel='Average SNR', xlabel='Trial duration [s]')
ax.axhline(1, ls='--', c='r')
fig.show()


I am working on the file "0.23/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Frequency-tagging: Basic analysis of an SSVEP/vSSR dataset
In this tutorial we compute the frequency spectrum and quantify signal-to-noise
ratio (SNR) at a target frequency in EEG data recorded during fast periodic
visual stimulation (FPVS) at 12 Hz and 15 Hz in different trials.
Extracting SNR at stimulation frequency is a simple way to quantify frequency
tagged responses in MEEG (a.k.a. steady state visually evoked potentials,
SSVEP, or visual steady-state responses, vSSR in the visual domain,
or auditory steady-state responses, ASSR in the auditory domain).
For a general introduction to the method see
Norcia et al. (2015) <https://doi.org/10.1167/15.6.4> for the visual domain,
and Picton et al. (2003) <https://doi.org/10.3109/14992020309101316> for
the auditory domain.
Data and outline:
We use a simple example dataset with frequency tagged visual stimulation:
N=2 participants observed checkerboard patterns inverting with a constant
frequency of either 12.0 Hz of 15.0 Hz.
32 channels wet EEG was recorded.
(see ssvep-dataset for more information).
We will visualize both the power-spectral density (PSD) and the SNR
spectrum of the epoched data,
extract SNR at stimulation frequency,
plot the topography of the response,
and statistically separate 12 Hz and 15 Hz responses in the different trials.
Since the evoked response is mainly generated in early visual areas of the
brain the statistical analysis will be carried out on an occipital
ROI.
   :depth: 2
Can you write Python code for it?

# Authors: Dominik Welke <dominik.welke@web.de>
#          Evgenii Kalenkovich <e.kalenkovich@gmail.com>
#
# License: BSD (3-clause)

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


I am working on the file "0.23/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Get indices for the different trial types
Can you write Python code for it?

i_trial_12hz = np.where(epochs.events[:, 2] == event_id['12hz'])[0]
i_trial_15hz = np.where(epochs.events[:, 2] == event_id['15hz'])[0]


I am working on the file "0.23/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Get indices of EEG channels forming the ROI
Can you write Python code for it?

# Define different ROIs
roi_vis = ['POz', 'Oz', 'O1', 'O2', 'PO3', 'PO4', 'PO7',
           'PO8', 'PO9', 'PO10', 'O9', 'O10']  # visual roi

# Find corresponding indices using mne.pick_types()
picks_roi_vis = mne.pick_types(epochs.info, eeg=True, stim=False,
                               exclude='bads', selection=roi_vis)


I am working on the file "0.23/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
Topography of the vSSR
But wait...
As described in the intro, we have decided a priori to work with average
SNR over a subset of occipital channels - a visual region of interest (ROI)
- because we expect SNR to be higher on these channels than in other
channels.
Let's check out, whether this was a good decision!
Here we will plot average SNR for each channel location as a topoplot.
Then we will do a simple paired T-test to check, whether average SNRs over
the two sets of channels are significantly different.
Can you write Python code for it?

# get average SNR at 12 Hz for ALL channels
snrs_12hz = snrs[i_trial_12hz, :, i_bin_12hz]
snrs_12hz_chaverage = snrs_12hz.mean(axis=0)

# plot SNR topography
fig, ax = plt.subplots(1)
mne.viz.plot_topomap(snrs_12hz_chaverage, epochs.info, vmin=1., axes=ax)

print("sub 2, 12 Hz trials, SNR at 12 Hz")
print("average SNR (all channels): %f" % snrs_12hz_chaverage.mean())
print("average SNR (occipital ROI): %f" % snrs_target.mean())

tstat_roi_vs_scalp = \
    ttest_rel(snrs_target.mean(axis=1), snrs_12hz.mean(axis=1))
print("12 Hz SNR in occipital ROI is significantly larger than 12 Hz SNR over "
      "all channels: t = %.3f, p = %f" % tstat_roi_vs_scalp)


I am working on the file "0.23/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
We can see, that 1) this participant indeed exhibits a cluster of channels
with high SNR in the occipital region and 2) that the average SNR over all
channels is smaller than the average of the visual ROI computed above.
The difference is statistically significant. Great!
Such a topography plot can be a nice tool to explore and play with your data
- e.g. you could try how changing the reference will affect the spatial
distribution of SNR values.
However, we also wanted to show this plot to point at a potential
problem with frequency-tagged (or any other brain imaging) data:
there are many channels and somewhere you will likely find some
statistically significant effect.
It is very easy - even unintended - to end up double-dipping or p-hacking.
So if you want to work with an ROI or individual channels, ideally select
them a priori - before collecting or looking at the data - and preregister
this decision so people will believe you.
If you end up selecting an ROI or individual channel for reporting because
this channel or ROI shows an effect, e.g. in an explorative analysis, this
is also fine but make it transparently and correct for multiple comparison.
Statistical separation of 12 Hz and 15 Hz vSSR
After this little detour into open science, let's move on and
do the analyses we actually wanted to do:
We will show that we can easily detect and discriminate the brains responses
in the trials with different stimulation frequencies.
In the frequency and SNR spectrum plot above, we had all trials mixed up.
Now we will extract 12 and 15 Hz SNR in both types of trials individually,
and compare the values with a simple t-test.
We will also extract SNR of the 1st and 2nd harmonic for both stimulation
frequencies. These are often reported as well and can show interesting
interactions.
Can you write Python code for it?

snrs_roi = snrs[:, picks_roi_vis, :].mean(axis=1)

freq_plot = [12, 15, 24, 30, 36, 45]
color_plot = [
    'darkblue', 'darkgreen', 'mediumblue', 'green', 'blue', 'seagreen'
]
xpos_plot = [-5. / 12, -3. / 12, -1. / 12, 1. / 12, 3. / 12, 5. / 12]
fig, ax = plt.subplots()
labels = ['12 Hz trials', '15 Hz trials']
x = np.arange(len(labels))  # the label locations
width = 0.6  # the width of the bars
res = dict()

# loop to plot SNRs at stimulation frequencies and harmonics
for i, f in enumerate(freq_plot):
    # extract snrs
    stim_12hz_tmp = \
        snrs_roi[i_trial_12hz, np.argmin(abs(freqs - f))]
    stim_15hz_tmp = \
        snrs_roi[i_trial_15hz, np.argmin(abs(freqs - f))]
    SNR_tmp = [stim_12hz_tmp.mean(), stim_15hz_tmp.mean()]
    # plot (with std)
    ax.bar(
        x + width * xpos_plot[i], SNR_tmp, width / len(freq_plot),
        yerr=np.std(SNR_tmp),
        label='%i Hz SNR' % f, color=color_plot[i])
    # store results for statistical comparison
    res['stim_12hz_snrs_%ihz' % f] = stim_12hz_tmp
    res['stim_15hz_snrs_%ihz' % f] = stim_15hz_tmp

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('SNR')
ax.set_title('Average SNR at target frequencies')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend(['%i Hz' % f for f in freq_plot], title='SNR at:')
ax.set_ylim([0, 70])
ax.axhline(1, ls='--', c='r')
fig.show()


I am working on the file "0.23/_downloads/a786781c3c54739f0be7add5b76a068f/50_ssvep.ipynb".
The first task is:
You can see that the signal estimate / our SNR measure increases with the
trial duration.
This should be easy to understand: in longer recordings there is simply
more signal (one second of additional stimulation adds, in our case, 12
cycles of signal) while the noise is (hopefully) stochastic and not locked
to the stimulation frequency.
In other words: with more data the signal term grows faster than the noise
term.
We can further see that the very short trials with FFT windows < 2-3s are not
great - here we've either hit the noise floor and/or the transient response
at the trial onset covers too much of the trial.
Again, this tutorial doesn't statistically test for the presence of a neural
response, but an F-test or Hotelling T² would be appropriate for this
purpose.
Time resolved SNR
..and finally we can trick MNE's PSD implementation to make it a
sliding window analysis and come up with a time resolved SNR measure.
This will reveal whether a participant blinked or scratched their head..
Each of the ten trials is coded with a different color in the plot below.
Can you write Python code for it?

# 3s sliding window
window_length = 4
window_starts = [i for i in range(20 - window_length)]
window_snrs = [[]] * len(window_starts)

for i_win, win in enumerate(window_starts):
    # compute spectrogram
    windowed_psd, windowed_freqs = mne.time_frequency.psd_welch(
        epochs[str(event_id['12hz'])],
        n_fft=int(sfreq * window_length) - 1,
        n_overlap=0, n_per_seg=None,
        window='boxcar',
        tmin=win, tmax=win + window_length,
        fmin=fmin, fmax=fmax,
        verbose=False)
    # define a bandwidth of 1 Hz around stimfreq for SNR computation
    bin_width = windowed_freqs[1] - windowed_freqs[0]
    skip_neighbor_freqs = \
        round((stim_bandwidth / 2) / bin_width - bin_width / 2. - .5) if (
            bin_width < stim_bandwidth) else 0
    n_neighbor_freqs = \
        int((sum((windowed_freqs <= 13) & (windowed_freqs >= 11)
                 ) - 1 - 2 * skip_neighbor_freqs) / 2)
    # compute snr
    windowed_snrs = snr_spectrum(
        windowed_psd,
        noise_n_neighbor_freqs=n_neighbor_freqs if (
            n_neighbor_freqs > 0) else 1,
        noise_skip_neighbor_freqs=skip_neighbor_freqs)
    window_snrs[i_win] = \
        windowed_snrs[:, picks_roi_vis, np.argmin(
            abs(windowed_freqs - 12.))].mean(axis=1)

fig, ax = plt.subplots(1)
colors = plt.get_cmap('Greys')(np.linspace(0, 1, 10))
for i in range(10):
    ax.plot(window_starts, np.array(window_snrs)[:, i], color=colors[i])
ax.set(title='Time resolved 12 Hz SNR - %is sliding window' % window_length,
       ylabel='Average SNR', xlabel='t0 of analysis window [s]')
ax.axhline(1, ls='--', c='r')
ax.legend(['individual trials in greyscale'])
fig.show()


I am working on the file "0.23/_downloads/a7a52312db171a64d51a6e3f9acfe5f7/20_seeg.ipynb".
The first task is:
Let's check to make sure everything is aligned.
Can you write Python code for it?

fig = mne.viz.plot_alignment(raw.info, trans, 'fsaverage',
                             subjects_dir=subjects_dir, show_axes=True,
                             surfaces=["pial", "head"])


I am working on the file "0.23/_downloads/a7a52312db171a64d51a6e3f9acfe5f7/20_seeg.ipynb".
The first task is:
Let's load some sEEG electrode locations and names, and turn them into
a :class:mne.channels.DigMontage class. First, use pandas to read in the
.tsv file.
Can you write Python code for it?

# In mne-python, the electrode coordinates are required to be in meters
elec_df = pd.read_csv(misc_path + '/seeg/sample_seeg_electrodes.tsv',
                      sep='\t', header=0, index_col=None)
ch_names = elec_df['name'].tolist()
ch_coords = elec_df[['x', 'y', 'z']].to_numpy(dtype=float)

# the test channel coordinates were in mm, so we convert them to meters
ch_coords = ch_coords / 1000.

# create dictionary of channels and their xyz coordinates (now in MNI space)
ch_pos = dict(zip(ch_names, ch_coords))

# Ideally the nasion/LPA/RPA will also be present from the digitization, here
# we use fiducials estimated from the subject's FreeSurfer MNI transformation:
lpa, nasion, rpa = mne.coreg.get_mni_fiducials(
    subject, subjects_dir=subjects_dir)
lpa, nasion, rpa = lpa['r'], nasion['r'], rpa['r']


I am working on the file "0.23/_downloads/a7a52312db171a64d51a6e3f9acfe5f7/20_seeg.ipynb".
The first task is:
Now that we have our montage, we can load in our corresponding
time-series data and set the montage to the raw data.
Can you write Python code for it?

# first we'll load in the sample dataset
raw = mne.io.read_raw_edf(misc_path + '/seeg/sample_seeg.edf')

# drop bad channels
raw.info['bads'].extend([ch for ch in raw.ch_names if ch not in ch_names])
raw.load_data()
raw.drop_channels(raw.info['bads'])
raw.crop(0, 2)  # just process 2 sec of data for speed

# attach montage
raw.set_montage(montage)

# set channel types to sEEG (instead of EEG) that have actual positions
raw.set_channel_types(
    {ch_name: 'seeg' if np.isfinite(ch_pos[ch_name]).all() else 'misc'
     for ch_name in raw.ch_names})


I am working on the file "0.23/_downloads/a7a52312db171a64d51a6e3f9acfe5f7/20_seeg.ipynb".
The first task is:
We can visualize this raw data on the fsaverage brain (in MNI space) as
a heatmap. This works by first creating an Evoked data structure
from the data of interest (in this example, it is just the raw LFP).
Then one should generate a stc data structure, which will be able
to visualize source activity on the brain in various different formats.
Can you write Python code for it?

# get standard fsaverage volume (5mm grid) source space
fname_src = op.join(subjects_dir, 'fsaverage', 'bem',
                    'fsaverage-vol-5-src.fif')
vol_src = mne.read_source_spaces(fname_src)

evoked = mne.EvokedArray(raw.get_data(), raw.info).crop(0, 1)  # shorter
stc = mne.stc_near_sensors(
    evoked, trans, subject, subjects_dir=subjects_dir, src=vol_src,
    verbose='error')  # ignore missing electrode warnings
stc = abs(stc)  # just look at magnitude
clim = dict(kind='value', lims=np.percentile(abs(evoked.data), [10, 50, 75]))


I am working on the file "0.23/_downloads/a7a52312db171a64d51a6e3f9acfe5f7/20_seeg.ipynb".
The first task is:
Working with sEEG 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
stereoelectroencephalography (sEEG) data.
This example shows how to use:

sEEG data
channel locations in MNI space
projection into a volume

Note that our sample sEEG electrodes are already assumed to be in MNI
space. If you want to map positions from your subject MRI space to MNI
fsaverage space, you must apply the FreeSurfer's talairach.xfm transform
for your dataset. You can take a look at tut-freesurfer-mne for
more information.
For an example that involves ECoG data, channel locations in a
subject-specific MRI, or projection into a surface, see
tut_working_with_ecog. In the ECoG example, we show
how to visualize surface grid channels on the brain.
Can you write Python code for it?

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

import os.path as op

import numpy as np
import pandas as pd

import mne
from mne.datasets import fetch_fsaverage

print(__doc__)

# paths to mne datasets - sample sEEG and FreeSurfer's fsaverage subject
# which is in MNI space
misc_path = mne.datasets.misc.data_path()
sample_path = mne.datasets.sample.data_path()
subject = 'fsaverage'
subjects_dir = sample_path + '/subjects'

# use mne-python's fsaverage data
fetch_fsaverage(subjects_dir=subjects_dir, verbose=True)  # downloads if needed


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

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

from time import time

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

print(__doc__)


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

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


I am working on the file "0.23/_downloads/a96f6d7ea0f7ccafcacc578a25e1f8c5/ica_comparison.ipynb".
The first task is:
Extended Infomax
Can you write Python code for it?


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


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


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


I am working on the file "0.23/_downloads/a96f6d7ea0f7ccafcacc578a25e1f8c5/ica_comparison.ipynb".
The first task is:
Read and preprocess the data. Preprocessing consists of:

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

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

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

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


I am working on the file "0.23/_downloads/a9e07affc8c71aa96bb4ffe855ff552c/morph_surface_stc.ipynb".
The first task is:
Apply morph to (Vector) SourceEstimate
The morph will be applied to the source estimate data, by giving it as the
first argument to the morph we computed above.
Can you write Python code for it?


I am working on the file "0.23/_downloads/a9e07affc8c71aa96bb4ffe855ff552c/morph_surface_stc.ipynb".
The first task is:
As inflated surface
Can you write Python code for it?

brain_inf = stc_fsaverage.plot(surface='inflated', **surfer_kwargs)

# Add title
brain_inf.add_text(0.1, 0.9, 'Morphed to fsaverage (inflated)', 'title',
                   font_size=16)


I am working on the file "0.23/_downloads/a9e07affc8c71aa96bb4ffe855ff552c/morph_surface_stc.ipynb".
The first task is:
Load example data
Can you write Python code for it?

# Read stc from file
stc = mne.read_source_estimate(fname_stc, subject='sample')


I am working on the file "0.23/_downloads/a9e07affc8c71aa96bb4ffe855ff552c/morph_surface_stc.ipynb".
The first task is:
Setting up SourceMorph for SourceEstimate
In MNE, surface source estimates represent the source space simply as
lists of vertices (see tut-source-estimate-class).
This list can either be obtained from :class:mne.SourceSpaces (src) or from
the stc itself. If you use the source space, be sure to use the
source space from the forward or inverse operator, because vertices
can be excluded during forward computation due to proximity to the BEM
inner skull surface:
Can you write Python code for it?

src_orig = mne.read_source_spaces(fname_src)
print(src_orig)  # n_used=4098, 4098
fwd = mne.read_forward_solution(fname_fwd)
print(fwd['src'])  # n_used=3732, 3766
print([len(v) for v in stc.vertices])


I am working on the file "0.23/_downloads/a9e07affc8c71aa96bb4ffe855ff552c/morph_surface_stc.ipynb".
The first task is:
Setup paths
Can you write Python code for it?

data_path = sample.data_path()
sample_dir = op.join(data_path, 'MEG', 'sample')
subjects_dir = op.join(data_path, 'subjects')
fname_src = op.join(subjects_dir, 'sample', 'bem', 'sample-oct-6-src.fif')
fname_fwd = op.join(sample_dir, 'sample_audvis-meg-oct-6-fwd.fif')
fname_fsaverage_src = os.path.join(subjects_dir, 'fsaverage', 'bem',
                                   'fsaverage-ico-5-src.fif')

fname_stc = os.path.join(sample_dir, 'sample_audvis-meg')


I am working on the file "0.23/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
Dipole fits
For computing a dipole fit, we need to load the noise covariance, the BEM
solution, and the coregistration transformation files. Note that for the
other methods, these were already used to generate the inverse operator.
Can you write Python code for it?

fname_cov = os.path.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif')
fname_bem = os.path.join(subjects_dir, 'sample', 'bem',
                         'sample-5120-bem-sol.fif')
fname_trans = os.path.join(data_path, 'MEG', 'sample',
                           'sample_audvis_raw-trans.fif')


I am working on the file "0.23/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
Dipoles are fit independently for each time point, so let us crop our time
series to visualize the dipole fit for the time point of interest.
Can you write Python code for it?

evoked.crop(0.1, 0.1)
dip = mne.fit_dipole(evoked, fname_cov, fname_bem, fname_trans)[0]


I am working on the file "0.23/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
Finally, we can visualize the dipole.
Can you write Python code for it?


I am working on the file "0.23/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
For this visualization, nilearn must be installed.
This visualization is interactive. Click on any of the anatomical slices
to explore the time series. Clicking on any time point will bring up the
corresponding anatomical map.
We could visualize the source estimate on a glass brain. Unlike the previous
visualization, a glass brain does not show us one slice but what we would
see if the brain was transparent like glass, and
:term:maximum intensity projection) is used:
Can you write Python code for it?

stc.plot(src, subject='sample', subjects_dir=subjects_dir, mode='glass_brain')


I am working on the file "0.23/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
Note that here we used initial_time=0.1, but we can also browse through
time using time_viewer=True.
In case mayavi is not available, we also offer a matplotlib
backend. Here we use verbose='error' to ignore a warning that not all
vertices were used in plotting.
Can you write Python code for it?

mpl_fig = stc.plot(subjects_dir=subjects_dir, initial_time=initial_time,
                   backend='matplotlib', verbose='error')


I am working on the file "0.23/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
The SourceEstimate object is in fact a surface source estimate. MNE also
supports volume-based source estimates but more on that later.
We can plot the source estimate using the
:func:stc.plot <mne.SourceEstimate.plot> just as in other MNE
objects. Note that for this visualization to work, you must have mayavi
and pysurfer installed on your machine.
Can you write Python code for it?

initial_time = 0.1
brain = stc.plot(subjects_dir=subjects_dir, initial_time=initial_time,
                 clim=dict(kind='value', lims=[3, 6, 9]))


I am working on the file "0.23/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
The source estimate is computed using the inverse operator and the
sensor-space data.
Can you write Python code for it?

snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)
stc = apply_inverse(evoked, inv, lambda2, method)
del inv


I am working on the file "0.23/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
This time, we have a different container
(:class:VolSourceEstimate <mne.VolSourceEstimate>) for the source time
course.
Can you write Python code for it?


I am working on the file "0.23/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
Vector Source Estimates
If we choose to use pick_ori='vector' in
:func:apply_inverse <mne.minimum_norm.apply_inverse>
Can you write Python code for it?

fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
inv = read_inverse_operator(fname_inv)
stc = apply_inverse(evoked, inv, lambda2, 'dSPM', pick_ori='vector')
brain = stc.plot(subject='sample', subjects_dir=subjects_dir,
                 initial_time=initial_time, brain_kwargs=dict(
                     silhouette=True))


I am working on the file "0.23/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
Visualize source time courses (stcs)
This tutorial focuses on visualization of :term:source estimates<STC>.
Surface Source Estimates
First, we get the paths for the evoked data and the time courses (stcs).
Can you write Python code for it?

import os
import os.path as op

import numpy as np
import matplotlib.pyplot as plt

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

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

fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
fname_stc = os.path.join(sample_dir, 'sample_audvis-meg')
fetch_hcp_mmp_parcellation(subjects_dir)


I am working on the file "0.23/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
Volume Source Estimates
We can also visualize volume source estimates (used for deep structures).
Let us load the sensor-level evoked data. We select the MEG channels
to keep things simple.
Can you write Python code for it?

evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
evoked.pick_types(meg=True, eeg=False).crop(0.05, 0.15)
# this risks aliasing, but these data are very smooth
evoked.decimate(10, verbose='error')


I am working on the file "0.23/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
You can also extract label time courses using volumetric atlases. Here we'll
use the built-in aparc.a2009s+aseg.mgz:
Can you write Python code for it?

fname_aseg = op.join(subjects_dir, 'sample', 'mri', 'aparc.a2009s+aseg.mgz')
label_names = mne.get_volume_labels_from_aseg(fname_aseg)
label_tc = stc.extract_label_time_course(fname_aseg, src=src)

lidx, tidx = np.unravel_index(np.argmax(label_tc), label_tc.shape)
fig, ax = plt.subplots(1)
ax.plot(stc.times, label_tc.T, 'k', lw=1., alpha=0.5)
xy = np.array([stc.times[tidx], label_tc[lidx, tidx]])
xytext = xy + [0.01, 1]
ax.annotate(
    label_names[lidx], xy, xytext, arrowprops=dict(arrowstyle='->'), color='r')
ax.set(xlim=stc.times[[0, -1]], xlabel='Time (s)', ylabel='Activation')
for key in ('right', 'top'):
    ax.spines[key].set_visible(False)
fig.tight_layout()


I am working on the file "0.23/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
You can also morph it to fsaverage and visualize it using a flatmap.
Can you write Python code for it?

stc_fs = mne.compute_source_morph(stc, 'sample', 'fsaverage', subjects_dir,
                                  smooth=5, verbose='error').apply(stc)
brain = stc_fs.plot(subjects_dir=subjects_dir, initial_time=initial_time,
                    clim=dict(kind='value', lims=[3, 6, 9]),
                    surface='flat', hemi='both', size=(1000, 500),
                    smoothing_steps=5, time_viewer=False,
                    add_data_kwargs=dict(
                        colorbar_kwargs=dict(label_font_size=10)))

# to help orient us, let's add a parcellation (red=auditory, green=motor,
# blue=visual)
brain.add_annotation('HCPMMP1_combined', borders=2, subjects_dir=subjects_dir)

# You can save a movie like the one on our documentation website with:
# brain.save_movie(time_dilation=20, tmin=0.05, tmax=0.16,
#                  interpolation='linear', framerate=10)


I am working on the file "0.23/_downloads/ab9aa98c1c3d10ded0b9447abaef0b61/30_ecog.ipynb".
The first task is:
Load in data and perform basic preprocessing
Let's load some ECoG electrode data with mne-bids
<https://mne.tools/mne-bids/>_.
Can you write Python code for it?

# first define the bids path
bids_path = BIDSPath(root=bids_root, subject='pt1', session='presurgery',
                     task='ictal', datatype='ieeg', extension='vhdr')

# then we'll use it to load in the sample dataset
# Here we use a format (iEEG) that is only available in MNE-BIDS 0.7+, so it
# will emit a warning on versions <= 0.6
raw = read_raw_bids(bids_path=bids_path, verbose=False)

# Pick only the ECoG channels, removing the EKG channels
raw.pick_types(ecog=True)

# Load the data
raw.load_data()

# Then we remove line frequency interference
raw.notch_filter([60], trans_bandwidth=3)

# drop bad channels
raw.drop_channels(raw.info['bads'])

# the coordinate frame of the montage
print(raw.get_montage().get_positions()['coord_frame'])

# Find the annotated events
events, event_id = mne.events_from_annotations(raw)

# Make a 25 second epoch that spans before and after the seizure onset
epoch_length = 25  # seconds
epochs = mne.Epochs(raw, events, event_id=event_id['onset'],
                    tmin=13, tmax=13 + epoch_length, baseline=None)

# And then load data and downsample.
# .. note: This is just to save execution time in this example, you should
#          not need to do this in general!
epochs.load_data()
epochs.resample(200)  # Hz, will also load the data for us

# Finally, make evoked from the one epoch
evoked = epochs.average()


I am working on the file "0.23/_downloads/ab9aa98c1c3d10ded0b9447abaef0b61/30_ecog.ipynb".
The first task is:
Visualize the time-evolution of the gamma power on the brain
Say we want to visualize the evolution of the power in the gamma band,
instead of just plotting the average. We can use
matplotlib.animation.FuncAnimation to create an animation and apply this
to the brain figure.
Can you write Python code for it?

# convert from a dictionary to array to plot
xy_pts = np.vstack([xy[ch] for ch in raw.info['ch_names']])

# get a colormap to color nearby points similar colors
cmap = get_cmap('viridis')

# create the figure of the brain with the electrode positions
fig, ax = plt.subplots(figsize=(5, 5))
ax.set_title('Gamma power over time', size='large')
ax.imshow(im)
ax.set_axis_off()

# normalize gamma power for plotting
gamma_power = -100 * gamma_power_t.data / gamma_power_t.data.max()
# add the time course overlaid on the positions
x_line = np.linspace(-0.025 * im.shape[0], 0.025 * im.shape[0],
                     gamma_power_t.data.shape[1])
for i, pos in enumerate(xy_pts):
    x, y = pos
    color = cmap(i / xy_pts.shape[0])
    ax.plot(x_line + x, gamma_power[i] + y, linewidth=0.5, color=color)