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

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


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


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


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

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

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

raw = mne.io.read_raw_fif(raw_fname).crop(0, 60).pick('meg').load_data()

reject = dict(mag=5e-12, grad=4000e-13)
raw.filter(1, 30, fir_design='firwin')


I am working on the file "0.24/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
And we can project these label time courses back to their original
locations and see how the plot has been smoothed:
Can you write Python code for it?

stc_back = mne.labels_to_stc(fname_aseg, label_tc, src=src)
stc_back.plot(src, subjects_dir=subjects_dir, mode='glass_brain')


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

fname_cov = op.join(sample_dir, 'sample_audvis-cov.fif')
fname_bem = op.join(subjects_dir, 'sample', 'bem', 'sample-5120-bem-sol.fif')
fname_trans = op.join(sample_dir, 'sample_audvis_raw-trans.fif')


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


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

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


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

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


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

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


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

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


I am working on the file "0.24/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
Then, we can load the precomputed inverse operator from a file.
Can you write Python code for it?

fname_inv = data_path + '/MEG/sample/sample_audvis-meg-vol-7-meg-inv.fif'
inv = read_inverse_operator(fname_inv)
src = inv['src']
mri_head_t = inv['mri_head_t']


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

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


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

import os.path as op

import numpy as np
import matplotlib.pyplot as plt

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

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

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


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

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


I am working on the file "0.24/_downloads/ab20eadd8e6e3c70dc4dd75cfef6ca4c/60_visualize_stc.ipynb".
The first task is:
We can plot several labels with the most activation in their time course
for a more fine-grained view of the anatomical loci of activation.
Can you write Python code for it?

labels = [label_names[idx] for idx in np.argsort(label_tc.max(axis=1))[:7]
          if 'unknown' not in label_names[idx].lower()]  # remove catch-all
brain = mne.viz.Brain('sample', hemi='both', surf='pial', alpha=0.5,
                      cortex='low_contrast', subjects_dir=subjects_dir)
brain.add_volume_labels(aseg='aparc+aseg', labels=labels)
brain.show_view(azimuth=250, elevation=40, distance=400)
brain.enable_depth_peeling()


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

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

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


I am working on the file "0.24/_downloads/ab9aa98c1c3d10ded0b9447abaef0b61/30_ecog.ipynb".
The first task is:
Compute frequency features of the data
Next, we'll compute the signal power in the gamma (30-90 Hz) band,
downsampling the result to 10 Hz (to save time).
Can you write Python code for it?

sfreq = 10
gamma_power_t = evoked.copy().filter(30, 90).apply_hilbert(
    envelope=True).resample(sfreq)
gamma_info = gamma_power_t.info


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

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

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

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

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


I am working on the file "0.24/_downloads/ab9aa98c1c3d10ded0b9447abaef0b61/30_ecog.ipynb".
The first task is:
We can project gamma power from the sensor data to the nearest locations on
the pial surface and visualize that:
As shown in the plot, the epileptiform activity starts in the temporal lobe,
progressing posteriorly. The seizure becomes generalized eventually, after
this example short time section. This dataset is available using
:func:mne.datasets.epilepsy_ecog.data_path for you to examine.
Can you write Python code for it?

xyz_pts = np.array([dig['r'] for dig in evoked.info['dig']])

src = mne.read_source_spaces(
    op.join(subjects_dir, 'fsaverage', 'bem', 'fsaverage-ico-5-src.fif'))
stc = mne.stc_near_sensors(gamma_power_t, trans='fsaverage',
                           subject='fsaverage', src=src,
                           mode='nearest', subjects_dir=subjects_dir,
                           distance=0.02)
vmin, vmid, vmax = np.percentile(gamma_power_t.data, [10, 25, 90])
clim = dict(kind='value', lims=[vmin, vmid, vmax])
brain = stc.plot(surface='pial', hemi='rh', colormap='inferno', colorbar=False,
                 clim=clim, views=['lat', 'med'], subjects_dir=subjects_dir,
                 size=(250, 250), smoothing_steps='nearest',
                 time_viewer=False)
brain.add_sensors(raw.info, trans='fsaverage')

# You can save a movie like the one on our documentation website with:
# brain.save_movie(time_dilation=1, interpolation='linear', framerate=3,
#                  time_viewer=True)


I am working on the file "0.24/_downloads/ab9aa98c1c3d10ded0b9447abaef0b61/30_ecog.ipynb".
The first task is:
Working with ECoG data
MNE supports working with more than just MEG and EEG data. Here we show some
of the functions that can be used to facilitate working with
electrocorticography (ECoG) data.
This example shows how to use:

ECoG data (available here <https://openneuro.org/datasets/ds003029>__) from
  an epilepsy patient during a seizure
channel locations in FreeSurfer's fsaverage MRI space
projection onto a pial surface

For a complementary example that involves sEEG data, channel locations in
MNI space, or projection into a volume, see tut-working-with-seeg.
Can you write Python code for it?

# Authors: Eric Larson <larson.eric.d@gmail.com>
#          Chris Holdgraf <choldgraf@gmail.com>
#          Adam Li <adam2392@gmail.com>
#          Alex Rockhill <aprockhill@mailbox.org>
#          Liberty Hamilton <libertyhamilton@gmail.com>
#
# License: BSD-3-Clause

import os.path as op

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap
from mne_bids import BIDSPath, read_raw_bids

import mne
from mne.viz import plot_alignment, snapshot_brain_montage

print(__doc__)

# paths to mne datasets - sample ECoG and FreeSurfer subject
bids_root = mne.datasets.epilepsy_ecog.data_path()
sample_path = mne.datasets.sample.data_path()
subjects_dir = op.join(sample_path, 'subjects')


I am working on the file "0.24/_downloads/b2637a9801fb152d611a08a816cc5583/sensor_regression.ipynb".
The first task is:
Analysing continuous features with binning and regression in sensor space
Predict single trial activity from a continuous variable.
A single-trial regression is performed in each sensor and timepoint
individually, resulting in an :class:mne.Evoked object which contains the
regression coefficient (beta value) for each combination of sensor and
timepoint. This example shows the regression coefficient; the t and p values
are also calculated automatically.
Here, we repeat a few of the analyses from :footcite:DufauEtAl2015. This
can be easily performed by accessing the metadata object, which contains
word-level information about various psycholinguistically relevant features
of the words for which we have EEG activity.
For the general methodology, see e.g. :footcite:HaukEtAl2006.
References
.. footbibliography::
Can you write Python code for it?

# Authors: Tal Linzen <linzen@nyu.edu>
#          Denis A. Engemann <denis.engemann@gmail.com>
#          Jona Sassenhagen <jona.sassenhagen@gmail.com>
#
# License: BSD-3-Clause

import pandas as pd
import mne
from mne.stats import linear_regression, fdr_correction
from mne.viz import plot_compare_evokeds
from mne.datasets import kiloword

# Load the data
path = kiloword.data_path() + '/kword_metadata-epo.fif'
epochs = mne.read_epochs(path)
print(epochs.metadata.head())


I am working on the file "0.24/_downloads/b2637a9801fb152d611a08a816cc5583/sensor_regression.ipynb".
The first task is:
Because the :func:~mne.stats.linear_regression function also estimates
p values, we can --
after applying FDR correction for multiple comparisons -- also visualise the
statistical significance of the regression of word concreteness.
The :func:mne.viz.plot_evoked_image function takes a mask parameter.
If we supply it with a boolean mask of the positions where we can reject
the null hypothesis, points that are not significant will be shown
transparently, and if desired, in a different colour palette and surrounded
by dark contour lines.
Can you write Python code for it?

reject_H0, fdr_pvals = fdr_correction(res["Concreteness"].p_val.data)
evoked = res["Concreteness"].beta
evoked.plot_image(mask=reject_H0, time_unit='s')


I am working on the file "0.24/_downloads/b2637a9801fb152d611a08a816cc5583/sensor_regression.ipynb".
The first task is:
Psycholinguistically relevant word characteristics are continuous. I.e.,
concreteness or imaginability is a graded property. In the metadata,
we have concreteness ratings on a 5-point scale. We can show the dependence
of the EEG on concreteness by dividing the data into bins and plotting the
mean activity per bin, color coded.
Can you write Python code for it?

name = "Concreteness"
df = epochs.metadata
df[name] = pd.cut(df[name], 11, labels=False) / 10
colors = {str(val): val for val in df[name].unique()}
epochs.metadata = df.assign(Intercept=1)  # Add an intercept for later
evokeds = {val: epochs[name + " == " + val].average() for val in colors}
plot_compare_evokeds(evokeds, colors=colors, split_legend=True,
                     cmap=(name + " Percentile", "viridis"))


I am working on the file "0.24/_downloads/b2637a9801fb152d611a08a816cc5583/sensor_regression.ipynb".
The first task is:
We observe that there appears to be a monotonic dependence of EEG on
concreteness. We can also conduct a continuous analysis: single-trial level
regression with concreteness as a continuous (although here, binned)
feature. We can plot the resulting regression coefficient just like an
Event-related Potential.
Can you write Python code for it?

names = ["Intercept", name]
res = linear_regression(epochs, epochs.metadata[names], names=names)
for cond in names:
    res[cond].beta.plot_joint(title=cond, ts_args=dict(time_unit='s'),
                              topomap_args=dict(time_unit='s'))


I am working on the file "0.24/_downloads/b36af73820a7a52a4df3c42b66aef8a5/source_power_spectrum_opm.ipynb".
The first task is:
Alignment and forward
Can you write Python code for it?

# Here we use a reduced size source space (oct5) just for speed
src = mne.setup_source_space(
    subject, 'oct5', add_dist=False, subjects_dir=subjects_dir)
# This line removes source-to-source distances that we will not need.
# We only do it here to save a bit of memory, in general this is not required.
del src[0]['dist'], src[1]['dist']
bem = mne.read_bem_solution(bem_fname)
# For speed, let's just use a 1-layer BEM
bem = mne.make_bem_solution(bem['surfs'][-1:])
fwd = dict()

# check alignment and generate forward for VectorView
kwargs = dict(azimuth=0, elevation=90, distance=0.6, focalpoint=(0., 0., 0.))
fig = mne.viz.plot_alignment(
    raws['vv'].info, trans=vv_trans_fname, subject=subject,
    subjects_dir=subjects_dir, dig=True, coord_frame='mri',
    surfaces=('head', 'white'))
mne.viz.set_3d_view(figure=fig, **kwargs)
fwd['vv'] = mne.make_forward_solution(
    raws['vv'].info, vv_trans_fname, src, bem, eeg=False, verbose=True)


I am working on the file "0.24/_downloads/b36af73820a7a52a4df3c42b66aef8a5/source_power_spectrum_opm.ipynb".
The first task is:
And for OPM:
Can you write Python code for it?

with mne.use_coil_def(opm_coil_def_fname):
    fig = mne.viz.plot_alignment(
        raws['opm'].info, trans=opm_trans, subject=subject,
        subjects_dir=subjects_dir, dig=False, coord_frame='mri',
        surfaces=('head', 'white'))
    mne.viz.set_3d_view(figure=fig, **kwargs)
    fwd['opm'] = mne.make_forward_solution(
        raws['opm'].info, opm_trans, src, bem, eeg=False, verbose=True)

del src, bem


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

fig_beta, brain_beta = plot_band('vv', 'beta')


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

freq_bands = dict(alpha=(8, 12), beta=(15, 29))
topos = dict(vv=dict(), opm=dict())
stcs = dict(vv=dict(), opm=dict())

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


I am working on the file "0.24/_downloads/b36af73820a7a52a4df3c42b66aef8a5/source_power_spectrum_opm.ipynb".
The first task is:
Explore data
Can you write Python code for it?

titles = dict(vv='VectorView', opm='OPM')
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.24/_downloads/b36af73820a7a52a4df3c42b66aef8a5/source_power_spectrum_opm.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.
Alpha
Can you write Python code for it?

def plot_band(kind, band):
    """Plot activity within a frequency band on the subject's brain."""
    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',
        time_viewer=False, show_traces=False,
        clim=dict(kind='percent', lims=(70, 85, 99)), smoothing_steps=10)
    brain.show_view(azimuth=0, elevation=0, roll=0)
    return fig, brain

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


