I am working on the file "0.23/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
EEG processing and Event Related Potentials (ERPs)
This tutorial shows how to perform standard ERP analyses in MNE-Python. Most of
the material here is covered in other tutorials too, but for convenience the
functions and methods most useful for ERP analyses are collected here, with
links to other tutorials where more detailed information is given.
As usual we'll start by importing the modules we need and loading some example
data. Instead of parsing the events from the raw data's :term:stim channel
(like we do in this tutorial <tut-events-vs-annotations>), we'll load
the events from an external events file. Finally, to speed up computations so
our documentation server can handle them, we'll crop the raw data from ~4.5
minutes down to 90 seconds.
Can you write Python code for it?

import os
import numpy as np
import matplotlib.pyplot as plt
import mne

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, preload=False)

sample_data_events_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                       'sample_audvis_filt-0-40_raw-eve.fif')
events = mne.read_events(sample_data_events_file)

raw.crop(tmax=90)  # in seconds; happens in-place
# discard events >90 seconds (not strictly necessary: avoids some warnings)
events = events[events[:, 0] <= raw.last_samp]


I am working on the file "0.23/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
Evoked responses: epoching and averaging
The general process for extracting evoked responses from continuous data is
to use the ~mne.Epochs constructor, and then average the resulting epochs
to create an ~mne.Evoked object. In MNE-Python, events are represented as
a :class:NumPy array <numpy.ndarray> of sample numbers and integer event
codes. The event codes are stored in the last column of the events array:
Can you write Python code for it?


I am working on the file "0.23/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
Global field power (GFP)
Global field power :footcite:Lehmann1980,Lehmann1984,Murray2008 is,
generally speaking, a measure of agreement of the signals picked up by all
sensors across the entire scalp: if all sensors have the same value at a
given time point, the GFP will be zero at that time point; if the signals
differ, the GFP will be non-zero at that time point. GFP
peaks may reflect "interesting" brain activity, warranting further
investigation. Mathematically, the GFP is the population standard
deviation across all sensors, calculated separately for every time point.
You can plot the GFP using evoked.plot(gfp=True) <mne.Evoked.plot>. The GFP
trace will be black if spatial_colors=True and green otherwise. The EEG
reference does not affect the GFP:
Can you write Python code for it?

for evk in (l_aud, l_vis):
    evk.plot(gfp=True, spatial_colors=True, ylim=dict(eeg=[-12, 12]))


I am working on the file "0.23/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
If you're working with a standard montage like the 10-20 <ten_twenty_>_
system, you can add sensor locations to the data like this:
raw.set_montage('standard_1020').  See tut-sensor-locations for
info on what other standard montages are built-in to MNE-Python.
If you have digitized realistic sensor locations, there are dedicated
functions for loading those digitization files into MNE-Python; see
reading-dig-montages for discussion and dig-formats for a list
of supported formats. Once loaded, the digitized sensor locations can be
added to the data by passing the loaded montage object to
raw.set_montage().
Setting the EEG reference
As mentioned above, this data already has an EEG common average reference
added as a :term:projector. We can view the effect of this on the raw data
by plotting with and without the projector applied:
Can you write Python code for it?

for proj in (False, True):
    fig = raw.plot(n_channels=5, proj=proj, scalings=dict(eeg=50e-6))
    fig.subplots_adjust(top=0.9)  # make room for title
    ref = 'Average' if proj else 'No'
    fig.suptitle(f'{ref} reference', size='xx-large', weight='bold')


I am working on the file "0.23/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
Now we can create a new Evoked with 2 virtual channels (one for each ROI):
Can you write Python code for it?

roi_dict = dict(left_ROI=left_ix, right_ROI=right_ix)
roi_evoked = mne.channels.combine_channels(l_aud, roi_dict, method='mean')
print(roi_evoked.info['ch_names'])
roi_evoked.plot()


I am working on the file "0.23/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
Now we can extract epochs from the continuous data. An interactive plot
allows you to click on epochs to mark them as "bad" and drop them from the
analysis (it is not interactive on the documentation website, but will be
when you run epochs.plot() <mne.Epochs.plot> in a Python console).
Can you write Python code for it?

epochs = mne.Epochs(raw, events, event_id=event_dict, tmin=-0.3, tmax=0.7,
                    preload=True)
fig = epochs.plot()


I am working on the file "0.23/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
Scalp topographies can also be obtained non-interactively with the
~mne.Evoked.plot_topomap method. Here we display topomaps of the average
field in 50 ms time windows centered at -200 ms, 100 ms, and 400 ms.
Can you write Python code for it?

l_aud.plot_topomap(times=[-0.2, 0.1, 0.4], average=0.05)


I am working on the file "0.23/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
The file that we loaded has already been partially processed: 3D sensor
locations have been saved as part of the .fif file, the data have been
low-pass filtered at 40 Hz, and a common average reference is set for the
EEG channels, stored as a projector (see section-avg-ref-proj in the
tut-set-eeg-ref tutorial for more info about when you may want to do
this). We'll discuss how to do each of these below.
Since this is a combined EEG+MEG dataset, let's start by restricting the data
to just the EEG and EOG channels. This will cause the other projectors saved
in the file (which apply only to magnetometer channels) to be removed. By
looking at the measurement info we can see that we now have 59 EEG channels
and 1 EOG channel.
Can you write Python code for it?


I am working on the file "0.23/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
The referencing scheme can be changed with the function
mne.set_eeg_reference (which by default operates on a copy of the data)
or the raw.set_eeg_reference() <mne.io.Raw.set_eeg_reference> method (which
always modifies the data in-place). The tutorial tut-set-eeg-ref shows
several examples of this.
Filtering
MNE-Python has extensive support for different ways of filtering data. For a
general discussion of filter characteristics and MNE-Python defaults, see
disc-filtering. For practical examples of how to apply filters to your
data, see tut-filter-resample. Here, we'll apply a simple high-pass
filter for illustration:
Can you write Python code for it?


