I am working on the file "0.17/_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.17/_downloads/5aed7e184bbc15d957e5af18b0edfb7e/plot_object_annotations.ipynb".
The first task is:
First we'll create and plot events associated with the experimental paradigm:
Can you write Python code for it?

# extract the events array from the stim channel
events = mne.find_events(raw)

# Specify event_id dictionary based on the meaning of experimental triggers
event_id = {'Auditory/Left': 1, 'Auditory/Right': 2,
            'Visual/Left': 3, 'Visual/Right': 4,
            'smiley': 5, 'button': 32}
color = {1: 'green', 2: 'yellow', 3: 'red', 4: 'c', 5: 'black', 32: 'blue'}

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


I am working on the file "0.17/_downloads/5aed7e184bbc15d957e5af18b0edfb7e/plot_object_annotations.ipynb".
The first task is:
It is possible to concatenate two annotations with the + operator (just like
lists) if both share the same orig_time
Can you write Python code for it?

annot = mne.Annotations(onset=[10], duration=[0.5],
                        description=['foobar'],
                        orig_time=orig_time)
annot = annot_orig + annot  # concatenation
print(annot)


I am working on the file "0.17/_downloads/5aed7e184bbc15d957e5af18b0edfb7e/plot_object_annotations.ipynb".
The first task is:
Next, we're going to detect eye blinks and turn them into
:class:~mne.Annotations:
Can you write Python code for it?

# find blinks
annotated_blink_raw = raw.copy()
eog_events = mne.preprocessing.find_eog_events(raw)
n_blinks = len(eog_events)

# Turn blink events into Annotations of 0.5 seconds duration,
# each centered on the blink event:
onset = eog_events[:, 0] / raw.info['sfreq'] - 0.25
duration = np.repeat(0.5, n_blinks)
description = ['bad blink'] * n_blinks
annot = mne.Annotations(onset, duration, description,
                        orig_time=raw.info['meas_date'])
annotated_blink_raw.set_annotations(annot)

# plot the annotated raw
annotated_blink_raw.plot()


I am working on the file "0.17/_downloads/5aed7e184bbc15d957e5af18b0edfb7e/plot_object_annotations.ipynb".
The first task is:
Notice again that for the case where orig_time is None,
it is assumed that the orig_time is the time of the first sample of data.
Can you write Python code for it?

raw_delta = (1 / raw.info['sfreq'])
print('raw.first_sample is {}'.format(raw.first_samp * raw_delta))
print('annot_none.onset[0] is {}'.format(annot_none.onset[0]))
print('raw_a.annotations.onset[0] is {}'.format(raw_a.annotations.onset[0]))


I am working on the file "0.17/_downloads/5aed7e184bbc15d957e5af18b0edfb7e/plot_object_annotations.ipynb".
The first task is:
Now we create two raw objects and set each with different annotations.
Then we plot both raw objects to compare the annotations.
Can you write Python code for it?

# Create two cropped copies of raw with the two previous annotations
raw_a = raw.copy().crop(tmax=12).set_annotations(annot_none)
raw_b = raw.copy().crop(tmax=12).set_annotations(annot_orig)

# Plot the raw objects
raw_a.plot()
raw_b.plot()


I am working on the file "0.17/_downloads/5aed7e184bbc15d957e5af18b0edfb7e/plot_object_annotations.ipynb".
The first task is:
Working with Annotations
An important element of :class:~mne.Annotations is
orig_time which is the time reference for the onset.
It is key to understand that when calling
:func:raw.set_annotations <mne.io.Raw.set_annotations>, given
annotations are copied and transformed so that
:class:raw.annotations.orig_time <mne.Annotations>
matches the recording time of the raw object.
Refer to the documentation of :class:~mne.Annotations to see
the expected behavior depending on meas_date and orig_time.
Where meas_date is the recording time stored in
:class:Info <mne.Info>.
You can find more information about :class:Info <mne.Info> in
sphx_glr_auto_tutorials_plot_info.py.
We'll now manipulate some simulated annotations.
The first annotations has orig_time set to None while the
second is set to a chosen POSIX timestamp for illustration purposes.
Note that both annotations have different onset values.
Can you write Python code for it?

# Create an annotation object with orig_time undefined (default)
annot_none = mne.Annotations(onset=[0, 2, 9], duration=[0.5, 4, 0],
                             description=['foo', 'bar', 'foo'],
                             orig_time=None)
print(annot_none)

# Create an annotation object with orig_time
orig_time = '2002-12-03 19:01:31.676071'
annot_orig = mne.Annotations(onset=[22, 24, 31], duration=[0.5, 4, 0],
                             description=['foo', 'bar', 'foo'],
                             orig_time=orig_time)
print(annot_orig)


I am working on the file "0.17/_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.17/_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.17/_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.17/_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.17/_downloads/5bfa8c81761f280190ee0aad29f36ae8/decoding_rsa.ipynb".
The first task is:
Let's plot some conditions
Can you write Python code for it?


I am working on the file "0.17/_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.17/_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.17/_downloads/5bfa8c81761f280190ee0aad29f36ae8/decoding_rsa.ipynb".
The first task is:
Representational Similarity Analysis
Representational Similarity Analysis is used to perform summary statistics
on supervised classifications where the number of classes is relatively high.
It consists in characterizing the structure of the confusion matrix to infer
the similarity between brain responses and serves as a proxy for characterizing
the space of mental representations [1] [2] [3]_.
In this example, we perform RSA on responses to 24 object images (among
a list of 92 images). Subjects were presented with images of human, animal
and inanimate objects [4]_. Here we use the 24 unique images of faces
and body parts.

Note

this example will download a very large (~6GB) file, so we will not
          build the images below.

References
.. [1] Shepard, R. "Multidimensional scaling, tree-fitting, and clustering."
       Science 210.4468 (1980): 390-398.
.. [2] Laakso, A. & Cottrell, G.. "Content and cluster analysis:
       assessing representational similarity in neural systems." Philosophical
       psychology 13.1 (2000): 47-76.
.. [3] Kriegeskorte, N., Marieke, M., & Bandettini.  P. "Representational
       similarity analysis-connecting the branches of systems neuroscience."
       Frontiers in systems neuroscience 2 (2008): 4.
.. [4] Cichy, R. M., Pantazis, D., & Oliva, A. "Resolving human object
       recognition in space and time." Nature neuroscience (2014): 17(3),
       455-462.
Can you write Python code for it?

# Authors: Jean-Remi King <jeanremi.king@gmail.com>
#          Jaakko Leppakangas <jaeilepp@student.jyu.fi>
#          Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)

import os.path as op
import numpy as np
from pandas import read_csv
import matplotlib.pyplot as plt

from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.manifold import MDS

import mne
from mne.io import read_raw_fif, concatenate_raws
from mne.datasets import visual_92_categories

print(__doc__)

data_path = visual_92_categories.data_path()

# Define stimulus - trigger mapping
fname = op.join(data_path, 'visual_stimuli.csv')
conds = read_csv(fname)
print(conds.head(5))


I am working on the file "0.17/_downloads/5bfa8c81761f280190ee0aad29f36ae8/decoding_rsa.ipynb".
The first task is:
Representational Similarity Analysis (RSA) is a neuroimaging-specific
appelation to refer to statistics applied to the confusion matrix
also referred to as the representational dissimilarity matrices (RDM).
Compared to the approach from Cichy et al. we'll use a multiclass
classifier (Multinomial Logistic Regression) while the paper uses
all pairwise binary classification task to make the RDM.
Also we use here the ROC-AUC as performance metric while the
paper uses accuracy. Finally here for the sake of time we use
RSA on a window of data while Cichy et al. did it for all time
instants separately.
Can you write Python code for it?

# Classify using the average signal in the window 50ms to 300ms
# to focus the classifier on the time interval with best SNR.
clf = make_pipeline(StandardScaler(),
                    LogisticRegression(C=1, solver='liblinear',
                                       multi_class='auto'))
X = epochs.copy().crop(0.05, 0.3).get_data().mean(axis=2)
y = epochs.events[:, 2]

classes = set(y)
cv = StratifiedKFold(n_splits=5, random_state=0, shuffle=True)

