I am working on the file "0.18/_downloads/11f39f61bd7f4cfd5791b0d10da462f2/plot_eeg_erp.ipynb".
The first task is:
By looking at the measurement info you will see that we have now
59 EEG channels and 1 EOG channel
Can you write Python code for it?


I am working on the file "0.18/_downloads/11f39f61bd7f4cfd5791b0d10da462f2/plot_eeg_erp.ipynb".
The first task is:
Custom reference: Use the mean of channels EEG 001 and EEG 002 as
a reference
Can you write Python code for it?

raw_custom, _ = mne.set_eeg_reference(raw, ['EEG 001', 'EEG 002'])
evoked_custom = mne.Epochs(raw_custom, **epochs_params).average()
del raw_custom  # save memory

title = 'EEG Custom reference'
evoked_custom.plot(titles=dict(eeg=title), time_unit='s')
evoked_custom.plot_topomap(times=[0.1], size=3., title=title, time_unit='s')


I am working on the file "0.18/_downloads/11f39f61bd7f4cfd5791b0d10da462f2/plot_eeg_erp.ipynb".
The first task is:
EEG processing and Event Related Potentials (ERPs)
For a generic introduction to the computation of ERP and ERF
see tut_epoching_and_averaging.
   :depth: 1
Can you write Python code for it?

import mne
from mne.datasets import sample


I am working on the file "0.18/_downloads/11f39f61bd7f4cfd5791b0d10da462f2/plot_eeg_erp.ipynb".
The first task is:
Evoked arithmetic (e.g. differences)
Trial subsets from Epochs can be selected using 'tags' separated by '/'.
Evoked objects support basic arithmetic.
First, we create an Epochs object containing 4 conditions.
Can you write Python code for it?

event_id = {'left/auditory': 1, 'right/auditory': 2,
            'left/visual': 3, 'right/visual': 4}
epochs_params = dict(events=events, event_id=event_id, tmin=tmin, tmax=tmax,
                     reject=reject)
epochs = mne.Epochs(raw, **epochs_params)

print(epochs)


I am working on the file "0.18/_downloads/11f39f61bd7f4cfd5791b0d10da462f2/plot_eeg_erp.ipynb".
The first task is:
In practice it's quite common to have some EEG channels that are actually
EOG channels. To change a channel type you can use the
:func:mne.io.Raw.set_channel_types method. For example
to treat an EOG channel as EEG you can change its type using
Can you write Python code for it?

raw.set_channel_types(mapping={'EOG 061': 'eeg'})
print(raw.info)


I am working on the file "0.18/_downloads/11f39f61bd7f4cfd5791b0d10da462f2/plot_eeg_erp.ipynb".
The first task is:
Let's restrict the data to the EEG channels
Can you write Python code for it?


I am working on the file "0.18/_downloads/11f39f61bd7f4cfd5791b0d10da462f2/plot_eeg_erp.ipynb".
The first task is:
Often, it makes sense to store Evoked objects in a dictionary or a list -
either different conditions, or different subjects.
Can you write Python code for it?

# If they are stored in a list, they can be easily averaged, for example,
# for a grand average across subjects (or conditions).
grand_average = mne.grand_average(all_evokeds)
mne.write_evokeds('/tmp/tmp-ave.fif', all_evokeds)

# If Evokeds objects are stored in a dictionary, they can be retrieved by name.
all_evokeds = dict((cond, epochs[cond].average()) for cond in event_id)
print(all_evokeds['left/auditory'])

# Besides for explicit access, this can be used for example to set titles.
for cond in all_evokeds:
    all_evokeds[cond].plot_joint(title=cond, **joint_kwargs)


I am working on the file "0.18/_downloads/11f39f61bd7f4cfd5791b0d10da462f2/plot_eeg_erp.ipynb".
The first task is:
Setting EEG Montage (using standard montages)
In the case where your data don't have locations you can set them
using a :class:mne.channels.Montage. MNE comes with a set of default
montages. To read one of them do:
Can you write Python code for it?

montage = mne.channels.read_montage('standard_1020')
print(montage)


I am working on the file "0.18/_downloads/11f39f61bd7f4cfd5791b0d10da462f2/plot_eeg_erp.ipynb".
The first task is:
Setup for reading the raw data
Can you write Python code for it?

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
# these data already have an EEG average reference
raw = mne.io.read_raw_fif(raw_fname, preload=True)


I am working on the file "0.18/_downloads/11f39f61bd7f4cfd5791b0d10da462f2/plot_eeg_erp.ipynb".
The first task is:
The EEG channels in the sample dataset already have locations.
These locations are available in the 'loc' of each channel description.
For the first channel we get
Can you write Python code for it?


I am working on the file "0.18/_downloads/11f39f61bd7f4cfd5791b0d10da462f2/plot_eeg_erp.ipynb".
The first task is:
This can be simplified with a Python list comprehension:
Can you write Python code for it?

all_evokeds = [epochs[cond].average() for cond in sorted(event_id.keys())]
print(all_evokeds)

# Then, we construct and plot an unweighted average of left vs. right trials
# this way, too:
mne.combine_evoked(
    [aud_l, -aud_r, vis_l, -vis_r], weights='equal').plot_joint(**joint_kwargs)


I am working on the file "0.18/_downloads/11f39f61bd7f4cfd5791b0d10da462f2/plot_eeg_erp.ipynb".
The first task is:
This is an equal-weighting difference. If you have imbalanced trial numbers,
you could also consider either equalizing the number of events per
condition (using
:meth:epochs.equalize_event_counts <mne.Epochs.equalize_event_counts>).
As an example, first, we create individual ERPs for each condition.
Can you write Python code for it?

aud_l = epochs["auditory", "left"].average()
aud_r = epochs["auditory", "right"].average()
vis_l = epochs["visual", "left"].average()
vis_r = epochs["visual", "right"].average()

all_evokeds = [aud_l, aud_r, vis_l, vis_r]
print(all_evokeds)


I am working on the file "0.18/_downloads/11f39f61bd7f4cfd5791b0d10da462f2/plot_eeg_erp.ipynb".
The first task is:
To apply a montage on your data use the set_montage method.
function. Here don't actually call this function as our demo dataset
already contains good EEG channel locations.
Next we'll explore the definition of the reference.
Setting EEG reference
Let's first remove the reference from our Raw object.
This explicitly prevents MNE from adding a default EEG average reference
required for source localization.
Can you write Python code for it?

raw_no_ref, _ = mne.set_eeg_reference(raw, [])


I am working on the file "0.18/_downloads/13161608f5f01f8a66c6efa4aab22d71/plot_sensor_connectivity.ipynb".
The first task is:
Compute all-to-all connectivity in sensor space
Computes the Phase Lag Index (PLI) between all gradiometers and shows the
connectivity in 3D using the helmet geometry. The left visual stimulation data
are used which produces strong connectvitiy in the right occipital sensors.
Can you write Python code for it?

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

import numpy as np
from scipy import linalg

import mne
from mne import io
from mne.connectivity import spectral_connectivity
from mne.datasets import sample

print(__doc__)


I am working on the file "0.18/_downloads/13161608f5f01f8a66c6efa4aab22d71/plot_sensor_connectivity.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

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

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

# Add a bad channel
raw.info['bads'] += ['MEG 2443']

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

# Create epochs for the visual condition
event_id, tmin, tmax = 3, -0.2, 1.5  # need a long enough epoch for 5 cycles
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6))

# Compute connectivity for band containing the evoked response.
# We exclude the baseline period
fmin, fmax = 3., 9.
sfreq = raw.info['sfreq']  # the sampling frequency
tmin = 0.0  # exclude the baseline period
con, freqs, times, n_epochs, n_tapers = spectral_connectivity(
    epochs, method='pli', mode='multitaper', sfreq=sfreq, fmin=fmin, fmax=fmax,
    faverage=True, tmin=tmin, mt_adaptive=False, n_jobs=1)

# the epochs contain an EOG channel, which we remove now
ch_names = epochs.ch_names
idx = [ch_names.index(name) for name in ch_names if name.startswith('MEG')]
con = con[idx][:, idx]

# con is a 3D array where the last dimension is size one since we averaged
# over frequencies in a single band. Here we make it 2D
con = con[:, :, 0]

# Now, visualize the connectivity in 3D
from mayavi import mlab  # noqa

mlab.figure(size=(600, 600), bgcolor=(0.5, 0.5, 0.5))

# Plot the sensor locations
sens_loc = [raw.info['chs'][picks[i]]['loc'][:3] for i in idx]
sens_loc = np.array(sens_loc)

pts = mlab.points3d(sens_loc[:, 0], sens_loc[:, 1], sens_loc[:, 2],
                    color=(1, 1, 1), opacity=1, scale_factor=0.005)