I am working on the file "0.23/_downloads/27d6cff3f645408158cdf4f3f05a21b6/30_eeg_erp.ipynb".
The first task is:
These ~mne.Evoked objects have their own interactive plotting method
(though again, it won't be interactive on the documentation website):
click-dragging a span of time will generate a scalp field topography for that
time span. Here we also demonstrate built-in color-coding the channel traces
by location:
Can you write Python code for it?

fig1 = l_aud.plot()
fig2 = l_vis.plot(spatial_colors=True)


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

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

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

print(__doc__)


I am working on the file "0.23/_downloads/299b3deaa8eb66e88d34f06090d06628/evoked_ers_source_power.ipynb".
The first task is:
Compute some source estimates
Here we will use DICS, LCMV beamformer, and dSPM.
See ex-inverse-source-power for more information about DICS.
Can you write Python code for it?

def _gen_dics(active_win, baseline_win, epochs):
    freqs = np.logspace(np.log10(12), np.log10(30), 9)
    csd = csd_morlet(epochs, freqs, tmin=-1, tmax=1.5, decim=20)
    csd_baseline = csd_morlet(epochs, freqs, tmin=baseline_win[0],
                              tmax=baseline_win[1], decim=20)
    csd_ers = csd_morlet(epochs, freqs, tmin=active_win[0], tmax=active_win[1],
                         decim=20)
    filters = make_dics(epochs.info, fwd, csd.mean(), pick_ori='max-power',
                        reduce_rank=True, real_filter=True)
    stc_base, freqs = apply_dics_csd(csd_baseline.mean(), filters)
    stc_act, freqs = apply_dics_csd(csd_ers.mean(), filters)
    stc_act /= stc_base
    return stc_act

# generate lcmv source estimate
def _gen_lcmv(active_cov, baseline_cov, common_cov):
    filters = make_lcmv(epochs.info, fwd, common_cov, reg=0.05,
                        noise_cov=None, pick_ori='max-power')
    stc_base = apply_lcmv_cov(baseline_cov, filters)
    stc_act = apply_lcmv_cov(active_cov, filters)
    stc_act /= stc_base
    return stc_act

# generate mne/dSPM source estimate
def _gen_mne(active_cov, baseline_cov, common_cov, fwd, info, method='dSPM'):
    inverse_operator = make_inverse_operator(info, fwd, common_cov)
    stc_act = apply_inverse_cov(active_cov, info, inverse_operator,
                                method=method, verbose=True)
    stc_base = apply_inverse_cov(baseline_cov, info, inverse_operator,
                                 method=method, verbose=True)
    stc_act /= stc_base
    return stc_act

# Compute source estimates
stc_dics = _gen_dics(active_win, baseline_win, epochs)
stc_lcmv = _gen_lcmv(active_cov, baseline_cov, common_cov)
stc_dspm = _gen_mne(active_cov, baseline_cov, common_cov, fwd, epochs.info)


I am working on the file "0.23/_downloads/299b3deaa8eb66e88d34f06090d06628/evoked_ers_source_power.ipynb".
The first task is:
LCMV:
Can you write Python code for it?

brain_lcmv = stc_lcmv.plot(
    hemi='rh', subjects_dir=subjects_dir, subject=subject,
    time_label='LCMV source power in the 12-30 Hz frequency band')


I am working on the file "0.23/_downloads/299b3deaa8eb66e88d34f06090d06628/evoked_ers_source_power.ipynb".
The first task is:
Reading the raw data and creating epochs:
Can you write Python code for it?

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

# crop to 5 minutes to save memory
raw = mne.io.read_raw_fif(raw_fname).crop(0, 300)

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

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

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

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

fwd = mne.read_forward_solution(fname_fwd)


I am working on the file "0.23/_downloads/299b3deaa8eb66e88d34f06090d06628/evoked_ers_source_power.ipynb".
The first task is:
dSPM:
Can you write Python code for it?

brain_dspm = stc_dspm.plot(
    hemi='rh', subjects_dir=subjects_dir, subject=subject,
    time_label='dSPM source power in the 12-30 Hz frequency band')


I am working on the file "0.23/_downloads/2d3a2ce4cdcb2dad9804801c80816516/parcellation.ipynb".
The first task is:
Plot a cortical parcellation
In this example, we download the HCP-MMP1.0 parcellation
:footcite:GlasserEtAl2016 and show it on fsaverage.
We will also download the customized 448-label aparc
parcellation from :footcite:KhanEtAl2018.

Note

The HCP-MMP dataset has license terms restricting its use.
          Of particular relevance:

              "I will acknowledge the use of WU-Minn HCP data and data
              derived from WU-Minn HCP data when publicly presenting any
              results or algorithms that benefitted from their use."

Can you write Python code for it?

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

import mne
Brain = mne.viz.get_brain_class()

subjects_dir = mne.datasets.sample.data_path() + '/subjects'
mne.datasets.fetch_hcp_mmp_parcellation(subjects_dir=subjects_dir,
                                        verbose=True)

mne.datasets.fetch_aparc_sub_parcellation(subjects_dir=subjects_dir,
                                          verbose=True)

labels = mne.read_labels_from_annot(
    'fsaverage', 'HCPMMP1', 'lh', subjects_dir=subjects_dir)

brain = Brain('fsaverage', 'lh', 'inflated', subjects_dir=subjects_dir,
              cortex='low_contrast', background='white', size=(800, 600))
brain.add_annotation('HCPMMP1')
aud_label = [label for label in labels if label.name == 'L_A1_ROI-lh'][0]
brain.add_label(aud_label, borders=False)


I am working on the file "0.23/_downloads/2d3a2ce4cdcb2dad9804801c80816516/parcellation.ipynb".
The first task is:
We can add another custom parcellation
Can you write Python code for it?

brain = Brain('fsaverage', 'lh', 'inflated', subjects_dir=subjects_dir,
              cortex='low_contrast', background='white', size=(800, 600))
brain.add_annotation('aparc_sub')


I am working on the file "0.23/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Adding SourceEstimate (STC) plot to a report
Now we see how :class:~mne.Report handles :class:~mne.SourceEstimate
data. The following will produce a :term:stc plot with vertex
time courses. In this scenario, we also demonstrate how to use the
:meth:mne.viz.Brain.screenshot method to save the figs in a slider.
Can you write Python code for it?

report = mne.Report(verbose=True)
fname_stc = os.path.join(path, 'MEG', 'sample', 'sample_audvis-meg')
stc = mne.read_source_estimate(fname_stc, subject='sample')
figs = list()
kwargs = dict(subjects_dir=subjects_dir, initial_time=0.13,
              clim=dict(kind='value', lims=[3, 6, 9]))
for hemi in ('lh', 'rh'):
    brain = stc.plot(hemi=hemi, **kwargs)
    brain.toggle_interface(False)
    figs.append(brain.screenshot(time_viewer=True))
    brain.close()

# add the stc plot to the report:
report.add_slider_to_section(figs)

report.save('report_stc.html', overwrite=True)


I am working on the file "0.23/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Adding a slider
Sliders provide an intuitive way for users to interactively browse a
predefined set of images. You can add sliders via
:meth:~mne.Report.add_slider_to_section:
Can you write Python code for it?

report = mne.Report(verbose=True)

figs = list()
times = evoked_aud_left.times[::30]
for t in times:
    figs.append(evoked_aud_left.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'

report.save('report_slider.html', overwrite=True)


I am working on the file "0.23/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Adding coregistration plot to a report
Now we see how :class:~mne.Report can plot coregistration results. This is
very useful to check the quality of the :term:trans coregistration file
that allows to align anatomy and MEG sensors.
Can you write Python code for it?

report = mne.Report(info_fname=info_fname, subject='sample',
                    subjects_dir=subjects_dir, verbose=True)
pattern = "sample_audvis_raw-trans.fif"
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_coreg.html', overwrite=True)


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

report = mne.Report(verbose=True)

fname_raw = os.path.join(path, 'MEG', 'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(fname_raw, verbose=False).crop(tmax=60)
events = mne.find_events(raw, stim_channel='STI 014')
event_id = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
            'visual/right': 4, 'face': 5, 'buttonpress': 32}

# create some epochs and ensure we drop a few, so we can then plot the drop log
reject = dict(eeg=150e-6)
epochs = mne.Epochs(raw=raw, events=events, event_id=event_id,
                    tmin=-0.2, tmax=0.7, reject=reject, preload=True)
fig_drop_log = epochs.plot_drop_log(subject='sample', show=False)

# now also plot an evoked response
evoked_aud_left = epochs['auditory/left'].average()
fig_evoked = evoked_aud_left.plot(spatial_colors=True, show=False)

# add the custom plots to the report:
report.add_figs_to_section([fig_drop_log, fig_evoked],
                           captions=['Dropped Epochs',
                                     'Evoked: Left Auditory'],
                           section='drop-and-evoked')
report.save('report_custom.html', overwrite=True)


I am working on the file "0.23/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Before getting started with :class:mne.Report, make sure the files you want
to render follow the filename conventions defined by MNE:
.. cssclass:: table-bordered
.. rst-class:: midvalign
============== ==============================================================
Data object    Filename convention (ends with)
============== ==============================================================
raw            -raw.fif(.gz), -raw_sss.fif(.gz), -raw_tsss.fif(.gz),
               _meg.fif(.gz), _eeg.fif(.gz), _ieeg.fif(.gz)
events         -eve.fif(.gz)
epochs         -epo.fif(.gz)
evoked         -ave.fif(.gz)
covariance     -cov.fif(.gz)
SSP projectors -proj.fif(.gz)
trans          -trans.fif(.gz)
forward        -fwd.fif(.gz)
inverse        -inv.fif(.gz)
============== ==============================================================
Alternatively, the dash - in the filename may be replaced with an
underscore _.
Basic reports
The basic process for creating an HTML report is to instantiate the
:class:~mne.Report class, then use the :meth:~mne.Report.parse_folder
method to select particular files to include in the report. Which files are
included depends on both the pattern parameter passed to
:meth:~mne.Report.parse_folder and also the subject and
subjects_dir parameters provided to the :class:~mne.Report constructor.
.. sidebar: Viewing the report
On successful creation of the report, the :meth:~mne.Report.save method
   will open the HTML in a new tab in the browser. To disable this, use the
   open_browser=False parameter of :meth:~mne.Report.save.
For our first example, we'll generate a barebones report for all the
:file:.fif files containing raw data in the sample dataset, by passing the
pattern *raw.fif to :meth:~mne.Report.parse_folder. We'll omit the
subject and subjects_dir parameters from the :class:~mne.Report
constructor, but we'll also pass render_bem=False to the
:meth:~mne.Report.parse_folder method — otherwise we would get a warning
about not being able to render MRI and trans files without knowing the
subject.
Can you write Python code for it?

path = mne.datasets.sample.data_path(verbose=False)
report = mne.Report(verbose=True)
report.parse_folder(path, pattern='*raw.fif', render_bem=False)
report.save('report_basic.html', overwrite=True)


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

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


I am working on the file "0.23/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Managing report sections
The MNE report command internally manages the sections so that plots
belonging to the same section are rendered consecutively. Within a section,
the plots are ordered in the same order that they were added using the
:meth:~mne.Report.add_figs_to_section command. Each section is identified
by a toggle button in the top navigation bar of the report which can be used
to show or hide the contents of the section. To toggle the show/hide state of
all sections in the HTML report, press :kbd:t, or press the toggle-all
button in the upper right.
.. sidebar:: Structure
Although we've been generating separate reports in each of these examples,
   you could easily create a single report for all :file:.fif files (raw,
   evoked, covariance, etc) by passing pattern='*.fif'.
Editing a saved report
Saving to HTML is a write-only operation, meaning that we cannot read an
.html file back as a :class:~mne.Report object. In order to be able
to edit a report once it's no longer in-memory in an active Python session,
save it as an HDF5 file instead of HTML:
Can you write Python code for it?

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


I am working on the file "0.23/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
Now let's look at how :class:~mne.Report handles :class:~mne.Evoked data
(we will skip the MRIs to save computation time). The following code will
produce butterfly plots, topomaps, and comparisons of the global field
power (GFP) for different experimental conditions.
Can you write Python code for it?

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


I am working on the file "0.23/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
The sample dataset also contains SSP projectors stored as individual files.
To add them to a report, we also have to provide the path to a file
containing an ~mne.Info dictionary, from which the channel locations can be
read.
Can you write Python code for it?

info_fname = os.path.join(path, 'MEG', 'sample',
                          'sample_audvis_filt-0-40_raw.fif')
pattern = 'sample_audvis_*proj.fif'
report = mne.Report(info_fname=info_fname, verbose=True)
report.parse_folder(path, pattern=pattern, render_bem=False)
report.save('report_proj.html', overwrite=True)


I am working on the file "0.23/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
This allows the possibility of multiple scripts adding figures to the same
report. To make this even easier, :class:mne.Report can be used as a
context manager:
Can you write Python code for it?

with mne.open_report('report.h5') as report:
    report.add_figs_to_section(fig_evoked,
                               captions='Left Auditory',
                               section='evoked',
                               replace=True)
    report.save('report_final.html', overwrite=True)


I am working on the file "0.23/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
This report yields a textual summary of the :class:~mne.io.Raw files
selected by the pattern. For a slightly more useful report, we'll ask for the
power spectral density of the :class:~mne.io.Raw files, by passing
raw_psd=True to the :class:~mne.Report constructor. We'll also
visualize the SSP projectors stored in the raw data's ~mne.Info dictionary
by setting projs=True. Lastly, let's also refine our pattern to select
only the filtered raw recording (omitting the unfiltered data and the
empty-room noise recordings):
Can you write Python code for it?

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


I am working on the file "0.23/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
This time we'll pass a specific subject and subjects_dir (even though
there's only one subject in the sample dataset) and remove our
render_bem=False parameter so we can see the MRI slices, with BEM
contours overlaid on top if available. Since this is computationally
expensive, we'll also pass the mri_decim parameter for the benefit of our
documentation servers, and skip processing the :file:.fif files:
Can you write Python code for it?

subjects_dir = os.path.join(path, 'subjects')
report = mne.Report(subject='sample', subjects_dir=subjects_dir, verbose=True)
report.parse_folder(path, pattern='', mri_decim=25)
report.save('report_mri_bem.html', overwrite=True)


I am working on the file "0.23/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
To render whitened :class:~mne.Evoked files with baseline correction, pass
the baseline argument we just used, and add the noise covariance file.
This will display ERP/ERF plots for both the original and whitened
:class:~mne.Evoked objects, but scalp topomaps only for the original.
Can you write Python code for it?

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


I am working on the file "0.23/_downloads/2d6a273bc3ded0e873d80d802edc2b7e/70_report.ipynb".
The first task is:
You have probably noticed that the EEG recordings look particularly odd. This
is because by default, ~mne.Report does not apply baseline correction
before rendering evoked data. So if the dataset you wish to add to the report
has not been baseline-corrected already, you can request baseline correction
here. The MNE sample dataset we're using in this example has not been
baseline-corrected; so let's do this now for the report!
To request baseline correction, pass a baseline argument to
~mne.Report, which should be a tuple with the starting and ending time of
the baseline period. For more details, see the documentation on
~mne.Evoked.apply_baseline. Here, we will apply baseline correction for a
baseline period from the beginning of the time interval to time point zero.
Can you write Python code for it?

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


I am working on the file "0.23/_downloads/2dd868e4ea307404d807080fb341eb26/evoked_topomap.ipynb".
The first task is:
Additional :func:~mne.viz.plot_topomap options
We can also use a range of various :func:mne.viz.plot_topomap arguments
that control how the topography is drawn. For example:

cmap - to specify the color map
res - to control the resolution of the topographies (lower resolution
  means faster plotting)
outlines='skirt' to see the topography stretched beyond the head circle
contours to define how many contour lines should be plotted
Can you write Python code for it?

evoked.plot_topomap(times, ch_type='mag', cmap='Spectral_r', res=32,
                    outlines='skirt', contours=4, time_unit='s')


I am working on the file "0.23/_downloads/2dd868e4ea307404d807080fb341eb26/evoked_topomap.ipynb".
The first task is:
Animating the topomap
Instead of using a still image we can plot magnetometer data as an animation,
which animates properly only in matplotlib interactive mode.
Can you write Python code for it?

times = np.arange(0.05, 0.151, 0.01)
fig, anim = evoked.animate_topomap(
    times=times, ch_type='mag', frame_rate=2, time_unit='s', blit=False)


I am working on the file "0.23/_downloads/2dd868e4ea307404d807080fb341eb26/evoked_topomap.ipynb".
The first task is:
Basic :func:~mne.viz.plot_topomap options
We plot evoked topographies using :func:mne.Evoked.plot_topomap. The first
argument, times allows to specify time instants (in seconds!) for which
topographies will be shown. We select timepoints from 50 to 150 ms with a
step of 20ms and plot magnetometer data:
Can you write Python code for it?

times = np.arange(0.05, 0.151, 0.02)
evoked.plot_topomap(times, ch_type='mag', time_unit='s')


I am working on the file "0.23/_downloads/2dd868e4ea307404d807080fb341eb26/evoked_topomap.ipynb".
The first task is:
If times is set to None at most 10 regularly spaced topographies will be
shown:
Can you write Python code for it?


I am working on the file "0.23/_downloads/2dd868e4ea307404d807080fb341eb26/evoked_topomap.ipynb".
The first task is:
More advanced usage
Now we plot magnetometer data as topomap at a single time point: 100 ms
post-stimulus, add channel labels, title and adjust plot margins:
Can you write Python code for it?

evoked.plot_topomap(0.1, ch_type='mag', show_names=True, colorbar=False,
                    size=6, res=128, title='Auditory response',
                    time_unit='s')
plt.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.88)


I am working on the file "0.23/_downloads/2dd868e4ea307404d807080fb341eb26/evoked_topomap.ipynb".
The first task is:
Plotting topographic maps of evoked data
Load evoked data and plot topomaps for selected time points using multiple
additional options.
Can you write Python code for it?

# Authors: Christian Brodbeck <christianbrodbeck@nyu.edu>
#          Tal Linzen <linzen@nyu.edu>
#          Denis A. Engeman <denis.engemann@gmail.com>
#          Mikołaj Magnuski <mmagnuski@swps.edu.pl>
#          Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

from mne.datasets import sample
from mne import read_evokeds

print(__doc__)

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

# load evoked corresponding to a specific condition
# from the fif file and subtract baseline
condition = 'Left Auditory'
evoked = read_evokeds(fname, condition=condition, baseline=(None, 0))


I am working on the file "0.23/_downloads/2dd868e4ea307404d807080fb341eb26/evoked_topomap.ipynb".
The first task is:
We can plot gradiometer data (plots the RMS for each pair of gradiometers)
Can you write Python code for it?


I am working on the file "0.23/_downloads/2dd868e4ea307404d807080fb341eb26/evoked_topomap.ipynb".
The first task is:
We can use nrows and ncols parameter to create multiline plots
with more timepoints.
Can you write Python code for it?

all_times = np.arange(-0.2, 0.5, 0.03)
evoked.plot_topomap(all_times, ch_type='mag', time_unit='s',
                    ncols=8, nrows='auto')


I am working on the file "0.23/_downloads/31239620dd9631320a99b07ac4a81074/interpolate_bad_channels.ipynb".
The first task is:
Compute interpolation (also works with Raw and Epochs objects)
Can you write Python code for it?

evoked_interp = evoked.copy().interpolate_bads(reset_bads=False)
evoked_interp.plot(exclude=[], picks=('grad', 'eeg'))


I am working on the file "0.23/_downloads/31239620dd9631320a99b07ac4a81074/interpolate_bad_channels.ipynb".
The first task is:
Interpolate bad channels for MEG/EEG channels
This example shows how to interpolate bad MEG/EEG channels

Using spherical splines from :footcite:PerrinEtAl1989 for EEG data.
Using field interpolation for MEG and EEG data.

In this example, the bad channels will still be marked as bad.
Only the data in those channels is replaced.
Can you write Python code for it?

# Authors: Denis A. Engemann <denis.engemann@gmail.com>
#          Mainak Jas <mainak.jas@telecom-paristech.fr>
#
# License: BSD (3-clause)

import mne
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
evoked = mne.read_evokeds(fname, condition='Left Auditory',
                          baseline=(None, 0))

# plot with bads
evoked.plot(exclude=[], picks=('grad', 'eeg'))


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

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

import numpy as np
import matplotlib.pyplot as plt

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

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


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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

    X = epochs.get_data()

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


I am working on the file "0.23/_downloads/31346d4139299a77a0b57c1c39fff3ee/decoding_csp_timefreq.ipynb".
The first task is:
Plot time-frequency results
Can you write Python code for it?

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

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


I am working on the file "0.23/_downloads/33d5dd5786fed13908838e94d55ac785/90_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.23/_downloads/33d5dd5786fed13908838e94d55ac785/90_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.23/_downloads/33d5dd5786fed13908838e94d55ac785/90_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)


I am working on the file "0.23/_downloads/33d5dd5786fed13908838e94d55ac785/90_compute_covariance.ipynb".
The first task is:
This plot displays both, the whitened evoked signals for each channels and
the whitened :term:GFP. The numbers in the GFP panel represent the
estimated rank of the data, which amounts to the effective degrees of freedom
by which the squared sum across sensors is divided when computing the
whitened :term:GFP. The whitened :term:GFP also helps detecting spurious
late evoked components which can be the consequence of over- or
under-regularization.
Note that if data have been processed using signal space separation
(SSS) :footcite:TauluEtAl2005,
gradiometers and magnetometers will be displayed jointly because both are
reconstructed from the same SSS basis vectors with the same numerical rank.
This also implies that both sensor types are not any longer statistically
independent.
These methods for evaluation can be used to assess model violations.
Additional
introductory materials can be found here <https://goo.gl/ElWrxe>_.
For expert use cases or debugging the alternative estimators can also be
compared (see ex-evoked-whitening) and
ex-covariance-whitening-dspm):
Can you write Python code for it?