# Compute confusion matrix for each cross-validation fold
y_pred = np.zeros((len(y), len(classes)))
for train, test in cv.split(X, y):
    # Fit
    clf.fit(X[train], y[train])
    # Probabilistic prediction (necessary for ROC-AUC scoring metric)
    y_pred[test] = clf.predict_proba(X[test])


I am working on the file "0.17/_downloads/5c761b4eaf61d9e6642d568c8bc535a2/plot_source_power_spectrum.ipynb".
The first task is:
Compute power spectrum densities of the sources with dSPM
Returns an STC file containing the PSD (in dB) of each of the sources.
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, compute_source_psd

print(__doc__)


I am working on the file "0.17/_downloads/5c761b4eaf61d9e6642d568c8bc535a2/plot_source_power_spectrum.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'
fname_label = data_path + '/MEG/sample/labels/Aud-lh.label'

# Setup for reading the raw data
raw = io.read_raw_fif(raw_fname, verbose=False)
events = mne.find_events(raw, stim_channel='STI 014')
inverse_operator = read_inverse_operator(fname_inv)
raw.info['bads'] = ['MEG 2443', 'EEG 053']

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

tmin, tmax = 0, 120  # use the first 120s of data
fmin, fmax = 4, 100  # look at frequencies between 4 and 100Hz
n_fft = 2048  # the FFT size (n_fft). Ideally a power of 2
label = mne.read_label(fname_label)

stc = compute_source_psd(raw, inverse_operator, lambda2=1. / 9., method="dSPM",
                         tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax,
                         pick_ori="normal", n_fft=n_fft, label=label,
                         dB=True)

stc.save('psd_dSPM')


I am working on the file "0.17/_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.17/_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.17/_downloads/5d2190fa4d2e36b882cc913879fb6f3b/plot_decoding_time_generalization_conditions.ipynb".
The first task is:
We will train the classifier on all left visual vs auditory trials
and test on all right visual vs auditory trials.
Can you write Python code for it?

clf = make_pipeline(StandardScaler(), LogisticRegression(solver='lbfgs'))
time_gen = GeneralizingEstimator(clf, scoring='roc_auc', n_jobs=1,
                                 verbose=True)

# Fit classifiers on the epochs where the stimulus was presented to the left.
# Note that the experimental condition y indicates auditory or visual
time_gen.fit(X=epochs['Left'].get_data(),
             y=epochs['Left'].events[:, 2] > 2)


I am working on the file "0.17/_downloads/6282ffffa1a074ca0a88e33605afaf0b/plot_object_evoked.ipynb".
The first task is:
If you want to import evoked data from some other system and you have it in a
numpy array you can use :class:mne.EvokedArray for that. All you need is
the data and some info about the evoked data. For more information, see
tut_creating_data_structures.
Can you write Python code for it?

evoked = mne.EvokedArray(data, evoked.info, tmin=evoked.times[0])
evoked.plot(time_unit='s')


I am working on the file "0.17/_downloads/6282ffffa1a074ca0a88e33605afaf0b/plot_object_evoked.ipynb".
The first task is:
If you're gone through the tutorials of raw and epochs datasets, you're
probably already familiar with the :class:Info <mne.Info> attribute.
There is nothing new or special with the evoked.info. All the relevant
info is still there.
Can you write Python code for it?


I am working on the file "0.17/_downloads/6282ffffa1a074ca0a88e33605afaf0b/plot_object_evoked.ipynb".
The first task is:
The :class:Evoked <mne.Evoked> data structure: evoked/averaged data
The :class:Evoked <mne.Evoked> data structure is mainly used for storing
averaged data over trials. In MNE the evoked objects are usually created by
averaging epochs data with :func:mne.Epochs.average.
Can you write Python code for it?


I am working on the file "0.17/_downloads/6282ffffa1a074ca0a88e33605afaf0b/plot_object_evoked.ipynb".
The first task is:
The data is also easily accessible. Since the evoked data arrays are usually
much smaller than raw or epochs datasets, they are preloaded into the memory
when the evoked object is constructed. You can access the data as a numpy
array.
Can you write Python code for it?


I am working on the file "0.17/_downloads/6282ffffa1a074ca0a88e33605afaf0b/plot_object_evoked.ipynb".
The first task is:
The data is arranged in an array of shape (n_channels, n_times). Notice
that unlike epochs, evoked object does not support indexing. This means that
to access the data of a specific channel you must use the data array
directly.
Can you write Python code for it?

print('Data from channel {0}:'.format(evoked.ch_names[10]))
print(data[10])


I am working on the file "0.17/_downloads/6282ffffa1a074ca0a88e33605afaf0b/plot_object_evoked.ipynb".
The first task is:
The evoked data structure also contains some new attributes easily
accessible:
Can you write Python code for it?

print(evoked.nave)  # Number of averaged epochs.
print(evoked.first)  # First time sample.
print(evoked.last)  # Last time sample.
print(evoked.comment)  # Comment on dataset. Usually the condition.
print(evoked.kind)  # Type of data, either average or standard_error.


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

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

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

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

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

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

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

    return signal


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

# The locations on the cortex where the signal will originate from. These
# locations are indicated as vertex numbers.
source_vert1 = 146374
source_vert2 = 33830

# The timeseries at each vertex: one part signal, one part silence
timeseries1 = np.hstack([signal1, np.zeros_like(signal1)])
timeseries2 = np.hstack([signal2, np.zeros_like(signal2)])

# Construct a SourceEstimate object that describes the signal at the cortical
# level.
stc = mne.SourceEstimate(
    np.vstack((timeseries1, timeseries2)),  # The two timeseries
    vertices=[[source_vert1], [source_vert2]],  # Their locations
    tmin=0,
    tstep=1. / sfreq,
    subject='sample',  # We use the brain model of the MNE-Sample dataset
)


I am working on the file "0.17/_downloads/62a5f854bee83e557e411d3a953b9499/plot_dics.ipynb".
The first task is:
Now we run the signal through the forward model to obtain simulated sensor
data. To save computation time, we'll only simulate gradiometer data. You can
try simulating other types of sensors as well.
Some noise is added based on the baseline noise covariance matrix from the
sample dataset, scaled to implement the desired SNR.
Can you write Python code for it?

# Read the info from the sample dataset. This defines the location of the
# sensors and such.
info = mne.io.read_info(raw_fname)
info.update(sfreq=sfreq, bads=[])

# Only use gradiometers
picks = mne.pick_types(info, meg='grad', stim=True, exclude=())
mne.pick_info(info, picks, copy=False)

# This is the raw object that will be used as a template for the simulation.
raw = mne.io.RawArray(np.zeros((info['nchan'], len(stc.times))), info)

# Define a covariance matrix for the simulated noise. In this tutorial, we use
# a simple diagonal matrix.
cov = mne.cov.make_ad_hoc_cov(info)
cov['data'] *= (20. / snr) ** 2  # Scale the noise to achieve the desired SNR

# Simulate the raw data, with a lowpass filter on the noise
raw = simulate_raw(raw, stc, trans_fname, src_fname, bem_fname, cov=cov,
                   random_state=rand, iir_filter=[4, -4, 0.8])


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

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

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

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

# Indicate the true locations of the source activity on the plot.
brain.add_foci(source_vert1, coords_as_verts=True, hemi='lh')
brain.add_foci(source_vert2, coords_as_verts=True, hemi='rh')

# Rotate the view and add a title.
mlab.view(0, 0, 550, [0, 0, 0])
mlab.title('MNE-dSPM inverse (RMS)', height=0.9)


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

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

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

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

# Filenames for various files we'll be using
meg_path = op.join(data_path, 'MEG', 'sample')
raw_fname = op.join(meg_path, 'sample_audvis_raw.fif')
trans_fname = op.join(meg_path, 'sample_audvis_raw-trans.fif')
src_fname = op.join(mri_path, 'bem/sample-oct-6-src.fif')
bem_fname = op.join(mri_path, 'bem/sample-5120-5120-5120-bem-sol.fif')
fwd_fname = op.join(meg_path, 'sample_audvis-meg-eeg-oct-6-fwd.fif')
cov_fname = op.join(meg_path, 'sample_audvis-cov.fif')

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


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