I am working on the file "0.24/_downloads/b36af73820a7a52a4df3c42b66aef8a5/source_power_spectrum_opm.ipynb".
The first task is:
Then OPM:
Can you write Python code for it?

fig_beta_opm, brain_beta_opm = plot_band('opm', 'beta')


I am working on the file "0.24/_downloads/b6ccbb801939862ed915d2c7295ac245/sensor_permutation_test.ipynb".
The first task is:
Permutation T-test on sensor data
One tests if the signal significantly deviates from 0
during a fixed time window of interest. Here computation
is performed on MNE sample dataset between 40 and 60 ms.
Can you write Python code for it?

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

import numpy as np

import mne
from mne import io
from mne.stats import permutation_t_test
from mne.datasets import sample

print(__doc__)


I am working on the file "0.24/_downloads/b6ccbb801939862ed915d2c7295ac245/sensor_permutation_test.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)

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

temporal_mask = np.logical_and(0.04 <= times, times <= 0.06)
data = np.mean(data[:, :, temporal_mask], axis=2)

n_permutations = 50000
T0, p_values, H0 = permutation_t_test(data, n_permutations, n_jobs=1)

significant_sensors = picks[p_values <= 0.05]
significant_sensors_names = [raw.ch_names[k] for k in significant_sensors]

print("Number of significant sensors : %d" % len(significant_sensors))
print("Sensors names : %s" % significant_sensors_names)


I am working on the file "0.24/_downloads/b7659d33d6ffe8531d004e9d6051f16f/forward_sensitivity_maps.ipynb".
The first task is:
Compare sensitivity map with distribution of source depths
Can you write Python code for it?

# source space with vertices
src = fwd['src']

# Compute minimum Euclidean distances between vertices and MEG sensors
depths = compute_distance_to_sensors(src=src, info=fwd['info'],
                                     picks=picks_meg).min(axis=1)
maxdep = depths.max()  # for scaling

vertices = [src[0]['vertno'], src[1]['vertno']]

depths_map = SourceEstimate(data=depths, vertices=vertices, tmin=0.,
                            tstep=1.)

brain_dep = depths_map.plot(
    subject='sample', subjects_dir=subjects_dir,
    clim=dict(kind='value', lims=[0, maxdep / 2., maxdep]), figure=2)
brain_dep.add_text(0.1, 0.9, 'Source depth (m)', 'title', font_size=16)


I am working on the file "0.24/_downloads/b7659d33d6ffe8531d004e9d6051f16f/forward_sensitivity_maps.ipynb".
The first task is:
Compute sensitivity maps
Can you write Python code for it?

grad_map = mne.sensitivity_map(fwd, ch_type='grad', mode='fixed')
mag_map = mne.sensitivity_map(fwd, ch_type='mag', mode='fixed')
eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed')


I am working on the file "0.24/_downloads/b7659d33d6ffe8531d004e9d6051f16f/forward_sensitivity_maps.ipynb".
The first task is:
Display sensitivity maps for EEG and MEG sensors
Sensitivity maps can be produced from forward operators that
indicate how well different sensor types will be able to detect
neural currents from different regions of the brain.
To get started with forward modeling see tut-forward.
Can you write Python code for it?

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

import numpy as np
import mne
from mne.datasets import sample
from mne.source_space import compute_distance_to_sensors
from mne.source_estimate import SourceEstimate
import matplotlib.pyplot as plt

print(__doc__)

data_path = sample.data_path()

fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'

subjects_dir = data_path + '/subjects'

# Read the forward solutions with surface orientation
fwd = mne.read_forward_solution(fwd_fname)
mne.convert_forward_solution(fwd, surf_ori=True, copy=False)
leadfield = fwd['sol']['data']
print("Leadfield size : %d x %d" % leadfield.shape)


I am working on the file "0.24/_downloads/b7659d33d6ffe8531d004e9d6051f16f/forward_sensitivity_maps.ipynb".
The first task is:
Sensitivity is likely to co-vary with the distance between sources to
sensors. To determine the strength of this relationship, we can compute the
correlation between source depth and sensitivity values.
Can you write Python code for it?

corr = np.corrcoef(depths, grad_map.data[:, 0])[0, 1]
print('Correlation between source depth and gradiomter sensitivity values: %f.'
      % corr)


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

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


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

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


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

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

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

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

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

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

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

    return signal


I am working on the file "0.24/_downloads/b89584de6ec99a847868d7b80a32cf50/80_dics.ipynb".
The first task is:
Let's simulate two timeseries and plot some basic information about them.
Can you write Python code for it?

signal1 = coh_signal_gen()
signal2 = coh_signal_gen()

fig, axes = plt.subplots(2, 2, figsize=(8, 4))

# Plot the timeseries
ax = axes[0][0]
ax.plot(times, 1e9 * signal1, lw=0.5)
ax.set(xlabel='Time (s)', xlim=times[[0, -1]], ylabel='Amplitude (Am)',
       title='Signal 1')
ax = axes[0][1]
ax.plot(times, 1e9 * signal2, lw=0.5)
ax.set(xlabel='Time (s)', xlim=times[[0, -1]], title='Signal 2')

# Power spectrum of the first timeseries
f, p = welch(signal1, fs=sfreq, nperseg=128, nfft=256)
ax = axes[1][0]
# Only plot the first 100 frequencies
ax.plot(f[:100], 20 * np.log10(p[:100]), lw=1.)
ax.set(xlabel='Frequency (Hz)', xlim=f[[0, 99]],
       ylabel='Power (dB)', title='Power spectrum of signal 1')

# Compute the coherence between the two timeseries
f, coh = coherence(signal1, signal2, fs=sfreq, nperseg=100, noverlap=64)
ax = axes[1][1]
ax.plot(f[:50], coh[:50], lw=1.)
ax.set(xlabel='Frequency (Hz)', xlim=f[[0, 49]], ylabel='Coherence',
       title='Coherence between the timeseries')
fig.tight_layout()


I am working on the file "0.24/_downloads/b89584de6ec99a847868d7b80a32cf50/80_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.
vertices = [[146374], [33830]]

# Construct SourceEstimates that describe the signals at the cortical level.
data = np.vstack((signal1, signal2))
stc_signal = mne.SourceEstimate(
    data, vertices, tmin=0, tstep=1. / sfreq, subject='sample')
stc_noise = stc_signal * 0.


I am working on the file "0.24/_downloads/b89584de6ec99a847868d7b80a32cf50/80_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_raw(raw_fname).crop(0, 1).resample(50).info

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

# 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
stcs = [(stc_signal, unit_impulse(n_samp, dtype=int) * 1),
        (stc_noise, unit_impulse(n_samp, dtype=int) * 2)]  # stacked in time
duration = (len(stc_signal.times) * 2) / sfreq
raw = simulate_raw(info, stcs, forward=fwd)
add_noise(raw, cov, iir_filter=[4, -4, 0.8], random_state=rand)


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

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

brain1 = plot_approach(power_approach1, 1)


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

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

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

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

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

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


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

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

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


I am working on the file "0.24/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
Adding new columns to describe stimulation side and response correctness
Perfect! Now it's time to define which responses were correct and incorrect.
We first add a column encoding the side of stimulation, and then simply
check whether the response matches the stimulation side, and add this result
to another column.
Can you write Python code for it?

# left-side stimulation
metadata.loc[metadata['first_stimulus'].isin(['compatible/target_left',
                                              'incompatible/target_left']),
             'stimulus_side'] = 'left'