# Get the strongest connections
n_con = 20  # show up to 20 connections
min_dist = 0.05  # exclude sensors that are less than 5cm apart
threshold = np.sort(con,...


I am working on the file "0.18/_downloads/18ee52b07a5bc1258587ad0c3ea7326f/plot_sensors_time_frequency.ipynb".
The first task is:
Alternatively, you can also create PSDs from Epochs objects with functions
that start with psd_ such as
:func:mne.time_frequency.psd_multitaper and
:func:mne.time_frequency.psd_welch.
Can you write Python code for it?

f, ax = plt.subplots()
psds, freqs = psd_multitaper(epochs, fmin=2, fmax=40, n_jobs=1)
psds = 10. * np.log10(psds)
psds_mean = psds.mean(0).mean(0)
psds_std = psds.mean(0).std(0)

ax.plot(freqs, psds_mean, color='k')
ax.fill_between(freqs, psds_mean - psds_std, psds_mean + psds_std,
                color='k', alpha=.5)
ax.set(title='Multitaper PSD (gradiometers)', xlabel='Frequency',
       ylabel='Power Spectral Density (dB)')
plt.show()


I am working on the file "0.18/_downloads/18ee52b07a5bc1258587ad0c3ea7326f/plot_sensors_time_frequency.ipynb".
The first task is:
Frequency analysis
We start by exploring the frequence content of our epochs.
Let's first check out all channel types by averaging across epochs.
Can you write Python code for it?


I am working on the file "0.18/_downloads/18ee52b07a5bc1258587ad0c3ea7326f/plot_sensors_time_frequency.ipynb".
The first task is:
Now let's take a look at the spatial distributions of the PSD.
Can you write Python code for it?


I am working on the file "0.18/_downloads/18ee52b07a5bc1258587ad0c3ea7326f/plot_sensors_time_frequency.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

data_path = somato.data_path()
raw_fname = data_path + '/MEG/somato/sef_raw_sss.fif'

# Setup for reading the raw data
raw = mne.io.read_raw_fif(raw_fname)
events = mne.find_events(raw, stim_channel='STI 014')

# picks MEG gradiometers
picks = mne.pick_types(raw.info, meg='grad', eeg=False, eog=True, stim=False)

# Construct Epochs
event_id, tmin, tmax = 1, -1., 3.
baseline = (None, 0)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=baseline, reject=dict(grad=4000e-13, eog=350e-6),
                    preload=True)

epochs.resample(150., npad='auto')  # resample to reduce computation time


I am working on the file "0.18/_downloads/18ee52b07a5bc1258587ad0c3ea7326f/plot_sensors_time_frequency.ipynb".
The first task is:
Time-frequency analysis: power and inter-trial coherence
We now compute time-frequency representations (TFRs) from our Epochs.
We'll look at power and inter-trial coherence (ITC).
To this we'll use the function :func:mne.time_frequency.tfr_morlet
but you can also use :func:mne.time_frequency.tfr_multitaper
or :func:mne.time_frequency.tfr_stockwell.
Can you write Python code for it?

# define frequencies of interest (log-spaced)
freqs = np.logspace(*np.log10([6, 35]), num=8)
n_cycles = freqs / 2.  # different number of cycle per frequency
power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True,
                        return_itc=True, decim=3, n_jobs=1)


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
Advanced artifact detection
Let's use a more efficient way to find artifacts
Can you write Python code for it?

eog_average = create_eog_epochs(raw, reject=dict(mag=5e-12, grad=4000e-13),
                                picks='meg').average()

eog_epochs = create_eog_epochs(raw, reject=reject)  # get single EOG trials
eog_inds, scores = ica.find_bads_eog(eog_epochs)  # find via correlation

ica.plot_scores(scores, exclude=eog_inds)  # look at r scores of components
# we can see that only one component is highly correlated and that this
# component got detected by our correlation analysis (red).

ica.plot_sources(eog_average, exclude=eog_inds)  # look at source time course


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
Artifact Correction with ICA
ICA finds directions in the feature space
corresponding to projections with high non-Gaussianity. We thus obtain
a decomposition into independent components, and the artifact's contribution
is typically localized in only a small number of components.
These components have to be correctly identified and removed.
If EOG or ECG recordings are available, they can be used in ICA to
automatically select the corresponding artifact components from the
decomposition. To do so, you have to first build an :class:mne.Epochs object
around blink or heartbeat events.
ICA is implemented in MNE using the :class:mne.preprocessing.ICA class,
which we will review here.
Can you write Python code for it?

import numpy as np

import mne
from mne.datasets import sample

from mne.preprocessing import ICA
from mne.preprocessing import create_eog_epochs, create_ecg_epochs

# getting some data ready
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'

raw = mne.io.read_raw_fif(raw_fname, preload=True)
# 1Hz high pass is often helpful for fitting ICA (already lowpassed @ 40 Hz)
raw.filter(1., None, n_jobs=1, fir_design='firwin')


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
Before applying artifact correction please learn about your actual artifacts
by reading tut-artifact-detection.

Warning

ICA is sensitive to low-frequency drifts and therefore
             requires the data to be high-pass filtered prior to fitting.
             Typically, a cutoff frequency of 1 Hz is recommended. Note that
             FIR filters prior to MNE 0.15 used the ``'firwin2'`` design
             method, which generally produces rather shallow filters that
             might not work for ICA processing. Therefore, it is recommended
             to use IIR filters for MNE up to 0.14. In MNE 0.15, FIR filters
             can be designed with the ``'firwin'`` method, which generally
             produces much steeper filters. This method will be the default
             FIR design method in MNE 0.16. In MNE 0.15, you need to
             explicitly set ``fir_design='firwin'`` to use this method. This
             is the recommended filter method for ICA preprocessing.

Fit ICA
First, choose the ICA method. There are currently three possible choices:
fastica, picard, and infomax.

Note

The default method in MNE is FastICA, which along with Infomax is
          one of the most widely used ICA algorithms. Picard is a
          new algorithm that is expected to converge faster than FastICA and
          Infomax, especially when the aim is to recover accurate maps with
          a low tolerance parameter, see [1]_ for more information.

Can you write Python code for it?

method = 'fastica'

# Choose other parameters
n_components = 25  # if float, select n_components by explained variance of PCA
decim = 3  # we need sufficient statistics, not all time points -> saves time

# we will also set state of the random number generator - ICA is a
# non-deterministic algorithm, but we want to have the same decomposition
# and the same order of components each time this tutorial is run
random_state = 23


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
Define the ICA object instance
Can you write Python code for it?

ica = ICA(n_components=n_components, method=method, random_state=random_state)
print(ica)


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
Indeed it looks like an EOG, also in the average time course.
We construct a list where our reference run is the first element. Then we
can detect similar components from the other runs (the other ICA objects)
using :func:mne.preprocessing.corrmap. So our template must be a tuple like
(reference_run_index, component_index):
Can you write Python code for it?

icas = [reference_ica] + icas_from_other_data
template = (0, eog_inds[0])


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
Nice, we have found similar ICs from the other (simulated) runs!
In this way, you can detect a type of artifact semi-automatically for example
for all subjects in a study.
The detected template can also be retrieved as an array and stored; this
array can be used as an alternative template to
:func:mne.preprocessing.corrmap.
Can you write Python code for it?

eog_component = reference_ica.get_components()[:, eog_inds[0]]


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
Note that nothing is yet removed from the raw data. To remove the effects of
the rejected components,
:meth:the apply method <mne.preprocessing.ICA.apply> must be called.
Here we apply it on the copy of the first ten seconds, so that the rest of
this tutorial still works as intended.
Can you write Python code for it?

raw_copy = raw.copy().crop(0, 10)
ica.apply(raw_copy)
raw_copy.plot()  # check the result


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
Plot ICA components
Can you write Python code for it?

ica.plot_components()  # can you spot some potential bad guys?


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
Remember, don't do this at home! Start by reading in a collection of ICA
solutions instead. Something like:
icas = [mne.preprocessing.read_ica(fname) for fname in ica_fnames]
Can you write Python code for it?


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
That component is showing a prototypical average vertical EOG time course.
Pay attention to the labels, a customized read-out of the
mne.preprocessing.ICA.labels_:
Can you write Python code for it?


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
The idea behind corrmap is that artifact patterns are similar across subjects
and can thus be identified by correlating the different patterns resulting
from each solution with a template. The procedure is therefore
semi-automatic. :func:mne.preprocessing.corrmap hence takes a list of
ICA solutions and a template, that can be an index or an array.
As we don't have different subjects or runs available today, here we will
simulate ICA solutions from different subjects by fitting ICA models to
different parts of the same recording. Then we will use one of the components
from our original ICA as a template in order to detect sufficiently similar
components in the simulated ICAs.
The following block of code simulates having ICA solutions from different
runs/subjects so it should not be used in real analysis - use independent
data sets instead.
Can you write Python code for it?

# We'll start by simulating a group of subjects or runs from a subject
start, stop = [0, raw.times[-1]]
intervals = np.linspace(start, stop, 4, dtype=np.float)
icas_from_other_data = list()
raw.pick_types(meg=True, eeg=False)  # take only MEG channels
for ii, start in enumerate(intervals):
    if ii + 1 < len(intervals):
        stop = intervals[ii + 1]
        print('fitting ICA from {0} to {1} seconds'.format(start, stop))
        this_ica = ICA(n_components=n_components, method=method).fit(
            raw, start=start, stop=stop, reject=reject)
        icas_from_other_data.append(this_ica)


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
These labels were used by the plotters and are added automatically
by artifact detection functions. You can also manually edit them to annotate
components.
Now let's see how we would modify our signals if we removed this component
from the data.
Can you write Python code for it?

ica.plot_overlay(eog_average, exclude=eog_inds, show=False)
# red -> before, black -> after. Yes! We remove quite a lot!

# to definitely register this component as a bad one to be removed
# there is the ``ica.exclude`` attribute, a simple Python list
ica.exclude.extend(eog_inds)

# from now on the ICA will reject this component even if no exclude
# parameter is passed, and this information will be stored to disk
# on saving

# uncomment this for reading and writing
# ica.save('my-ica.fif')
# ica = read_ica('my-ica.fif')


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
Which one is the bad EOG component?
Here we rely on our previous detection algorithm. You would need to decide
yourself if no automatic detection was available.
Can you write Python code for it?


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
we avoid fitting ICA on crazy environmental artifacts that would
dominate the variance and decomposition
Can you write Python code for it?