t0 = raw.first_samp  # First sample in the data
t1 = t0 + n_times - 1  # Sample just before the second trial
epochs = mne.Epochs(
    raw,
    events=np.array([[t0, 0, 1], [t1, 0, 2]]),
    event_id=dict(signal=1, noise=2),
    tmin=0, tmax=10,
    preload=True,
)

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


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

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

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

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

filters_approach2 = make_dics(
    info, fwd, csd_signal, reg=0.1, pick_ori='max-power', normalize_fwd=False,
    inversion='matrix', weight_norm='unit-noise-gain')
print(filters_approach2)

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

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

# Plot the DICS power maps for both approaches.
for approach, power in enumerate([power_approach1, power_approach2], 1):
    brain = power.plot('sample', subjects_dir=subjects_dir, hemi='both',
                       figure=approach + 1, size=600)

    # Indicate the true locations of the source activity on the plot.
    brain.add_foci(source_vert1, coords_as_verts=True, hemi='lh')
    brain.add_foci(source_vert2, coords_as_verts=True, hemi='rh')

    # Rotate the view and add a title.
    mlab.view(0, 0, 550, [0, 0, 0])
    mlab.title('DICS power map, approach %d' % approach, height=0.9)


I am working on the file "0.17/_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.17/_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.17/_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.17/_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.17/_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.17/_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.17/_downloads/62cc7f00e993cd712f75bc4ad788e028/plot_artifacts_correction_maxwell_filtering.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
ctc_fname = data_path + '/SSS/ct_sparse_mgh.fif'
fine_cal_fname = data_path + '/SSS/sss_cal_mgh.dat'


I am working on the file "0.17/_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.17/_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.17/_downloads/64973b551d79441db82e99316267b5b7/plot_whitened.ipynb".
The first task is:
Epochs with whitening
Can you write Python code for it?


I am working on the file "0.17/_downloads/64973b551d79441db82e99316267b5b7/plot_whitened.ipynb".
The first task is:
Evoked data with whitening
Can you write Python code for it?

evoked = epochs.average()
evoked.plot(time_unit='s')
evoked.plot(noise_cov=noise_cov, time_unit='s')


I am working on the file "0.17/_downloads/64973b551d79441db82e99316267b5b7/plot_whitened.ipynb".
The first task is:
Plotting whitened data
This tutorial demonstrates how to plot whitened evoked data.
Data are whitened for many processes, including dipole fitting, source
localization and some decoding algorithms. Viewing whitened data thus gives
a different perspective on the data that these algorithms operate on.
Let's start by loading some data and computing a signal (spatial) covariance
that we'll consider to be noise.
Can you write Python code for it?

import mne
from mne.datasets import sample


I am working on the file "0.17/_downloads/64973b551d79441db82e99316267b5b7/plot_whitened.ipynb".
The first task is:
Topographic plot with whitening
Can you write Python code for it?

evoked.comment = 'All trials'
evoked.plot_topo(title='Evoked data')
evoked.plot_topo(noise_cov=noise_cov, title='Whitened evoked data')


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

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

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

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

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

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

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


I am working on the file "0.17/_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.17/_downloads/70978e0c1030bf99d8cb79959d26efdd/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.17/_downloads/70978e0c1030bf99d8cb79959d26efdd/plot_ica_from_raw.ipynb".
The first task is:
3) Assess component selection and unmixing quality.
Can you write Python code for it?

# estimate average artifact
ecg_evoked = ecg_epochs.average()
ica.plot_sources(ecg_evoked, exclude=ecg_inds)  # plot ECG sources + selection
ica.plot_overlay(ecg_evoked, exclude=ecg_inds)  # plot ECG cleaning

eog_evoked = create_eog_epochs(raw, tmin=-.5, tmax=.5, picks=picks).average()
ica.plot_sources(eog_evoked, exclude=eog_inds)  # plot EOG sources + selection
ica.plot_overlay(eog_evoked, exclude=eog_inds)  # plot EOG cleaning

# check the amplitudes do not change
ica.plot_overlay(raw)  # EOG artifacts remain

# To save an ICA solution you can say:
# ica.save('my_ica.fif')

# You can later load the solution by saying:
# from mne.preprocessing import read_ica
# read_ica('my_ica.fif')

# Apply the solution to Raw, Epochs or Evoked like this:
# ica.apply(epochs)


I am working on the file "0.17/_downloads/70978e0c1030bf99d8cb79959d26efdd/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.17/_downloads/73d54262ed918b5836ccb242d27450bb/plot_read_noise_covariance_matrix.ipynb".
The first task is:
=========================================
Reading/Writing a noise covariance matrix
=========================================
Plot a noise covariance matrix.
Can you write Python code for it?

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

from os import path as op
import mne
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()
fname_cov = op.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif')
fname_evo = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')

cov = mne.read_cov(fname_cov)
print(cov)
evoked = mne.read_evokeds(fname_evo)[0]


I am working on the file "0.17/_downloads/761d2ef56f566126781628d5cf3dcfb3/plot_artifacts_correction_ssp.ipynb".
The first task is:
Apply SSP projections
MNE is handling projections at the level of the info,
so to register them populate the list that you find in the 'proj' field
Can you write Python code for it?

raw.info['projs'] += eog_projs + ecg_projs


I am working on the file "0.17/_downloads/761d2ef56f566126781628d5cf3dcfb3/plot_artifacts_correction_ssp.ipynb".
The first task is:
Artifact Correction with SSP
This tutorial explains how to estimate Signal Subspace Projectors (SSP)
for correction of ECG and EOG artifacts.
See sphx_glr_auto_examples_io_plot_read_proj.py for how to read
and visualize already present SSP projection vectors.
Can you write Python code for it?

import numpy as np

import mne
from mne.datasets import sample
from mne.preprocessing import compute_proj_ecg, compute_proj_eog

# 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)


I am working on the file "0.17/_downloads/761d2ef56f566126781628d5cf3dcfb3/plot_artifacts_correction_ssp.ipynb".
The first task is:
Looks cool right? It is however often not clear how many components you
should take and unfortunately this can have bad consequences as can be seen
interactively using the delayed SSP mode:
Can you write Python code for it?

evoked = mne.Epochs(raw, events, event_id, tmin=-0.2, tmax=0.5,
                    proj='delayed', baseline=(None, 0),
                    reject=reject).average()

# set time instants in seconds (from 50 to 150ms in a step of 10ms)
times = np.arange(0.05, 0.15, 0.01)

fig = evoked.plot_topomap(times, proj='interactive', time_unit='s')


I am working on the file "0.17/_downloads/761d2ef56f566126781628d5cf3dcfb3/plot_artifacts_correction_ssp.ipynb".
The first task is:
Now let's do EOG. Here we compute an EEG projector, and need to pass
the measurement info so the topomap coordinates can be created.
Can you write Python code for it?

projs, events = compute_proj_eog(raw, n_grad=1, n_mag=1, n_eeg=1, average=True)
print(projs)

eog_projs = projs[-3:]
mne.viz.plot_projs_topomap(eog_projs, info=raw.info)


I am working on the file "0.17/_downloads/761d2ef56f566126781628d5cf3dcfb3/plot_artifacts_correction_ssp.ipynb".
The first task is:
Yes this was it. Now MNE will apply the projs on demand at any later stage,
so watch out for proj parmeters in functions or to it explicitly
with the .apply_proj method
Demonstrate SSP cleaning on some evoked data
Can you write Python code for it?

events = mne.find_events(raw, stim_channel='STI 014')
reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)
# this can be highly data dependent
event_id = {'auditory/left': 1}

epochs_no_proj = mne.Epochs(raw, events, event_id, tmin=-0.2, tmax=0.5,
                            proj=False, baseline=(None, 0), reject=reject)
epochs_no_proj.average().plot(spatial_colors=True, time_unit='s')

epochs_proj = mne.Epochs(raw, events, event_id, tmin=-0.2, tmax=0.5, proj=True,
                         baseline=(None, 0), reject=reject)
epochs_proj.average().plot(spatial_colors=True, time_unit='s')


