I am working on the file "0.22/_downloads/70d3a0e5dfbb415abf141d93f82df981/plot_55_setting_eeg_reference.ipynb".
The first task is:
Background
EEG measures a voltage (difference in electric potential) between each
electrode and a reference electrode. This means that whatever signal is
present at the reference electrode is effectively subtracted from all the
measurement electrodes. Therefore, an ideal reference signal is one that
captures none of the brain-specific fluctuations in electric potential,
while capturing all of the environmental noise/interference that is being
picked up by the measurement electrodes.
In practice, this means that the reference electrode is often placed in a
location on the subject's body and close to their head (so that any
environmental interference affects the reference and measurement electrodes
similarly) but as far away from the neural sources as possible (so that the
reference signal doesn't pick up brain-based fluctuations). Typical reference
locations are the subject's earlobe, nose, mastoid process, or collarbone.
Each of these has advantages and disadvantages regarding how much brain
signal it picks up (e.g., the mastoids pick up a fair amount compared to the
others), and regarding the environmental noise it picks up (e.g., earlobe
electrodes may shift easily, and have signals more similar to electrodes on
the same side of the head).
Even in cases where no electrode is specifically designated as the reference,
EEG recording hardware will still treat one of the scalp electrodes as the
reference, and the recording software may or may not display it to you (it
might appear as a completely flat channel, or the software might subtract out
the average of all signals before displaying, making it look like there is
no reference).
Setting or changing the reference channel
If you want to recompute your data with a different reference than was used
when the raw data were recorded and/or saved, MNE-Python provides the
:meth:~mne.io.Raw.set_eeg_reference method on :class:~mne.io.Raw objects
as well as the :func:mne.add_reference_channels function. To use an
existing channel as the new reference, use...
Can you write Python code for it?

# code lines below are commented out because the sample data doesn't have
# earlobe or mastoid channels, so this is just for demonstration purposes:

# use a single channel reference (left earlobe)
# raw.set_eeg_reference(ref_channels=['A1'])

# use average of mastoid channels as reference
# raw.set_eeg_reference(ref_channels=['M1', 'M2'])


I am working on the file "0.22/_downloads/70d3a0e5dfbb415abf141d93f82df981/plot_55_setting_eeg_reference.ipynb".
The first task is:
Creating the average reference as a projector
If using an average reference, it is possible to create the reference as a
:term:projector rather than subtracting the reference from the data
immediately by specifying projection=True:
Can you write Python code for it?


I am working on the file "0.22/_downloads/70d3a0e5dfbb415abf141d93f82df981/plot_55_setting_eeg_reference.ipynb".
The first task is:
Creating the average reference as a projector has a few advantages:

It is possible to turn projectors on or off when plotting, so it is easy
   to visualize the effect that the average reference has on the data.

If additional channels are marked as "bad" or if a subset of channels are
   later selected, the projector will be re-computed to take these changes
   into account (thus guaranteeing that the signal is zero-mean).

If there are other unapplied projectors affecting the EEG channels (such
   as SSP projectors for removing heartbeat or blink artifacts), EEG
   re-referencing cannot be performed until those projectors are either
   applied or removed; adding the EEG reference as a projector is not subject
   to that constraint. (The reason this wasn't a problem when we applied the
   non-projector average reference to raw_avg_ref above is that the
   empty-room projectors included in the sample data :file:.fif file were
   only computed for the magnetometers.)
Can you write Python code for it?

for title, proj in zip(['Original', 'Average'], [False, True]):
    fig = raw.plot(proj=proj, n_channels=len(raw))
    # make room for title
    fig.subplots_adjust(top=0.9)
    fig.suptitle('{} reference'.format(title), size='xx-large', weight='bold')


I am working on the file "0.22/_downloads/70d3a0e5dfbb415abf141d93f82df981/plot_55_setting_eeg_reference.ipynb".
The first task is:
If a scalp electrode was used as reference but was not saved alongside the
raw data (reference channels often aren't), you may wish to add it back to
the dataset before re-referencing. For example, if your EEG system recorded
with channel Fp1 as the reference but did not include Fp1 in the data
file, using :meth:~mne.io.Raw.set_eeg_reference to set (say) Cz as the
new reference will then subtract out the signal at Cz without restoring
the signal at Fp1. In this situation, you can add back Fp1 as a flat
channel prior to re-referencing using :func:~mne.add_reference_channels.
(Since our example data doesn't use the 10-20 electrode naming system_, the
example below adds EEG 999 as the missing reference, then sets the
reference to EEG 050.) Here's how the data looks in its original state:
Can you write Python code for it?


I am working on the file "0.22/_downloads/70d3a0e5dfbb415abf141d93f82df981/plot_55_setting_eeg_reference.ipynb".
The first task is:
Notice that the new reference (EEG 050) is now flat, while the original
reference channel that we added back to the data (EEG 999) has a non-zero
signal. Notice also that EEG 053 (which is marked as "bad" in
raw.info['bads']) is not affected by the re-referencing.
Setting average reference
To set a "virtual reference" that is the average of all channels, you can use
:meth:~mne.io.Raw.set_eeg_reference with ref_channels='average'. Just
as above, this will not affect any channels marked as "bad", nor will it
include bad channels when computing the average. However, it does modify the
:class:~mne.io.Raw object in-place, so we'll make a copy first so we can
still go back to the unmodified :class:~mne.io.Raw object later:
Can you write Python code for it?

# use the average of all channels as reference
raw_avg_ref = raw.copy().set_eeg_reference(ref_channels='average')
raw_avg_ref.plot()


I am working on the file "0.22/_downloads/70d3a0e5dfbb415abf141d93f82df981/plot_55_setting_eeg_reference.ipynb".
The first task is:
Setting the EEG reference
This tutorial describes how to set or change the EEG reference in MNE-Python.
   :depth: 2
As usual we'll start by importing the modules we need, loading some
example data <sample-dataset>, and cropping it to save memory. Since
this tutorial deals specifically with EEG, we'll also restrict the dataset to
just a few EEG channels so the plots are easier to see:
Can you write Python code for it?

import os
import mne

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)
raw.crop(tmax=60).load_data()
raw.pick(['EEG 0{:02}'.format(n) for n in range(41, 60)])


I am working on the file "0.22/_downloads/70d3a0e5dfbb415abf141d93f82df981/plot_55_setting_eeg_reference.ipynb".
The first task is:
Using an infinite reference (REST)
To use the "point at infinity" reference technique described in
:footcite:Yao2001 requires a forward model, which we can create in a few
steps. Here we use a fairly large spacing of vertices (pos = 15 mm) to
reduce computation time; a 5 mm spacing is more typical for real data
analysis:
Can you write Python code for it?

raw.del_proj()  # remove our average reference projector first
sphere = mne.make_sphere_model('auto', 'auto', raw.info)
src = mne.setup_volume_source_space(sphere=sphere, exclude=30., pos=15.)
forward = mne.make_forward_solution(raw.info, trans=None, src=src, bem=sphere)
raw_rest = raw.copy().set_eeg_reference('REST', forward=forward)

for title, _raw in zip(['Original', 'REST (∞)'], [raw, raw_rest]):
    fig = _raw.plot(n_channels=len(raw), scalings=dict(eeg=5e-5))
    # make room for title
    fig.subplots_adjust(top=0.9)
    fig.suptitle('{} reference'.format(title), size='xx-large', weight='bold')


I am working on the file "0.22/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
By default, ~mne.io.read_raw_fif displays some information about the file
it's loading; for example, here it tells us that there are four "projection
items" in the file along with the recorded data; those are :term:SSP
projectors <projector> calculated to remove environmental noise from the MEG
signals, plus a projector to mean-reference the EEG channels; these are
discussed in the tutorial tut-projectors-background. In addition to
the information displayed during loading, you can get a glimpse of the basic
details of a ~mne.io.Raw object by printing it; even more is available by
printing its info attribute (a dictionary-like object <mne.Info> that
is preserved across ~mne.io.Raw, ~mne.Epochs, and ~mne.Evoked objects).
The info data structure keeps track of channel locations, applied
filters, projectors, etc. Notice especially the chs entry, showing that
MNE-Python detects different sensor types and handles each appropriately. See
tut-info-class for more on the ~mne.Info class.
Can you write Python code for it?


I am working on the file "0.22/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
Detecting experimental events
The sample dataset includes several :term:"STIM" channels <stim channel>
that recorded electrical signals sent from the stimulus delivery computer (as
brief DC shifts / squarewave pulses). These pulses (often called "triggers")
are used in this dataset to mark experimental events: stimulus onset,
stimulus type, and participant response (button press). The individual STIM
channels are combined onto a single channel, in such a way that voltage
levels on that channel can be unambiguously decoded as a particular event
type. On older Neuromag systems (such as that used to record the sample data)
this summation channel was called STI 014, so we can pass that channel
name to the mne.find_events function to recover the timing and identity of
the stimulus events.
Can you write Python code for it?

events = mne.find_events(raw, stim_channel='STI 014')
print(events[:5])  # show the first 5


I am working on the file "0.22/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
Estimating evoked responses
Now that we have our conditions in aud_epochs and vis_epochs, we can
get an estimate of evoked responses to auditory versus visual stimuli by
averaging together the epochs in each condition. This is as simple as calling
the ~mne.Epochs.average method on the ~mne.Epochs object, and then using
a function from the :mod:mne.viz module to compare the global field power
for each sensor type of the two ~mne.Evoked objects:
Can you write Python code for it?

aud_evoked = aud_epochs.average()
vis_evoked = vis_epochs.average()

mne.viz.plot_compare_evokeds(dict(auditory=aud_evoked, visual=vis_evoked),
                             legend='upper left', show_sensors='upper right')


I am working on the file "0.22/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
Event dictionaries like this one are used when extracting epochs from
continuous data; the / character in the dictionary keys allows pooling
across conditions by requesting partial condition descriptors (i.e.,
requesting 'auditory' will select all epochs with Event IDs 1 and 2;
requesting 'left' will select all epochs with Event IDs 1 and 3). An
example of this is shown in the next section. There is also a convenient
~mne.viz.plot_events function for visualizing the distribution of events
across the duration of the recording (to make sure event detection worked as
expected). Here we'll also make use of the ~mne.Info attribute to get the
sampling frequency of the recording (so our x-axis will be in seconds instead
of in samples).
Can you write Python code for it?

fig = mne.viz.plot_events(events, event_id=event_dict, sfreq=raw.info['sfreq'],
                          first_samp=raw.first_samp)


I am working on the file "0.22/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
Evoked objects can also be combined to show contrasts between conditions,
using the mne.combine_evoked function. A simple difference can be
generated by passing weights=[1, -1]. We'll then plot the difference wave
at each sensor using ~mne.Evoked.plot_topo:
Can you write Python code for it?

evoked_diff = mne.combine_evoked([aud_evoked, vis_evoked], weights=[1, -1])
evoked_diff.pick_types(meg='mag').plot_topo(color='r', legend=False)


I am working on the file "0.22/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
Finally, in order to plot the source estimate on the subject's cortical
surface we'll also need the path to the sample subject's structural MRI files
(the subjects_dir):
Can you write Python code for it?

# path to subjects' MRI files
subjects_dir = os.path.join(sample_data_folder, 'subjects')
# plot
stc.plot(initial_time=0.1, hemi='split', views=['lat', 'med'],
         subjects_dir=subjects_dir)


I am working on the file "0.22/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
For paradigms that are not event-related (e.g., analysis of resting-state
data), you can extract regularly spaced (possibly overlapping) spans of data
by creating events using mne.make_fixed_length_events and then proceeding
with epoching as described in the next section.
Epoching continuous data
The ~mne.io.Raw object and the events array are the bare minimum needed to
create an ~mne.Epochs object, which we create with the ~mne.Epochs class
constructor. Here we'll also specify some data quality constraints: we'll
reject any epoch where peak-to-peak signal amplitude is beyond reasonable
limits for that channel type. This is done with a rejection dictionary; you
may include or omit thresholds for any of the channel types present in your
data. The values given here are reasonable for this particular dataset, but
may need to be adapted for different hardware or recording conditions. For a
more automated approach, consider using the autoreject package_.
Can you write Python code for it?


I am working on the file "0.22/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
Inverse modeling
Finally, we can estimate the origins of the evoked activity by projecting the
sensor data into this subject's :term:source space (a set of points either
on the cortical surface or within the cortical volume of that subject, as
estimated by structural MRI scans). MNE-Python supports lots of ways of doing
this (dynamic statistical parametric mapping, dipole fitting, beamformers,
etc.); here we'll use minimum-norm estimation (MNE) to generate a continuous
map of activation constrained to the cortical surface. MNE uses a linear
:term:inverse operator to project EEG+MEG sensor measurements into the
source space. The inverse operator is computed from the
:term:forward solution for this subject and an estimate of the
covariance of sensor measurements <tut_compute_covariance>. For this
tutorial we'll skip those computational steps and load a pre-computed inverse
operator from disk (it's included with the sample data
<sample-dataset>). Because this "inverse problem" is underdetermined (there
is no unique solution), here we further constrain the solution by providing a
regularization parameter specifying the relative smoothness of the current
estimates in terms of a signal-to-noise ratio (where "noise" here is akin to
baseline activity level across all of cortex).
Can you write Python code for it?