reject = dict(mag=5e-12, grad=4000e-13)
ica.fit(raw, picks='meg', decim=decim, reject=reject)
print(ica)


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
we can also take a look at multiple different components at once:
Can you write Python code for it?

ica.plot_properties(raw, picks=[1, 2], psd_args={'fmax': 35.})


I am working on the file "0.18/_downloads/19760b3068251666d2866a483589cbfa/plot_artifacts_correction_ica.ipynb".
The first task is:
we can see that the data were filtered so the spectrum plot is not
very informative, let's change that:
Can you write Python code for it?

ica.plot_properties(raw, picks=0, psd_args={'fmax': 35.})


I am working on the file "0.18/_downloads/1a4a7584ec39fc35bbee19c028a6a895/plot_artifacts_correction_rejection.ipynb".
The first task is:

Note

Interpolation is a linear operation that can be performed also on
    Raw and Epochs objects.

For more details on interpolation see the page channel_interpolation.
Marking bad raw segments with annotations
MNE provides an :class:mne.Annotations class that can be used to mark
segments of raw data and to reject epochs that overlap with bad segments
of data. The annotations are automatically synchronized with raw data as
long as the timestamps of raw data and annotations are in sync.
See tut-brainstorm-auditory
for a long example exploiting the annotations for artifact removal.
The instances of annotations are created by providing a list of onsets and
offsets with descriptions for each segment. The onsets and offsets are marked
as seconds. onset refers to time from start of the data. offset is
the duration of the annotation. The instance of :class:mne.Annotations
can be added as an attribute of :class:mne.io.Raw.
Can you write Python code for it?

eog_events = mne.preprocessing.find_eog_events(raw)
n_blinks = len(eog_events)
# Center to cover the whole blink with full duration of 0.5s:
onset = eog_events[:, 0] / raw.info['sfreq'] - 0.25
duration = np.repeat(0.5, n_blinks)
annot = mne.Annotations(onset, duration, ['bad blink'] * n_blinks,
                        orig_time=raw.info['meas_date'])
raw.set_annotations(annot)
print(raw.annotations)  # to get information about what annotations we have
raw.plot(events=eog_events)  # To see the annotated segments.


I am working on the file "0.18/_downloads/1a4a7584ec39fc35bbee19c028a6a895/plot_artifacts_correction_rejection.ipynb".
The first task is:

Note

The rejection values can be highly data dependent. You should be careful
   when adjusting these values. Make sure not too many epochs are rejected
   and look into the cause of the rejections. Maybe it's just a matter
   of marking a single channel as bad and you'll be able to save a lot
   of data.

We then construct the epochs
Can you write Python code for it?

events = mne.find_events(raw, stim_channel='STI 014')
event_id = {"auditory/left": 1}
tmin = -0.2  # start of each epoch (200ms before the trigger)
tmax = 0.5  # end of each epoch (500ms after the trigger)
baseline = (None, 0)  # means from the first instant to t = 0
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    picks=['meg', 'eog'], baseline=baseline, reject=reject,
                    reject_by_annotation=True)


I am working on the file "0.18/_downloads/1a4a7584ec39fc35bbee19c028a6a895/plot_artifacts_correction_rejection.ipynb".
The first task is:
And plot the so-called drop log that details the reason for which some
epochs have been dropped.
Can you write Python code for it?

print(epochs.drop_log[40:45])  # only a subset
epochs.plot_drop_log()


I am working on the file "0.18/_downloads/1a4a7584ec39fc35bbee19c028a6a895/plot_artifacts_correction_rejection.ipynb".
The first task is:
Let's now interpolate the bad channels (displayed in red above)
Can you write Python code for it?


I am working on the file "0.18/_downloads/1a4a7584ec39fc35bbee19c028a6a895/plot_artifacts_correction_rejection.ipynb".
The first task is:
Let's plot the cleaned data
Can you write Python code for it?


I am working on the file "0.18/_downloads/1a4a7584ec39fc35bbee19c028a6a895/plot_artifacts_correction_rejection.ipynb".
The first task is:
We then drop/reject the bad epochs
Can you write Python code for it?


I am working on the file "0.18/_downloads/1e53d1b1e265859ba0683a6745c36ed7/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Compute statistic
To use an algorithm optimized for spatio-temporal clustering, we
just pass the spatial connectivity matrix (instead of spatio-temporal)
Can you write Python code for it?

print('Computing connectivity.')
connectivity = mne.spatial_src_connectivity(src)

#    Note that X needs to be a multi-dimensional array of shape
#    samples (subjects) x time x space, so we permute dimensions
X = np.transpose(X, [2, 1, 0])

#    Now let's actually do the clustering. This can take a long time...
#    Here we set the threshold quite high to reduce computation.
p_threshold = 0.001
t_threshold = -stats.distributions.t.ppf(p_threshold / 2., n_subjects - 1)
print('Clustering.')
T_obs, clusters, cluster_p_values, H0 = clu = \
    spatio_temporal_cluster_1samp_test(X, connectivity=connectivity, n_jobs=1,
                                       threshold=t_threshold, buffer_size=None,
                                       verbose=True)
#    Now select the clusters that are sig. at p < 0.05 (note that this value
#    is multiple-comparisons corrected).
good_cluster_inds = np.where(cluster_p_values < 0.05)[0]


I am working on the file "0.18/_downloads/1e53d1b1e265859ba0683a6745c36ed7/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Finally, we want to compare the overall activity levels in each condition,
the diff is taken along the last axis (condition). The negative sign makes
it so condition1 > condition2 shows up as "red blobs" (instead of blue).
Can you write Python code for it?

X = np.abs(X)  # only magnitude
X = X[:, :, :, 0] - X[:, :, :, 1]  # make paired contrast


I am working on the file "0.18/_downloads/1e53d1b1e265859ba0683a6745c36ed7/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
It's a good idea to spatially smooth the data, and for visualization
purposes, let's morph these to fsaverage, which is a grade 5 source space
with vertices 0:10242 for each hemisphere. Usually you'd have to morph
each subject's data separately (and you might want to use morph_data
instead), but here since all estimates are on 'sample' we can use one
morph matrix for all the heavy lifting.
Can you write Python code for it?

# Read the source space we are morphing to
src = mne.read_source_spaces(src_fname)
fsave_vertices = [s['vertno'] for s in src]
morph_mat = mne.compute_source_morph(
    src=inverse_operator['src'], subject_to='fsaverage',
    spacing=fsave_vertices, subjects_dir=subjects_dir).morph_mat

n_vertices_fsave = morph_mat.shape[0]

#    We have to change the shape for the dot() to work properly
X = X.reshape(n_vertices_sample, n_times * n_subjects * 2)
print('Morphing data.')
X = morph_mat.dot(X)  # morph_mat is a sparse matrix
X = X.reshape(n_vertices_fsave, n_times, n_subjects, 2)


I am working on the file "0.18/_downloads/1e53d1b1e265859ba0683a6745c36ed7/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Read epochs for all channels, removing a bad one
Can you write Python code for it?

raw.info['bads'] += ['MEG 2443']
picks = mne.pick_types(raw.info, meg=True, eog=True, exclude='bads')
event_id = 1  # L auditory
reject = dict(grad=1000e-13, mag=4000e-15, eog=150e-6)
epochs1 = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                     baseline=(None, 0), reject=reject, preload=True)

event_id = 3  # L visual
epochs2 = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                     baseline=(None, 0), reject=reject, preload=True)

#    Equalize trial counts to eliminate bias (which would otherwise be
#    introduced by the abs() performed below)
equalize_epoch_counts([epochs1, epochs2])


I am working on the file "0.18/_downloads/1e53d1b1e265859ba0683a6745c36ed7/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
subjects_dir = data_path + '/subjects'
src_fname = subjects_dir + '/fsaverage/bem/fsaverage-ico-5-src.fif'

tmin = -0.2
tmax = 0.3  # Use a lower tmax to reduce multiple comparisons

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


I am working on the file "0.18/_downloads/1e53d1b1e265859ba0683a6745c36ed7/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Transform to common cortical space
Normally you would read in estimates across several subjects and morph
them to the same cortical space (e.g. fsaverage). For example purposes,
we will simulate this by just having each "subject" have the same
response (just noisy in source space) here.

Note

Note that for 7 subjects with a two-sided statistical test, the minimum
    significance under a permutation test is only p = 1/(2 ** 6) = 0.015,
    which is large.

Can you write Python code for it?

n_vertices_sample, n_times = condition1.data.shape
n_subjects = 7
print('Simulating data for %d subjects.' % n_subjects)

#    Let's make sure our results replicate, so set the seed.
np.random.seed(0)
X = randn(n_vertices_sample, n_times, n_subjects, 2) * 10
X[:, :, :, 0] += condition1.data[:, :, np.newaxis]
X[:, :, :, 1] += condition2.data[:, :, np.newaxis]


I am working on the file "0.18/_downloads/1e53d1b1e265859ba0683a6745c36ed7/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Transform to source space
Can you write Python code for it?

fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE, sLORETA, or eLORETA)
inverse_operator = read_inverse_operator(fname_inv)
sample_vertices = [s['vertno'] for s in inverse_operator['src']]

#    Let's average and compute inverse, resampling to speed things up
evoked1 = epochs1.average()
evoked1.resample(50, npad='auto')
condition1 = apply_inverse(evoked1, inverse_operator, lambda2, method)
evoked2 = epochs2.average()
evoked2.resample(50, npad='auto')
condition2 = apply_inverse(evoked2, inverse_operator, lambda2, method)

#    Let's only deal with t > 0, cropping to reduce multiple comparisons
condition1.crop(0, None)
condition2.crop(0, None)
tmin = condition1.tmin
tstep = condition1.tstep