noise_covs = mne.compute_covariance(
    epochs, tmax=0., method=('empirical', 'shrunk'), return_estimators=True,
    rank=None)
evoked.plot_white(noise_covs, time_unit='s')


I am working on the file "0.23/_downloads/33d5dd5786fed13908838e94d55ac785/90_compute_covariance.ipynb".
The first task is:
This procedure evaluates the noise covariance quantitatively by how well it
whitens the data using the
negative log-likelihood of unseen data. The final result can also be visually
inspected.
Under the assumption that the baseline does not contain a systematic signal
(time-locked to the event of interest), the whitened baseline signal should
be follow a multivariate Gaussian distribution, i.e.,
whitened baseline signals should be between -1.96 and 1.96 at a given time
sample.
Based on the same reasoning, the expected value for the :term:global field
power (GFP) <GFP> is 1 (calculation of the GFP should take into account the
true degrees of freedom, e.g. ddof=3 with 2 active SSP vectors):
Can you write Python code for it?

evoked = epochs.average()
evoked.plot_white(noise_cov_reg, time_unit='s')


I am working on the file "0.23/_downloads/33d5dd5786fed13908838e94d55ac785/90_compute_covariance.ipynb".
The first task is:
This will plot the whitened evoked for the optimal estimator and display the
:term:GFP for all estimators as separate lines in the related panel.
Finally, let's have a look at the difference between empty room and
event related covariance, hacking the "method" option so that their types
are shown in the legend of the plot.
Can you write Python code for it?