# load inverse operator
inverse_operator_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                     'sample_audvis-meg-oct-6-meg-inv.fif')
inv_operator = mne.minimum_norm.read_inverse_operator(inverse_operator_file)
# set signal-to-noise ratio (SNR) to compute regularization parameter (λ²)
snr = 3.
lambda2 = 1. / snr ** 2
# generate the source time course (STC)
stc = mne.minimum_norm.apply_inverse(vis_evoked, inv_operator,
                                     lambda2=lambda2,
                                     method='MNE')  # or dSPM, sLORETA, eLORETA


I am working on the file "0.22/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
Loading data
MNE-Python data structures are based around the FIF file format from
Neuromag, but there are reader functions for a wide variety of other
data formats <data-formats>. MNE-Python also has interfaces to a
variety of publicly available datasets <datasets>,
which MNE-Python can download and manage for you.
We'll start this tutorial by loading one of the example datasets (called
"sample-dataset"), which contains EEG and MEG data from one subject
performing an audiovisual experiment, along with structural MRI scans for
that subject. The mne.datasets.sample.data_path function will automatically
download the dataset if it isn't found in one of the expected locations, then
return the directory path to the dataset (see the documentation of
~mne.datasets.sample.data_path for a list of places it checks before
downloading). Note also that for this tutorial to run smoothly on our
servers, we're using a filtered and downsampled version of the data
(:file:sample_audvis_filt-0-40_raw.fif), but an unfiltered version
(:file:sample_audvis_raw.fif) is also included in the sample dataset and
could be substituted here when running the tutorial locally.
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_filt-0-40_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file)