I am working on the file "0.18/_downloads/1e53d1b1e265859ba0683a6745c36ed7/plot_stats_cluster_spatio_temporal.ipynb".
The first task is:
Visualize the clusters
Can you write Python code for it?

print('Visualizing clusters.')

#    Now let's build a convenient representation of each cluster, where each
#    cluster becomes a "time point" in the SourceEstimate
stc_all_cluster_vis = summarize_clusters_stc(clu, tstep=tstep,
                                             vertices=fsave_vertices,
                                             subject='fsaverage')

#    Let's actually plot the first "time point" in the SourceEstimate, which
#    shows all the clusters, weighted by duration
subjects_dir = op.join(data_path, 'subjects')
# blue blobs are for condition A < condition B, red for A > B
brain = stc_all_cluster_vis.plot(
    hemi='both', views='lateral', subjects_dir=subjects_dir,
    time_label='Duration significant (ms)', size=(800, 800),
    smoothing_steps=5, clim=dict(kind='value', pos_lims=[0, 1, 40]))
# brain.save_image('clusters.png')


I am working on the file "0.18/_downloads/2187adaa95700a6de5f9ba2004254a87/plot_sensor_noise_level.ipynb".
The first task is:
We can plot the absolute noise levels:
Can you write Python code for it?

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


I am working on the file "0.18/_downloads/285b08fd9daa300c4b586365a3234831/plot_read_evoked.ipynb".
The first task is:
Reading and writing an evoked file
This script shows how to read and write evoked datasets.
Can you write Python code for it?

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

from mne import read_evokeds
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

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

# Reading
condition = 'Left Auditory'
evoked = read_evokeds(fname, condition=condition, baseline=(None, 0),
                      proj=True)


I am working on the file "0.18/_downloads/285b08fd9daa300c4b586365a3234831/plot_read_evoked.ipynb".
The first task is:
Show result as a butterfly plot:
By using exclude=[] bad channels are not excluded and are shown in red
Can you write Python code for it?

evoked.plot(exclude=[], time_unit='s')

# Show result as a 2D image (x: time, y: channels, color: amplitude)
evoked.plot_image(exclude=[], time_unit='s')


I am working on the file "0.18/_downloads/2ca67ec2532318d668bdc8f5a0fd1b69/plot_read_epochs.ipynb".
The first task is:
Reading epochs from a raw FIF file
This script shows how to read the epochs from a raw file given
a list of events. For illustration, we compute the evoked responses
for both MEG and EEG data by averaging all the epochs.
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Matti Hamalainen <msh@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)

import mne
from mne import io
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()


I am working on the file "0.18/_downloads/2ca67ec2532318d668bdc8f5a0fd1b69/plot_read_epochs.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

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

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

# Set up pick list: EEG + MEG - bad channels (modify to your needs)
raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True,
                       exclude='bads')

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

evoked = epochs.average()  # average epochs to get the evoked response


I am working on the file "0.18/_downloads/3a40d74661a066ddd49c83c766d57670/plot_visualize_epochs.ipynb".
The first task is:
This tutorial focuses on visualization of epoched data. All of the functions
introduced here are basically high level matplotlib functions with built in
intelligence to work with epoched data. All the methods return a handle to
matplotlib figure instance.
Events used for constructing the epochs here are the triggers for subject
being presented a smiley face at the center of the visual field. More of the
paradigm at BABDHIFJ.
All plotting functions start with plot. Let's start with the most
obvious. :func:mne.Epochs.plot offers an interactive browser that allows
rejection by hand when called in combination with a keyword block=True.
This blocks the execution of the script until the browser window is closed.
Can you write Python code for it?


I am working on the file "0.18/_downloads/3a40d74661a066ddd49c83c766d57670/plot_visualize_epochs.ipynb".
The first task is:
Visualize Epochs data
Can you write Python code for it?

# sphinx_gallery_thumbnail_number = 7

import os.path as op

import mne

data_path = op.join(mne.datasets.sample.data_path(), 'MEG', 'sample')
raw = mne.io.read_raw_fif(
    op.join(data_path, 'sample_audvis_raw.fif'), preload=True)
raw.load_data().filter(None, 9, fir_design='firwin')
raw.set_eeg_reference('average', projection=True)  # set EEG average reference
event_id = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
            'visual/right': 4, 'smiley': 5, 'button': 32}
events = mne.read_events(op.join(data_path, 'sample_audvis_raw-eve.fif'))
epochs = mne.Epochs(raw, events, event_id=event_id, tmin=-0.2, tmax=.5)


I am working on the file "0.18/_downloads/3a40d74661a066ddd49c83c766d57670/plot_visualize_epochs.ipynb".
The first task is:
You also have functions for plotting channelwise information arranged into a
shape of the channel array. The image plotting uses automatic scaling by
default, but noisy channels and different channel types can cause the scaling
to be a bit off. Here we define the limits by hand.
Can you write Python code for it?

epochs.plot_topo_image(vmin=-250, vmax=250, title='ERF images', sigma=2.,
                       fig_facecolor='w', font_color='k')


I am working on the file "0.18/_downloads/3c22b754d3ee35b041302de37d5f9515/plot_decoding_spatio_temporal_source.ipynb".
The first task is:
Decoding in sensor space using a logistic regression
Can you write Python code for it?

# Retrieve source space data into an array
X = np.array([stc.lh_data for stc in stcs])  # only keep left hemisphere
y = epochs.events[:, 2]

# prepare a series of classifier applied at each time sample
clf = make_pipeline(StandardScaler(),  # z-score normalization
                    SelectKBest(f_classif, k=500),  # select features for speed
                    LinearModel(LogisticRegression(C=1, solver='liblinear')))
time_decod = SlidingEstimator(clf, scoring='roc_auc')

# Run cross-validated decoding analyses:
scores = cross_val_multiscore(time_decod, X, y, cv=5, n_jobs=1)

# Plot average decoding scores of 5 splits
fig, ax = plt.subplots(1)
ax.plot(epochs.times, scores.mean(0), label='score')
ax.axhline(.5, color='k', linestyle='--', label='chance')
ax.axvline(0, color='k')
plt.legend()


I am working on the file "0.18/_downloads/3c22b754d3ee35b041302de37d5f9515/plot_decoding_spatio_temporal_source.ipynb".
The first task is:
Decoding source space data
Decoding to MEG data in source space on the left cortical surface. Here
univariate feature selection is employed for speed purposes to confine the
classification to a small number of potentially relevant features. The
classifier then is trained to selected features of epochs in source space.
Can you write Python code for it?

# sphinx_gallery_thumbnail_number = 2

# Author: Denis A. Engemann <denis.engemann@gmail.com>
#         Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#         Jean-Remi King <jeanremi.king@gmail.com>
#         Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression

import mne
from mne.minimum_norm import apply_inverse_epochs, read_inverse_operator
from mne.decoding import (cross_val_multiscore, LinearModel, SlidingEstimator,
                          get_coef)

print(__doc__)

data_path = mne.datasets.sample.data_path()
fname_fwd = data_path + 'MEG/sample/sample_audvis-meg-oct-6-fwd.fif'
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
subjects_dir = data_path + '/subjects'


I am working on the file "0.18/_downloads/3c22b754d3ee35b041302de37d5f9515/plot_decoding_spatio_temporal_source.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
fname_cov = data_path + '/MEG/sample/sample_audvis-cov.fif'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'

tmin, tmax = -0.2, 0.8
event_id = dict(aud_r=2, vis_r=4)  # load contra-lateral conditions

# Setup for reading the raw data
raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.filter(None, 10., fir_design='firwin')
events = mne.read_events(event_fname)

# Set up pick list: MEG - bad channels (modify to your needs)
raw.info['bads'] += ['MEG 2443']  # mark bads
picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True,
                       exclude='bads')

# Read epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    picks=picks, baseline=(None, 0), preload=True,
                    reject=dict(grad=4000e-13, eog=150e-6),
                    decim=5)  # decimate to save memory and increase speed


I am working on the file "0.18/_downloads/4365eab31ed2fa347de7f294ac9500c3/plot_label_from_stc.ipynb".
The first task is:
Generate a functional label from source estimates
Threshold source estimates and produce a functional label. The label
is typically the region of interest that contains high values.
Here we compare the average time course in the anatomical label obtained
by FreeSurfer segmentation and the average time course from the
functional label. As expected the time course in the functional
label yields higher values.
Can you write Python code for it?

# Author: Luke Bloy <luke.bloy@gmail.com>
#         Alex Gramfort <alexandre.gramfort@telecom-paristech.fr>
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

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

print(__doc__)

data_path = sample.data_path()
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
subjects_dir = data_path + '/subjects'
subject = 'sample'

snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM"  # use dSPM method (could also be MNE or sLORETA)

# Compute a label/ROI based on the peak power between 80 and 120 ms.
# The label bankssts-lh is used for the comparison.
aparc_label_name = 'bankssts-lh'
tmin, tmax = 0.080, 0.120

# Load data
evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
inverse_operator = read_inverse_operator(fname_inv)
src = inverse_operator['src']  # get the source space

# Compute inverse solution
stc = apply_inverse(evoked, inverse_operator, lambda2, method,
                    pick_ori='normal')

# Make an STC in the time interval of interest and take the mean
stc_mean = stc.copy().crop(tmin, tmax).mean()

# use the stc_mean to generate a functional label
# region growing is halted at 60% of the peak value within the
# anatomical label / ROI specified by aparc_label_name
label = mne.read_labels_from_annot(subject, parc='aparc',
                                   subjects_dir=subjects_dir,
                                   regexp=aparc_label_name)[0]