# right-side stimulation
metadata.loc[metadata['first_stimulus'].isin(['compatible/target_right',
                                              'incompatible/target_right']),
             'stimulus_side'] = 'right'

# first assume all responses were incorrect, then mark those as correct where
# the stimulation side matches the response side
metadata['response_correct'] = False
metadata.loc[metadata['stimulus_side'] == metadata['first_response'],
             'response_correct'] = True

correct_response_count = metadata['response_correct'].sum()
print(f'Correct responses: {correct_response_count}\n'
      f'Incorrect responses: {len(metadata) - correct_response_count}')


I am working on the file "0.24/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
Aside from the fact that the data for the (much fewer) slow responses looks
noisier – which is entirely to be expected – not much of an ERP difference
can be seen.
Applying the knowledge: visualizing the ERN component
In the following analysis, we will use the same dataset as above, but
we'll time-lock our epochs to the response events, not to the stimulus
onset. Comparing ERPs associated with correct and incorrect behavioral
responses, we should be able to see the error-related negativity (ERN) in
the difference wave.
Since we want to time-lock our analysis to responses, for the automated
metadata generation we'll consider events occurring up to 1500 ms before
the response trigger.
We only wish to consider the last stimulus and response in each time
window: Remember that we're dealing with rapid stimulus presentations in
this paradigm; taking the last response – at time point zero – and the last
stimulus – the one closest to the response – ensures we actually create
the right stimulus-response pairings. We can achieve this by passing the
keep_last parameter, which works exactly like keep_first we got to
know above, only that it keeps the last occurrences of the specified
events and stores them in columns whose names start with last_.
Can you write Python code for it?

metadata_tmin, metadata_tmax = -1.5, 0
row_events = ['response/left', 'response/right']
keep_last = ['stimulus', 'response']

metadata, events, event_id = mne.epochs.make_metadata(
    events=all_events, event_id=all_event_id,
    tmin=metadata_tmin, tmax=metadata_tmax, sfreq=raw.info['sfreq'],
    row_events=row_events,
    keep_last=keep_last)


I am working on the file "0.24/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
Auto-generating Epochs metadata
This tutorial shows how to auto-generate metadata for ~mne.Epochs, based on
events via mne.epochs.make_metadata.
We are going to use data from the erp-core-dataset (derived from
:footcite:Kappenman2021). This is EEG data from a single participant
performing an active visual task (Eriksen flanker task).

Note

If you wish to skip the introductory parts of this tutorial, you may jump
   straight to `tut-autogenerate-metadata-ern` after completing the data
   import and event creation in the
   `tut-autogenerate-metadata-preparation` section.

This tutorial is loosely divided into two parts:

We will first focus on producing ERP time-locked to the visual
   stimulation, conditional on response correctness and response time in
   order to familiarize ourselves with the ~mne.epochs.make_metadata
   function.
After that, we will calculate ERPs time-locked to the responses – again,
   conditional on response correctness – to visualize the error-related
   negativity (ERN), i.e. the ERP component associated with incorrect
   behavioral responses.

Preparation
Let's start by reading, filtering, and producing a simple visualization of the
raw data. The data is pretty clean and contains very few blinks, so there's no
need to apply sophisticated preprocessing and data cleaning procedures.
We will also convert the ~mne.Annotations contained in this dataset to events
by calling mne.events_from_annotations.
Can you write Python code for it?

from pathlib import Path
import matplotlib.pyplot as plt
import mne

data_dir = Path(mne.datasets.erp_core.data_path())
infile = data_dir / 'ERP-CORE_Subject-001_Task-Flankers_eeg.fif'

raw = mne.io.read_raw(infile, preload=True)
raw.filter(l_freq=0.1, h_freq=40)
raw.plot(start=60)

# extract events
all_events, all_event_id = mne.events_from_annotations(raw)


I am working on the file "0.24/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
Bummer! It seems the very first two responses were recorded before the
first stimulus appeared: the values in the stimulus column are None.
There is a very simple way to select only those epochs that do have a
stimulus (i.e., are not None):
Can you write Python code for it?


I am working on the file "0.24/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
Creating Epochs with metadata, and visualizing ERPs
It's finally time to create our epochs! We set the metadata directly on
instantiation via the metadata parameter. Also it is important to
remember to pass events and event_id as returned from
~mne.epochs.make_metadata, as we only created metadata for a subset of
our original events by passing row_events. Otherwise, the length
of the metadata and the number of epochs would not match and MNE-Python
would raise an error.
Can you write Python code for it?

epochs_tmin, epochs_tmax = -0.1, 0.4  # epochs range: [-0.1, 0.4] s
reject = {'eeg': 250e-6}  # exclude epochs with strong artifacts
epochs = mne.Epochs(raw=raw, tmin=epochs_tmin, tmax=epochs_tmax,
                    events=events, event_id=event_id, metadata=metadata,
                    reject=reject, preload=True)


I am working on the file "0.24/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
Exactly like in the previous example, create new columns stimulus_side
and response_correct.
Can you write Python code for it?

# left-side stimulation
metadata.loc[metadata['last_stimulus'].isin(['compatible/target_left',
                                             'incompatible/target_left']),
             'stimulus_side'] = 'left'

# right-side stimulation
metadata.loc[metadata['last_stimulus'].isin(['compatible/target_right',
                                             'incompatible/target_right']),
             'stimulus_side'] = 'right'

# first assume all responses were incorrect, then mark those as correct where
# the stimulation side matches the response side
metadata['response_correct'] = False
metadata.loc[metadata['stimulus_side'] == metadata['last_response'],
             'response_correct'] = True

metadata


I am working on the file "0.24/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
We can see a strong negative deflection immediately after incorrect
responses, compared to correct responses. The topoplot, too, leaves no doubt:
what we're looking at is, in fact, the ERN.
Some researchers suggest to construct the difference wave between ERPs for
correct and incorrect responses, as it more clearly reveals signal
differences, while ideally also improving the signal-to-noise ratio (under
the assumption that the noise level in "correct" and "incorrect" trials is
similar). Let's do just that and put it into a publication-ready
visualization.
Can you write Python code for it?

# difference wave: incorrect minus correct responses
resp_erp_diff = mne.combine_evoked([resp_erp_incorrect, resp_erp_correct],
                                   weights=[1, -1])

fig, ax = plt.subplots()
resp_erp_diff.plot(picks='FCz', axes=ax, selectable=False, show=False)

# make ERP trace bolder
ax.lines[0].set_linewidth(1.5)

# add lines through origin
ax.axhline(0, ls='dotted', lw=0.75, color='gray')
ax.axvline(0, ls=(0, (10, 10)), lw=0.75, color='gray',
           label='response trigger')

# mark trough
trough_time_idx = resp_erp_diff.copy().pick('FCz').data.argmin()
trough_time = resp_erp_diff.times[trough_time_idx]
ax.axvline(trough_time, ls=(0, (10, 10)), lw=0.75, color='red',
           label='max. negativity')

# legend, axis labels, title
ax.legend(loc='lower left')
ax.set_xlabel('Time (s)', fontweight='bold')
ax.set_ylabel('Amplitude (µV)', fontweight='bold')
ax.set_title('Channel: FCz')
fig.suptitle('ERN (Difference Wave)', fontweight='bold')

fig


I am working on the file "0.24/_downloads/b99fcf919e5d2f612fcfee22adcfc330/40_autogenerate_metadata.ipynb".
The first task is:
We're facing a similar issue with the stimulus events, and now there are not
only two, but four different types: stimulus/compatible/target_left,
stimulus/compatible/target_right, stimulus/incompatible/target_left,
and stimulus/incompatible/target_right. Even more, because in the present
paradigm stimuli were presented in rapid succession, sometimes multiple
stimulus events occurred within the 1.5 second time window we're using to
generate our metadata. See for example:
Can you write Python code for it?

metadata.loc[metadata['stimulus/compatible/target_left'].notna() &
             metadata['stimulus/compatible/target_right'].notna(),
             :]


I am working on the file "0.24/_downloads/bcaf3ed1f43ea7377c6c0b00137d728f/custom_inverse_solver.ipynb".
The first task is:
Apply your custom solver
Can you write Python code for it?

# loose, depth = 0.2, 0.8  # corresponds to loose orientation
loose, depth = 1., 0.  # corresponds to free orientation
stc = apply_solver(solver, evoked, forward, noise_cov, loose, depth)


I am working on the file "0.24/_downloads/bcaf3ed1f43ea7377c6c0b00137d728f/custom_inverse_solver.ipynb".
The first task is:
Auxiliary function to run the solver
Can you write Python code for it?

def apply_solver(solver, evoked, forward, noise_cov, loose=0.2, depth=0.8):
    """Call a custom solver on evoked data.

    This function does all the necessary computation:

    - to select the channels in the forward given the available ones in
      the data
    - to take into account the noise covariance and do the spatial whitening
    - to apply loose orientation constraint as MNE solvers
    - to apply a weigthing of the columns of the forward operator as in the
      weighted Minimum Norm formulation in order to limit the problem
      of depth bias.

    Parameters
    ----------
    solver : callable
        The solver takes 3 parameters: data M, gain matrix G, number of
        dipoles orientations per location (1 or 3). A solver shall return
        2 variables: X which contains the time series of the active dipoles
        and an active set which is a boolean mask to specify what dipoles are
        present in X.
    evoked : instance of mne.Evoked
        The evoked data
    forward : instance of Forward
        The forward solution.
    noise_cov : instance of Covariance
        The noise covariance.
    loose : float in [0, 1] | 'auto'
        Value that weights the source variances of the dipole components
        that are parallel (tangential) to the cortical surface. If loose
        is 0 then the solution is computed with fixed orientation.
        If loose is 1, it corresponds to free orientations.
        The default value ('auto') is set to 0.2 for surface-oriented source
        space and set to 1.0 for volumic or discrete source space.
    depth : None | float in [0, 1]
        Depth weighting coefficients. If None, no depth weighting is performed.

    Returns
    -------
    stc : instance of SourceEstimate
        The source estimates.
    """
    # Import the necessary private functions
    from mne.inverse_sparse.mxne_inverse import \
        (_prepare_gain, is_fixed_orient,
         _reapply_source_weighting, _make_sparse_stc)

    all_ch_names = evoked.ch_names

    # Handle...