I am working on the file "0.22/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
Next we'll pool across left/right stimulus presentations so we can compare
auditory versus visual responses. To avoid biasing our signals to the left or
right, we'll use ~mne.Epochs.equalize_event_counts first to randomly sample
epochs from each condition to match the number of epochs present in the
condition with the fewest good epochs.
Can you write Python code for it?

conds_we_care_about = ['auditory/left', 'auditory/right',
                       'visual/left', 'visual/right']
epochs.equalize_event_counts(conds_we_care_about)  # this operates in-place
aud_epochs = epochs['auditory']
vis_epochs = epochs['visual']
del raw, epochs  # free up memory


I am working on the file "0.22/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
Preprocessing
MNE-Python supports a variety of preprocessing approaches and techniques
(maxwell filtering, signal-space projection, independent components analysis,
filtering, downsampling, etc); see the full list of capabilities in the
:mod:mne.preprocessing and :mod:mne.filter submodules. Here we'll clean
up our data by performing independent components analysis
(~mne.preprocessing.ICA); for brevity we'll skip the steps that helped us
determined which components best capture the artifacts (see
tut-artifact-ica for a detailed walk-through of that process).
Can you write Python code for it?

# set up and fit the ICA
ica = mne.preprocessing.ICA(n_components=20, random_state=97, max_iter=800)
ica.fit(raw)
ica.exclude = [1, 2]  # details on how we picked these are omitted here
ica.plot_properties(raw, picks=ica.exclude)


event_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
              'visual/right': 4, 'smiley': 5, 'buttonpress': 32}


I am working on the file "0.22/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
We'll also pass the event dictionary as the event_id parameter (so we can
work with easy-to-pool event labels instead of the integer event IDs), and
specify tmin and tmax (the time relative to each event at which to
start and end each epoch). As mentioned above, by default ~mne.io.Raw and
~mne.Epochs data aren't loaded into memory (they're accessed from disk only
when needed), but here we'll force loading into memory using the
preload=True parameter so that we can see the results of the rejection
criteria being applied:
Can you write Python code for it?

epochs = mne.Epochs(raw, events, event_id=event_dict, tmin=-0.2, tmax=0.5,
                    reject=reject_criteria, preload=True)


I am working on the file "0.22/_downloads/78dfec6019dc9e7214e1efd97200f1c4/plot_10_overview.ipynb".
The first task is:
~mne.io.Raw objects also have several built-in plotting methods; here we
show the power spectral density (PSD) for each sensor type with
~mne.io.Raw.plot_psd, as well as a plot of the raw sensor traces with
~mne.io.Raw.plot. In the PSD plot, we'll only plot frequencies below 50 Hz
(since our data are low-pass filtered at 40 Hz). In interactive Python
sessions, ~mne.io.Raw.plot is interactive and allows scrolling, scaling,
bad channel marking, annotation, projector toggling, etc.
Can you write Python code for it?


I am working on the file "0.22/_downloads/7b0095430c62d9ef92be2dd3af2614f6/plot_30_annotate_raw.ipynb".
The first task is:

Note

If your annotations fall outside the range of data times in the
    `~mne.io.Raw` object, the annotations outside the data range will
    not be added to ``raw.annotations``, and a warning will be issued.

Now that your annotations have been added to a ~mne.io.Raw object,
you can see them when you visualize the ~mne.io.Raw object:
Can you write Python code for it?


I am working on the file "0.22/_downloads/7b0095430c62d9ef92be2dd3af2614f6/plot_30_annotate_raw.ipynb".
The first task is:
If you know that your annotation onsets are relative to some other time, you
can set orig_time before you call :meth:~mne.io.Raw.set_annotations,
and the onset times will get adjusted based on the time difference between
your specified orig_time and raw.info['meas_date'], but without the
additional adjustment for raw.first_samp. orig_time can be specified
in various ways (see the documentation of ~mne.Annotations for the
options); here we'll use an ISO 8601_ formatted string, and set it to be 50
seconds later than raw.info['meas_date'].
Can you write Python code for it?

time_format = '%Y-%m-%d %H:%M:%S.%f'
new_orig_time = (meas_date + timedelta(seconds=50)).strftime(time_format)
print(new_orig_time)

later_annot = mne.Annotations(onset=[3, 5, 7],
                              duration=[1, 0.5, 0.25],
                              description=['DDD', 'EEE', 'FFF'],
                              orig_time=new_orig_time)

raw2 = raw.copy().set_annotations(later_annot)
print(later_annot.onset)
print(raw2.annotations.onset)


I am working on the file "0.22/_downloads/7b0095430c62d9ef92be2dd3af2614f6/plot_30_annotate_raw.ipynb".
The first task is:
Notice that orig_time is None, because we haven't specified it. In
those cases, when you add the annotations to a ~mne.io.Raw object,
it is assumed that the orig_time matches the time of the first sample of
the recording, so orig_time will be set to match the recording
measurement date (raw.info['meas_date']).
Can you write Python code for it?