stc_mean_label = stc_mean.in_label(label)
data = np.abs(stc_mean_label.data)
stc_mean_label.data[data < 0.6 * np.max(data)] = 0.

# 8.5% of original source space vertices were omitted during forward
# calculation, suppress the warning here with verbose='error'
func_labels, _ = mne.stc_to_label(stc_mean_label, src=src, smooth=True,
                                  subjects_dir=subjects_dir, connected=True,
                          ...


I am working on the file "0.18/_downloads/4457f677e595ddd6eaad6bb91f5bea1a/plot_source_space_time_frequency.ipynb".
The first task is:
Compute induced power in the source space with dSPM
Returns STC files ie source estimates of induced power
for different bands in the source space. The inverse method
is linear based on dSPM inverse operator.
Can you write Python code for it?

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

import matplotlib.pyplot as plt

import mne
from mne import io
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, source_band_induced_power

print(__doc__)


I am working on the file "0.18/_downloads/4457f677e595ddd6eaad6bb91f5bea1a/plot_source_space_time_frequency.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
tmin, tmax, event_id = -0.2, 0.5, 1

# Setup for reading the raw data
raw = io.read_raw_fif(raw_fname)
events = mne.find_events(raw, stim_channel='STI 014')
inverse_operator = read_inverse_operator(fname_inv)

include = []
raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more

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

# Load condition 1
event_id = 1
events = events[:10]  # take 10 events to keep the computation time low
# Use linear detrend to reduce any edge artifacts
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6),
                    preload=True, detrend=1)

# Compute a source estimate per frequency band
bands = dict(alpha=[9, 11], beta=[18, 22])

stcs = source_band_induced_power(epochs, inverse_operator, bands, n_cycles=2,
                                 use_fft=False, n_jobs=1)

for b, stc in stcs.items():
    stc.save('induced_power_%s' % b)


I am working on the file "0.18/_downloads/469b6692cc10fb0680563c52afebc05c/plot_channel_epochs_image.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

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

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

# Set up pick list: EEG + MEG - bad channels (modify to your needs)
raw.info['bads'] = ['MEG 2443', 'EEG 053']

# Create epochs, here for gradiometers + EOG only for simplicity
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    picks=('grad', 'eog'), baseline=(None, 0), preload=True,
                    reject=dict(grad=4000e-13, eog=150e-6))


I am working on the file "0.18/_downloads/4702564ec4882e1756a75c62d2a92ee4/plot_stats_cluster_1samp_test_time_frequency.ipynb".
The first task is:
Non-parametric 1 sample cluster statistic on single trial power
This script shows how to estimate significant clusters
in time-frequency power estimates. It uses a non-parametric
statistical procedure based on permutations and cluster
level statistics.
The procedure consists in:

extracting epochs
compute single trial power estimates
baseline line correct the power estimates (power ratios)
compute stats to see if ratio deviates from 1.
Can you write Python code for it?

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

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne.time_frequency import tfr_morlet
from mne.stats import permutation_cluster_1samp_test
from mne.datasets import sample

print(__doc__)


I am working on the file "0.18/_downloads/47de0e2137654670a631ea71dfab4b62/plot_lcmv_beamformer_volume.ipynb".
The first task is:
Compute LCMV inverse solution in volume source space
Compute LCMV beamformer on an auditory evoked dataset in a volume source space.
Can you write Python code for it?

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

# sphinx_gallery_thumbnail_number = 3

import mne
from mne.datasets import sample
from mne.beamformer import make_lcmv, apply_lcmv

print(__doc__)


I am working on the file "0.18/_downloads/47de0e2137654670a631ea71dfab4b62/plot_lcmv_beamformer_volume.ipynb".
The first task is:
Compute covariance matrices, fit and apply  spatial filter.
Can you write Python code for it?

# Read regularized noise covariance and compute regularized data covariance
noise_cov = mne.compute_covariance(epochs, tmin=tmin, tmax=0, method='shrunk',
                                   rank=None)
data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15,
                                  method='shrunk', rank=None)

# Compute weights of free orientation (vector) beamformer with weight
# normalization (neural activity index, NAI). Providing a noise covariance
# matrix enables whitening of the data and forward solution. Source orientation
# is optimized by setting pick_ori to 'max-power'.
# weight_norm can also be set to 'unit-noise-gain'. Source orientation can also
# be 'normal' (but only when using a surface-based source space) or None,
# which computes a vector beamfomer. Note, however, that not all combinations
# of orientation selection and weight normalization are implemented yet.
filters = make_lcmv(evoked.info, forward, data_cov, reg=0.05,
                    noise_cov=noise_cov, pick_ori='max-power',
                    weight_norm='nai', rank=None)
print(filters)

# You can save these with:
# filters.save('filters-lcmv.h5')

# Apply this spatial filter to the evoked data.
stc = apply_lcmv(evoked, filters, max_ori_out='signed')


I am working on the file "0.18/_downloads/47de0e2137654670a631ea71dfab4b62/plot_lcmv_beamformer_volume.ipynb".
The first task is:
We can also visualize the activity on a "glass brain" (shown here with
absolute values):
Can you write Python code for it?

clim = dict(kind='value', lims=[0.3, 0.6, 0.9])
abs(stc).plot(src=forward['src'], subject='sample', subjects_dir=subjects_dir,
              mode='glass_brain', clim=clim)


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

import os.path as op

import mne
from mne.datasets import sample


I am working on the file "0.18/_downloads/4d74528a24c597c5e2cf1e334cf2a4f0/plot_compute_covariance.ipynb".
The first task is:
How should I regularize the covariance matrix?
The estimated covariance can be numerically
unstable and tends to induce correlations between estimated source amplitudes
and the number of samples available. The MNE manual therefore suggests to
regularize the noise covariance matrix (see
cov_regularization), especially if only few samples are available.
Unfortunately it is not easy to tell the effective number of samples, hence,
to choose the appropriate regularization.
In MNE-Python, regularization is done using advanced regularization methods
described in [1]_. For this the 'auto' option can be used. With this
option cross-validation will be used to learn the optimal regularization:
Can you write Python code for it?

noise_cov_reg = mne.compute_covariance(epochs, tmax=0., method='auto',
                                       rank=None)


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

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


I am working on the file "0.18/_downloads/4d74528a24c597c5e2cf1e334cf2a4f0/plot_compute_covariance.ipynb".
The first task is:
Now that you have the covariance matrix in an MNE-Python object you can
save it to a file with :func:mne.write_cov. Later you can read it back
using :func:mne.read_cov.
You can also use the pre-stimulus baseline to estimate the noise covariance.
First we have to construct the epochs. When computing the covariance, you
should use baseline correction when constructing the epochs. Otherwise the
covariance matrix will be inaccurate. In MNE this is done by default, but
just to be sure, we define it here manually.
Can you write Python code for it?

events = mne.find_events(raw)
epochs = mne.Epochs(raw, events, event_id=1, tmin=-0.2, tmax=0.5,
                    baseline=(-0.2, 0.0), decim=3,  # we'll decimate for speed
                    verbose='error')  # and ignore the warning about aliasing


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

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

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


I am working on the file "0.18/_downloads/4d74528a24c597c5e2cf1e334cf2a4f0/plot_compute_covariance.ipynb".
The first task is:
This plot displays both, the whitened evoked signals for each channels and
the whitened 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 GFP.
The whitened 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) [2],
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
sphx_glr_auto_examples_visualization_plot_evoked_whitening.py) and
sphx_glr_auto_examples_inverse_plot_covariance_whitening_dspm.py):
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.18/_downloads/4d74528a24c597c5e2cf1e334cf2a4f0/plot_compute_covariance.ipynb".
The first task is:
This will plot the whitened evoked for the optimal estimator and display the
GFPs 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.18/_downloads/4eb6243ca7f447169baac6cdad977ee8/plot_stats_spatio_temporal_cluster_sensors.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
event_id = {'Aud/L': 1, 'Aud/R': 2, 'Vis/L': 3, 'Vis/R': 4}
tmin = -0.2
tmax = 0.5

# Setup for reading the raw data
raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.filter(1, 30, fir_design='firwin')
events = mne.read_events(event_fname)


I am working on the file "0.18/_downloads/4eb6243ca7f447169baac6cdad977ee8/plot_stats_spatio_temporal_cluster_sensors.ipynb".
The first task is:
Spatiotemporal permutation F-test on full sensor data
Tests for differential evoked responses in at least
one condition using a permutation clustering test.
The FieldTrip neighbor templates will be used to determine
the adjacency between sensors. This serves as a spatial prior
to the clustering. Spatiotemporal clusters will then
be visualized using custom matplotlib code.
Caveat for the interpretation of "significant" clusters: see
the FieldTrip website_.
Can you write Python code for it?

# Authors: Denis Engemann <denis.engemann@gmail.com>
#          Jona Sassenhagen <jona.sassenhagen@gmail.com>
#
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mne.viz import plot_topomap

import mne
from mne.stats import spatio_temporal_cluster_test
from mne.datasets import sample
from mne.channels import find_ch_connectivity
from mne.viz import plot_compare_evokeds

print(__doc__)


I am working on the file "0.18/_downloads/50f27a42fcbd35f08d90ddc7386b7140/plot_compute_raw_data_spectrum.ipynb".
The first task is:
Alternative functions for PSDs
There are also several functions in MNE that create a PSD using a Raw
object. These are in the :mod:mne.time_frequency module and begin with
psd_*. For example, we'll use a multitaper method to compute the PSD
below.
Can you write Python code for it?

f, ax = plt.subplots()
psds, freqs = psd_multitaper(raw, low_bias=True, tmin=tmin, tmax=tmax,
                             fmin=fmin, fmax=fmax, proj=True, picks=picks,
                             n_jobs=1)