evoked_meg = evoked.copy().pick('meg')
noise_cov['method'] = 'empty_room'
noise_cov_baseline['method'] = 'baseline'
evoked_meg.plot_white([noise_cov_baseline, noise_cov], time_unit='s')


I am working on the file "0.23/_downloads/3bb9354e99617f5fdf32e50748fc566d/15_inplace.ipynb".
The first task is:
Channel picking
Another group of methods where data is modified in-place are the
channel-picking methods. For example:
Can you write Python code for it?

print(f'original data had {original_raw.info["nchan"]} channels.')
original_raw.pick('eeg')  # selects only the EEG channels
print(f'after picking, it has {original_raw.info["nchan"]} channels.')


I am working on the file "0.23/_downloads/3bb9354e99617f5fdf32e50748fc566d/15_inplace.ipynb".
The first task is:
Modifying data in-place
Many of MNE-Python's data objects (~mne.io.Raw, ~mne.Epochs, ~mne.Evoked,
etc) have methods that modify the data in-place (either optionally or
obligatorily). This can be advantageous when working with large datasets
because it reduces the amount of computer memory needed to perform the
computations. However, it can lead to unexpected results if you're not aware
that it's happening. This tutorial provides a few examples of in-place
processing, and how and when to avoid it.
As usual we'll start by importing the modules we need and
loading some example data <sample-dataset>:
Can you write Python code for it?

import os
import 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')
# the preload flag loads the data into memory now
raw = mne.io.read_raw_fif(sample_data_raw_file, preload=True)
raw.crop(tmax=10.)  # raw.crop() always happens in-place


I am working on the file "0.23/_downloads/3bb9354e99617f5fdf32e50748fc566d/15_inplace.ipynb".
The first task is:
Signal processing
Most MNE-Python data objects have built-in methods for filtering, including
high-, low-, and band-pass filters (~mne.io.Raw.filter), band-stop filters
(~mne.io.Raw.notch_filter),
Hilbert transforms (~mne.io.Raw.apply_hilbert),
and even arbitrary or user-defined functions (~mne.io.Raw.apply_function).
These typically always modify data in-place, so if we want to preserve
the unprocessed data for comparison, we must first make a copy of it. For
example:
Can you write Python code for it?

original_raw = raw.copy()
raw.apply_hilbert()
print(f'original data type was {original_raw.get_data().dtype}, after '
      f'apply_hilbert the data type changed to {raw.get_data().dtype}.')


I am working on the file "0.23/_downloads/3d564af6b3f1e758cf01cd38abefd45f/50_epochs_to_data_frame.ipynb".
The first task is:
Converting an Epochs object to a DataFrame
Once we have our :class:~mne.Epochs object, converting it to a
:class:~pandas.DataFrame is simple: just call :meth:epochs.to_data_frame()
<mne.Epochs.to_data_frame>. Each channel's data will be a column of the new
:class:~pandas.DataFrame, alongside three additional columns of event name,
epoch number, and sample time. Here we'll just show the first few rows and
columns:
Can you write Python code for it?

df = epochs.to_data_frame()
df.iloc[:5, :10]


I am working on the file "0.23/_downloads/3d564af6b3f1e758cf01cd38abefd45f/50_epochs_to_data_frame.ipynb".
The first task is:
Exporting Epochs to Pandas DataFrames
This tutorial shows how to export the data in :class:~mne.Epochs objects to a
:class:Pandas DataFrame <pandas.DataFrame>, and applies a typical Pandas
:doc:split-apply-combine <pandas:user_guide/groupby> workflow to examine the
latencies of the response maxima across epochs and conditions.
We'll use the sample-dataset dataset, but load a version of the raw file
that has already been filtered and downsampled, and has an average reference
applied to its EEG channels. As usual we'll start by importing the modules we
need and loading the data:
Can you write Python code for it?

import os
import seaborn as sns
import mne

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, verbose=False)


I am working on the file "0.23/_downloads/3d564af6b3f1e758cf01cd38abefd45f/50_epochs_to_data_frame.ipynb".
The first task is:
Next we'll load a list of events from file, map them to condition names with
an event dictionary, set some signal rejection thresholds (cf.
tut-reject-epochs-section), and segment the continuous data into
epochs:
Can you write Python code for it?

sample_data_events_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                       'sample_audvis_filt-0-40_raw-eve.fif')
events = mne.read_events(sample_data_events_file)

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

reject_criteria = dict(mag=3000e-15,     # 3000 fT
                       grad=3000e-13,    # 3000 fT/cm
                       eeg=100e-6,       # 100 µV
                       eog=200e-6)       # 200 µV

tmin, tmax = (-0.2, 0.5)  # epoch from 200 ms before event to 500 ms after it
baseline = (None, 0)      # baseline period from start of epoch to time=0

epochs = mne.Epochs(raw, events, event_dict, tmin, tmax, proj=True,
                    baseline=baseline, reject=reject_criteria, preload=True)
del raw


I am working on the file "0.23/_downloads/3d564af6b3f1e758cf01cd38abefd45f/50_epochs_to_data_frame.ipynb".
The first task is:
Notice that the time values are no longer integers, and the channel values
have changed by several orders of magnitude compared to the earlier
DataFrame.
Setting the index
It is also possible to move one or more of the indicator columns (event name,
epoch number, and sample time) into the index <pandas:indexing>, by
passing a string or list of strings as the index parameter. We'll also
demonstrate here the effect of time_format='timedelta', yielding
:class:~pandas.Timedelta values in the "time" column.
Can you write Python code for it?

df = epochs.to_data_frame(index=['condition', 'epoch'],
                          time_format='timedelta')
df.iloc[:5, :10]


I am working on the file "0.23/_downloads/3d564af6b3f1e758cf01cd38abefd45f/50_epochs_to_data_frame.ipynb".
The first task is:
Scaling time and channel values
By default, time values are converted from seconds to milliseconds and
then rounded to the nearest integer; if you don't want this, you can pass
time_format=None to keep time as a :class:float value in seconds, or
convert it to a :class:~pandas.Timedelta value via
time_format='timedelta'.
Note also that, by default, channel measurement values are scaled so that EEG
data are converted to µV, magnetometer data are converted to fT, and
gradiometer data are converted to fT/cm. These scalings can be customized
through the scalings parameter, or suppressed by passing
scalings=dict(eeg=1, mag=1, grad=1).
Can you write Python code for it?

df = epochs.to_data_frame(time_format=None,
                          scalings=dict(eeg=1, mag=1, grad=1))
df.iloc[:5, :10]


I am working on the file "0.23/_downloads/3d564af6b3f1e758cf01cd38abefd45f/50_epochs_to_data_frame.ipynb".
The first task is:
We can also now use all the power of Pandas for grouping and transforming our
data. Here, we find the latency of peak activation of 2 gradiometers (one
near auditory cortex and one near visual cortex), and plot the distribution
of the timing of the peak in each channel as a :func:~seaborn.violinplot:
Can you write Python code for it?

df = epochs.to_data_frame(time_format=None)
peak_latency = (df.filter(regex=r'condition|epoch|MEG 1332|MEG 2123')
                .groupby(['condition', 'epoch'])
                .aggregate(lambda x: df['time'].iloc[x.idxmax()])
                .reset_index()
                .melt(id_vars=['condition', 'epoch'],
                      var_name='channel',
                      value_name='latency of peak')
                )

ax = sns.violinplot(x='channel', y='latency of peak', hue='condition',
                    data=peak_latency, palette='deep', saturation=1)


I am working on the file "0.23/_downloads/47923e53e0be940f05f054346a1ec113/elekta_epochs.ipynb".
The first task is:
Check DACQ defined averaging categories and other info
Can you write Python code for it?


I am working on the file "0.23/_downloads/47923e53e0be940f05f054346a1ec113/elekta_epochs.ipynb".
The first task is:
Extract epochs corresponding to a category
Can you write Python code for it?

cond = raw.acqparser.get_condition(raw, 'Auditory right')
epochs = mne.Epochs(raw, **cond)
epochs.average().plot_topo(background_color='w')


I am working on the file "0.23/_downloads/47923e53e0be940f05f054346a1ec113/elekta_epochs.ipynb".
The first task is:
Getting averaging info from .fif files
Parse averaging information defined in Elekta Vectorview/TRIUX DACQ (data
acquisition). Extract and average epochs accordingly. Modify some
averaging parameters and get epochs.
Can you write Python code for it?

# Author: Jussi Nurminen (jnu@iki.fi)
#
# License: BSD (3-clause)

import mne
import os
from mne.datasets import multimodal

fname_raw = os.path.join(multimodal.data_path(), 'multimodal_raw.fif')

print(__doc__)


I am working on the file "0.23/_downloads/47923e53e0be940f05f054346a1ec113/elekta_epochs.ipynb".
The first task is:
Read raw file
Can you write Python code for it?