I am working on the file "0.17/_downloads/76291d3769ed01aa3e696d309cd4e2fd/plot_creating_data_structures.ipynb".
The first task is:

Note

When assigning new values to the fields of an
          :class:`mne.Info` object, it is important that the
          fields are consistent:

          - The length of the channel information field `chs` must be
            `nchan`.
          - The length of the `ch_names` field must be `nchan`.
          - The `ch_names` field should be consistent with the `name` field
            of the channel information contained in `chs`.

Creating :class:Raw <mne.io.Raw> objects
To create a :class:mne.io.Raw object from scratch, you can use the
:class:mne.io.RawArray class, which implements raw data that is backed by a
numpy array. The correct units for the data are:

V: eeg, eog, seeg, emg, ecg, bio, ecog
T: mag
T/m: grad
M: hbo, hbr
Am: dipole
AU: misc

The :class:mne.io.RawArray constructor simply takes the data matrix and
:class:mne.Info object:
Can you write Python code for it?

# Generate some random data
data = np.random.randn(5, 1000)

# Initialize an info structure
info = mne.create_info(
    ch_names=['MEG1', 'MEG2', 'EEG1', 'EEG2', 'EOG'],
    ch_types=['grad', 'grad', 'eeg', 'eeg', 'eog'],
    sfreq=100
)

custom_raw = mne.io.RawArray(data, info)
print(custom_raw)


I am working on the file "0.17/_downloads/76291d3769ed01aa3e696d309cd4e2fd/plot_creating_data_structures.ipynb".
The first task is:
Creating :class:Evoked <mne.Evoked> Objects
If you already have data that is collapsed across trials, you may also
directly create an evoked array.  Its constructor accepts an array of
shape(n_chans, n_times) in addition to some bookkeeping parameters.
The proper units of measure for the data are listed above.
Can you write Python code for it?

# The averaged data
data_evoked = data.mean(0)

# The number of epochs that were averaged
nave = data.shape[0]

# A comment to describe to evoked (usually the condition name)
comment = "Smiley faces"

# Create the Evoked object
evoked_array = mne.EvokedArray(data_evoked, info, tmin,
                               comment=comment, nave=nave)
print(evoked_array)
_ = evoked_array.plot(time_unit='s')


I am working on the file "0.17/_downloads/76291d3769ed01aa3e696d309cd4e2fd/plot_creating_data_structures.ipynb".
The first task is:
Creating :class:Info <mne.Info> objects

Note

for full documentation on the `Info` object, see
          `tut_info_objects`. See also
          `sphx_glr_auto_examples_io_plot_objects_from_arrays.py`.

Normally, :class:mne.Info objects are created by the various
data import functions <ch_convert>.
However, if you wish to create one from scratch, you can use the
:func:mne.create_info function to initialize the minimally required
fields. Further fields can be assigned later as one would with a regular
dictionary.
The following creates the absolute minimum info structure:
Can you write Python code for it?

# Create some dummy metadata
n_channels = 32
sampling_rate = 200
info = mne.create_info(n_channels, sampling_rate)
print(info)


I am working on the file "0.17/_downloads/76291d3769ed01aa3e696d309cd4e2fd/plot_creating_data_structures.ipynb".
The first task is:
Creating MNE's data structures from scratch
MNE provides mechanisms for creating various core objects directly from
NumPy arrays.
Can you write Python code for it?


I am working on the file "0.17/_downloads/76291d3769ed01aa3e696d309cd4e2fd/plot_creating_data_structures.ipynb".
The first task is:
More information about the event codes: subject was either smiling or
frowning
Can you write Python code for it?


I am working on the file "0.17/_downloads/76291d3769ed01aa3e696d309cd4e2fd/plot_creating_data_structures.ipynb".
The first task is:
Now we can create the :class:mne.EpochsArray object
Can you write Python code for it?

custom_epochs = mne.EpochsArray(data, info, events, tmin, event_id)

print(custom_epochs)

# We can treat the epochs object as we would any other
_ = custom_epochs['smiling'].average().plot(time_unit='s')


I am working on the file "0.17/_downloads/78709b76a2a2e07e4ff056048455fb17/plot_objects_from_arrays.ipynb".
The first task is:
Create a dummy :class:mne.io.RawArray object
Can you write Python code for it?

raw = mne.io.RawArray(data, info)

# Scaling of the figure.
# For actual EEG/MEG data different scaling factors should be used.
scalings = {'mag': 2, 'grad': 2}

raw.plot(n_channels=4, scalings=scalings, title='Data from arrays',
         show=True, block=True)

# It is also possible to auto-compute scalings
scalings = 'auto'  # Could also pass a dictionary with some value == 'auto'
raw.plot(n_channels=4, scalings=scalings, title='Auto-scaled Data from arrays',
         show=True, block=True)


I am working on the file "0.17/_downloads/78709b76a2a2e07e4ff056048455fb17/plot_objects_from_arrays.ipynb".
The first task is:
Create an :class:info <mne.Info> object.
Can you write Python code for it?

# It is also possible to use info from another raw object.
info = mne.create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)


I am working on the file "0.17/_downloads/78709b76a2a2e07e4ff056048455fb17/plot_objects_from_arrays.ipynb".
The first task is:
Create epochs by windowing the raw data.
Can you write Python code for it?

# The events are spaced evenly every 1 second.
duration = 1.

# create a fixed size events array
# start=0 and stop=None by default
events = mne.make_fixed_length_events(raw, event_id, duration=duration)
print(events)

# for fixed size events no start time before and after event
tmin = 0.
tmax = 0.99  # inclusive tmax, 1 second epochs

# create :class:`Epochs <mne.Epochs>` object
epochs = mne.Epochs(raw, events=events, event_id=event_id, tmin=tmin,
                    tmax=tmax, baseline=None, verbose=True)
epochs.plot(scalings='auto', block=True)


I am working on the file "0.17/_downloads/78709b76a2a2e07e4ff056048455fb17/plot_objects_from_arrays.ipynb".
The first task is:
Creating MNE objects from data arrays
In this simple example, the creation of MNE objects from
numpy arrays is demonstrated. In the last example case, a
NEO file format is used as a source for the data.
Can you write Python code for it?

# Author: Jaakko Leppakangas <jaeilepp@student.jyu.fi>
#
# License: BSD (3-clause)

import numpy as np
import neo

import mne

print(__doc__)


I am working on the file "0.17/_downloads/78709b76a2a2e07e4ff056048455fb17/plot_objects_from_arrays.ipynb".
The first task is:
EvokedArray
Can you write Python code for it?

nave = len(epochs_data)  # Number of averaged epochs
evoked_data = np.mean(epochs_data, axis=0)

evokeds = mne.EvokedArray(evoked_data, info=info, tmin=-0.2,
                          comment='Arbitrary', nave=nave)
evokeds.plot(picks=picks, show=True, units={'mag': '-'},
             titles={'mag': 'sin and cos averaged'}, time_unit='s')


I am working on the file "0.17/_downloads/793e913bab4b20ad5f4863ca669c17f8/plot_tf_lcmv.ipynb".
The first task is:
Read raw data, preload to allow filtering
Can you write Python code for it?

raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.info['bads'] = ['MEG 2443']  # 1 bad MEG channel

# Pick a selection of magnetometer channels. A subset of all channels was used
# to speed up the example. For a solution based on all MEG channels use
# meg=True, selection=None and add grad=4000e-13 to the reject dictionary.
# We could do this with a "picks" argument to Epochs and the LCMV functions,
# but here we use raw.pick_types() to save memory.
left_temporal_channels = mne.read_selection('Left-temporal')
raw.pick_types(meg='mag', eeg=False, eog=False, stim=False, exclude='bads',
               selection=left_temporal_channels)
reject = dict(mag=4e-12)
# Re-normalize our empty-room projectors, which should be fine after
# subselection
raw.info.normalize_proj()

# Setting time limits for reading epochs. Note that tmin and tmax are set so
# that time-frequency beamforming will be performed for a wider range of time
# points than will later be displayed on the final spectrogram. This ensures
# that all time bins displayed represent an average of an equal number of time
# windows.
tmin, tmax = -0.5, 0.75  # s
tmin_plot, tmax_plot = -0.3, 0.5  # s