I am working on the file "0.24/_downloads/bcaf3ed1f43ea7377c6c0b00137d728f/custom_inverse_solver.ipynb".
The first task is:
Define your solver
Can you write Python code for it?

def solver(M, G, n_orient):
    """Run L2 penalized regression and keep 10 strongest locations.

    Parameters
    ----------
    M : array, shape (n_channels, n_times)
        The whitened data.
    G : array, shape (n_channels, n_dipoles)
        The gain matrix a.k.a. the forward operator. The number of locations
        is n_dipoles / n_orient. n_orient will be 1 for a fixed orientation
        constraint or 3 when using a free orientation model.
    n_orient : int
        Can be 1 or 3 depending if one works with fixed or free orientations.
        If n_orient is 3, then ``G[:, 2::3]`` corresponds to the dipoles that
        are normal to the cortex.

    Returns
    -------
    X : array, (n_active_dipoles, n_times)
        The time series of the dipoles in the active set.
    active_set : array (n_dipoles)
        Array of bool. Entry j is True if dipole j is in the active set.
        We have ``X_full[active_set] == X`` where X_full is the full X matrix
        such that ``M = G X_full``.
    """
    inner = np.dot(G, G.T)
    trace = np.trace(inner)
    K = linalg.solve(inner + 4e-6 * trace * np.eye(G.shape[0]), G).T
    K /= np.linalg.norm(K, axis=1)[:, None]
    X = np.dot(K, M)

    indices = np.argsort(np.sum(X ** 2, axis=1))[-10:]
    active_set = np.zeros(G.shape[1], dtype=bool)
    for idx in indices:
        idx -= idx % n_orient
        active_set[idx:idx + n_orient] = True
    X = X[active_set]
    return X, active_set


I am working on the file "0.24/_downloads/bcaf3ed1f43ea7377c6c0b00137d728f/custom_inverse_solver.ipynb".
The first task is:
Source localization with a custom inverse solver
The objective of this example is to show how to plug a custom inverse solver
in MNE in order to facilate empirical comparison with the methods MNE already
implements (wMNE, dSPM, sLORETA, eLORETA, LCMV, DICS, (TF-)MxNE etc.).
This script is educational and shall be used for methods
evaluations and new developments. It is not meant to be an example
of good practice to analyse your data.
The example makes use of 2 functions apply_solver and solver
so changes can be limited to the solver function (which only takes three
parameters: the whitened data, the gain matrix and the number of orientations)
in order to try out another inverse algorithm.
Can you write Python code for it?

import numpy as np
from scipy import linalg
import mne
from mne.datasets import sample
from mne.viz import plot_sparse_source_estimates

data_path = sample.data_path()
fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
ave_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
cov_fname = data_path + '/MEG/sample/sample_audvis-shrunk-cov.fif'
subjects_dir = data_path + '/subjects'
condition = 'Left Auditory'

# Read noise covariance matrix
noise_cov = mne.read_cov(cov_fname)
# Handling average file
evoked = mne.read_evokeds(ave_fname, condition=condition, baseline=(None, 0))
evoked.crop(tmin=0.04, tmax=0.18)

evoked = evoked.pick_types(eeg=False, meg=True)
# Handling forward solution
forward = mne.read_forward_solution(fwd_fname)


I am working on the file "0.24/_downloads/bcaf3ed1f43ea7377c6c0b00137d728f/custom_inverse_solver.ipynb".
The first task is:
View in 2D and 3D ("glass" brain like 3D plot)
Can you write Python code for it?

plot_sparse_source_estimates(forward['src'], stc, bgcolor=(1, 1, 1),
                             opacity=0.1)


I am working on the file "0.24/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
.. sidebar:: Head coordinate frame
 The head coordinate frame in MNE is the "Neuromag" head coordinate
 frame. The origin is given by the intersection between a line connecting
 the LPA and RPA and the line orthogonal to it that runs through the
 nasion. It is also in RAS orientation, meaning that +X runs through
 the RPA, +Y goes through the nasion, and +Z is orthogonal to these
 pointing upward. See `coordinate_systems` for more information.

Notice that in "head" coordinate frame the nasion has values of 0 for the
x and z directions (which makes sense given that the nasion is used
to define the y axis in that system).
To convert from head coordinate frame to voxels, we first apply the head →
MRI (surface RAS) transform
from a :file:trans file (typically created with the MNE-Python
coregistration GUI), then convert meters → millimeters, and finally apply the
inverse of Torig to get to voxels.
Under the hood, functions like :func:mne.setup_source_space,
:func:mne.setup_volume_source_space, and :func:mne.compute_source_morph
make extensive use of these coordinate frames.
Can you write Python code for it?

trans = mne.read_trans(
    os.path.join(data_path, 'MEG', 'sample', 'sample_audvis_raw-trans.fif'))

# first we transform from head to MRI, and *then* convert to millimeters
nasion_dig_mri = apply_trans(trans, nasion_head['r']) * 1000

# ...then we can use Torig to convert MRI to voxels:
nasion_dig_vox = np.round(
    apply_trans(np.linalg.inv(Torig), nasion_dig_mri)).astype(int)
imshow_mri(data, t1, nasion_dig_vox, dict(MRI=nasion_dig_mri),
           'Nasion transformed from digitization')


I am working on the file "0.24/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:

Warning

Some source space vertices can be removed during forward computation.
   See `tut-forward` for more information.

FreeSurfer's MNI affine transformation
In addition to surface-based approaches, FreeSurfer also provides a simple
affine coregistration of each subject's data to the fsaverage subject.
Let's pick a point for sample and plot it on the brain:
Can you write Python code for it?

brain = mne.viz.Brain('sample', 'lh', 'white', subjects_dir=subjects_dir,
                      background='w')
xyz = np.array([[-55, -10, 35]])
brain.add_foci(xyz, hemi='lh', color='k')
brain.show_view('lat')


I am working on the file "0.24/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
And because fsaverage is special in that it's already in MNI space
(its MRI-to-MNI transform is identity), it should land in the equivalent
anatomical location:
Can you write Python code for it?

brain = mne.viz.Brain('fsaverage', 'lh', 'white', subjects_dir=subjects_dir,
                      background='w')
brain.add_foci(xyz_mni, hemi='lh', color='k')
brain.show_view('lat')


I am working on the file "0.24/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
Knowing these relationships and being mindful about transformations, we
can get from a point in any given space to any other space. Let's start out
by plotting the Nasion on a saggital MRI slice:
Can you write Python code for it?

fiducials = mne.coreg.get_mni_fiducials(subject, subjects_dir=subjects_dir)
nasion_mri = [d for d in fiducials if d['ident'] == FIFF.FIFFV_POINT_NASION][0]
print(nasion_mri)  # note it's in Freesurfer MRI coords


I am working on the file "0.24/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
Let's actually plot it:
Can you write Python code for it?

renderer = mne.viz.backends.renderer.create_3d_figure(
    size=(600, 600), bgcolor='w', scene=False)
gray = (0.5, 0.5, 0.5)
renderer.mesh(*rr_mm.T, triangles=tris, color=gray)
view_kwargs = dict(elevation=90, azimuth=0)
mne.viz.set_3d_view(
    figure=renderer.figure, distance=350, focalpoint=(0., 0., 40.),
    **view_kwargs)
renderer.show()


I am working on the file "0.24/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
Let's look a bit more closely at the spherical alignment by overlaying the
two spherical meshes as wireframes and zooming way in (the purple points are
separated by about 1 mm):
Can you write Python code for it?

cyan = '#66CCEE'
purple = '#AA3377'
renderer = mne.viz.backends.renderer.create_3d_figure(
    size=(800, 800), scene=False, **renderer_kwargs)
fnames = [os.path.join(subjects_dir, subj, 'surf', 'rh.sphere')
          for subj in ('sample', 'fsaverage')]
colors = [cyan, purple]
for name, color in zip(fnames, colors):
    this_rr, this_tri = mne.read_surface(name)
    renderer.mesh(*this_rr.T, triangles=this_tri, color=color,
                  representation='wireframe')
mne.viz.set_3d_view(figure=renderer.figure, distance=20, **view_kwargs)
renderer.show()


I am working on the file "0.24/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
MRI coordinate frames
Let's start out by looking at the sample subject MRI. Following standard
FreeSurfer convention, we look at :file:T1.mgz, which gets created from the
original MRI :file:sample/mri/orig/001.mgz when you run the FreeSurfer
command recon-all <https://surfer.nmr.mgh.harvard.edu/fswiki/recon-all>_.
Here we use :mod:nibabel to load the T1 image, and the resulting object's
:meth:~nibabel.spatialimages.SpatialImage.orthoview method to view it.
Can you write Python code for it?

data_path = mne.datasets.sample.data_path()
subjects_dir = os.path.join(data_path, 'subjects')
subject = 'sample'
t1_fname = os.path.join(subjects_dir, subject, 'mri', 'T1.mgz')
t1 = nibabel.load(t1_fname)
t1.orthoview()


I am working on the file "0.24/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
Notice that the axis scales (i, j, and k) are still in voxels
(ranging from 0-255); it's only the annotation text that we've translated
into real-world RAS in millimeters.
"MRI coordinates" in MNE-Python: FreeSurfer surface RAS
While :mod:nibabel uses scanner RAS (x, y, z) coordinates,
FreeSurfer uses a slightly different coordinate frame: MRI surface RAS.
The transform from voxels to the FreeSurfer MRI surface RAS coordinate frame
is known in the FreeSurfer documentation
<https://surfer.nmr.mgh.harvard.edu/fswiki/CoordinateSystems>_ as Torig,
and in nibabel as :meth:vox2ras_tkr
<nibabel.freesurfer.mghformat.MGHHeader.get_vox2ras_tkr>. This
transformation sets the center of its coordinate frame in the middle of the
conformed volume dimensions (N / 2.) with the axes oriented along the
axes of the volume itself. For more information, see
coordinate_systems.