I am working on the file "0.23/_downloads/48e14d460d6470997b890b156746a671/30_strf.ipynb".
The first task is:
Compare model performance
Below we visualize the model performance of each regularization method
(ridge vs. Laplacian) for different levels of alpha. As you can see, the
Laplacian method performs better in general, because it imposes a smoothness
constraint along the time and feature dimensions of the coefficients.
This matches the "true" receptive field structure and results in a better
model fit.
Can you write Python code for it?

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

# Plot the STRF of each ridge parameter
xlim = times[[0, -1]]
for ii, (rf_lap, rf, i_alpha) in enumerate(zip(models_lap, models, alphas)):
    ax = plt.subplot2grid([3, len(alphas)], [0, ii], 1, 1)
    ax.pcolormesh(times, rf_lap.feature_names, rf_lap.coef_[0], **kwargs)
    ax.set(xticks=[], yticks=[], xlim=xlim)
    if ii == 0:
        ax.set(ylabel='Laplacian')
    ax = plt.subplot2grid([3, len(alphas)], [1, ii], 1, 1)
    ax.pcolormesh(times, rf.feature_names, rf.coef_[0], **kwargs)
    ax.set(xticks=[], yticks=[], xlim=xlim)
    if ii == 0:
        ax.set(ylabel='Ridge')
fig.suptitle('Model coefficients / scores for laplacian regularization', y=1)
mne.viz.tight_layout()


I am working on the file "0.23/_downloads/48e14d460d6470997b890b156746a671/30_strf.ipynb".
The first task is:
Create a receptive field
We'll simulate a linear receptive field for a theoretical neural signal. This
defines how the signal will respond to power in this receptive field space.
Can you write Python code for it?

n_freqs = 20
tmin, tmax = -0.1, 0.4

# To simulate the data we'll create explicit delays here
delays_samp = np.arange(np.round(tmin * sfreq),
                        np.round(tmax * sfreq) + 1).astype(int)
delays_sec = delays_samp / sfreq
freqs = np.linspace(50, 5000, n_freqs)
grid = np.array(np.meshgrid(delays_sec, freqs))

# We need data to be shaped as n_epochs, n_features, n_times, so swap axes here
grid = grid.swapaxes(0, -1).swapaxes(0, 1)

# Simulate a temporal receptive field with a Gabor filter
means_high = [.1, 500]
means_low = [.2, 2500]
cov = [[.001, 0], [0, 500000]]
gauss_high = multivariate_normal.pdf(grid, means_high, cov)
gauss_low = -1 * multivariate_normal.pdf(grid, means_low, cov)
weights = gauss_high + gauss_low  # Combine to create the "true" STRF
kwargs = dict(vmax=np.abs(weights).max(), vmin=-np.abs(weights).max(),
              cmap='RdBu_r', shading='gouraud')

fig, ax = plt.subplots()
ax.pcolormesh(delays_sec, freqs, weights, **kwargs)
ax.set(title='Simulated STRF', xlabel='Time Lags (s)', ylabel='Frequency (Hz)')
plt.setp(ax.get_xticklabels(), rotation=45)
plt.autoscale(tight=True)
mne.viz.tight_layout()


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

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


I am working on the file "0.23/_downloads/48e14d460d6470997b890b156746a671/30_strf.ipynb".
The first task is:
Plot the original STRF, and the one that we recovered with modeling.
Can you write Python code for it?

rf = models[ix_best_alpha]
rf_lap = models_lap[ix_best_alpha_lap]
_, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(9, 3),
                                  sharey=True, sharex=True)
ax1.pcolormesh(delays_sec, freqs, weights, **kwargs)
ax2.pcolormesh(times, rf.feature_names, rf.coef_[0], **kwargs)
ax3.pcolormesh(times, rf_lap.feature_names, rf_lap.coef_[0], **kwargs)
ax1.set_title('Original STRF')
ax2.set_title('Best Ridge STRF')
ax3.set_title('Best Laplacian STRF')
plt.setp([iax.get_xticklabels() for iax in [ax1, ax2, ax3]], rotation=45)
plt.autoscale(tight=True)
mne.viz.tight_layout()


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

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

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

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

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

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

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


I am working on the file "0.23/_downloads/48e14d460d6470997b890b156746a671/30_strf.ipynb".
The first task is:
Spectro-temporal receptive field (STRF) estimation on continuous data
This demonstrates how an encoding model can be fit with multiple continuous
inputs. In this case, we simulate the model behind a spectro-temporal receptive
field (or STRF). First, we create a linear filter that maps patterns in
spectro-temporal space onto an output, representing neural activity. We fit
a receptive field model that attempts to recover the original linear filter
that was used to create this data.
Can you write Python code for it?

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

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.decoding import ReceptiveField, TimeDelayingRidge

from scipy.stats import multivariate_normal
from scipy.io import loadmat
from sklearn.preprocessing import scale
rng = np.random.RandomState(1337)  # To make this example reproducible


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

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

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

ix_best_alpha_lap = np.argmax(scores_lap)


I am working on the file "0.23/_downloads/48e14d460d6470997b890b156746a671/30_strf.ipynb".
The first task is:
Visualize the effects of regularization
Above we fit a :class:mne.decoding.ReceptiveField model for one of many
values for the ridge regularization parameter. Here we will plot the model
score as well as the model coefficients for each value, in order to
visualize how coefficients change with different levels of regularization.
These issues as well as the STRF pipeline are described in detail
in :footcite:TheunissenEtAl2001,WillmoreSmyth2003,HoldgrafEtAl2016.
Can you write Python code for it?

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

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


I am working on the file "0.23/_downloads/499a81f33500445fc2e1eac0be346d47/temporal_whitening.ipynb".
The first task is:
Temporal whitening with AR model
Here we fit an AR model to the data and use it
to temporally whiten the signals.
Can you write Python code for it?

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

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

import mne
from mne.time_frequency import fit_iir_model_raw
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
proj_fname = data_path + '/MEG/sample/sample_audvis_ecg-proj.fif'

raw = mne.io.read_raw_fif(raw_fname)
proj = mne.read_proj(proj_fname)
raw.info['projs'] += proj
raw.info['bads'] = ['MEG 2443', 'EEG 053']  # mark bad channels

# Set up pick list: Gradiometers - bad channels
picks = mne.pick_types(raw.info, meg='grad', exclude='bads')

order = 5  # define model order
picks = picks[:1]

# Estimate AR models on raw data
b, a = fit_iir_model_raw(raw, order=order, picks=picks, tmin=60, tmax=180)
d, times = raw[0, 10000:20000]  # look at one channel from now on
d = d.ravel()  # make flat vector
innovation = signal.convolve(d, a, 'valid')
d_ = signal.lfilter(b, a, innovation)  # regenerate the signal
d_ = np.r_[d_[0] * np.ones(order), d_]  # dummy samples to keep signal length


I am working on the file "0.23/_downloads/4a4a8e5bd5ae7cafea93a04d8c0a0d00/psf_ctf_vertices_lcmv.ipynb".
The first task is:
Compute LCMV filters with different data covariance matrices
Can you write Python code for it?

# compute LCMV beamformer filters for pre-stimulus interval
filters_pre = make_lcmv(info, forward, cov_pre, reg=0.05,
                        noise_cov=noise_cov,
                        pick_ori=None, rank=None,
                        weight_norm=None,
                        reduce_rank=False,
                        verbose=False)

# compute LCMV beamformer filters for post-stimulus interval
filters_post = make_lcmv(info, forward, cov_post, reg=0.05,
                         noise_cov=noise_cov,
                         pick_ori=None, rank=None,
                         weight_norm=None,
                         reduce_rank=False,
                         verbose=False)


I am working on the file "0.23/_downloads/4a4a8e5bd5ae7cafea93a04d8c0a0d00/psf_ctf_vertices_lcmv.ipynb".
The first task is:
Compute cross-talk functions for LCMV beamformers
Visualise cross-talk functions at one vertex for LCMV beamformers computed
with different data covariance matrices, which affects their cross-talk
functions.
Can you write Python code for it?

# Author: Olaf Hauk <olaf.hauk@mrc-cbu.cam.ac.uk>
#
# License: BSD (3-clause)

import mne
from mne.datasets import sample
from mne.beamformer import make_lcmv, make_lcmv_resolution_matrix
from mne.minimum_norm import get_cross_talk

print(__doc__)

data_path = sample.data_path()
subjects_dir = data_path + '/subjects/'
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
fname_cov = data_path + '/MEG/sample/sample_audvis-cov.fif'
fname_evo = data_path + '/MEG/sample/sample_audvis-ave.fif'
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'

# Read raw data
raw = mne.io.read_raw_fif(raw_fname)

# only pick good EEG/MEG sensors
raw.info['bads'] += ['EEG 053']  # bads + 1 more
picks = mne.pick_types(raw.info, meg=True, eeg=True, exclude='bads')

# Find events
events = mne.find_events(raw)

# event_id = {'aud/l': 1, 'aud/r': 2, 'vis/l': 3, 'vis/r': 4}
event_id = {'vis/l': 3, 'vis/r': 4}

tmin, tmax = -.2, .25  # epoch duration
epochs = mne.Epochs(raw, events, event_id=event_id, tmin=tmin, tmax=tmax,
                    picks=picks, baseline=(-.2, 0.), preload=True)
del raw

# covariance matrix for pre-stimulus interval
tmin, tmax = -.2, 0.
cov_pre = mne.compute_covariance(epochs, tmin=tmin, tmax=tmax,
                                 method='empirical')

# covariance matrix for post-stimulus interval (around main evoked responses)
tmin, tmax = 0.05, .25
cov_post = mne.compute_covariance(epochs, tmin=tmin, tmax=tmax,
                                  method='empirical')
info = epochs.info
del epochs