# Read epochs. Note that preload is set to False to enable tf_lcmv to read the
# underlying raw object.
# Filtering is then performed on raw data in tf_lcmv and the epochs
# parameters passed here are used to create epochs from filtered data. However,
# reading epochs without preloading means that bad epoch rejection is delayed
# until later. To perform bad epoch rejection based on the reject parameter
# passed here, run epochs.drop_bad(). This is done automatically in
# tf_lcmv to reject bad epochs based on unfiltered data.
event_id = 1
events = mne.read_events(event_fname)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    baseline=None, preload=False, reject=reject)

# Read empty room noise, preload to allow filtering, and pick subselection
raw_noise = mne.io.read_raw_fif(noise_fname, preload=True)
raw_noise.info['bads'] =...


I am working on the file "0.17/_downloads/793e913bab4b20ad5f4863ca669c17f8/plot_tf_lcmv.ipynb".
The first task is:
Time-frequency beamforming based on LCMV
Can you write Python code for it?

# Setting frequency bins as in Dalal et al. 2008 (high gamma was subdivided)
freq_bins = [(4, 12), (12, 30), (30, 55), (65, 299)]  # Hz
win_lengths = [0.3, 0.2, 0.15, 0.1]  # s

# Setting the time step
tstep = 0.05

# Setting the whitened data covariance regularization parameter
data_reg = 0.001

# Subtract evoked response prior to computation?
subtract_evoked = False

# Calculating covariance from empty room noise. To use baseline data as noise
# substitute raw for raw_noise, epochs.events for epochs_noise.events, tmin for
# desired baseline length, and 0 for tmax_plot.
# Note, if using baseline data, the averaged evoked response in the baseline
# period should be flat.
noise_covs = []
for (l_freq, h_freq) in freq_bins:
    raw_band = raw_noise.copy()
    raw_band.filter(l_freq, h_freq, n_jobs=1, fir_design='firwin')
    epochs_band = mne.Epochs(raw_band, epochs_noise.events, event_id,
                             tmin=tmin_plot, tmax=tmax_plot, baseline=None,
                             proj=True)

    noise_cov = compute_covariance(epochs_band, method='shrunk', rank=None)
    noise_covs.append(noise_cov)
    del raw_band  # to save memory

# Computing LCMV solutions for time-frequency windows in a label in source
# space for faster computation, use label=None for full solution
stcs = tf_lcmv(epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths,
               freq_bins=freq_bins, subtract_evoked=subtract_evoked,
               reg=data_reg, label=label, rank=None)

# Plotting source spectrogram for source with maximum activity.
# Note that tmin and tmax are set to display a time range that is smaller than
# the one for which beamforming estimates were calculated. This ensures that
# all time bins shown are a result of smoothing across an identical number of
# time windows.
plot_source_spectrogram(stcs, freq_bins, tmin=tmin_plot, tmax=tmax_plot,
                        source_index=None, colorbar=True)


I am working on the file "0.17/_downloads/81258b1255ee7242b3b6c9f251dcfbd8/plot_xdawn_denoising.ipynb".
The first task is:
Set parameters and read data
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'
tmin, tmax = -0.1, 0.3
event_id = dict(vis_r=4)

# Setup for reading the raw data
raw = io.read_raw_fif(raw_fname, preload=True)
raw.filter(1, 20, fir_design='firwin')  # replace baselining with high-pass
events = read_events(event_fname)

raw.info['bads'] = ['MEG 2443']  # set bad channels
picks = pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False,
                   exclude='bads')
# Epoching
epochs = Epochs(raw, events, event_id, tmin, tmax, proj=False,
                picks=picks, baseline=None, preload=True,
                verbose=False)

# Plot image epoch before xdawn
plot_epochs_image(epochs['vis_r'], picks=[230], vmin=-500, vmax=500)

# Estimates signal covariance
signal_cov = compute_raw_covariance(raw, picks=picks)

# Xdawn instance
xd = Xdawn(n_components=2, signal_cov=signal_cov)

# Fit xdawn
xd.fit(epochs)

# Denoise epochs
epochs_denoised = xd.apply(epochs)

# Plot image epoch after Xdawn
plot_epochs_image(epochs_denoised['vis_r'], picks=[230], vmin=-500, vmax=500)


I am working on the file "0.17/_downloads/81258b1255ee7242b3b6c9f251dcfbd8/plot_xdawn_denoising.ipynb".
The first task is:
XDAWN Denoising
XDAWN filters are trained from epochs, signal is projected in the sources
space and then projected back in the sensor space using only the first two
XDAWN components. The process is similar to an ICA, but is
supervised in order to maximize the signal to signal + noise ratio of the
evoked response.

Warning

As this denoising method exploits the known events to
             maximize SNR of the contrast between conditions it can lead
             to overfitting. To avoid a statistical analysis problem you
             should split epochs used in fit with the ones used in
             apply method.

References
[1] Rivet, B., Souloumiac, A., Attina, V., & Gibert, G. (2009). xDAWN
algorithm to enhance evoked potentials: application to brain-computer
interface. Biomedical Engineering, IEEE Transactions on, 56(8), 2035-2043.
[2] Rivet, B., Cecotti, H., Souloumiac, A., Maby, E., & Mattout, J. (2011,
August). Theoretical analysis of xDAWN algorithm: application to an
efficient sensor selection in a P300 BCI. In Signal Processing Conference,
2011 19th European (pp. 1382-1386). IEEE.
Can you write Python code for it?

# Authors: Alexandre Barachant <alexandre.barachant@gmail.com>
#
# License: BSD (3-clause)

from mne import (io, compute_raw_covariance, read_events, pick_types, Epochs)
from mne.datasets import sample
from mne.preprocessing import Xdawn
from mne.viz import plot_epochs_image

print(__doc__)

data_path = sample.data_path()


I am working on the file "0.17/_downloads/82dd66e6bdf7150b8691eaa46b63bcf9/plot_read_events.ipynb".
The first task is:
Reading events
Below we'll read in an events file. We suggest that this file end in
-eve.fif. Note that we can read in the entire events file, or only
events corresponding to particular event types with the include and
exclude parameters.
Can you write Python code for it?

events_1 = mne.read_events(fname, include=1)
events_1_2 = mne.read_events(fname, include=[1, 2])
events_not_4_32 = mne.read_events(fname, exclude=[4, 32])


I am working on the file "0.17/_downloads/82dd66e6bdf7150b8691eaa46b63bcf9/plot_read_events.ipynb".
The first task is:
Writing events
Finally, we can write events to disk. Remember to use the naming convention
-eve.fif for your file.
Can you write Python code for it?


I am working on the file "0.17/_downloads/87d1dcf691504bdd82c2df2447562f10/plot_object_raw.ipynb".
The first task is:

Note

This size can also be obtained by examining `raw._data.shape`.
          However this is a private attribute as its name starts
          with an `_`. This suggests that you should **not** access this
          variable directly but rely on indexing syntax detailed just below.

Information about the channels contained in the :class:Raw <mne.io.Raw>
object is contained in the :class:Info <mne.Info> attribute.
This is essentially a dictionary with a number of relevant fields (see
tut_info_objects).
Indexing data
To access the data stored within :class:Raw <mne.io.Raw> objects,
it is possible to index the :class:Raw <mne.io.Raw> object.
Indexing a :class:Raw <mne.io.Raw> object will return two arrays: an array
of times, as well as the data representing those timepoints. This works
even if the data is not preloaded, in which case the data will be read from
disk when indexing. The syntax is as follows:
Can you write Python code for it?

# Extract data from the first 5 channels, from 1 s to 3 s.
sfreq = raw.info['sfreq']
data, times = raw[:5, int(sfreq * 1):int(sfreq * 3)]
_ = plt.plot(times, data.T)
_ = plt.title('Sample channels')


I am working on the file "0.17/_downloads/87d1dcf691504bdd82c2df2447562f10/plot_object_raw.ipynb".
The first task is:
And drop channels by name
Can you write Python code for it?