Note

In general, you should assume that the MRI coordinate system for
          a given subject is specific to that subject, i.e., it is not the
          same coordinate MRI coordinate system that is used for any other
          FreeSurfer subject. Even though during processing FreeSurfer will
          align each subject's MRI to ``fsaverage`` to do reconstruction,
          all data (surfaces, MRIs, etc.) get stored in the coordinate frame
          specific to that subject. This is why it's important for group
          analyses to transform data to a common coordinate frame for example
          by `surface <ex-morph-surface>` or
          `volumetric <ex-morph-volume>` morphing, or even by just
          applying `mni-affine-transformation` to points.

Since MNE-Python uses FreeSurfer extensively for surface computations (e.g.,
white matter, inner/outer skull meshes), internally MNE-Python uses the
Freeurfer surface RAS coordinate system (not the :mod:nibabel scanner RAS
system) for as many computations as possible, such as all source space
and BEM mesh vertex definitions.
Whenever you see...
Can you write Python code for it?

Torig = t1.header.get_vox2ras_tkr()
print(t1.affine)
print(Torig)
xyz_mri = apply_trans(Torig, vox)
imshow_mri(data, t1, vox, dict(MRI=xyz_mri), 'MRI slice')


I am working on the file "0.24/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
These data are voxel intensity values. Here they are unsigned integers in the
range 0-255, though in general they can be floating point values. A value
data[i, j, k] at a given index triplet (i, j, k) corresponds to some
real-world physical location (x, y, z) in space. To get its physical
location, first we have to choose what coordinate frame we're going to use.
For example, we could choose a geographical coordinate
frame, with origin is at the center of the earth, Z axis through the north
pole, X axis through the prime meridian (zero degrees longitude), and Y axis
orthogonal to these forming a right-handed coordinate system. This would not
be a very useful choice for defining the physical locations of the voxels
during the MRI acquisition for analysis, but you could nonetheless figure out
the transformation that related the (i, j, k) to this coordinate frame.
Instead, each scanner defines a more practical, native coordinate system that
it uses during acquisition, usually related to the physical orientation of
the scanner itself and/or the subject within it. During acquisition the
relationship between the voxel indices (i, j, k) and the physical
location (x, y, z) in the scanner's native coordinate frame is saved in
the image's affine transformation.
.. sidebar:: Under the hood
``mne.transforms.apply_trans`` effectively does a matrix multiplication
(i.e., :func:`numpy.dot`), with a little extra work to handle the shape
mismatch (the affine has shape ``(4, 4)`` because it includes a
*translation*, which is applied separately).

We can use :mod:nibabel to examine this transformation, keeping in mind
that it processes everything in units of millimeters, unlike MNE where things
are always in SI units (meters).
This allows us to take an arbitrary voxel or slice of data and know where it
is in the scanner's native physical space (x, y, z) (in mm) by applying
the affine transformation to the voxel coordinates.
Can you write Python code for it?

print(t1.affine)
vox = np.array([122, 119, 102])
xyz_ras = apply_trans(t1.affine, vox)
print('Our voxel has real-world coordinates {}, {}, {} (mm)'
      .format(*np.round(xyz_ras, 3)))


I am working on the file "0.24/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
This is the method used by :func:mne.viz.plot_bem to show the BEM surfaces.
Cortical alignment (spherical)
A critical function provided by FreeSurfer is spherical surface alignment
of cortical surfaces, maximizing sulcal-gyral alignment. FreeSurfer first
expands the cortical surface to a sphere, then aligns it optimally with
fsaverage. Because the vertex ordering is preserved when expanding to a
sphere, a given vertex in the source (sample) mesh can be mapped easily
to the same location in the destination (fsaverage) mesh, and vice-versa.
Can you write Python code for it?

renderer_kwargs = dict(bgcolor='w', smooth_shading=False)
renderer = mne.viz.backends.renderer.create_3d_figure(
    size=(800, 400), scene=False, **renderer_kwargs)
curvs = [
    (mne.surface.read_curvature(os.path.join(
        subjects_dir, subj, 'surf', 'rh.curv'),
        binary=False) > 0).astype(float)
    for subj in ('sample', 'fsaverage') for _ in range(2)]
fnames = [os.path.join(subjects_dir, subj, 'surf', surf)
          for subj in ('sample', 'fsaverage')
          for surf in ('rh.white', 'rh.sphere')]
y_shifts = [-450, -150, 450, 150]
z_shifts = [-40, 0, -30, 0]
for name, y_shift, z_shift, curv in zip(fnames, y_shifts, z_shifts, curvs):
    this_rr, this_tri = mne.read_surface(name)
    this_rr += [0, y_shift, z_shift]
    renderer.mesh(*this_rr.T, triangles=this_tri, color=None, scalars=curv,
                  colormap='copper_r', vmin=-0.2, vmax=1.2)
zero = [0., 0., 0.]
width = 50.
y = np.sort(y_shifts)
y = (y[1:] + y[:-1]) / 2. - width / 2.
renderer.quiver3d(zero, y, zero,
                  zero, [1] * 3, zero, 'k', width, 'arrow')
view_kwargs['focalpoint'] = (0., 0., 0.)
mne.viz.set_3d_view(figure=renderer.figure, distance=1000, **view_kwargs)
renderer.show()


I am working on the file "0.24/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
We can also plot the mesh on top of an MRI slice. The mesh surfaces are
defined in millimeters in the MRI (FreeSurfer surface RAS) coordinate frame,
so we can convert them to voxels by applying the inverse of the Torig
transform:
Can you write Python code for it?

rr_vox = apply_trans(np.linalg.inv(Torig), rr_mm)
fig = imshow_mri(data, t1, vox, {'Scanner RAS': xyz_ras}, 'MRI slice')
# Based on how imshow_mri works, the "X" here is the last dim of the MRI vol,
# the "Y" is the middle dim, and the "Z" is the first dim, so now that our
# points are in the correct coordinate frame, we need to ask matplotlib to
# do a tricontour slice like:
fig.axes[0].tricontour(rr_vox[:, 2], rr_vox[:, 1], tris, rr_vox[:, 0],
                       levels=[vox[0]], colors='r', linewidths=1.0,
                       zorder=1)


I am working on the file "0.24/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
We can also take the digitization point from the MEG data, which is in the
"head" coordinate frame.
Let's look at the nasion in the head coordinate frame:
Can you write Python code for it?