raw.set_annotations(my_annot)
print(raw.annotations)

# convert meas_date (a tuple of seconds, microseconds) into a float:
meas_date = raw.info['meas_date']
orig_time = raw.annotations.orig_time
print(meas_date == orig_time)


I am working on the file "0.22/_downloads/7b0095430c62d9ef92be2dd3af2614f6/plot_30_annotate_raw.ipynb".
The first task is:
Reading and writing Annotations to/from a file
~mne.Annotations objects have a :meth:~mne.Annotations.save method
which can write :file:.fif, :file:.csv, and :file:.txt formats (the
format to write is inferred from the file extension in the filename you
provide). There is a corresponding :func:~mne.read_annotations function to
load them from disk:
Can you write Python code for it?

raw.annotations.save('saved-annotations.csv')
annot_from_file = mne.read_annotations('saved-annotations.csv')
print(annot_from_file)


I am working on the file "0.22/_downloads/7b0095430c62d9ef92be2dd3af2614f6/plot_30_annotate_raw.ipynb".
The first task is:
The colored rings are clickable, and determine which existing label will be
created by the next click-and-drag operation in the main plot window. New
annotation descriptions can be added by typing the new description,
clicking the :guilabel:Add label button; the new description will be added
to the list of descriptions and automatically selected.
During interactive annotation it is also possible to adjust the start and end
times of existing annotations, by clicking-and-dragging on the left or right
edges of the highlighting rectangle corresponding to that annotation.

Warning

Calling :meth:`~mne.io.Raw.set_annotations` **replaces** any annotations
    currently stored in the `~mne.io.Raw` object, so be careful when
    working with annotations that were created interactively (you could lose
    a lot of work if you accidentally overwrite your interactive
    annotations). A good safeguard is to run
    ``interactive_annot = raw.annotations`` after you finish an interactive
    annotation session, so that the annotations are stored in a separate
    variable outside the `~mne.io.Raw` object.

How annotations affect preprocessing and analysis
You may have noticed that the description for new labels in the annotation
controls window defaults to BAD_. The reason for this is that annotation
is often used to mark bad temporal spans of data (such as movement artifacts
or environmental interference that cannot be removed in other ways such as
projection <tut-projectors-background> or filtering). Several
MNE-Python operations
are "annotation aware" and will avoid using data that is annotated with a
description that begins with "bad" or "BAD"; such operations typically have a
boolean reject_by_annotation parameter. Examples of such operations are
independent components analysis (mne.preprocessing.ICA), functions
for finding heartbeat and blink artifacts
(:func:~mne.preprocessing.find_ecg_events,
:func:~mne.preprocessing.find_eog_events), and creation of epoched...
Can you write Python code for it?

new_annot = mne.Annotations(onset=3.75, duration=0.75, description='AAA')
raw.set_annotations(my_annot + new_annot)
raw.plot(start=2, duration=6)


I am working on the file "0.22/_downloads/7b0095430c62d9ef92be2dd3af2614f6/plot_30_annotate_raw.ipynb".
The first task is:
The three annotations appear as differently colored rectangles because they
have different description values (which are printed along the top
edge of the plot area). Notice also that colored spans appear in the small
scroll bar at the bottom of the plot window, making it easy to quickly view
where in a ~mne.io.Raw object the annotations are so you can easily
browse through the data to find and examine them.
Annotating Raw objects interactively
Annotations can also be added to a ~mne.io.Raw object interactively
by clicking-and-dragging the mouse in the plot window. To do this, you must
first enter "annotation mode" by pressing :kbd:a while the plot window is
focused; this will bring up the annotation controls window:
Can you write Python code for it?


I am working on the file "0.22/_downloads/7bbeb6a728b7d16c6e61cd487ba9e517/plot_morph_volume_stc.ipynb".
The first task is:
Compute example data. For reference see
sphx_glr_auto_examples_inverse_plot_compute_mne_inverse_volume.py
Load data:
Can you write Python code for it?

evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
inverse_operator = read_inverse_operator(fname_inv)

# Apply inverse operator
stc = apply_inverse(evoked, inverse_operator, 1.0 / 3.0 ** 2, "dSPM")

# To save time
stc.crop(0.09, 0.09)