psds = 10 * np.log10(psds)
psds_mean = psds.mean(0)
psds_std = psds.std(0)

ax.plot(freqs, psds_mean, color='k')
ax.fill_between(freqs, psds_mean - psds_std, psds_mean + psds_std,
                color='k', alpha=.5)
ax.set(title='Multitaper PSD', xlabel='Frequency',
       ylabel='Power Spectral Density (dB)')
plt.show()


I am working on the file "0.18/_downloads/50f27a42fcbd35f08d90ddc7386b7140/plot_compute_raw_data_spectrum.ipynb".
The first task is:
Compute the power spectral density of raw data
This script shows how to compute the power spectral density (PSD)
of measurements on a raw dataset. It also show the effect of applying SSP
to the data to reduce ECG and EOG artifacts.
Can you write Python code for it?

# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#          Eric Larson <larson.eric.d@gmail.com>
# License: BSD (3-clause)

import numpy as np
import matplotlib.pyplot as plt

import mne
from mne import io, read_proj, read_selection
from mne.datasets import sample
from mne.time_frequency import psd_multitaper

print(__doc__)


I am working on the file "0.18/_downloads/50f27a42fcbd35f08d90ddc7386b7140/plot_compute_raw_data_spectrum.ipynb".
The first task is:
Plot the raw PSD
First we'll visualize the raw PSD of our data. We'll do this on all of the
channels first. Note that there are several parameters to the
:meth:mne.io.Raw.plot_psd method, some of which will be explained below.
Can you write Python code for it?

raw.plot_psd(area_mode='range', tmax=10.0, show=False, average=True)


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

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

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

print(__doc__)

data_path = sample.data_path()
fname = data_path
fname += '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'

inv = read_inverse_operator(fname)

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


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

lh_points = inv['src'][0]['rr']
lh_faces = inv['src'][0]['use_tris']
rh_points = inv['src'][1]['rr']
rh_faces = inv['src'][1]['use_tris']
from mayavi import mlab  # noqa

mlab.figure(size=(600, 600), bgcolor=(0, 0, 0))
mesh = mlab.triangular_mesh(lh_points[:, 0], lh_points[:, 1], lh_points[:, 2],
                            lh_faces, colormap='RdBu')
mesh.module_manager.scalar_lut_manager.reverse_lut = True

mesh = mlab.triangular_mesh(rh_points[:, 0], rh_points[:, 1], rh_points[:, 2],
                            rh_faces, colormap='RdBu')
mesh.module_manager.scalar_lut_manager.reverse_lut = True


I am working on the file "0.18/_downloads/597e5dfe47820d56eb232e93bcc62128/plot_mne_dspm_source_localization.ipynb".
The first task is:
Compute inverse solution
Can you write Python code for it?

method = "dSPM"
snr = 3.
lambda2 = 1. / snr ** 2
stc, residual = apply_inverse(evoked, inverse_operator, lambda2,
                              method=method, pick_ori=None,
                              return_residual=True, verbose=True)


I am working on the file "0.18/_downloads/597e5dfe47820d56eb232e93bcc62128/plot_mne_dspm_source_localization.ipynb".
The first task is:
Compute the evoked response
Let's just use MEG channels for simplicity.
Can you write Python code for it?

evoked = epochs.average().pick('meg')
evoked.plot(time_unit='s')
evoked.plot_topomap(times=np.linspace(0.05, 0.15, 5), ch_type='mag',
                    time_unit='s')

# Show whitening
evoked.plot_white(noise_cov, time_unit='s')

del epochs  # to save memory


I am working on the file "0.18/_downloads/597e5dfe47820d56eb232e93bcc62128/plot_mne_dspm_source_localization.ipynb".
The first task is:
Dipole orientations
The pick_ori parameter of the
:func:mne.minimum_norm.apply_inverse function controls
the orientation of the dipoles. One useful setting is pick_ori='vector',
which will return an estimate that does not only contain the source power at
each dipole, but also the orientation of the dipoles.
Can you write Python code for it?

stc_vec = apply_inverse(evoked, inverse_operator, lambda2,
                        method=method, pick_ori='vector')
brain = stc_vec.plot(**surfer_kwargs)
brain.add_text(0.1, 0.9, 'Vector solution', 'title', font_size=20)
del stc_vec


I am working on the file "0.18/_downloads/597e5dfe47820d56eb232e93bcc62128/plot_mne_dspm_source_localization.ipynb".
The first task is:
Examine the original data and the residual after fitting:
Can you write Python code for it?

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


I am working on the file "0.18/_downloads/597e5dfe47820d56eb232e93bcc62128/plot_mne_dspm_source_localization.ipynb".
The first task is:
Here we use peak getter to move visualization to the time point of the peak
and draw a marker at the maximum peak vertex.
Can you write Python code for it?

vertno_max, time_max = stc.get_peak(hemi='rh')

subjects_dir = data_path + '/subjects'
surfer_kwargs = dict(
    hemi='rh', subjects_dir=subjects_dir,
    clim=dict(kind='value', lims=[8, 12, 15]), views='lateral',
    initial_time=time_max, time_unit='s', size=(800, 800), smoothing_steps=5)
brain = stc.plot(**surfer_kwargs)
brain.add_foci(vertno_max, coords_as_verts=True, hemi='rh', color='blue',
               scale_factor=0.6, alpha=0.5)
brain.add_text(0.1, 0.9, 'dSPM (plus location of maximal activation)', 'title',
               font_size=14)


I am working on the file "0.18/_downloads/597e5dfe47820d56eb232e93bcc62128/plot_mne_dspm_source_localization.ipynb".
The first task is:
Note that there is a relationship between the orientation of the dipoles and
the surface of the cortex. For this reason, we do not use an inflated
cortical surface for visualization, but the original surface used to define
the source space.
For more information about dipole orientations, see
tut-dipole-orientations.
Now let's look at each solver:
Can you write Python code for it?

for mi, (method, lims) in enumerate((('dSPM', [8, 12, 15]),
                                     ('sLORETA', [3, 5, 7]),
                                     ('eLORETA', [0.75, 1.25, 1.75]),)):
    surfer_kwargs['clim']['lims'] = lims
    stc = apply_inverse(evoked, inverse_operator, lambda2,
                        method=method, pick_ori=None)
    brain = stc.plot(figure=mi, **surfer_kwargs)
    brain.add_text(0.1, 0.9, method, 'title', font_size=20)
    del stc


I am working on the file "0.18/_downloads/597e5dfe47820d56eb232e93bcc62128/plot_mne_dspm_source_localization.ipynb".
The first task is:
Process MEG data
Can you write Python code for it?

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

raw = mne.io.read_raw_fif(raw_fname)  # already has an average reference
events = mne.find_events(raw, stim_channel='STI 014')

event_id = dict(aud_l=1)  # event trigger and conditions
tmin = -0.2  # start of each epoch (200ms before the trigger)
tmax = 0.5  # end of each epoch (500ms after the trigger)
raw.info['bads'] = ['MEG 2443', 'EEG 053']
baseline = (None, 0)  # means from the first instant to t = 0
reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)

epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    picks=('meg', 'eog'), baseline=baseline, reject=reject)


I am working on the file "0.18/_downloads/597e5dfe47820d56eb232e93bcc62128/plot_mne_dspm_source_localization.ipynb".
The first task is:
Visualization
View activation time-series
Can you write Python code for it?

plt.figure()
plt.plot(1e3 * stc.times, stc.data[::100, :].T)
plt.xlabel('time (ms)')
plt.ylabel('%s value' % method)
plt.show()


I am working on the file "0.18/_downloads/5b60b1d2b62e31ceb3bcab30d238498d/plot_ica_from_raw.ipynb".
The first task is:
1) Fit ICA model using the FastICA algorithm.
Other available choices are picard or infomax.

Note

The default method in MNE is FastICA, which along with Infomax is
          one of the most widely used ICA algorithm. Picard is a
          new algorithm that is expected to converge faster than FastICA and
          Infomax, especially when the aim is to recover accurate maps with
          a low tolerance parameter, see [1]_ for more information.

We pass a float value between 0 and 1 to select n_components based on the
percentage of variance explained by the PCA components.
Can you write Python code for it?

ica = ICA(n_components=0.95, method='fastica', random_state=0, max_iter=100)

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

# low iterations -> does not fully converge
ica.fit(raw, picks=picks, decim=3, reject=dict(mag=4e-12, grad=4000e-13))

# maximum number of components to reject
n_max_ecg, n_max_eog = 3, 1  # here we don't expect horizontal EOG components


I am working on the file "0.18/_downloads/5b60b1d2b62e31ceb3bcab30d238498d/plot_ica_from_raw.ipynb".
The first task is:
2) identify bad components by analyzing latent sources.
Can you write Python code for it?

title = 'Sources related to %s artifacts (red)'

# generate ECG epochs use detection via phase statistics

ecg_epochs = create_ecg_epochs(raw, tmin=-.5, tmax=.5, picks=picks)

ecg_inds, scores = ica.find_bads_ecg(ecg_epochs, method='ctps')
ica.plot_scores(scores, exclude=ecg_inds, title=title % 'ecg', labels='ecg')

show_picks = np.abs(scores).argsort()[::-1][:5]

ica.plot_sources(raw, show_picks, exclude=ecg_inds, title=title % 'ecg')
ica.plot_components(ecg_inds, title=title % 'ecg', colorbar=True)

ecg_inds = ecg_inds[:n_max_ecg]
ica.exclude += ecg_inds

# detect EOG by correlation