info = mne.io.read_info(
    os.path.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif'))
nasion_head = [d for d in info['dig'] if
               d['kind'] == FIFF.FIFFV_POINT_CARDINAL and
               d['ident'] == FIFF.FIFFV_POINT_NASION][0]
print(nasion_head)  # note it's in "head" coordinates


I am working on the file "0.24/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
We can also then look at how these two meshes compare by plotting the
original, high-density mesh as well as our decimated mesh white surfaces.
Can you write Python code for it?

renderer = mne.viz.backends.renderer.create_3d_figure(
    size=(800, 400), scene=False, **renderer_kwargs)
y_shifts = [-125, 125]
tris = [src[1]['tris'], src[1]['use_tris']]
for y_shift, tris in zip(y_shifts, tris):
    this_rr = src[1]['rr'] * 1000. + [0, y_shift, -40]
    renderer.mesh(*this_rr.T, triangles=tris, color=None, scalars=curvs[0],
                  colormap='copper_r', vmin=-0.2, vmax=1.2)
renderer.quiver3d([0], [-width / 2.], [0], [0], [1], [0], 'k', width, 'arrow')
mne.viz.set_3d_view(figure=renderer.figure, distance=400, **view_kwargs)
renderer.show()


I am working on the file "0.24/_downloads/bdc8ac519d8f54d70a73a5e0de598566/50_background_freesurfer_mne.ipynb".
The first task is:
When we print the nasion, it displays as a DigPoint and shows its
coordinates in millimeters, but beware that the underlying data is
actually stored in meters <units>,
so before transforming and plotting we'll convert to millimeters:
Can you write Python code for it?

nasion_mri = nasion_mri['r'] * 1000  # meters → millimeters
nasion_vox = np.round(
    apply_trans(np.linalg.inv(Torig), nasion_mri)).astype(int)
imshow_mri(data, t1, nasion_vox, dict(MRI=nasion_mri),
           'Nasion estimated from MRI transform')


I am working on the file "0.24/_downloads/bdc99305dd93336f2d973c05e0c46d24/25_automated_coreg.ipynb".
The first task is:
Do a final coregistration fit
Can you write Python code for it?

coreg.fit_icp(n_iterations=20, nasion_weight=10., verbose=True)
fig = mne.viz.plot_alignment(info, trans=coreg.trans, **plot_kwargs)
mne.viz.set_3d_view(fig, **view_kwargs)

dists = coreg.compute_dig_mri_distances() * 1e3  # in mm
print(
    f"Distance between HSP and MRI (mean/min/max):\n{np.mean(dists):.2f} mm "
    f"/ {np.min(dists):.2f} mm / {np.max(dists):.2f} mm"
)


I am working on the file "0.24/_downloads/bdc99305dd93336f2d973c05e0c46d24/25_automated_coreg.ipynb".
The first task is:
Do first a coregistration fit using only 3 fiducial points. This allows
to find a good initial solution before further optimization using
head shape points. This can also be useful to detect outlier head shape
points which are too far from the skin surface. One can see for example
that on this dataset there is one such point and we will omit it from
the subsequent fit.
Can you write Python code for it?

coreg.fit_fiducials(verbose=True)
fig = mne.viz.plot_alignment(info, trans=coreg.trans, **plot_kwargs)


I am working on the file "0.24/_downloads/bdc99305dd93336f2d973c05e0c46d24/25_automated_coreg.ipynb".
The first task is:
It is now very clear that we have one point that is an outlier
and that should be removed.
Can you write Python code for it?

coreg.omit_head_shape_points(distance=5. / 1000)  # distance is in meters


I am working on the file "0.24/_downloads/bdc99305dd93336f2d973c05e0c46d24/25_automated_coreg.ipynb".
The first task is:
Next we refine the transformation using a few iteration of the
Iterative Closest Point (ICP) algorithm. As the initial fiducials
are obtained from fsaverage and not from precise manual picking in the
GUI we do a fit with reduced weight for the nasion.
Can you write Python code for it?

coreg.fit_icp(n_iterations=6, nasion_weight=2., verbose=True)
fig = mne.viz.plot_alignment(info, trans=coreg.trans, **plot_kwargs)


I am working on the file "0.24/_downloads/bdc99305dd93336f2d973c05e0c46d24/25_automated_coreg.ipynb".
The first task is:
Set up the coregistration model
Can you write Python code for it?

fiducials = "estimated"  # get fiducials from fsaverage
coreg = Coregistration(info, subject, subjects_dir, fiducials=fiducials)
fig = mne.viz.plot_alignment(info, trans=coreg.trans, **plot_kwargs)


I am working on the file "0.24/_downloads/bdc99305dd93336f2d973c05e0c46d24/25_automated_coreg.ipynb".
The first task is:
Using an automated approach to coregistration
This example shows how to use the coregistration functions to perform an
automated MEG-MRI coregistration via scripting.

Warning

The quality of the coregistration depends heavily upon the
             quality of the head shape points (HSP) collected during subject
             prepration and the quality of your T1-weighted MRI. Use with
             caution and check the coregistration error.

Can you write Python code for it?

# Author: Jon Houck <jon.houck@gmail.com>
#         Guillaume Favelier <guillaume.favelier@gmail.com>
#
# License: BSD-3-Clause

import os.path as op
import numpy as np

import mne
from mne.coreg import Coregistration
from mne.io import read_info

data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
subject = 'sample'

fname_raw = op.join(data_path, 'MEG', subject, subject + '_audvis_raw.fif')
info = read_info(fname_raw)
plot_kwargs = dict(subject=subject, subjects_dir=subjects_dir,
                   surfaces="head-dense", dig=True, eeg=[],
                   meg='sensors', show_axes=True,
                   coord_frame='meg')
view_kwargs = dict(azimuth=45, elevation=90, distance=0.6,
                   focalpoint=(0., 0., 0.))


I am working on the file "0.24/_downloads/c1dad3cf15579a4724c19d6df916b111/mixed_norm_inverse.ipynb".
The first task is:
Compute sparse inverse solution with mixed norm: MxNE and irMxNE
Runs an (ir)MxNE (L1/L2 :footcite:GramfortEtAl2012 or L0.5/L2
:footcite:StrohmeierEtAl2014 mixed norm) inverse solver.
L0.5/L2 is done with irMxNE which allows for sparser source estimates with less
amplitude bias due to the non-convexity of the L0.5/L2 mixed norm penalty.
Can you write Python code for it?

# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#         Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: BSD-3-Clause

import numpy as np

import mne
from mne.datasets import sample
from mne.inverse_sparse import mixed_norm, make_stc_from_dipoles
from mne.minimum_norm import make_inverse_operator, apply_inverse
from mne.viz import (plot_sparse_source_estimates,
                     plot_dipole_locations, plot_dipole_amplitudes)

print(__doc__)

data_path = sample.data_path()
fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
ave_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
cov_fname = data_path + '/MEG/sample/sample_audvis-shrunk-cov.fif'
subjects_dir = data_path + '/subjects'

# Read noise covariance matrix
cov = mne.read_cov(cov_fname)
# Handling average file
condition = 'Left Auditory'
evoked = mne.read_evokeds(ave_fname, condition=condition, baseline=(None, 0))
evoked.crop(tmin=0, tmax=0.3)
# Handling forward solution
forward = mne.read_forward_solution(fwd_fname)


I am working on the file "0.24/_downloads/c37ac181bfe2eb2f1fa69c3fab30417d/mne_cov_power.ipynb".
The first task is:
Compute and plot covariances
In addition to the empty-room covariance above, we compute two additional
covariances:

Baseline covariance, which captures signals not of interest in our
   analysis (e.g., sensor noise, environmental noise, physiological
   artifacts, and also resting-state-like brain activity / "noise").
Data covariance, which captures our activation of interest (in addition
   to noise sources).
Can you write Python code for it?

base_cov = mne.compute_covariance(
    epochs, tmin=-0.2, tmax=0, method='shrunk', verbose=True)
data_cov = mne.compute_covariance(
    epochs, tmin=0., tmax=0.2, method='shrunk', verbose=True)

fig_noise_cov = mne.viz.plot_cov(noise_cov, epochs.info, show_svd=False)
fig_base_cov = mne.viz.plot_cov(base_cov, epochs.info, show_svd=False)
fig_data_cov = mne.viz.plot_cov(data_cov, epochs.info, show_svd=False)


I am working on the file "0.24/_downloads/c37ac181bfe2eb2f1fa69c3fab30417d/mne_cov_power.ipynb".
The first task is:
Compute empty-room covariance
First we compute an empty-room covariance, which captures noise from the
sensors and environment.
Can you write Python code for it?

raw_empty_room_fname = op.join(
    data_path, 'MEG', 'sample', 'ernoise_raw.fif')
raw_empty_room = mne.io.read_raw_fif(raw_empty_room_fname)
raw_empty_room.crop(0, 30)  # cropped just for speed
raw_empty_room.info['bads'] = ['MEG 2443']
raw_empty_room.add_proj(raw.info['projs'])
noise_cov = mne.compute_raw_covariance(raw_empty_room, method='shrunk')
del raw_empty_room


I am working on the file "0.24/_downloads/c37ac181bfe2eb2f1fa69c3fab30417d/mne_cov_power.ipynb".
The first task is:
Compute source power estimate by projecting the covariance with MNE
We can apply the MNE inverse operator to a covariance matrix to obtain
an estimate of source power. This is computationally more efficient than first
estimating the source timecourses and then computing their power. This
code is based on the code from :footcite:Sabbagh2020 and has been useful to
correct for individual field spread using source localization in the context of
predictive modeling.
References
.. footbibliography::
Can you write Python code for it?

# Author: Denis A. Engemann <denis-alexander.engemann@inria.fr>
#         Luke Bloy <luke.bloy@gmail.com>
#
# License: BSD-3-Clause

import os.path as op
import numpy as np

import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse_cov

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read_raw_fif(raw_fname)


I am working on the file "0.24/_downloads/c37ac181bfe2eb2f1fa69c3fab30417d/mne_cov_power.ipynb".
The first task is:
Epoch the data
Can you write Python code for it?

raw.pick(['meg', 'stim', 'eog']).load_data().filter(4, 12)
raw.info['bads'] = ['MEG 2443']
events = mne.find_events(raw, stim_channel='STI 014')
event_id = dict(aud_l=1, aud_r=2, vis_l=3, vis_r=4)
tmin, tmax = -0.2, 0.5
baseline = (None, 0)  # means from the first instant to t = 0
reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                    proj=True, picks=('meg', 'eog'), baseline=None,
                    reject=reject, preload=True, decim=5, verbose='error')
del raw


I am working on the file "0.24/_downloads/c37ac181bfe2eb2f1fa69c3fab30417d/mne_cov_power.ipynb".
The first task is:
Project our data and baseline covariance to source space:
Can you write Python code for it?

stc_data = apply_inverse_cov(data_cov, evoked.info, inverse_operator,
                             nave=len(epochs), method='dSPM', verbose=True)
stc_base = apply_inverse_cov(base_cov, evoked.info, inverse_operator,
                             nave=len(epochs), method='dSPM', verbose=True)


I am working on the file "0.24/_downloads/c37ac181bfe2eb2f1fa69c3fab30417d/mne_cov_power.ipynb".
The first task is:
We can also look at the covariances using topomaps, here we just show the
baseline and data covariances, followed by the data covariance whitened
by the baseline covariance:
Can you write Python code for it?

evoked = epochs.average().pick('meg')
evoked.drop_channels(evoked.info['bads'])
evoked.plot(time_unit='s')
evoked.plot_topomap(times=np.linspace(0.05, 0.15, 5), ch_type='mag')
noise_cov.plot_topomap(evoked.info, 'grad', title='Noise')
data_cov.plot_topomap(evoked.info, 'grad', title='Data')
data_cov.plot_topomap(evoked.info, 'grad', noise_cov=noise_cov,
                      title='Whitened data')


I am working on the file "0.24/_downloads/c4c1adf6983ad491e45e3941a0c10d6e/time_frequency_mixed_norm_inverse.ipynb".
The first task is:
Plot dipole activations
Can you write Python code for it?


I am working on the file "0.24/_downloads/c4c1adf6983ad491e45e3941a0c10d6e/time_frequency_mixed_norm_inverse.ipynb".
The first task is:
Plot location of the strongest dipole with MRI slices
Can you write Python code for it?

idx = np.argmax([np.max(np.abs(dip.amplitude)) for dip in dipoles])
plot_dipole_locations(dipoles[idx], forward['mri_head_t'], 'sample',
                      subjects_dir=subjects_dir, mode='orthoview',
                      idx='amplitude')

# # Plot dipole locations of all dipoles with MRI slices:
# for dip in dipoles:
#     plot_dipole_locations(dip, forward['mri_head_t'], 'sample',
#                           subjects_dir=subjects_dir, mode='orthoview',
#                           idx='amplitude')


I am working on the file "0.24/_downloads/c4c1adf6983ad491e45e3941a0c10d6e/time_frequency_mixed_norm_inverse.ipynb".
The first task is:
Run solver
Can you write Python code for it?