# read forward solution
forward = mne.read_forward_solution(fname_fwd)
# use forward operator with fixed source orientations
mne.convert_forward_solution(forward, surf_ori=True,
                             force_fixed=True, copy=False)

# read noise covariance matrix
noise_cov = mne.read_cov(fname_cov)

# regularize noise covariance (we used 'empirical' above)
noise_cov = mne.cov.regularize(noise_cov, info, mag=0.1, grad=0.1,
                               eeg=0.1, rank='info')


I am working on the file "0.23/_downloads/4a4a8e5bd5ae7cafea93a04d8c0a0d00/psf_ctf_vertices_lcmv.ipynb".
The first task is:
Compute resolution matrices for the two LCMV beamformers
Can you write Python code for it?

rm_pre = make_lcmv_resolution_matrix(filters_pre, forward, info)

rm_post = make_lcmv_resolution_matrix(filters_post, forward, info)

# compute cross-talk functions (CTFs) for one target vertex
sources = [3000]

stc_pre = get_cross_talk(rm_pre, forward['src'], sources, norm=True)

stc_post = get_cross_talk(rm_post, forward['src'], sources, norm=True)
verttrue = [forward['src'][0]['vertno'][sources[0]]]  # pick one vertex
del forward


I am working on the file "0.23/_downloads/4a4a8e5bd5ae7cafea93a04d8c0a0d00/psf_ctf_vertices_lcmv.ipynb".
The first task is:
Post:
Can you write Python code for it?

brain_post = stc_post.plot('sample', 'inflated', 'lh',
                           subjects_dir=subjects_dir,
                           figure=2, clim=dict(kind='value', lims=(0, .2, .4)))

brain_post.add_text(0.1, 0.9, 'LCMV beamformer with post-stimulus\ndata '
                    'covariance matrix', 'title', font_size=16)

brain_post.add_foci(verttrue, coords_as_verts=True, scale_factor=1.,
                    hemi='lh', color='green')


I am working on the file "0.23/_downloads/4a4a8e5bd5ae7cafea93a04d8c0a0d00/psf_ctf_vertices_lcmv.ipynb".
The first task is:
Visualize
Pre:
Can you write Python code for it?

brain_pre = stc_pre.plot('sample', 'inflated', 'lh', subjects_dir=subjects_dir,
                         figure=1, clim=dict(kind='value', lims=(0, .2, .4)))

brain_pre.add_text(0.1, 0.9, 'LCMV beamformer with pre-stimulus\ndata '
                   'covariance matrix', 'title', font_size=16)

# mark true source location for CTFs
brain_pre.add_foci(verttrue, coords_as_verts=True, scale_factor=1., hemi='lh',
                   color='green')


I am working on the file "0.23/_downloads/4d3b714a9291625bb4b01d7f9c7c3a16/compute_source_psd_epochs.ipynb".
The first task is:
Compute Power Spectral Density of inverse solution from single epochs
Compute PSD of dSPM inverse solution on single trial epochs restricted
to a brain label. The PSD is computed using a multi-taper method with
Discrete Prolate Spheroidal Sequence (DPSS) windows.
Can you write Python code for it?

# Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)

import matplotlib.pyplot as plt

import mne
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, compute_source_psd_epochs

print(__doc__)

data_path = sample.data_path()
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_raw = data_path + '/MEG/sample/sample_audvis_raw.fif'
fname_event = data_path + '/MEG/sample/sample_audvis_raw-eve.fif'
label_name = 'Aud-lh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name
subjects_dir = data_path + '/subjects'

event_id, tmin, tmax = 1, -0.2, 0.5
snr = 1.0  # use smaller SNR for raw data
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

# Load data
inverse_operator = read_inverse_operator(fname_inv)
label = mne.read_label(fname_label)
raw = mne.io.read_raw_fif(fname_raw)
events = mne.read_events(fname_event)

# Set up pick list
include = []
raw.info['bads'] += ['EEG 053']  # bads + 1 more

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

# define frequencies of interest
fmin, fmax = 0., 70.
bandwidth = 4.  # bandwidth of the windows in Hz


I am working on the file "0.23/_downloads/4d3b714a9291625bb4b01d7f9c7c3a16/compute_source_psd_epochs.ipynb".
The first task is:
Compute source space PSD in label
..note:: By using "return_generator=True" stcs will be a generator object
         instead of a list. This allows us so to iterate without having to
         keep everything in memory.
Can you write Python code for it?

n_epochs_use = 10
stcs = compute_source_psd_epochs(epochs[:n_epochs_use], inverse_operator,
                                 lambda2=lambda2,
                                 method=method, fmin=fmin, fmax=fmax,
                                 bandwidth=bandwidth, label=label,
                                 return_generator=True, verbose=True)

# compute average PSD over the first 10 epochs
psd_avg = 0.
for i, stc in enumerate(stcs):
    psd_avg += stc.data
psd_avg /= n_epochs_use
freqs = stc.times  # the frequencies are stored here
stc.data = psd_avg  # overwrite the last epoch's data with the average


I am working on the file "0.23/_downloads/4d3b714a9291625bb4b01d7f9c7c3a16/compute_source_psd_epochs.ipynb".
The first task is:
Visualize the 10 Hz PSD:
Can you write Python code for it?

brain = stc.plot(initial_time=10., hemi='lh', views='lat',  # 10 HZ
                 clim=dict(kind='value', lims=(20, 40, 60)),
                 smoothing_steps=3, subjects_dir=subjects_dir)
brain.add_label(label, borders=True, color='k')


I am working on the file "0.23/_downloads/4d3b714a9291625bb4b01d7f9c7c3a16/compute_source_psd_epochs.ipynb".
The first task is:
Visualize the entire spectrum:
Can you write Python code for it?

fig, ax = plt.subplots()
ax.plot(freqs, psd_avg.mean(axis=0))
ax.set_xlabel('Freq (Hz)')
ax.set_xlim(stc.times[[0, -1]])
ax.set_ylabel('Power Spectral Density')


I am working on the file "0.23/_downloads/5050ef6c79955f686202b68899c9d8b8/mne_inverse_coherence_epochs.ipynb".
The first task is:
Choose channels for coherence estimation
Next we'll calculate our channel sources. Then we'll find the most active
vertex in the left auditory cortex, which we will later use as seed for the
connectivity computation.
Can you write Python code for it?

snr = 3.0
lambda2 = 1.0 / snr ** 2
evoked = epochs.average()
stc = apply_inverse(evoked, inverse_operator, lambda2, method,
                    pick_ori="normal")

# Restrict the source estimate to the label in the left auditory cortex.
stc_label = stc.in_label(label_lh)

# Find number and index of vertex with most power.
src_pow = np.sum(stc_label.data ** 2, axis=1)
seed_vertno = stc_label.vertices[0][np.argmax(src_pow)]
seed_idx = np.searchsorted(stc.vertices[0], seed_vertno)  # index in orig stc

# Generate index parameter for seed-based connectivity analysis.
n_sources = stc.data.shape[0]
indices = seed_target_indices([seed_idx], np.arange(n_sources))


I am working on the file "0.23/_downloads/5050ef6c79955f686202b68899c9d8b8/mne_inverse_coherence_epochs.ipynb".
The first task is:
Compute coherence in source space using a MNE inverse solution
This example computes the coherence between a seed in the left
auditory cortex and the rest of the brain based on single-trial
MNE-dSPM inverse solutions.
Can you write Python code for it?

# Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)

import numpy as np

import mne
from mne.datasets import sample
from mne.minimum_norm import (apply_inverse, apply_inverse_epochs,
                              read_inverse_operator)
from mne.connectivity import seed_target_indices, spectral_connectivity

print(__doc__)


I am working on the file "0.23/_downloads/5050ef6c79955f686202b68899c9d8b8/mne_inverse_coherence_epochs.ipynb".
The first task is:
Compute the inverse solution for each epoch. By using "return_generator=True"
stcs will be a generator object instead of a list. This allows us so to
compute the coherence without having to keep all source estimates in memory.
Can you write Python code for it?

snr = 1.0  # use lower SNR for single epochs
lambda2 = 1.0 / snr ** 2
stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method,
                            pick_ori="normal", return_generator=True)


I am working on the file "0.23/_downloads/508d9d76b6c08ece701565f76bf102db/movement_compensation.ipynb".
The first task is:
First, take the average of stationary data (bilateral auditory patterns).
Can you write Python code for it?

evoked_stat = mne.Epochs(raw_stat, events, 1, -0.2, 0.8).average()
evoked_stat.plot_topomap(title='Stationary', **topo_kwargs)


I am working on the file "0.23/_downloads/508d9d76b6c08ece701565f76bf102db/movement_compensation.ipynb".
The first task is:
Third, use raw movement compensation (restores pattern).
Can you write Python code for it?

raw_sss = maxwell_filter(raw, head_pos=head_pos)
evoked_raw_mc = mne.Epochs(raw_sss, events, 1, -0.2, 0.8).average()
evoked_raw_mc.plot_topomap(title='Moving: movement compensated (raw)',
                           **topo_kwargs)


I am working on the file "0.23/_downloads/508d9d76b6c08ece701565f76bf102db/movement_compensation.ipynb".
The first task is:
Visualize the "subject" head movements. By providing the measurement
information, the distance to the nearest sensor in each direction
(e.g., left/right for the X direction, forward/backward for Y) can
be shown in blue, and the destination (if given) shown in red.
Can you write Python code for it?

mne.viz.plot_head_positions(
    head_pos, mode='traces', destination=raw.info['dev_head_t'], info=raw.info)