nchan = raw.info['nchan']
raw = raw.drop_channels(['MEG 0241', 'EEG 001'])
print('Number of channels reduced from', nchan, 'to', raw.info['nchan'])


I am working on the file "0.17/_downloads/87d1dcf691504bdd82c2df2447562f10/plot_object_raw.ipynb".
The first task is:
Concatenating :class:Raw <mne.io.Raw> objects
:class:Raw <mne.io.Raw> objects can be concatenated in time by using the
:func:append <mne.io.Raw.append> function. For this to work, they must
have the same number of channels and their :class:Info
<mne.Info> structures should be compatible.
Can you write Python code for it?

# Create multiple :class:`Raw <mne.io.RawFIF>` objects
raw1 = raw.copy().crop(0, 10)
raw2 = raw.copy().crop(10, 20)
raw3 = raw.copy().crop(20, 40)

# Concatenate in time (also works without preloading)
raw1.append([raw2, raw3])
print('Time extends from', raw1.times.min(), 's to', raw1.times.max(), 's')


I am working on the file "0.17/_downloads/87d1dcf691504bdd82c2df2447562f10/plot_object_raw.ipynb".
The first task is:
Notice the different scalings of these types
Can you write Python code for it?

f, (a1, a2) = plt.subplots(2, 1)
eeg, times = eeg_only[0, :int(sfreq * 2)]
meg, times = meg_only[0, :int(sfreq * 2)]
a1.plot(times, meg[0])
a2.plot(times, eeg[0])
del eeg, meg, meg_only, grad_only, eeg_only, data, specific_chans


I am working on the file "0.17/_downloads/87d1dcf691504bdd82c2df2447562f10/plot_object_raw.ipynb".
The first task is:
Selecting subsets of channels and samples
It is possible to use more intelligent indexing to extract data, using
channel names, types or time ranges.
Can you write Python code for it?

# Pull all MEG gradiometer channels:
# Make sure to use .copy() or it will overwrite the data
meg_only = raw.copy().pick_types(meg=True)
eeg_only = raw.copy().pick_types(meg=False, eeg=True)

# The MEG flag in particular lets you specify a string for more specificity
grad_only = raw.copy().pick_types(meg='grad')

# Or you can use custom channel names
pick_chans = ['MEG 0112', 'MEG 0111', 'MEG 0122', 'MEG 0123']
specific_chans = raw.copy().pick_channels(pick_chans)
print(meg_only)
print(eeg_only)
print(grad_only)
print(specific_chans)


I am working on the file "0.17/_downloads/87d1dcf691504bdd82c2df2447562f10/plot_object_raw.ipynb".
The first task is:
The :class:Raw <mne.io.Raw> data structure: continuous data
Continuous data is stored in objects of type :class:Raw <mne.io.Raw>.
The core data structure is simply a 2D numpy array (channels × samples)
(in memory or loaded on demand) combined with an
:class:Info <mne.Info> object (.info attribute)
(see tut_info_objects).
The most common way to load continuous data is from a .fif file. For more
information on loading data from other formats <ch_convert>, or
creating it from scratch <tut_creating_data_structures>.
Can you write Python code for it?

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


I am working on the file "0.17/_downloads/87d1dcf691504bdd82c2df2447562f10/plot_object_raw.ipynb".
The first task is:
You can restrict the data to a specific time range
Can you write Python code for it?

raw = raw.crop(0, 50)  # in seconds
print('New time range from', raw.times.min(), 's to', raw.times.max(), 's')


I am working on the file "0.17/_downloads/89cc396ae40816c48694b5fe5505a690/plot_tf_dics.ipynb".
The first task is:
Read raw data
Can you write Python code for it?

raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.info['bads'] = ['MEG 2443']  # 1 bad MEG channel

# Pick a selection of magnetometer channels. A subset of all channels was used
# to speed up the example. For a solution based on all MEG channels use
# meg=True, selection=None and add mag=4e-12 to the reject dictionary.
left_temporal_channels = mne.read_selection('Left-temporal')
picks = mne.pick_types(raw.info, meg='mag', eeg=False, eog=False,
                       stim=False, exclude='bads',
                       selection=left_temporal_channels)
raw.pick_channels([raw.ch_names[pick] for pick in picks])
reject = dict(mag=4e-12)
# Re-normalize our empty-room projectors, which should be fine after
# subselection
raw.info.normalize_proj()

# Setting time windows. Note that tmin and tmax are set so that time-frequency
# beamforming will be performed for a wider range of time points than will
# later be displayed on the final spectrogram. This ensures that all time bins
# displayed represent an average of an equal number of time windows.
tmin, tmax, tstep = -0.5, 0.75, 0.05  # s
tmin_plot, tmax_plot = -0.3, 0.5  # s

# Read epochs
event_id = 1
events = mne.read_events(event_fname)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                    baseline=None, preload=True, proj=True, reject=reject)

# Read empty room noise raw data
raw_noise = mne.io.read_raw_fif(noise_fname, preload=True)
raw_noise.info['bads'] = ['MEG 2443']  # 1 bad MEG channel
raw_noise.pick_channels([raw_noise.ch_names[pick] for pick in picks])
raw_noise.info.normalize_proj()

# Create noise epochs and make sure the number of noise epochs corresponds to
# the number of data epochs
events_noise = make_fixed_length_events(raw_noise, event_id)
epochs_noise = mne.Epochs(raw_noise, events_noise, event_id, tmin_plot,
                          tmax_plot, baseline=None, preload=True, proj=True,
                          reject=reject)
epochs_noise.info.normalize_proj()
epochs_noise.apply_proj()
# then make sure the number of epochs...


I am working on the file "0.17/_downloads/89cc396ae40816c48694b5fe5505a690/plot_tf_dics.ipynb".
The first task is:
Time-frequency beamforming based on DICS
Can you write Python code for it?

# Setting frequency bins as in Dalal et al. 2008
freq_bins = [(4, 12), (12, 30), (30, 55), (65, 300)]  # Hz
win_lengths = [0.3, 0.2, 0.15, 0.1]  # s
# Then set FFTs length for each frequency range.
# Should be a power of 2 to be faster.
n_ffts = [256, 128, 128, 128]

# Subtract evoked response prior to computation?
subtract_evoked = False

# Calculating noise cross-spectral density from empty room noise for each
# frequency bin and the corresponding time window length. To calculate noise
# from the baseline period in the data, change epochs_noise to epochs
noise_csds = []
for freq_bin, win_length, n_fft in zip(freq_bins, win_lengths, n_ffts):
    noise_csd = csd_fourier(epochs_noise, fmin=freq_bin[0], fmax=freq_bin[1],
                            tmin=-win_length, tmax=0, n_fft=n_fft)
    noise_csds.append(noise_csd.sum())

# Computing DICS solutions for time-frequency windows in a label in source
# space for faster computation, use label=None for full solution
stcs = tf_dics(epochs, forward, noise_csds, tmin, tmax, tstep, win_lengths,
               freq_bins=freq_bins, subtract_evoked=subtract_evoked,
               n_ffts=n_ffts, reg=0.05, label=label, inversion='matrix')

# Plotting source spectrogram for source with maximum activity
# Note that tmin and tmax are set to display a time range that is smaller than
# the one for which beamforming estimates were calculated. This ensures that
# all time bins shown are a result of smoothing across an identical number of
# time windows.
plot_source_spectrogram(stcs, freq_bins, tmin=tmin_plot, tmax=tmax_plot,
                        source_index=None, colorbar=True)


I am working on the file "0.17/_downloads/89cc396ae40816c48694b5fe5505a690/plot_tf_dics.ipynb".
The first task is:
Time-frequency beamforming using DICS
Compute DICS source power [1]_ in a grid of time-frequency windows.
References
.. [1] Dalal et al. Five-dimensional neuroimaging: Localization of the
       time-frequency dynamics of cortical activity.
       NeuroImage (2008) vol. 40 (4) pp. 1686-1700
Can you write Python code for it?

# Author: Roman Goj <roman.goj@gmail.com>
#
# License: BSD (3-clause)

import mne
from mne.event import make_fixed_length_events
from mne.datasets import sample
from mne.time_frequency import csd_fourier
from mne.beamformer import tf_dics
from mne.viz import plot_source_spectrogram