eog_inds, scores = ica.find_bads_eog(raw)
ica.plot_scores(scores, exclude=eog_inds, title=title % 'eog', labels='eog')

show_picks = np.abs(scores).argsort()[::-1][:5]

ica.plot_sources(raw, show_picks, exclude=eog_inds, title=title % 'eog')
ica.plot_components(eog_inds, title=title % 'eog', colorbar=True)

eog_inds = eog_inds[:n_max_eog]
ica.exclude += eog_inds


I am working on the file "0.18/_downloads/5b60b1d2b62e31ceb3bcab30d238498d/plot_ica_from_raw.ipynb".
The first task is:
Compute ICA on MEG data and remove artifacts
ICA is fit to MEG raw data.
The sources matching the ECG and EOG are automatically found and displayed.
Subsequently, artifact detection and rejection quality are assessed.
Can you write Python code for it?

# Authors: Denis Engemann <denis.engemann@gmail.com>
#          Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)

import numpy as np

import mne
from mne.preprocessing import ICA
from mne.preprocessing import create_ecg_epochs, create_eog_epochs
from mne.datasets import sample


I am working on the file "0.18/_downloads/5bfa8c81761f280190ee0aad29f36ae8/decoding_rsa.ipynb".
The first task is:
Compute confusion matrix using ROC-AUC
Can you write Python code for it?

confusion = np.zeros((len(classes), len(classes)))
for ii, train_class in enumerate(classes):
    for jj in range(ii, len(classes)):
        confusion[ii, jj] = roc_auc_score(y == train_class, y_pred[:, jj])
        confusion[jj, ii] = confusion[ii, jj]


I am working on the file "0.18/_downloads/5bfa8c81761f280190ee0aad29f36ae8/decoding_rsa.ipynb".
The first task is:
Confusion matrix related to mental representations have been historically
summarized with dimensionality reduction using multi-dimensional scaling [1].
See how the face samples cluster together.
Can you write Python code for it?

fig, ax = plt.subplots(1)
mds = MDS(2, random_state=0, dissimilarity='precomputed')
chance = 0.5
summary = mds.fit_transform(chance - confusion)
cmap = plt.get_cmap('rainbow')
colors = ['r', 'b']
names = list(conds['condition'].values)
for color, name in zip(colors, set(names)):
    sel = np.where([this_name == name for this_name in names])[0]
    size = 500 if name == 'human face' else 100
    ax.scatter(summary[sel, 0], summary[sel, 1], s=size,
               facecolors=color, label=name, edgecolors='k')
ax.axis('off')
ax.legend(loc='lower right', scatterpoints=1, ncol=2)
plt.tight_layout()
plt.show()


I am working on the file "0.18/_downloads/5bfa8c81761f280190ee0aad29f36ae8/decoding_rsa.ipynb".
The first task is:
Define stimulus - trigger mapping
Can you write Python code for it?

conditions = []
for c in conds.values:
    cond_tags = list(c[:2])
    cond_tags += [('not-' if i == 0 else '') + conds.columns[k]
                  for k, i in enumerate(c[2:], 2)]
    conditions.append('/'.join(map(str, cond_tags)))
print(conditions[:10])


I am working on the file "0.18/_downloads/5bfa8c81761f280190ee0aad29f36ae8/decoding_rsa.ipynb".
The first task is:
Epoch data
Can you write Python code for it?

picks = mne.pick_types(raw.info, meg=True)
epochs = mne.Epochs(raw, events=events, event_id=event_id, baseline=None,
                    picks=picks, tmin=-.1, tmax=.500, preload=True)


I am working on the file "0.18/_downloads/5bfa8c81761f280190ee0aad29f36ae8/decoding_rsa.ipynb".
The first task is:
Let's make the event_id dictionary
Can you write Python code for it?

event_id = dict(zip(conditions, conds.trigger + 1))
event_id['0/human bodypart/human/not-face/animal/natural']


I am working on the file "0.18/_downloads/5bfa8c81761f280190ee0aad29f36ae8/decoding_rsa.ipynb".
The first task is:
Let's restrict the number of conditions to speed up computation
Can you write Python code for it?

max_trigger = 24
conds = conds[:max_trigger]  # take only the first 24 rows


I am working on the file "0.18/_downloads/5bfa8c81761f280190ee0aad29f36ae8/decoding_rsa.ipynb".
The first task is:
Plot
Can you write Python code for it?

labels = [''] * 5 + ['face'] + [''] * 11 + ['bodypart'] + [''] * 6
fig, ax = plt.subplots(1)
im = ax.matshow(confusion, cmap='RdBu_r', clim=[0.3, 0.7])
ax.set_yticks(range(len(classes)))
ax.set_yticklabels(labels)
ax.set_xticks(range(len(classes)))
ax.set_xticklabels(labels, rotation=40, ha='left')
ax.axhline(11.5, color='k')
ax.axvline(11.5, color='k')
plt.colorbar(im)
plt.tight_layout()
plt.show()


I am working on the file "0.18/_downloads/5bfa8c81761f280190ee0aad29f36ae8/decoding_rsa.ipynb".
The first task is:
Read MEG data
Can you write Python code for it?

n_runs = 4  # 4 for full data (use less to speed up computations)
fname = op.join(data_path, 'sample_subject_%i_tsss_mc.fif')
raws = [read_raw_fif(fname % block, verbose='error')
        for block in range(n_runs)]  # ignore filename warnings
raw = concatenate_raws(raws)

events = mne.find_events(raw, min_duration=.002)

events = events[events[:, 2] <= max_trigger]


I am working on the file "0.18/_downloads/5c761b4eaf61d9e6642d568c8bc535a2/plot_source_power_spectrum.ipynb".
The first task is:
View PSD of sources in label
Can you write Python code for it?

plt.plot(1e3 * stc.times, stc.data.T)
plt.xlabel('Frequency (Hz)')
plt.ylabel('PSD (dB)')
plt.title('Source Power Spectrum (PSD)')
plt.show()


I am working on the file "0.18/_downloads/5d2190fa4d2e36b882cc913879fb6f3b/plot_decoding_time_generalization_conditions.ipynb".
The first task is:
Decoding sensor space data with generalization across time and conditions
This example runs the analysis described in [1]_. It illustrates how one can
fit a linear classifier to identify a discriminatory topography at a given time
instant and subsequently assess whether this linear model can accurately
predict all of the time samples of a second set of conditions.
References
.. [1] King & Dehaene (2014) 'Characterizing the dynamics of mental
       representations: the Temporal Generalization method', Trends In
       Cognitive Sciences, 18(4), 203-210. doi: 10.1016/j.tics.2014.01.002.
Can you write Python code for it?

# Authors: Jean-Remi King <jeanremi.king@gmail.com>
#          Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)

import matplotlib.pyplot as plt

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

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

print(__doc__)

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


I am working on the file "0.18/_downloads/5d2190fa4d2e36b882cc913879fb6f3b/plot_decoding_time_generalization_conditions.ipynb".
The first task is:
Plot
Can you write Python code for it?

fig, ax = plt.subplots(1)
im = ax.matshow(scores, vmin=0, vmax=1., cmap='RdBu_r', origin='lower',
                extent=epochs.times[[0, -1, 0, -1]])
ax.axhline(0., color='k')
ax.axvline(0., color='k')
ax.xaxis.set_ticks_position('bottom')
ax.set_xlabel('Testing Time (s)')
ax.set_ylabel('Training Time (s)')
ax.set_title('Generalization across time and condition')
plt.colorbar(im, ax=ax)
plt.show()


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

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


I am working on the file "0.18/_downloads/62c7de5c3dadb3e4bb93d667d4af9010/plot_opm_rest_data.ipynb".
The first task is:
Alignment and forward
Can you write Python code for it?

src = mne.read_source_spaces(src_fname)
bem = mne.read_bem_solution(bem_fname)
fwd = dict()
trans = dict(vv=vv_trans_fname, opm=opm_trans_fname)
# check alignment and generate forward
with mne.use_coil_def(opm_coil_def_fname):
    for kind in kinds:
        dig = True if kind == 'vv' else False
        fig = mne.viz.plot_alignment(
            raws[kind].info, trans=trans[kind], subject=subject,
            subjects_dir=subjects_dir, dig=dig, coord_frame='mri',
            surfaces=('head', 'white'))
        mlab.view(0, 90, focalpoint=(0., 0., 0.), distance=0.6, figure=fig)
        fwd[kind] = mne.make_forward_solution(
            raws[kind].info, trans[kind], src, bem, eeg=False, verbose=True)


I am working on the file "0.18/_downloads/62c7de5c3dadb3e4bb93d667d4af9010/plot_opm_rest_data.ipynb".
The first task is:
Alpha
Can you write Python code for it?

fig_alpha, brain_alpha = plot_band('vv', 'alpha')


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

fig_beta, brain_beta = plot_band('vv', 'beta')
fig_beta_opm, brain_beta_opm = plot_band('opm', 'beta')


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

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

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


I am working on the file "0.18/_downloads/62c7de5c3dadb3e4bb93d667d4af9010/plot_opm_rest_data.ipynb".
The first task is:
Explore data
Can you write Python code for it?

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


I am working on the file "0.18/_downloads/62c7de5c3dadb3e4bb93d667d4af9010/plot_opm_rest_data.ipynb".
The first task is:
Gamma
Can you write Python code for it?

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


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

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

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


I am working on the file "0.18/_downloads/62c7de5c3dadb3e4bb93d667d4af9010/plot_opm_rest_data.ipynb".
The first task is:
Now we can make some plots of each frequency band. Note that the OPM head
coverage is only over right motor cortex, so only localization
of beta is likely to be worthwhile.
Theta
Can you write Python code for it?