I am working on the file "0.23/_downloads/511c644e95ae48be8cf394cec24a1865/80_brainstorm_phantom_elekta.ipynb".
The first task is:
Brainstorm Elekta phantom dataset tutorial
Here we compute the evoked from raw for the Brainstorm Elekta phantom
tutorial dataset. For comparison, see :footcite:TadelEtAl2011 and:
https://neuroimage.usc.edu/brainstorm/Tutorials/PhantomElekta

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

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

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

import mne
from mne import find_events, fit_dipole
from mne.datasets.brainstorm import bst_phantom_elekta
from mne.io import read_raw_fif

print(__doc__)


I am working on the file "0.23/_downloads/511c644e95ae48be8cf394cec24a1865/80_brainstorm_phantom_elekta.ipynb".
The first task is:
Data channel array consisted of 204 MEG planor gradiometers,
102 axial magnetometers, and 3 stimulus channels. Let's get the events
for the phantom, where each dipole (1-32) gets its own event:
Can you write Python code for it?

events = find_events(raw, 'STI201')
raw.plot(events=events)
raw.info['bads'] = ['MEG1933', 'MEG2421']


I am working on the file "0.23/_downloads/511c644e95ae48be8cf394cec24a1865/80_brainstorm_phantom_elekta.ipynb".
The first task is:
Do a quick visualization of how much variance we explained, putting the
data and residuals on the same scale (here the "time points" are the
32 dipole peak values that we fit):
Can you write Python code for it?

fig, axes = plt.subplots(2, 1)
evoked.plot(axes=axes)
for ax in axes:
    ax.texts.clear()
    for line in ax.lines:
        line.set_color('#98df81')
residual.plot(axes=axes)


I am working on the file "0.23/_downloads/511c644e95ae48be8cf394cec24a1865/80_brainstorm_phantom_elekta.ipynb".
The first task is:
Let's do some dipole fits. We first compute the noise covariance,
then do the fits for each event_id taking the time instant that maximizes
the global field power.
Can you write Python code for it?

# here we can get away with using method='oas' for speed (faster than "shrunk")
# but in general "shrunk" is usually better
cov = mne.compute_covariance(epochs, tmax=bmax)
mne.viz.plot_evoked_white(epochs['1'].average(), cov)

data = []
t_peak = 0.036  # true for Elekta phantom
for ii in event_id:
    # Avoid the first and last trials -- can contain dipole-switching artifacts
    evoked = epochs[str(ii)][1:-1].average().crop(t_peak, t_peak)
    data.append(evoked.data[:, 0])
evoked = mne.EvokedArray(np.array(data).T, evoked.info, tmin=0.)
del epochs
dip, residual = fit_dipole(evoked, cov, sphere, n_jobs=1)


I am working on the file "0.23/_downloads/511c644e95ae48be8cf394cec24a1865/80_brainstorm_phantom_elekta.ipynb".
The first task is:
Let's plot the positions and the orientations of the actual and the estimated
dipoles
Can you write Python code for it?

actual_amp = np.ones(len(dip))  # misc amp to create Dipole instance
actual_gof = np.ones(len(dip))  # misc GOF to create Dipole instance
dip_true = \
    mne.Dipole(dip.times, actual_pos, actual_amp, actual_ori, actual_gof)

fig = mne.viz.plot_alignment(evoked.info, bem=sphere, surfaces='inner_skull',
                             coord_frame='head', meg='helmet', show_axes=True)

# Plot the position and the orientation of the actual dipole
fig = mne.viz.plot_dipole_locations(dipoles=dip_true, mode='arrow',
                                    subject=subject, color=(0., 0., 0.),
                                    fig=fig)

# Plot the position and the orientation of the estimated dipole
fig = mne.viz.plot_dipole_locations(dipoles=dip, mode='arrow', subject=subject,
                                    color=(0.2, 1., 0.5), fig=fig)

mne.viz.set_3d_view(figure=fig, azimuth=70, elevation=80, distance=0.5)


I am working on the file "0.23/_downloads/511c644e95ae48be8cf394cec24a1865/80_brainstorm_phantom_elekta.ipynb".
The first task is:
Let's use a sphere head geometry model <eeg_sphere_model>
and let's see the coordinate alignment and the sphere location. The phantom
is properly modeled by a single-shell sphere with origin (0., 0., 0.).
Can you write Python code for it?

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

mne.viz.plot_alignment(epochs.info, subject=subject, show_axes=True,
                       bem=sphere, dig=True, surfaces='head')


I am working on the file "0.23/_downloads/511c644e95ae48be8cf394cec24a1865/80_brainstorm_phantom_elekta.ipynb".
The first task is:
Now we can compare to the actual locations, taking the difference in mm:
Can you write Python code for it?

actual_pos, actual_ori = mne.dipole.get_phantom_dipoles()
actual_amp = 100.  # nAm

fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, ncols=1, figsize=(6, 7))

diffs = 1000 * np.sqrt(np.sum((dip.pos - actual_pos) ** 2, axis=-1))
print('mean(position error) = %0.1f mm' % (np.mean(diffs),))
ax1.bar(event_id, diffs)
ax1.set_xlabel('Dipole index')
ax1.set_ylabel('Loc. error (mm)')

angles = np.rad2deg(np.arccos(np.abs(np.sum(dip.ori * actual_ori, axis=1))))
print(u'mean(angle error) = %0.1f°' % (np.mean(angles),))
ax2.bar(event_id, angles)
ax2.set_xlabel('Dipole index')
ax2.set_ylabel(u'Angle error (°)')

amps = actual_amp - dip.amplitude / 1e-9
print('mean(abs amplitude error) = %0.1f nAm' % (np.mean(np.abs(amps)),))
ax3.bar(event_id, amps)
ax3.set_xlabel('Dipole index')
ax3.set_ylabel('Amplitude error (nAm)')

fig.tight_layout()
plt.show()


I am working on the file "0.23/_downloads/511c644e95ae48be8cf394cec24a1865/80_brainstorm_phantom_elekta.ipynb".
The first task is:
Our phantom produces sinusoidal bursts at 20 Hz:
Can you write Python code for it?


I am working on the file "0.23/_downloads/511c644e95ae48be8cf394cec24a1865/80_brainstorm_phantom_elekta.ipynb".
The first task is:
The data have strong line frequency (60 Hz and harmonics) and cHPI coil
noise (five peaks around 300 Hz). Here we plot only out to 60 seconds
to save memory:
Can you write Python code for it?


I am working on the file "0.23/_downloads/511c644e95ae48be8cf394cec24a1865/80_brainstorm_phantom_elekta.ipynb".
The first task is:
The data were collected with an Elekta Neuromag VectorView system at 1000 Hz
and low-pass filtered at 330 Hz. Here the medium-amplitude (200 nAm) data
are read to construct instances of :class:mne.io.Raw.
Can you write Python code for it?

data_path = bst_phantom_elekta.data_path(verbose=True)
subject = 'sample'

raw_fname = op.join(data_path, 'kojak_all_200nAm_pp_no_chpi_no_ms_raw.fif')
raw = read_raw_fif(raw_fname)


I am working on the file "0.23/_downloads/51cca4c9f4bd40623cb6bfa890e2eb4b/20_erp_stats.ipynb".
The first task is:
Absent specific hypotheses, we can also conduct an exploratory
mass-univariate analysis at all sensors and time points. This requires
correcting for multiple tests.
MNE offers various methods for this; amongst them, cluster-based permutation
methods allow deriving power from the spatio-temoral correlation structure
of the data. Here, we use TFCE.
Can you write Python code for it?

# Calculate adjacency matrix between sensors from their locations
adjacency, _ = find_ch_adjacency(epochs.info, "eeg")

# Extract data: transpose because the cluster test requires channels to be last
# In this case, inference is done over items. In the same manner, we could
# also conduct the test over, e.g., subjects.
X = [long_words.get_data().transpose(0, 2, 1),
     short_words.get_data().transpose(0, 2, 1)]
tfce = dict(start=.2, step=.2)

# Calculate statistical thresholds
t_obs, clusters, cluster_pv, h0 = spatio_temporal_cluster_test(
    X, tfce, adjacency=adjacency,
    n_permutations=100)  # a more standard number would be 1000+
significant_points = cluster_pv.reshape(t_obs.shape).T < .05
print(str(significant_points.sum()) + " points selected by TFCE ...")


I am working on the file "0.23/_downloads/51cca4c9f4bd40623cb6bfa890e2eb4b/20_erp_stats.ipynb".
The first task is:
If we have a specific point in space and time we wish to test, it can be
convenient to convert the data into Pandas Dataframe format. In this case,
the :class:mne.Epochs object has a convenient
:meth:mne.Epochs.to_data_frame method, which returns a dataframe.
This dataframe can then be queried for specific time windows and sensors.
The extracted data can be submitted to standard statistical tests. Here,
we conduct t-tests on the difference between long and short words.
Can you write Python code for it?

time_windows = ((.2, .25), (.35, .45))
elecs = ["Fz", "Cz", "Pz"]
index = ['condition', 'epoch', 'time']

# display the EEG data in Pandas format (first 5 rows)
print(epochs.to_data_frame(index=index)[elecs].head())

report = "{elec}, time: {tmin}-{tmax} s; t({df})={t_val:.3f}, p={p:.3f}"
print("\nTargeted statistical test results:")
for (tmin, tmax) in time_windows:
    long_df = long_words.copy().crop(tmin, tmax).to_data_frame(index=index)
    short_df = short_words.copy().crop(tmin, tmax).to_data_frame(index=index)
    for elec in elecs:
        # extract data
        A = long_df[elec].groupby("condition").mean()
        B = short_df[elec].groupby("condition").mean()

        # conduct t test
        t, p = ttest_ind(A, B)

        # display results
        format_dict = dict(elec=elec, tmin=tmin, tmax=tmax,
                           df=len(epochs.events) - 2, t_val=t, p=p)
        print(report.format(**format_dict))