# alpha parameter is between 0 and 100 (100 gives 0 active source)
alpha = 40.  # general regularization parameter
# l1_ratio parameter between 0 and 1 promotes temporal smoothness
# (0 means no temporal regularization)
l1_ratio = 0.03  # temporal regularization parameter

loose, depth = 0.2, 0.9  # loose orientation & depth weighting

# Compute dSPM solution to be used as weights in MxNE
inverse_operator = make_inverse_operator(evoked.info, forward, cov,
                                         loose=loose, depth=depth)
stc_dspm = apply_inverse(evoked, inverse_operator, lambda2=1. / 9.,
                         method='dSPM')

# Compute TF-MxNE inverse solution with dipole output
dipoles, residual = tf_mixed_norm(
    evoked, forward, cov, alpha=alpha, l1_ratio=l1_ratio, loose=loose,
    depth=depth, maxit=200, tol=1e-6, weights=stc_dspm, weights_min=8.,
    debias=True, wsize=16, tstep=4, window=0.05, return_as_dipoles=True,
    return_residual=True)

# Crop to remove edges
for dip in dipoles:
    dip.crop(tmin=-0.05, tmax=0.3)
evoked.crop(tmin=-0.05, tmax=0.3)
residual.crop(tmin=-0.05, tmax=0.3)


I am working on the file "0.24/_downloads/c4c1adf6983ad491e45e3941a0c10d6e/time_frequency_mixed_norm_inverse.ipynb".
The first task is:
Show the evoked response and the residual for gradiometers
Can you write Python code for it?

ylim = dict(grad=[-120, 120])
evoked.pick_types(meg='grad', exclude='bads')
evoked.plot(titles=dict(grad='Evoked Response: Gradiometers'), ylim=ylim,
            proj=True, time_unit='s')

residual.pick_types(meg='grad', exclude='bads')
residual.plot(titles=dict(grad='Residuals: Gradiometers'), ylim=ylim,
              proj=True, time_unit='s')


I am working on the file "0.24/_downloads/c4c1adf6983ad491e45e3941a0c10d6e/time_frequency_mixed_norm_inverse.ipynb".
The first task is:
View in 2D and 3D ("glass" brain like 3D plot)
Can you write Python code for it?

plot_sparse_source_estimates(forward['src'], stc, bgcolor=(1, 1, 1),
                             opacity=0.1, fig_name="TF-MxNE (cond %s)"
                             % condition, modes=['sphere'], scale_factors=[1.])

time_label = 'TF-MxNE time=%0.2f ms'
clim = dict(kind='value', lims=[10e-9, 15e-9, 20e-9])
brain = stc.plot('sample', 'inflated', 'rh', views='medial',
                 clim=clim, time_label=time_label, smoothing_steps=5,
                 subjects_dir=subjects_dir, initial_time=150, time_unit='ms')
brain.add_label("V1", color="yellow", scalar_thresh=.5, borders=True)
brain.add_label("V2", color="red", scalar_thresh=.5, borders=True)


I am working on the file "0.24/_downloads/c69e0120935518121b8298ecac72eed8/35_dipole_orientations.ipynb".
The first task is:
Discarding dipole orientation information
Often, further analysis of the data does not need information about the
orientation of the dipoles, but rather their magnitudes. The pick_ori
parameter of the :func:mne.minimum_norm.apply_inverse function allows you
to specify whether to return the full vector solution ('vector') or
rather the magnitude of the vectors (None, the default) or only the
activity in the direction perpendicular to the cortex ('normal').
Can you write Python code for it?

# Only retain vector magnitudes
stc = apply_inverse(left_auditory, inv, pick_ori=None)

# Visualize it at the moment of peak activity
_, time_max = stc.get_peak(hemi='lh')
brain = stc.plot(surface='white', subjects_dir=subjects_dir,
                 initial_time=time_max, time_unit='s', size=(600, 400))
mne.viz.set_3d_view(figure=brain, focalpoint=(0., 0., 50))


I am working on the file "0.24/_downloads/c69e0120935518121b8298ecac72eed8/35_dipole_orientations.ipynb".
The first task is:
Fixed dipole orientations
While the source space defines the position of the dipoles, the inverse
operator defines the possible orientations of them. One of the options is to
assign a fixed orientation. Since the neural currents from which MEG and EEG
signals originate flows mostly perpendicular to the cortex
:footcite:HamalainenEtAl1993, restricting the orientation of the dipoles
accordingly places a useful restriction on the source estimate.
By specifying fixed=True when calling
:func:mne.minimum_norm.make_inverse_operator, the dipole orientations are
fixed to be orthogonal to the surface of the cortex, pointing outwards. Let's
visualize this:
Can you write Python code for it?

fig = mne.viz.create_3d_figure(size=(600, 400))

# Plot the cortex
mne.viz.plot_alignment(
    subject=subject, subjects_dir=subjects_dir, trans=trans,
    surfaces='white', coord_frame='head', fig=fig)

# Show the dipoles as arrows pointing along the surface normal
mne.viz.plot_dipole_locations(
    dipoles=dipoles, trans=trans, mode='arrow', subject=subject,
    subjects_dir=subjects_dir, coord_frame='head', scale=7e-4, fig=fig)

mne.viz.set_3d_view(figure=fig, azimuth=180, distance=0.1)


I am working on the file "0.24/_downloads/c69e0120935518121b8298ecac72eed8/35_dipole_orientations.ipynb".
The first task is:
Limiting orientations, but not fixing them
Often, the best results will be obtained by allowing the dipoles to have
somewhat free orientation, but not stray too far from a orientation that is
perpendicular to the cortex. The loose parameter of the
:func:mne.minimum_norm.make_inverse_operator allows you to specify a value
between 0 (fixed) and 1 (unrestricted or "free") to indicate the amount the
orientation is allowed to deviate from the surface normal.
Can you write Python code for it?

# Set loose to 0.2, the default value
inv = make_inverse_operator(left_auditory.info, fwd, noise_cov, fixed=False,
                            loose=0.2)
stc = apply_inverse(left_auditory, inv, pick_ori='vector')

# Visualize it at the moment of peak activity.
_, time_max = stc.magnitude().get_peak(hemi='lh')
brain_loose = stc.plot(subjects_dir=subjects_dir, initial_time=time_max,
                       time_unit='s', size=(600, 400), overlay_alpha=0)
mne.viz.set_3d_view(figure=brain_loose, focalpoint=(0., 0., 50))


I am working on the file "0.24/_downloads/c69e0120935518121b8298ecac72eed8/35_dipole_orientations.ipynb".
The first task is:
The direction of the estimated current is now restricted to two directions:
inward and outward. In the plot, blue areas indicate current flowing inwards
and red areas indicate current flowing outwards. Given the curvature of the
cortex, groups of dipoles tend to point in the same direction: the direction
of the electromagnetic field picked up by the sensors.
Loose dipole orientations
Forcing the source dipoles to be strictly orthogonal to the cortex makes the
source estimate sensitive to the spacing of the dipoles along the cortex,
since the curvature of the cortex changes within each ~10 square mm patch.
Furthermore, misalignment of the MEG/EEG and MRI coordinate frames is more
critical when the source dipole orientations are strictly constrained
:footcite:LinEtAl2006. To lift the restriction on the orientation of the
dipoles, the inverse operator has the ability to place not one, but three
dipoles at each location defined by the source space. These three dipoles are
placed orthogonally to form a Cartesian coordinate system. Let's visualize
this:
Can you write Python code for it?

fig = mne.viz.create_3d_figure(size=(600, 400))

# Plot the cortex
mne.viz.plot_alignment(
    subject=subject, subjects_dir=subjects_dir, trans=trans,
    surfaces='white', coord_frame='head', fig=fig)

# Show the three dipoles defined at each location in the source space
mne.viz.plot_alignment(
    subject=subject, subjects_dir=subjects_dir, trans=trans, fwd=fwd,
    surfaces='white', coord_frame='head', fig=fig)

mne.viz.set_3d_view(figure=fig, azimuth=180, distance=0.1)


I am working on the file "0.24/_downloads/c69e0120935518121b8298ecac72eed8/35_dipole_orientations.ipynb".
The first task is:
The source space
Let's start by examining the source space as constructed by the
:func:mne.setup_source_space function. Dipoles are placed along fixed
intervals on the cortex, determined by the spacing parameter. The source
space does not define the orientation for these dipoles.
Can you write Python code for it?

lh = fwd['src'][0]  # Visualize the left hemisphere
verts = lh['rr']  # The vertices of the source space
tris = lh['tris']  # Groups of three vertices that form triangles
dip_pos = lh['rr'][lh['vertno']]  # The position of the dipoles
dip_ori = lh['nn'][lh['vertno']]
dip_len = len(dip_pos)
dip_times = [0]
white = (1.0, 1.0, 1.0)  # RGB values for a white color

actual_amp = np.ones(dip_len)  # misc amp to create Dipole instance
actual_gof = np.ones(dip_len)  # misc GOF to create Dipole instance
dipoles = mne.Dipole(dip_times, dip_pos, actual_amp, dip_ori, actual_gof)
trans = mne.read_trans(trans_fname)

fig = mne.viz.create_3d_figure(size=(600, 400), bgcolor=white)
coord_frame = 'mri'

# Plot the cortex
mne.viz.plot_alignment(
    subject=subject, subjects_dir=subjects_dir, trans=trans, surfaces='white',
    coord_frame=coord_frame, fig=fig)

# Mark the position of the dipoles with small red dots
mne.viz.plot_dipole_locations(
    dipoles=dipoles, trans=trans, mode='sphere', subject=subject,
    subjects_dir=subjects_dir, coord_frame=coord_frame, scale=7e-4, fig=fig)

mne.viz.set_3d_view(figure=fig, azimuth=180, distance=0.25)