print(__doc__)

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
noise_fname = data_path + '/MEG/sample/ernoise_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_raw-eve.fif'
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
subjects_dir = data_path + '/subjects'
label_name = 'Aud-lh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name


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

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

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


I am working on the file "0.17/_downloads/8a9d1481784df3b1e190b5615ba8fde7/plot_compute_source_psd_epochs.ipynb".
The first task is:
Visualize the 10 Hz PSD:
Can you write Python code for it?

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


I am working on the file "0.17/_downloads/8a9d1481784df3b1e190b5615ba8fde7/plot_compute_source_psd_epochs.ipynb".
The first task is:
Visualize the entire spectrum:
Can you write Python code for it?

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


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

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

plt.show()


I am working on the file "0.17/_downloads/8e91c4d84fe688d78859cf6274554a8b/plot_compute_csd.ipynb".
The first task is:
By default, CSD matrices are computed using all MEG/EEG channels. When
interpreting a CSD matrix with mixed sensor types, be aware that the
measurement units, and thus the scalings, differ across sensors. In this
example, for speed and clarity, we select a single channel type:
gradiometers.
Can you write Python code for it?

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

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


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

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


I am working on the file "0.17/_downloads/8e91c4d84fe688d78859cf6274554a8b/plot_compute_csd.ipynb".
The first task is:
Loading the sample dataset.
Can you write Python code for it?

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


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

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

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

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


I am working on the file "0.17/_downloads/908e04a8b6894ebc76b94910bf9a28cf/plot_forward.ipynb".
The first task is:
Compute Source Space
The source space defines the position of the candidate source locations.
The following code compute such a cortical source space with
an OCT-6 resolution.
See setting_up_source_space for details on source space definition
and spacing parameter.
Can you write Python code for it?

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


I am working on the file "0.17/_downloads/908e04a8b6894ebc76b94910bf9a28cf/plot_forward.ipynb".
The first task is:
Compute forward solution
We can now compute the forward solution.
To reduce computation we'll just compute a single layer BEM (just inner
skull) that can then be used for MEG (not EEG).
We specify if we want a one-layer or a three-layer BEM using the
conductivity parameter.
The BEM solution requires a BEM model which describes the geometry
of the head the conductivities of the different tissues.
Can you write Python code for it?

conductivity = (0.3,)  # for single layer
# conductivity = (0.3, 0.006, 0.3)  # for three layers
model = mne.make_bem_model(subject='sample', ico=4,
                           conductivity=conductivity,
                           subjects_dir=subjects_dir)
bem = mne.make_bem_solution(model)


I am working on the file "0.17/_downloads/908e04a8b6894ebc76b94910bf9a28cf/plot_forward.ipynb".
The first task is:
Computing the forward operator
To compute a forward operator we need:

a -trans.fif file that contains the coregistration info.
a source space
the BEM surfaces

Compute and visualize BEM surfaces
The BEM surfaces are the triangulations of the interfaces between different
tissues needed for forward computation. These surfaces are for example
the inner skull surface, the outer skull surface and the outer skill
surface.
Computing the BEM surfaces requires FreeSurfer and makes use of either of
the two following command line tools:

gen_mne_watershed_bem
gen_mne_flash_bem

Here we'll assume it's already computed. It takes a few minutes per subject.
For EEG we use 3 layers (inner skull, outer skull, and skin) while for
MEG 1 layer (inner skull) is enough.
Let's look at these surfaces. The function :func:mne.viz.plot_bem
assumes that you have the the bem folder of your subject FreeSurfer
reconstruction the necessary files.
Can you write Python code for it?

mne.viz.plot_bem(subject=subject, subjects_dir=subjects_dir,
                 brain_surfaces='white', orientation='coronal')


I am working on the file "0.17/_downloads/908e04a8b6894ebc76b94910bf9a28cf/plot_forward.ipynb".
The first task is:
Head model and forward computation
The aim of this tutorial is to be a getting started for forward
computation.
For more extensive details and presentation of the general
concepts for forward modeling. See ch_forward.
Can you write Python code for it?

import mne
from mne.datasets import sample
data_path = sample.data_path()

# the raw file containing the channel location + types
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
# The paths to Freesurfer reconstructions
subjects_dir = data_path + '/subjects'
subject = 'sample'


I am working on the file "0.17/_downloads/908e04a8b6894ebc76b94910bf9a28cf/plot_forward.ipynb".
The first task is:
Note that the BEM does not involve any use of the trans file. The BEM
only depends on the head geometry and conductivities.
It is therefore independent from the MEG data and the head position.
Let's now compute the forward operator, commonly referred to as the
gain or leadfield matrix.
See :func:mne.make_forward_solution for details on parameters meaning.
Can you write Python code for it?

fwd = mne.make_forward_solution(raw_fname, trans=trans, src=src, bem=bem,
                                meg=True, eeg=False, mindist=5.0, n_jobs=2)
print(fwd)


I am working on the file "0.17/_downloads/908e04a8b6894ebc76b94910bf9a28cf/plot_forward.ipynb".
The first task is:
To extract the numpy array containing the forward operator corresponding to
the source space fwd['src'] with cortical orientation constraint
we can use the following:
Can you write Python code for it?

fwd_fixed = mne.convert_forward_solution(fwd, surf_ori=True, force_fixed=True,
                                         use_cps=True)
leadfield = fwd_fixed['sol']['data']
print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape)


I am working on the file "0.17/_downloads/908e04a8b6894ebc76b94910bf9a28cf/plot_forward.ipynb".
The first task is:
src contains two parts, one for the left hemisphere (4098 locations) and
one for the right hemisphere (4098 locations). Sources can be visualized on
top of the BEM surfaces.
Can you write Python code for it?

mne.viz.plot_bem(subject=subject, subjects_dir=subjects_dir,
                 brain_surfaces='white', src=src, orientation='coronal')


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

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


I am working on the file "0.17/_downloads/912d9040f5b0b6e04a6acecb56608031/plot_visualize_stc.ipynb".
The first task is:
Finally, we can visualize the dipole.
Can you write Python code for it?


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

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


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

initial_time = 0.1
stc.plot(subjects_dir=subjects_dir, initial_time=initial_time)


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

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


I am working on the file "0.17/_downloads/912d9040f5b0b6e04a6acecb56608031/plot_visualize_stc.ipynb".
The first task is:
Then, we read the stc from file
Can you write Python code for it?

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


I am working on the file "0.17/_downloads/912d9040f5b0b6e04a6acecb56608031/plot_visualize_stc.ipynb".
The first task is:
This is a :class:SourceEstimate <mne.SourceEstimate> object
Can you write Python code for it?


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


I am working on the file "0.17/_downloads/912d9040f5b0b6e04a6acecb56608031/plot_visualize_stc.ipynb".
The first task is:
This too comes with a convenient plot method.
Can you write Python code for it?


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

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

inv = read_inverse_operator(fname_inv)
stc = apply_inverse(evoked, inv, lambda2, 'dSPM', pick_ori='vector')
stc.plot(subject='sample', subjects_dir=subjects_dir,
         initial_time=initial_time)


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

evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
evoked.pick_types(meg=True, eeg=False)


I am working on the file "0.17/_downloads/93d330ee6c0ab8305ae11bf7f764aeb8/plot_evoked_arrowmap.ipynb".
The first task is:
Plot gradiometer data as an arrowmap along with the topoplot at the time
of the maximum sensor space activity:
Can you write Python code for it?

plot_arrowmap(evoked_grad.data[:, max_time_idx], info_from=evoked_grad.info,
              info_to=evoked_mag.info)


I am working on the file "0.17/_downloads/93d330ee6c0ab8305ae11bf7f764aeb8/plot_evoked_arrowmap.ipynb".
The first task is:
Plot magnetometer data as an arrowmap along with the topoplot at the time
of the maximum sensor space activity:
Can you write Python code for it?

max_time_idx = np.abs(evoked_mag.data).mean(axis=0).argmax()
plot_arrowmap(evoked_mag.data[:, max_time_idx], evoked_mag.info)