I am working on the file "0.23/_downloads/524b9a6067f1a7bd3b66aa385465b921/20_source_alignment.ipynb".
The first task is:
.. raw:: html
<style>
   .pink {color:DarkSalmon; font-weight:bold}
   .blue {color:DeepSkyBlue; font-weight:bold}
   .gray {color:Gray; font-weight:bold}
   .magenta {color:Magenta; font-weight:bold}
   .purple {color:Indigo; font-weight:bold}
   .green {color:LimeGreen; font-weight:bold}
   .red {color:Red; font-weight:bold}
   </style>

.. role:: pink
.. role:: blue
.. role:: gray
.. role:: magenta
.. role:: purple
.. role:: green
.. role:: red
Understanding coordinate frames
For M/EEG source imaging, there are three coordinate frames must be
brought into alignment using two 3D transformation matrices <wiki_xform_>_
that define how to rotate and translate points in one coordinate frame
to their equivalent locations in another. The three main coordinate frames
are:

:blue:"meg": the coordinate frame for the physical locations of MEG
  sensors
:gray:"mri": the coordinate frame for MRI images, and scalp/skull/brain
  surfaces derived from the MRI images
:pink:"head": the coordinate frame for digitized sensor locations and
  scalp landmarks ("fiducials")

Each of these are described in more detail in the next section.
A good way to start visualizing these coordinate frames is to use the
mne.viz.plot_alignment function, which is used for creating or inspecting
the transformations that bring these coordinate frames into alignment, and
displaying the resulting alignment of EEG sensors, MEG sensors, brain
sources, and conductor models. If you provide subjects_dir and
subject parameters, the function automatically loads the subject's
Freesurfer MRI surfaces. Important for our purposes, passing
show_axes=True to ~mne.viz.plot_alignment will draw the origin of each
coordinate frame in a different color, with axes indicated by different sized
arrows:

shortest arrow: (R)ight / X
medium arrow: forward / (A)nterior / Y
longest arrow: up / (S)uperior / Z

Note that all three coordinate systems are RAS coordinate frames and
hence are also right-handed_ coordinate systems. Finally, note that the
coord_frame parameter...
Can you write Python code for it?

fig = mne.viz.plot_alignment(raw.info, trans=trans, subject='sample',
                             subjects_dir=subjects_dir, surfaces='head-dense',
                             show_axes=True, dig=True, eeg=[], meg='sensors',
                             coord_frame='meg', mri_fiducials='estimated')
mne.viz.set_3d_view(fig, 45, 90, distance=0.6, focalpoint=(0., 0., 0.))
print('Distance from head origin to MEG origin: %0.1f mm'
      % (1000 * np.linalg.norm(raw.info['dev_head_t']['trans'][:3, 3])))
print('Distance from head origin to MRI origin: %0.1f mm'
      % (1000 * np.linalg.norm(trans['trans'][:3, 3])))
dists = mne.dig_mri_distances(raw.info, trans, 'sample',
                              subjects_dir=subjects_dir)
print('Distance from %s digitized points to head surface: %0.1f mm'
      % (len(dists), 1000 * np.mean(dists)))


I am working on the file "0.23/_downloads/524b9a6067f1a7bd3b66aa385465b921/20_source_alignment.ipynb".
The first task is:
Alignment without MRI
The surface alignments above are possible if you have the surfaces available
from Freesurfer. :func:mne.viz.plot_alignment automatically searches for
the correct surfaces from the provided subjects_dir. Another option is
to use a spherical conductor model <eeg_sphere_model>. It is
passed through bem parameter.
Can you write Python code for it?

sphere = mne.make_sphere_model(info=raw.info, r0='auto', head_radius='auto')
src = mne.setup_volume_source_space(sphere=sphere, pos=10.)
mne.viz.plot_alignment(
    raw.info, eeg='projected', bem=sphere, src=src, dig=True,
    surfaces=['brain', 'inner_skull', 'outer_skull', 'outer_skin'],
    coord_frame='meg', show_axes=True)


I am working on the file "0.23/_downloads/524b9a6067f1a7bd3b66aa385465b921/20_source_alignment.ipynb".
The first task is:
Coordinate frame definitions

Neuromag/Elekta/MEGIN head coordinate frame ("head", :pink:pink axes)
     The head coordinate frame is defined through the coordinates of
     anatomical landmarks on the subject's head: usually the Nasion (NAS),
     and the left and right preauricular points (LPA and RPA).
     Different MEG manufacturers may have different definitions of the head
     coordinate frame. A good overview can be seen in the
     FieldTrip FAQ on coordinate systems.
For Neuromag/Elekta/MEGIN, the head coordinate frame is defined by the
 intersection of

the line between the LPA (:red:red sphere) and RPA
    (:purple:purple sphere), and
the line perpendicular to this LPA-RPA line one that goes through
    the Nasion (:green:green sphere).

The axes are oriented as X origin→RPA, Y origin→NAS,
 Z origin→upward (orthogonal to X and Y).
.. note:: The required 3D coordinates for defining the head coordinate
           frame (NAS, LPA, RPA) are measured at a stage separate from
           the MEG data recording. There exist numerous devices to
           perform such measurements, usually called "digitizers". For
           example, see the devices by the company Polhemus_.

MEG device coordinate frame ("meg", :blue:blue axes)
     The MEG device coordinate frame is defined by the respective MEG
     manufacturers. All MEG data is acquired with respect to this coordinate
     frame. To account for the anatomy and position of the subject's head, we
     use so-called head position indicator (HPI) coils. The HPI coils are
     placed at known locations on the scalp of the subject and emit
     high-frequency magnetic fields used to coregister the head coordinate
     frame with the device coordinate frame.
From the Neuromag/Elekta/MEGIN user manual:
 The origin of the device coordinate system is located at the center
 of the posterior spherical section of the helmet with X axis going
 from left to right and Y axis pointing front. The Z axis is, again
 normal to the plane with positive direction up.

.....
Can you write Python code for it?

mne.viz.plot_alignment(raw.info, trans=None, subject='sample', src=src,
                       subjects_dir=subjects_dir, dig=True,
                       surfaces=['head-dense', 'white'], coord_frame='meg')


I am working on the file "0.23/_downloads/524b9a6067f1a7bd3b66aa385465b921/20_source_alignment.ipynb".
The first task is:
Source alignment and coordinate frames
This tutorial shows how to visually assess the spatial alignment of MEG sensor
locations, digitized scalp landmark and sensor locations, and MRI volumes. This
alignment process is crucial for computing the forward solution, as is
understanding the different coordinate frames involved in this process.
Let's start out by loading some data.
Can you write Python code for it?

import os.path as op

import numpy as np
import nibabel as nib
from scipy import linalg

import mne
from mne.io.constants import FIFF

data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
trans_fname = op.join(data_path, 'MEG', 'sample',
                      'sample_audvis_raw-trans.fif')
raw = mne.io.read_raw_fif(raw_fname)
trans = mne.read_trans(trans_fname)
src = mne.read_source_spaces(op.join(subjects_dir, 'sample', 'bem',
                                     'sample-oct-6-src.fif'))

# Load the T1 file and change the header information to the correct units
t1w = nib.load(op.join(data_path, 'subjects', 'sample', 'mri', 'T1.mgz'))
t1w = nib.Nifti1Image(t1w.dataobj, t1w.affine)
t1w.header['xyzt_units'] = np.array(10, dtype='uint8')
t1_mgh = nib.MGHImage(t1w.dataobj, t1w.affine)


I am working on the file "0.23/_downloads/524b9a6067f1a7bd3b66aa385465b921/20_source_alignment.ipynb".
The first task is:
The relative orientations of the coordinate frames can be inferred by
observing the direction of the subject's nose. Notice also how the origin of
the :green:mri_voxel coordinate frame is in the corner of the volume
(above, behind, and to the left of the subject), whereas the other three
coordinate frames have their origin roughly in the center of the head.
Example: MRI defacing
For a real-world example of using these transforms, consider the task of
defacing the MRI to preserve subject anonymity. If you know the points in
the "head" coordinate frame (as you might if you're basing the defacing on
digitized points) you would need to transform them into "mri" or "mri_voxel"
in order to apply the blurring or smoothing operations to the MRI surfaces or
images. Here's what that would look like (we'll use the nasion landmark as a
representative example):
Can you write Python code for it?

# Get the nasion:
nasion = [p for p in raw.info['dig'] if
          p['kind'] == FIFF.FIFFV_POINT_CARDINAL and
          p['ident'] == FIFF.FIFFV_POINT_NASION][0]
assert nasion['coord_frame'] == FIFF.FIFFV_COORD_HEAD
nasion = nasion['r']  # get just the XYZ values

# Transform it from head to MRI space (recall that `trans` is head → mri)
nasion_mri = mne.transforms.apply_trans(trans, nasion, move=True)
# Then transform to voxel space, after converting from meters to millimeters
nasion_vox = mne.transforms.apply_trans(
    mri_to_vox, nasion_mri * 1e3, move=True)
# Plot it to make sure the transforms worked
renderer = mne.viz.backends.renderer.create_3d_figure(
    size=(400, 400), bgcolor='w', scene=False)
add_head(renderer, scalp_points_in_vox, 'green', opacity=1)
renderer.sphere(center=nasion_vox, color='orange', scale=10)
mne.viz.set_3d_view(figure=renderer.figure, distance=600.,
                    focalpoint=(0., 125., 250.), elevation=45, azimuth=180)
renderer.show()