I am working on the file "0.24/_downloads/c6baf7c1a2f53fda44e93271b91f45b8/50_beamformer_lcmv.ipynb".
The first task is:
Apply the spatial filter
The spatial filter can be applied to different data types: raw, epochs,
evoked data or the data covariance matrix to gain a static image of power.
The function to apply the spatial filter to :class:~mne.Evoked data is
:func:~mne.beamformer.apply_lcmv which is
what we will use here. The other functions are
:func:~mne.beamformer.apply_lcmv_raw,
:func:~mne.beamformer.apply_lcmv_epochs, and
:func:~mne.beamformer.apply_lcmv_cov.
Can you write Python code for it?

stc = apply_lcmv(evoked, filters, max_ori_out='signed')
stc_vec = apply_lcmv(evoked, filters_vec, max_ori_out='signed')
del filters, filters_vec


I am working on the file "0.24/_downloads/c6baf7c1a2f53fda44e93271b91f45b8/50_beamformer_lcmv.ipynb".
The first task is:
Computing the covariance matrices
Spatial filters use the data covariance to estimate the filter
weights. The data covariance matrix will be inverted_ during the spatial
filter computation, so it is valuable to plot the covariance matrix and its
eigenvalues to gauge whether matrix inversion will be possible.
Also, because we want to combine different channel types (magnetometers and
gradiometers), we need to account for the different amplitude scales of these
channel types. To do this we will supply a noise covariance matrix to the
beamformer, which will be used for whitening.
The data covariance matrix should be estimated from a time window that
includes the brain signal of interest,
and incorporate enough samples for a stable estimate. A rule of thumb is to
use more samples than there are channels in the data set; see
:footcite:BrookesEtAl2008 for more detailed advice on covariance estimation
for beamformers. Here, we use a time
window incorporating the expected auditory response at around 100 ms post
stimulus and extend the period to account for a low number of trials (72) and
low sampling rate of 150 Hz.
Can you write Python code for it?

data_cov = mne.compute_covariance(epochs, tmin=0.01, tmax=0.25,
                                  method='empirical')
noise_cov = mne.compute_covariance(epochs, tmin=tmin, tmax=0,
                                   method='empirical')
data_cov.plot(epochs.info)
del epochs


I am working on the file "0.24/_downloads/c6baf7c1a2f53fda44e93271b91f45b8/50_beamformer_lcmv.ipynb".
The first task is:
Handling depth bias
The forward model solution is inherently biased toward superficial sources.
When analyzing single conditions it is best to mitigate the depth bias
somehow. There are several ways to do this:

:func:mne.beamformer.make_lcmv has a depth parameter that normalizes
  the forward model prior to computing the spatial filters. See the docstring
  for details.
Unit-noise gain beamformers handle depth bias by normalizing the
  weights of the spatial filter. Choose this by setting
  weight_norm='unit-noise-gain'.
When computing the Neural activity index, the depth bias is handled by
  normalizing both the weights and the estimated noise (see
  :footcite:VanVeenEtAl1997). Choose this by setting weight_norm='nai'.

Note that when comparing conditions, the depth bias will cancel out and it is
possible to set both parameters to None.
Compute the spatial filter
Now we can compute the spatial filter. We'll use a unit-noise gain beamformer
to deal with depth bias, and will also optimize the orientation of the
sources such that output power is maximized.
This is achieved by setting pick_ori='max-power'.
This gives us one source estimate per source (i.e., voxel), which is known
as a scalar beamformer.
Can you write Python code for it?

filters = make_lcmv(evoked.info, forward, data_cov, reg=0.05,
                    noise_cov=noise_cov, pick_ori='max-power',
                    weight_norm='unit-noise-gain', rank=None)

# You can save the filter for later use with:
# filters.save('filters-lcmv.h5')


I am working on the file "0.24/_downloads/c6baf7c1a2f53fda44e93271b91f45b8/50_beamformer_lcmv.ipynb".
The first task is:
It is also possible to compute a vector beamformer, which gives back three
estimates per voxel, corresponding to the three direction components of the
source. This can be achieved by setting
pick_ori='vector' and will yield a :class:volume vector source estimate
<mne.VolVectorSourceEstimate>. So we will compute another set of filters
using the vector beamformer approach:
Can you write Python code for it?

filters_vec = make_lcmv(evoked.info, forward, data_cov, reg=0.05,
                        noise_cov=noise_cov, pick_ori='vector',
                        weight_norm='unit-noise-gain', rank=None)
# save a bit of memory
src = forward['src']
del forward


I am working on the file "0.24/_downloads/c6baf7c1a2f53fda44e93271b91f45b8/50_beamformer_lcmv.ipynb".
The first task is:
On MNI glass brain (orthoview; 2D)
Can you write Python code for it?

stc.plot(mode='glass_brain', clim=dict(kind='value', lims=lims), **kwargs)


I am working on the file "0.24/_downloads/c6baf7c1a2f53fda44e93271b91f45b8/50_beamformer_lcmv.ipynb".
The first task is:
Source reconstruction using an LCMV beamformer
This tutorial gives an overview of the beamformer method
and shows how to reconstruct source activity using an LCMV beamformer.
Can you write Python code for it?

# Authors: Britta Westner <britta.wstnr@gmail.com>
#          Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause

import matplotlib.pyplot as plt
import mne
from mne.datasets import sample, fetch_fsaverage
from mne.beamformer import make_lcmv, apply_lcmv


I am working on the file "0.24/_downloads/c7633c38a703b9d0a626a5a4fa161026/psf_ctf_label_leakage.ipynb".
The first task is:
Compute point-spread function summaries (PCA) for all labels
We summarise the PSFs per label by their first five principal components, and
use the first component to evaluate label-to-label leakage below.
Can you write Python code for it?

# Compute first PCA component across PSFs within labels.
# Note the differences in explained variance, probably due to different
# spatial extents of labels.
n_comp = 5
stcs_psf_mne, pca_vars_mne = get_point_spread(
    rm_mne, src, labels, mode='pca', n_comp=n_comp, norm=None,
    return_pca_vars=True)
n_verts = rm_mne.shape[0]
del rm_mne


I am working on the file "0.24/_downloads/c7633c38a703b9d0a626a5a4fa161026/psf_ctf_label_leakage.ipynb".
The first task is:
Load forward solution and inverse operator
We need a matching forward solution and inverse operator to compute
resolution matrices for different methods.
Can you write Python code for it?

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-fixed-inv.fif'
forward = mne.read_forward_solution(fname_fwd)
# Convert forward solution to fixed source orientations
mne.convert_forward_solution(
    forward, surf_ori=True, force_fixed=True, copy=False)
inverse_operator = read_inverse_operator(fname_inv)

# Compute resolution matrices for MNE
rm_mne = make_inverse_resolution_matrix(forward, inverse_operator,
                                        method='MNE', lambda2=1. / 3.**2)
src = inverse_operator['src']
del forward, inverse_operator  # save memory


I am working on the file "0.24/_downloads/c7633c38a703b9d0a626a5a4fa161026/psf_ctf_label_leakage.ipynb".
The first task is:
Read and organise labels for cortical parcellation
Get labels for FreeSurfer 'aparc' cortical parcellation with 34 labels/hemi
Can you write Python code for it?

labels = mne.read_labels_from_annot('sample', parc='aparc',
                                    subjects_dir=subjects_dir)
n_labels = len(labels)
label_colors = [label.color for label in labels]
# First, we reorder the labels based on their location in the left hemi
label_names = [label.name for label in labels]
lh_labels = [name for name in label_names if name.endswith('lh')]

# Get the y-location of the label
label_ypos = list()
for name in lh_labels:
    idx = label_names.index(name)
    ypos = np.mean(labels[idx].pos[:, 1])
    label_ypos.append(ypos)

# Reorder the labels based on their location
lh_labels = [label for (yp, label) in sorted(zip(label_ypos, lh_labels))]

# For the right hemi
rh_labels = [label[:-2] + 'rh' for label in lh_labels]


I am working on the file "0.24/_downloads/c7633c38a703b9d0a626a5a4fa161026/psf_ctf_label_leakage.ipynb".
The first task is:
The output shows the summed variance explained by the first five principal
components as well as the explained variances of the individual components.
Evaluate leakage based on label-to-label PSF correlations
Note that correlations ignore the overall amplitude of PSFs, i.e. they do
not show which region will potentially be the bigger "leaker".
Can you write Python code for it?

# get PSFs from Source Estimate objects into matrix
psfs_mat = np.zeros([n_labels, n_verts])
# Leakage matrix for MNE, get first principal component per label
for [i, s] in enumerate(stcs_psf_mne):
    psfs_mat[i, :] = s.data[:, 0]
# Compute label-to-label leakage as Pearson correlation of PSFs
# Sign of correlation is arbitrary, so take absolute values
leakage_mne = np.abs(np.corrcoef(psfs_mat))

# Save the plot order and create a circular layout
node_order = lh_labels[::-1] + rh_labels  # mirror label order across hemis
node_angles = circular_layout(label_names, node_order, start_pos=90,
                              group_boundaries=[0, len(label_names) / 2])
# Plot the graph using node colors from the FreeSurfer parcellation. We only
# show the 200 strongest connections.
fig = plt.figure(num=None, figsize=(8, 8), facecolor='black')
plot_connectivity_circle(leakage_mne, label_names, n_lines=200,
                         node_angles=node_angles, node_colors=label_colors,
                         title='MNE Leakage', fig=fig)


I am working on the file "0.24/_downloads/c7633c38a703b9d0a626a5a4fa161026/psf_ctf_label_leakage.ipynb".
The first task is:
We can show the explained variances of principal components per label. Note
how they differ across labels, most likely due to their varying spatial
extent.
Can you write Python code for it?

with np.printoptions(precision=1):
    for [name, var] in zip(label_names, pca_vars_mne):
        print(f'{name}: {var.sum():.1f}% {var}')