def plot_band(kind, band):
    title = "%s %s\n(%d-%d Hz)" % ((titles[kind], band,) + freq_bands[band])
    topos[kind][band].plot_topomap(
        times=0., scalings=1., cbar_fmt='%0.1f', vmin=0, cmap='inferno',
        time_format=title)
    brain = stcs[kind][band].plot(
        subject=subject, subjects_dir=subjects_dir, views='cau', hemi='both',
        time_label=title, title=title, colormap='inferno',
        clim=dict(kind='percent', lims=(70, 85, 99)))
    brain.show_view(dict(azimuth=0, elevation=0), roll=0)
    return fig, brain

fig_theta, brain_theta = plot_band('vv', 'theta')


I am working on the file "0.18/_downloads/62c7de5c3dadb3e4bb93d667d4af9010/plot_opm_rest_data.ipynb".
The first task is:
VectorView and OPM resting state datasets
Here we compute the resting state from raw for data recorded using
a Neuromag VectorView system and a custom OPM system.
The pipeline is meant to mostly follow the Brainstorm [1]
OMEGA resting tutorial pipeline <bst_omega_>.
The steps we use are:

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

Preprocessing
Can you write Python code for it?

# sphinx_gallery_thumbnail_number = 14

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

import os.path as op

from mne.filter import next_fast_len
from mayavi import mlab

import mne

print(__doc__)

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

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


I am working on the file "0.18/_downloads/635035741daf88c18928d17907998cb3/plot_run_ica.ipynb".
The first task is:
Compute ICA components on epochs
ICA is fit to MEG raw data.
We assume that the non-stationary EOG artifacts have already been removed.
The sources matching the ECG are automatically found and displayed.
Note that this example does quite a bit of processing, so even on a
fast machine it can take about a minute to complete.
Can you write Python code for it?

# Authors: Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)

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

print(__doc__)


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

ica = ICA(n_components=0.95, method='fastica').fit(epochs)

ecg_epochs = create_ecg_epochs(raw, tmin=-.5, tmax=.5)
ecg_inds, scores = ica.find_bads_ecg(ecg_epochs)

ica.plot_components(ecg_inds)


I am working on the file "0.18/_downloads/635035741daf88c18928d17907998cb3/plot_run_ica.ipynb".
The first task is:
Read and preprocess the data. Preprocessing consists of:

MEG channel selection
1-30 Hz band-pass filter
epoching -0.2 to 0.5 seconds with respect to events
Can you write Python code for it?

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

raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.pick_types(meg=True, eeg=False, exclude='bads', stim=True)
raw.filter(1, 30, fir_design='firwin')

# longer + more epochs for more artifact exposure
events = mne.find_events(raw, stim_channel='STI 014')
epochs = mne.Epochs(raw, events, event_id=None, tmin=-0.2, tmax=0.5)


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

# Authors: Christopher Holdgraf <choldgraf@berkeley.edu>
#
# License: BSD (3-clause)
from scipy.io import loadmat
import numpy as np
from mayavi import mlab
from matplotlib import pyplot as plt
from os import path as op

import mne
from mne.viz import ClickableImage  # noqa
from mne.viz import plot_alignment, snapshot_brain_montage

print(__doc__)

subjects_dir = mne.datasets.sample.data_path() + '/subjects'
path_data = mne.datasets.misc.data_path() + '/ecog/sample_ecog.mat'

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


I am working on the file "0.18/_downloads/66fec418bceb5ce89704fb8b44930330/plot_3d_to_2d.ipynb".
The first task is:
Load data
First we'll load a sample ECoG dataset which we'll use for generating
a 2D snapshot.
Can you write Python code for it?

mat = loadmat(path_data)
ch_names = mat['ch_names'].tolist()
elec = mat['elec']  # electrode coordinates in meters
dig_ch_pos = dict(zip(ch_names, elec))
mon = mne.channels.DigMontage(dig_ch_pos=dig_ch_pos)
info = mne.create_info(ch_names, 1000., 'ecog', montage=mon)
print('Created %s channel positions' % len(ch_names))


I am working on the file "0.18/_downloads/66fec418bceb5ce89704fb8b44930330/plot_3d_to_2d.ipynb".
The first task is:
Manually creating 2D electrode positions
If we don't have the 3D electrode positions then we can still create a
2D representation of the electrodes. Assuming that you can see the electrodes
on the 2D image, we can use :class:mne.viz.ClickableImage to open the image
interactively. You can click points on the image and the x/y coordinate will
be stored.
We'll open an image file, then use ClickableImage to
return 2D locations of mouse clicks (or load a file already created).
Then, we'll return these xy positions as a layout for use with plotting topo
maps.
Can you write Python code for it?

# This code opens the image so you can click on it. Commented out
# because we've stored the clicks as a layout file already.

# # The click coordinates are stored as a list of tuples
# im = plt.imread('./brain.png')
# click = ClickableImage(im)
# click.plot_clicks()

# # Generate a layout from our clicks and normalize by the image
# print('Generating and saving layout...')
# lt = click.to_layout()
# lt.save(op.join(layout_path, layout_name))  # To save if we want

# # We've already got the layout, load it
lt = mne.channels.read_layout(layout_name, path=layout_path, scale=False)
x = lt.pos[:, 0] * float(im.shape[1])
y = (1 - lt.pos[:, 1]) * float(im.shape[0])  # Flip the y-position
fig, ax = plt.subplots()
ax.imshow(im)
ax.scatter(x, y, s=120, color='r')
plt.autoscale(tight=True)
ax.set_axis_off()
plt.show()


I am working on the file "0.18/_downloads/66fec418bceb5ce89704fb8b44930330/plot_3d_to_2d.ipynb".
The first task is:
Project 3D electrodes to a 2D snapshot
Because we have the 3D location of each electrode, we can use the
:func:mne.viz.snapshot_brain_montage function to return a 2D image along
with the electrode positions on that image. We use this in conjunction with
:func:mne.viz.plot_alignment, which visualizes electrode positions.
Can you write Python code for it?

fig = plot_alignment(info, subject='sample', subjects_dir=subjects_dir,
                     surfaces=['pial'], meg=False)
mlab.view(200, 70)
xy, im = snapshot_brain_montage(fig, mon)

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

# Define an arbitrary "activity" pattern for viz
activity = np.linspace(100, 200, xy_pts.shape[0])

# This allows us to use matplotlib to create arbitrary 2d scatterplots
fig2, ax = plt.subplots(figsize=(10, 10))
ax.imshow(im)
ax.scatter(*xy_pts.T, c=activity, s=200, cmap='coolwarm')
ax.set_axis_off()
# fig2.savefig('./brain.png', bbox_inches='tight')  # For ClickableImage


I am working on the file "0.18/_downloads/6d7b5624e4fa6fee90fb68aca9314f7f/plot_evoked_topomap.ipynb".
The first task is:
Basic 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.18/_downloads/6d7b5624e4fa6fee90fb68aca9314f7f/plot_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.18/_downloads/6d7b5624e4fa6fee90fb68aca9314f7f/plot_evoked_topomap.ipynb".
The first task is:
If you look at the edges of the head circle of a single topomap you'll see
the effect of extrapolation. By default extrapolate='box' is used which
extrapolates to a large box stretching beyond the head circle.
Compare this with extrapolate='head' (second topography below) where
extrapolation goes to 0 at the head circle and extrapolate='local' where
extrapolation is performed only within some distance from channels:
Can you write Python code for it?

extrapolations = ['box', 'head', 'local']
fig, axes = plt.subplots(figsize=(7.5, 2.5), ncols=3)

for ax, extr in zip(axes, extrapolations):
    evoked.plot_topomap(0.1, ch_type='mag', size=2, extrapolate=extr, axes=ax,
                        show=False, colorbar=False)
    ax.set_title(extr, fontsize=14)


I am working on the file "0.18/_downloads/6d7b5624e4fa6fee90fb68aca9314f7f/plot_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.18/_downloads/6ec427414cb824661234889f12aed01b/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
Brainstorm CTF phantom dataset tutorial
Here we compute the evoked from raw for the Brainstorm CTF phantom
tutorial dataset. For comparison, see [1]_ and:
https://neuroimage.usc.edu/brainstorm/Tutorials/PhantomCtf

References
.. [1] Tadel F, Baillet S, Mosher JC, Pantazis D, Leahy RM.
       Brainstorm: A User-Friendly Application for MEG/EEG Analysis.
       Computational Intelligence and Neuroscience, vol. 2011, Article ID
       879716, 13 pages, 2011. doi:10.1155/2011/879716
Can you write Python code for it?

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

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

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

print(__doc__)


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

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


I am working on the file "0.18/_downloads/6ec427414cb824661234889f12aed01b/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
Compare the actual position with the estimated one.
Can you write Python code for it?

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


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

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


I am working on the file "0.18/_downloads/6ec427414cb824661234889f12aed01b/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
Our choice of tmin and tmax should capture exactly one cycle, so
we can make the unusual choice of baselining using the entire epoch
when creating our evoked data. We also then crop to a single time point
(@t=0) because this is a peak in our signal.
Can you write Python code for it?

tmin = -0.5 / dip_freq
tmax = -tmin
epochs = mne.Epochs(raw, events, event_id=1, tmin=tmin, tmax=tmax,
                    baseline=(None, None))
evoked = epochs.average()
evoked.plot(time_unit='s')
evoked.crop(0., 0.)


I am working on the file "0.18/_downloads/6ec427414cb824661234889f12aed01b/plot_brainstorm_phantom_ctf.ipynb".
The first task is:
The CTF software compensation works reasonably well:
Can you write Python code for it?


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

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