I am working on the file "0.22/_downloads/7bbeb6a728b7d16c6e61cd487ba9e517/plot_morph_volume_stc.ipynb".
The first task is:
Get a SourceMorph object for VolSourceEstimate
subject_from can typically be inferred from
:class:src <mne.SourceSpaces>,
and subject_to is  set to 'fsaverage' by default. subjects_dir can be
None when set in the environment. In that case SourceMorph can be initialized
taking src as only argument. See :class:mne.SourceMorph for more
details.
The default parameter setting for zooms will cause the reference volumes
to be resliced before computing the transform. A value of '5' would cause
the function to reslice to an isotropic voxel size of 5 mm. The higher this
value the less accurate but faster the computation will be.
The recommended way to use this is to morph to a specific destination source
space so that different subject_from morphs will go to the same space.`
A standard usage for volumetric data reads:
Can you write Python code for it?

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


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

# Author: Tommy Clausner <tommy.clausner@gmail.com>
#
# License: BSD (3-clause)
import os

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

print(__doc__)


I am working on the file "0.22/_downloads/7bbeb6a728b7d16c6e61cd487ba9e517/plot_morph_volume_stc.ipynb".
The first task is:
Plot results
Can you write Python code for it?

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

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

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


I am working on the file "0.22/_downloads/7c31b7bed6ff2a9686e321d607181951/plot_background_ica.ipynb".
The first task is:
Background on Independent Component Analysis (ICA)
:depth: 2
Many M/EEG signals including biological artifacts reflect non-Gaussian
processes. Therefore PCA-based artifact rejection will likely perform worse at
separating the signal from noise sources.
MNE-Python supports identifying artifacts and latent components using temporal ICA.
MNE-Python implements the :class:mne.preprocessing.ICA class that facilitates applying ICA
to MEG and EEG data. Here we discuss some
basics of ICA.
Concepts
ICA finds directions in the feature space corresponding to projections with high non-Gaussianity.

not necessarily orthogonal in the original feature space, but orthogonal in the whitened feature space.
In contrast, PCA finds orthogonal directions in the raw feature
  space that correspond to directions accounting for maximum variance.
or differently, if data only reflect Gaussian processes ICA and PCA are equivalent.

Example: Imagine 3 instruments playing simultaneously and 3 microphones
recording mixed signals. ICA can be used to recover the sources ie. what is played by each instrument.
ICA employs a very simple model: $X = AS$ where $X$ is our observations, $A$ is the mixing matrix and $S$ is the vector of independent (latent) sources.
The challenge is to recover $A$ and $S$ from $X$.
First generate simulated data
Can you write Python code for it?

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

from sklearn.decomposition import FastICA, PCA

np.random.seed(0)  # set seed for reproducible results
n_samples = 2000
time = np.linspace(0, 8, n_samples)

s1 = np.sin(2 * time)  # Signal 1 : sinusoidal signal
s2 = np.sign(np.sin(3 * time))  # Signal 2 : square signal
s3 = signal.sawtooth(2 * np.pi * time)  # Signal 3: sawtooth signal

S = np.c_[s1, s2, s3]
S += 0.2 * np.random.normal(size=S.shape)  # Add noise

S /= S.std(axis=0)  # Standardize data
# Mix data
A = np.array([[1, 1, 1], [0.5, 2, 1.0], [1.5, 1.0, 2.0]])  # Mixing matrix
X = np.dot(S, A.T)  # Generate observations


I am working on the file "0.22/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Accepting a shallower roll-off of the filter in the frequency domain makes
our time-domain response potentially much better. We end up with a more
gradual slope through the transition region, but a much cleaner time
domain signal. Here again for the 1 s filter:
Can you write Python code for it?

h = signal.firwin2(n, freq, gain, nyq=nyq)
plot_filter(h, sfreq, freq, gain, 'Windowed 10 Hz transition (1.0 s)',
            flim=flim, compensate=True)


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

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

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

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


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

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


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

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

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

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

import mne

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


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

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

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

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

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

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


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

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

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

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


I am working on the file "0.22/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
But if we shorten the filter too much (2 cycles of 10 Hz = 0.2 s),
our effective stop frequency gets pushed out past 60 Hz:
Can you write Python code for it?

n = int(round(sfreq * 0.2)) + 1
h = signal.firwin2(n, freq, gain, nyq=nyq)
plot_filter(h, sfreq, freq, gain, 'Windowed 10 Hz transition (0.2 s)',
            flim=flim, compensate=True)


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

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

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


I am working on the file "0.22/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Filter it with a shallow cutoff, linear-phase FIR (which allows us to
compensate for the constant filter delay):
Can you write Python code for it?

transition_band = 0.25 * f_p
f_s = f_p + transition_band
freq = [0., f_p, f_s, sfreq / 2.]
gain = [1., 1., 0., 0.]
# This would be equivalent:
h = mne.filter.create_filter(x, sfreq, l_freq=None, h_freq=f_p,
                             fir_design='firwin', verbose=True)
x_v16 = np.convolve(h, x)
# this is the linear->zero phase, causal-to-non-causal conversion / shift
x_v16 = x_v16[len(h) // 2:]

plot_filter(h, sfreq, freq, gain, 'MNE-Python 0.16 default', flim=flim,
            compensate=True)


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

Note

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

Can you write Python code for it?

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


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

Note

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

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

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


I am working on the file "0.22/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Let's also filter it with the MNE-C default, which is a long-duration
steep-slope FIR filter designed using frequency-domain techniques:
Can you write Python code for it?

h = mne.filter.design_mne_c_filter(sfreq, l_freq=None, h_freq=f_p + 2.5)
x_mne_c = np.convolve(h, x)[len(h) // 2:]

transition_band = 5  # Hz (default in MNE-C)
f_s = f_p + transition_band
freq = [0., f_p, f_s, sfreq / 2.]
gain = [1., 1., 0., 0.]
plot_filter(h, sfreq, freq, gain, 'MNE-C default', flim=flim, compensate=True)


I am working on the file "0.22/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Let's make the stop-band tighter still with a longer filter (10 s),
with a resulting larger x-axis:
Can you write Python code for it?

n = int(round(10. * sfreq))
n -= n % 2 - 1  # make it odd
t = np.arange(-(n // 2), n // 2 + 1) / sfreq
h = np.sinc(2 * f_p * t) / (4 * np.pi)
plot_filter(h, sfreq, freq, gain, 'Sinc (10.0 s)', flim=flim, compensate=True)


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

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

baseline_plot(x)


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

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


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

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


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

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

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

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

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

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


I am working on the file "0.22/_downloads/80342e62fc31882c2b53e38ec1ed14a6/plot_background_filtering.ipynb".
The first task is:
Take for example an ideal low-pass filter, which would give a magnitude
response of 1 in the pass-band (up to frequency $f_p$) and a magnitude
response of 0 in the stop-band (down to frequency $f_s$) such that
$f_p=f_s=40$ Hz here (shown to a lower limit of -60 dB for simplicity):
Can you write Python code for it?

nyq = sfreq / 2.  # the Nyquist frequency is half our sample rate
freq = [0, f_p, f_p, nyq]
gain = [1, 1, 0, 0]

third_height = np.array(plt.rcParams['figure.figsize']) * [1, 1. / 3.]
ax = plt.subplots(1, figsize=third_height)[1]
plot_ideal_filter(freq, gain, ax, title='Ideal %s Hz lowpass' % f_p, flim=flim)


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

Note

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

Let's increase the order, and note that now we have better attenuation,
with a longer impulse response. Let's also switch to using the MNE filter
design function, which simplifies a few things and gives us some information
about the resulting filter:
Can you write Python code for it?

iir_params = dict(order=8, ftype='butter')
filt = mne.filter.create_filter(x, sfreq, l_freq=None, h_freq=f_p,
                                method='iir', iir_params=iir_params,
                                verbose=True)
plot_filter(filt, sfreq, freq, gain, 'Butterworth order=8', flim=flim,
            compensate=True)
x_steep = signal.sosfiltfilt(filt['sos'], x)


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

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


I am working on the file "0.22/_downloads/81308ca6ca6807326a79661c989cfcba/plot_make_report.ipynb".
The first task is:
Add a custom section with an evoked slider:
Can you write Python code for it?

# Load the evoked data
evoked = read_evokeds(evoked_fname, condition='Left Auditory',
                      baseline=(None, 0), verbose=False)
evoked.crop(0, .2)
times = evoked.times[::4]
# Create a list of figs for the slider
figs = list()
for t in times:
    figs.append(evoked.plot_topomap(t, vmin=-300, vmax=300, res=100,
                                    show=False))
    plt.close(figs[-1])
report.add_slider_to_section(figs, times, 'Evoked Response',
                             image_format='png')  # can also use 'svg'

# Save the report
report.save('my_report.html', overwrite=True)


I am working on the file "0.22/_downloads/81308ca6ca6807326a79661c989cfcba/plot_make_report.ipynb".
The first task is:
Make an MNE-Report with a Slider
In this example, MEG evoked data are plotted in an HTML slider.
Can you write Python code for it?

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

from mne.report import Report
from mne.datasets import sample
from mne import read_evokeds
from matplotlib import pyplot as plt

data_path = sample.data_path()
meg_path = data_path + '/MEG/sample'
subjects_dir = data_path + '/subjects'
evoked_fname = meg_path + '/sample_audvis-ave.fif'


I am working on the file "0.22/_downloads/82590448493c884f52ea0c7ddc5b446b/plot_publication_figure.ipynb".
The first task is:
During interactive plotting, we might see figures like this:
Can you write Python code for it?

evoked.plot()

stc.plot(views='lat', hemi='split', size=(800, 400), subject='sample',
         subjects_dir=subjects_dir, initial_time=max_t,
         time_viewer=False, show_traces=False)


I am working on the file "0.22/_downloads/82590448493c884f52ea0c7ddc5b446b/plot_publication_figure.ipynb".
The first task is:
Evoked plot with brain activation
Suppose we want a figure with an evoked plot on top, and the brain activation
below, with the brain subplot slightly bigger than the evoked plot. Let's
start by loading some example data <sample-dataset>.
Can you write Python code for it?

data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
fname_stc = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg-eeg-lh.stc')
fname_evoked = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')

evoked = mne.read_evokeds(fname_evoked, 'Left Auditory')
evoked.pick_types(meg='grad').apply_baseline((None, 0.))
max_t = evoked.get_peak()[1]

stc = mne.read_source_estimate(fname_stc)


I am working on the file "0.22/_downloads/82590448493c884f52ea0c7ddc5b446b/plot_publication_figure.ipynb".
The first task is:
Let's make a plot.
Can you write Python code for it?

# channels to plot:
to_plot = [f"EEG {i:03}" for i in range(1, 5)]

# get the data for plotting in a short time interval from 10 to 20 seconds
start = int(raw.info['sfreq'] * 10)
stop = int(raw.info['sfreq'] * 20)
data, times = raw.get_data(picks=to_plot,
                           start=start, stop=stop, return_times=True)

# Scale the data from the MNE internal unit V to µV
data *= 1e6
# Take the mean of the channels
mean = np.mean(data, axis=0)
# make a figure
fig, ax = plt.subplots(figsize=(4.5, 3))
# plot some EEG data
ax.plot(times, mean)


I am working on the file "0.22/_downloads/82590448493c884f52ea0c7ddc5b446b/plot_publication_figure.ipynb".
The first task is:
Make figures more publication ready
In this example, we show several use cases to take MNE plots and
customize them for a more publication-ready look.
Can you write Python code for it?

# Authors: Eric Larson <larson.eric.d@gmail.com>
#          Daniel McCloy <dan.mccloy@gmail.com>
#          Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD (3-clause)


I am working on the file "0.22/_downloads/82590448493c884f52ea0c7ddc5b446b/plot_publication_figure.ipynb".
The first task is:
Now let's create our custom figure. There are lots of ways to do this step.
Here we'll create the figure and the subplot axes in one step, specifying
overall figure size, number and arrangement of subplots, and the ratio of
subplot heights for each row using :mod:GridSpec keywords
<matplotlib.gridspec>. Other approaches (using
:func:~matplotlib.pyplot.subplot2grid, or adding each axes manually) are
shown commented out, for reference.
Can you write Python code for it?

# figsize unit is inches
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(4.5, 3.),
                         gridspec_kw=dict(height_ratios=[3, 4]))

# alternate way #1: using subplot2grid
# fig = plt.figure(figsize=(4.5, 3.))
# axes = [plt.subplot2grid((7, 1), (0, 0), rowspan=3),
#         plt.subplot2grid((7, 1), (3, 0), rowspan=4)]

# alternate way #2: using figure-relative coordinates
# fig = plt.figure(figsize=(4.5, 3.))
# axes = [fig.add_axes([0.125, 0.58, 0.775, 0.3]),  # left, bot., width, height
#         fig.add_axes([0.125, 0.11, 0.775, 0.4])]

# we'll put the evoked plot in the upper axes, and the brain below
evoked_idx = 0
brain_idx = 1

# plot the evoked in the desired subplot, and add a line at peak activation
evoked.plot(axes=axes[evoked_idx])
peak_line = axes[evoked_idx].axvline(max_t, color='#66CCEE', ls='--')
# custom legend
axes[evoked_idx].legend(
    [axes[evoked_idx].lines[0], peak_line], ['MEG data', 'Peak time'],
    frameon=True, columnspacing=0.1, labelspacing=0.1,
    fontsize=8, fancybox=True, handlelength=1.8)
# remove the "N_ave" annotation
axes[evoked_idx].texts = []
# Remove spines and add grid
axes[evoked_idx].grid(True)
axes[evoked_idx].set_axisbelow(True)
for key in ('top', 'right'):
    axes[evoked_idx].spines[key].set(visible=False)
# Tweak the ticks and limits
axes[evoked_idx].set(
    yticks=np.arange(-200, 201, 100), xticks=np.arange(-0.2, 0.51, 0.1))
axes[evoked_idx].set(
    ylim=[-225, 225], xlim=[-0.2, 0.5])

# now add the brain to the lower axes
axes[brain_idx].imshow(cropped_screenshot)
axes[brain_idx].axis('off')
# add a vertical colorbar with the same properties as the 3D one
divider = make_axes_locatable(axes[brain_idx])
cax = divider.append_axes('right', size='5%', pad=0.2)
cbar = mne.viz.plot_brain_colorbar(cax, clim, colormap, label='Activation (F)')

# tweak margins and spacing
fig.subplots_adjust(
    left=0.15, right=0.9, bottom=0.01, top=0.9, wspace=0.1, hspace=0.5)

# add subplot labels
for ax, label in zip(axes, 'AB'):
    ax.text(0.03,...


I am working on the file "0.22/_downloads/82590448493c884f52ea0c7ddc5b446b/plot_publication_figure.ipynb".
The first task is:
There is only one! Those must be the sensor dots we were looking for.
We finally found exactly what we needed. Sometimes this can take a bit of
experimentation.
Can you write Python code for it?

sensor_dots = axins.collections[0]

# Recreate the figure once more; shrink the sensor dots; add axis labels
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(times, mean)
axins = inset_locator.inset_axes(ax, width="30%", height="30%", loc=2)
raw.copy().pick_channels(to_plot).plot_sensors(title="", axes=axins)
sensor_dots = axins.collections[0]
sensor_dots.set_sizes([1])
# add axis labels, and adjust bottom figure margin to make room for them
ax.set(xlabel="Time (s)", ylabel="Amplitude (µV)")
fig.subplots_adjust(bottom=0.2)


I am working on the file "0.22/_downloads/82590448493c884f52ea0c7ddc5b446b/plot_publication_figure.ipynb".
The first task is:
To make a publication-ready figure, first we'll re-plot the brain on a white
background, take a screenshot of it, and then crop out the white margins.
While we're at it, let's change the colormap, set custom colormap limits and
remove the default colorbar (so we can add a smaller, vertical one later):
Can you write Python code for it?

colormap = 'viridis'
clim = dict(kind='value', lims=[4, 8, 12])

# Plot the STC, get the brain image, crop it:
brain = stc.plot(views='lat', hemi='split', size=(800, 400), subject='sample',
                 subjects_dir=subjects_dir, initial_time=max_t, background='w',
                 colorbar=False, clim=clim, colormap=colormap,
                 time_viewer=False, show_traces=False)
screenshot = brain.screenshot()
brain.close()


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

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


I am working on the file "0.22/_downloads/8763e6c899a8b9971980be1308b5f693/plot_dics.ipynb".
The first task is:
DICS for power mapping
In this tutorial, we'll simulate two signals originating from two
locations on the cortex. These signals will be sinusoids, so we'll be looking
at oscillatory activity (as opposed to evoked activity).
We'll use dynamic imaging of coherent sources (DICS) :footcite:GrossEtAl2001
to map out spectral power along the cortex. Let's see if we can find our two
simulated sources.
Can you write Python code for it?

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


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

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

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

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

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

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

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

    return signal


I am working on the file "0.22/_downloads/8763e6c899a8b9971980be1308b5f693/plot_dics.ipynb".
The first task is:
Now the second:
Can you write Python code for it?

brain2 = plot_approach(power_approach2, 2)


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

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

brain1 = plot_approach(power_approach1, 1)


I am working on the file "0.22/_downloads/8763e6c899a8b9971980be1308b5f693/plot_dics.ipynb".
The first task is:
Power mapping
With our simulated dataset ready, we can now pretend to be researchers that
have just recorded this from a real subject and are going to study what parts
of the brain communicate with each other.
First, we'll create a source estimate of the MEG data. We'll use both a
straightforward MNE-dSPM inverse solution for this, and the DICS beamformer
which is specifically designed to work with oscillatory data.
Computing the inverse using MNE-dSPM:
Can you write Python code for it?

# Compute the inverse operator
fwd = mne.read_forward_solution(fwd_fname)
inv = make_inverse_operator(epochs.info, fwd, cov)

# Apply the inverse model to the trial that also contains the signal.
s = apply_inverse(epochs['signal'].average(), inv)

# Take the root-mean square along the time dimension and plot the result.
s_rms = np.sqrt((s ** 2).mean())
title = 'MNE-dSPM inverse (RMS)'
brain = s_rms.plot('sample', subjects_dir=subjects_dir, hemi='both', figure=1,
                   size=600, time_label=title, title=title)

# Indicate the true locations of the source activity on the plot.
brain.add_foci(vertices[0][0], coords_as_verts=True, hemi='lh')
brain.add_foci(vertices[1][0], coords_as_verts=True, hemi='rh')

# Rotate the view and add a title.
brain.show_view(view={'azimuth': 0, 'elevation': 0, 'distance': 550,
                'focalpoint': [0, 0, 0]})


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

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

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

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

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

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


I am working on the file "0.22/_downloads/8763e6c899a8b9971980be1308b5f693/plot_dics.ipynb".
The first task is:
We create an :class:mne.Epochs object containing two trials: one with
both noise and signal and one with just noise
Can you write Python code for it?

events = mne.find_events(raw, initial_event=True)
tmax = (len(stc_signal.times) - 1) / sfreq
epochs = mne.Epochs(raw, events, event_id=dict(signal=1, noise=2),
                    tmin=0, tmax=tmax, baseline=None, preload=True)
assert len(epochs) == 2  # ensure that we got the two expected events

# Plot some of the channels of the simulated data that are situated above one
# of our simulated sources.
picks = mne.pick_channels(epochs.ch_names, mne.read_selection('Left-frontal'))
epochs.plot(picks=picks)


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

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

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

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

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

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

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


I am working on the file "0.22/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:

Note

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

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

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

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


I am working on the file "0.22/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:

Note

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

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

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


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

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


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

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


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

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

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


I am working on the file "0.22/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
In the remaining sections, we'll look at different ways of choosing which ICs
to exclude prior to reconstructing the sensor signals.
Selecting ICA components manually
Once we're certain which components we want to exclude, we can specify that
manually by setting the ica.exclude attribute. Similar to marking bad
channels, merely setting ica.exclude doesn't do anything immediately (it
just adds the excluded ICs to a list that will get used later when it's
needed). Once the exclusions have been set, ICA methods like
~mne.preprocessing.ICA.plot_overlay will exclude those component(s)
even if no exclude parameter is passed, and the list of excluded
components will be preserved when using mne.preprocessing.ICA.save
and mne.preprocessing.read_ica.
Can you write Python code for it?

ica.exclude = [0, 1]  # indices chosen based on various plots above


I am working on the file "0.22/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Note that above we used ~mne.preprocessing.ICA.plot_sources on both
the original ~mne.io.Raw instance and also on an
~mne.Evoked instance of the extracted EOG artifacts. This can be
another way to confirm that ~mne.preprocessing.ICA.find_bads_eog has
identified the correct components.
Using a simulated channel to select ICA components
If you don't have an EOG channel,
~mne.preprocessing.ICA.find_bads_eog has a ch_name parameter that
you can use as a proxy for EOG. You can use a single channel, or create a
bipolar reference from frontal EEG sensors and use that as virtual EOG
channel. This carries a risk however: you must hope that the frontal EEG
channels only reflect EOG and not brain dynamics in the prefrontal cortex (or
you must not care about those prefrontal signals).
For ECG, it is easier: ~mne.preprocessing.ICA.find_bads_ecg can use
cross-channel averaging of magnetometer or gradiometer channels to construct
a virtual ECG channel, so if you have MEG channels it is usually not
necessary to pass a specific channel name.
~mne.preprocessing.ICA.find_bads_ecg also has two options for its
method parameter: 'ctps' (cross-trial phase statistics [3]_) and
'correlation' (Pearson correlation between data and ECG channel).
Can you write Python code for it?

ica.exclude = []
# find which ICs match the ECG pattern
ecg_indices, ecg_scores = ica.find_bads_ecg(raw, method='correlation',
                                            threshold='auto')
ica.exclude = ecg_indices

# barplot of ICA component "ECG match" scores
ica.plot_scores(ecg_scores)

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

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

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


I am working on the file "0.22/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Notice that the first subject has 3 different labels for the IC at index 0:
"eog/0/Fpz", "eog", and "blink". The first two were added by
~mne.preprocessing.ICA.find_bads_eog; the "blink" label was added by
the last call to ~mne.preprocessing.corrmap. Notice also that each
subject has at least one IC index labelled "blink", and subject 3 has two
components (0 and 2) labelled "blink" (consistent with the plot of IC sources
above). The labels_ attribute of ~mne.preprocessing.ICA objects
can also be manually edited to annotate the ICs with custom labels. They also
come in handy when plotting:
Can you write Python code for it?

icas[3].plot_components(picks=icas[3].labels_['blink'])
icas[3].exclude = icas[3].labels_['blink']
icas[3].plot_sources(raws[3], show_scrollbars=False)


I am working on the file "0.22/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
Now we get the message At least 1 IC detected for each subject (which is
good). At this point we'll re-run ~mne.preprocessing.corrmap with
parameters label='blink', plot=False to label the ICs from each subject
that capture the blink artifacts (without plotting them again).
Can you write Python code for it?

corrmap(icas, template=(0, eog_inds[0]), threshold=0.9, label='blink',
        plot=False)
print([ica.labels_ for ica in icas])


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

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


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

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

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


I am working on the file "0.22/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
The first figure shows the template map, while the second figure shows all
the maps that were considered a "match" for the template (including the
template itself). There were only three matches from the four subjects;
notice the output message No maps selected for subject(s) 1, consider a
more liberal threshold.  By default the threshold is set automatically by
trying several values; here it may have chosen a threshold that is too high.
Let's take a look at the ICA sources for each subject:
Can you write Python code for it?

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


I am working on the file "0.22/_downloads/8f7e6dfc30a66795f2d4e4ae5ca6d23e/plot_40_artifact_correction_ica.ipynb".
The first task is:
The last of these plots is especially useful: it shows us that the heartbeat
artifact is coming through on two ICs, and we've only caught one of them.
In fact, if we look closely at the output of
~mne.preprocessing.ICA.plot_sources (online, you can right-click →
"view image" to zoom in), it looks like ICA014 has a weak periodic
component that is in-phase with ICA001. It might be worthwhile to re-run
the ICA with more components to see if that second heartbeat artifact
resolves out a little better:
Can you write Python code for it?

# refit the ICA with 30 components this time
new_ica = ICA(n_components=30, random_state=97)
new_ica.fit(filt_raw)

# find which ICs match the ECG pattern
ecg_indices, ecg_scores = new_ica.find_bads_ecg(raw, method='correlation',
                                                threshold='auto')
new_ica.exclude = ecg_indices

# barplot of ICA component "ECG match" scores
new_ica.plot_scores(ecg_scores)

# plot diagnostics
new_ica.plot_properties(raw, picks=ecg_indices)

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

# plot ICs applied to the averaged ECG epochs, with ECG matches highlighted
new_ica.plot_sources(ecg_evoked)


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

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

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

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

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

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


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

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


I am working on the file "0.22/_downloads/90c71f0d36d740bc290fd9fa30bddd8c/plot_compute_covariance.ipynb".
The first task is:
Computing a covariance matrix
Many methods in MNE, including source estimation and some classification
algorithms, require covariance estimations from the recordings.
In this tutorial we cover the basics of sensor covariance computations and
construct a noise covariance matrix that can be used when computing the
minimum-norm inverse solution. For more information, see
minimum_norm_estimates.
Can you write Python code for it?

import os.path as op

import mne
from mne.datasets import sample


I am working on the file "0.22/_downloads/90c71f0d36d740bc290fd9fa30bddd8c/plot_compute_covariance.ipynb".
The first task is:
Note that this method also attenuates any activity in your
source estimates that resemble the baseline, if you like it or not.
Can you write Python code for it?

noise_cov_baseline = mne.compute_covariance(epochs, tmax=0)


I am working on the file "0.22/_downloads/90c71f0d36d740bc290fd9fa30bddd8c/plot_compute_covariance.ipynb".
The first task is:
Plot the covariance matrices
Try setting proj to False to see the effect. Notice that the projectors in
epochs are already applied, so proj parameter has no effect.
Can you write Python code for it?

noise_cov.plot(raw_empty_room.info, proj=True)
noise_cov_baseline.plot(epochs.info, proj=True)


I am working on the file "0.22/_downloads/90c71f0d36d740bc290fd9fa30bddd8c/plot_compute_covariance.ipynb".
The first task is:
Source estimation method such as MNE require a noise estimations from the
recordings. In this tutorial we cover the basics of noise covariance and
construct a noise covariance matrix that can be used when computing the
inverse solution. For more information, see minimum_norm_estimates.
Can you write Python code for it?

data_path = sample.data_path()
raw_empty_room_fname = op.join(
    data_path, 'MEG', 'sample', 'ernoise_raw.fif')
raw_empty_room = mne.io.read_raw_fif(raw_empty_room_fname)
raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(raw_fname)
raw.set_eeg_reference('average', projection=True)
raw.info['bads'] += ['EEG 053']  # bads + 1 more


I am working on the file "0.22/_downloads/90c71f0d36d740bc290fd9fa30bddd8c/plot_compute_covariance.ipynb".
The first task is:
The definition of noise depends on the paradigm. In MEG it is quite common
to use empty room measurements for the estimation of sensor noise. However if
you are dealing with evoked responses, you might want to also consider
resting state brain activity as noise.
First we compute the noise using empty room recording. Note that you can also
use only a part of the recording with tmin and tmax arguments. That can be
useful if you use resting state as a noise baseline. Here we use the whole
empty room recording to compute the noise covariance (tmax=None is the
same as the end of the recording, see :func:mne.compute_raw_covariance).
Keep in mind that you want to match your empty room dataset to your
actual MEG data, processing-wise. Ensure that filters
are all the same and if you use ICA, apply it to your empty-room and subject
data equivalently. In this case we did not filter the data and
we don't use ICA. However, we do have bad channels and projections in
the MEG data, and, hence, we want to make sure they get stored in the
covariance object.
Can you write Python code for it?

raw_empty_room.info['bads'] = [
    bb for bb in raw.info['bads'] if 'EEG' not in bb]
raw_empty_room.add_proj(
    [pp.copy() for pp in raw.info['projs'] if 'EEG' not in pp['desc']])

noise_cov = mne.compute_raw_covariance(
    raw_empty_room, tmin=0, tmax=None)