# Since planar gradiometers takes gradients along latitude and longitude,
# they need to be projected to the flatten manifold span by magnetometer
# or radial gradiometers before taking the gradients in the 2D Cartesian
# coordinate system for visualization on the 2D topoplot. You can use the
# ``info_from`` and ``info_to`` parameters to interpolate from
# gradiometer data to magnetometer data.


I am working on the file "0.17/_downloads/93d330ee6c0ab8305ae11bf7f764aeb8/plot_evoked_arrowmap.ipynb".
The first task is:
Plotting topographic arrowmaps of evoked data
Load evoked data and plot arrowmaps along with the topomap for selected time
points. An arrowmap is based upon the Hosaka-Cohen transformation and
represents an estimation of the current flow underneath the MEG sensors.
They are a poor man's MNE.
See [1]_ for details.
References
.. [1] D. Cohen, H. Hosaka
   "Part II magnetic field produced by a current dipole",
   Journal of electrocardiology, Volume 9, Number 4, pp. 409-417, 1976.
   DOI: 10.1016/S0022-0736(76)80041-6
Can you write Python code for it?

# Authors: Sheraz Khan <sheraz@khansheraz.com>
#
# License: BSD (3-clause)

import numpy as np
import mne
from mne.datasets import sample
from mne.datasets.brainstorm import bst_raw
from mne import read_evokeds
from mne.viz import plot_arrowmap

print(__doc__)

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

# load evoked data
condition = 'Left Auditory'
evoked = read_evokeds(fname, condition=condition, baseline=(None, 0))
evoked_mag = evoked.copy().pick_types(meg='mag')
evoked_grad = evoked.copy().pick_types(meg='grad')


I am working on the file "0.17/_downloads/9460321824116e4964fbe6d88d27462e/plot_cluster_stats_evoked.ipynb".
The first task is:
Compute statistic
Can you write Python code for it?

threshold = 6.0
T_obs, clusters, cluster_p_values, H0 = \
    permutation_cluster_test([condition1, condition2], n_permutations=1000,
                             threshold=threshold, tail=1, n_jobs=1)


I am working on the file "0.17/_downloads/9460321824116e4964fbe6d88d27462e/plot_cluster_stats_evoked.ipynb".
The first task is:
Plot
Can you write Python code for it?

times = epochs1.times
plt.close('all')
plt.subplot(211)
plt.title('Channel : ' + channel)
plt.plot(times, condition1.mean(axis=0) - condition2.mean(axis=0),
         label="ERF Contrast (Event 1 - Event 2)")
plt.ylabel("MEG (T / m)")
plt.legend()
plt.subplot(212)
for i_c, c in enumerate(clusters):
    c = c[0]
    if cluster_p_values[i_c] <= 0.05:
        h = plt.axvspan(times[c.start], times[c.stop - 1],
                        color='r', alpha=0.3)
    else:
        plt.axvspan(times[c.start], times[c.stop - 1], color=(0.3, 0.3, 0.3),
                    alpha=0.3)
hf = plt.plot(times, T_obs, 'g')
plt.legend((h, ), ('cluster p-value < 0.05', ))
plt.xlabel("time (ms)")
plt.ylabel("f-values")
plt.show()


I am working on the file "0.17/_downloads/9460321824116e4964fbe6d88d27462e/plot_cluster_stats_evoked.ipynb".
The first task is:
Set parameters
Can you write Python code for it?

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

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

channel = 'MEG 1332'  # include only this channel in analysis
include = [channel]


I am working on the file "0.17/_downloads/956c2e52efc7e768d096c7da98299333/plot_stats_cluster_spatio_temporal_2samp.ipynb".
The first task is:
2 samples permutation test on source data with spatio-temporal clustering
Tests if the source space data are significantly different between
2 groups of subjects (simulated here using one subject's data).
The multiple comparisons problem is addressed with a cluster-level
permutation test across space and time.
Can you write Python code for it?

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

import os.path as op

import numpy as np
from scipy import stats as stats

import mne
from mne import spatial_src_connectivity
from mne.stats import spatio_temporal_cluster_test, summarize_clusters_stc
from mne.datasets import sample

print(__doc__)


I am working on the file "0.17/_downloads/96cf5c207119de22548efa8f14198f9e/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 sphx_glr_auto_tutorials_plot_brainstorm_auditory.py
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.17/_downloads/96cf5c207119de22548efa8f14198f9e/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
picks_meg = mne.pick_types(raw.info, meg=True, eeg=False, eog=True,
                           stim=False, exclude='bads')
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    picks=picks_meg, baseline=baseline, reject=reject,
                    reject_by_annotation=True)


I am working on the file "0.17/_downloads/96cf5c207119de22548efa8f14198f9e/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.17/_downloads/96cf5c207119de22548efa8f14198f9e/plot_artifacts_correction_rejection.ipynb".
The first task is:
It is also possible to draw bad segments interactively using
:meth:raw.plot <mne.io.Raw.plot> (see
sphx_glr_auto_tutorials_plot_visualize_raw.py).
As the data is epoched, all the epochs overlapping with segments whose
description starts with 'bad' are rejected by default. To turn rejection off,
use keyword argument reject_by_annotation=False when constructing
:class:mne.Epochs. When working with neuromag data, the first_samp
offset of raw acquisition is also taken into account the same way as with
event lists. For more see :class:mne.Epochs and :class:mne.Annotations.
Rejecting bad epochs
When working with segmented data (Epochs) MNE offers a quite simple approach
to automatically reject/ignore bad epochs. This is done by defining
thresholds for peak-to-peak amplitude and flat signal detection.
In the following code we build Epochs from Raw object. One of the provided
parameter is named reject. It is a dictionary where every key is a
channel type as a string and the corresponding values are peak-to-peak
rejection parameters (amplitude ranges as floats). Below we define
the peak-to-peak rejection values for gradiometers,
magnetometers and EOG:
Can you write Python code for it?


I am working on the file "0.17/_downloads/96cf5c207119de22548efa8f14198f9e/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.17/_downloads/96cf5c207119de22548efa8f14198f9e/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.17/_downloads/96cf5c207119de22548efa8f14198f9e/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.17/_downloads/96cf5c207119de22548efa8f14198f9e/plot_artifacts_correction_rejection.ipynb".
The first task is:
Why setting a channel bad?: If a channel does not show
a signal at all (flat) it is important to exclude it from the
analysis. If a channel as a noise level significantly higher than the
other channels it should be marked as bad. Presence of bad channels
can have terribe consequences on down stream analysis. For a flat channel
some noise estimate will be unrealistically low and
thus the current estimate calculations will give a strong weight
to the zero signal on the flat channels and will essentially vanish.
Noisy channels can also affect others when signal-space projections
or EEG average electrode reference is employed. Noisy bad channels can
also adversely affect averaging and noise-covariance matrix estimation by
causing unnecessary rejections of epochs.
Recommended ways to identify bad channels are:

Observe the quality of data during data
  acquisition and make notes of observed malfunctioning channels to
  your measurement protocol sheet.

View the on-line averages and check the condition of the channels.

Compute preliminary off-line averages with artifact rejection,
  SSP/ICA, and EEG average electrode reference computation
  off and check the condition of the channels.

View raw data with :func:mne.io.Raw.plot without SSP/ICA
  enabled and identify bad channels.

Note

Setting the bad channels should be done as early as possible in the
    analysis pipeline. That's why it's recommended to set bad channels
    the raw objects/files. If present in the raw data
    files, the bad channel selections will be automatically transferred
    to averaged files, noise-covariance matrices, forward solution
    files, and inverse operator decompositions.

The actual removal happens using :func:pick_types <mne.pick_types> with
exclude='bads' option (see picking_channels).
Instead of removing the bad channels, you can also try to repair them.
This is done by interpolation of the data from other channels.
To illustrate how to use channel interpolation...
Can you write Python code for it?

# Reading data with a bad channel marked as bad:
fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
evoked = mne.read_evokeds(fname, condition='Left Auditory',
                          baseline=(None, 0))

# restrict the evoked to EEG and MEG channels
evoked.pick_types(meg=True, eeg=True, exclude=[])

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

print(evoked.info['bads'])