Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
#
# 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.
stc.plot(subjects_dir=subjects_dir, initial_time=initial_time,
backend='matplotlib', verbose='error')
###############################################################################
#
# 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.
evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
evoked.pick_types(meg=True, eeg=False)
###############################################################################
# Then, we can load the precomputed inverse operator from a file.
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-vol-7-meg-inv.fif'
inv = read_inverse_operator(fname_inv)
src = inv['src']
###############################################################################
# The source estimate is computed using the inverse operator and the
# sensor-space data.
snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM" # use dSPM method (could also be MNE or sLORETA)
stc = apply_inverse(evoked, inv, lambda2, method)
stc.crop(0.0, 0.2)
def calc_sub_cortical_activity(events_id, evoked_fn, inv_fn, sub_corticals_codes_file, baseline_min_t=None,
baseline_max_t = 0, snr = 3.0, inverse_method='dSPM'):
sub_corticals = read_sub_corticals_code_file(sub_corticals_codes_file)
if len(sub_corticals) == 0:
return
lambda2 = 1.0 / snr ** 2
lut = read_freesurfer_lookup_table(FREESURFER_HOME)
for cond in events_id.keys():
evo = evoked_fn.format(cond=cond)
evoked = {event:mne.read_evokeds(evo, baseline=(baseline_min_t, baseline_max_t))[0] for event in [event]}
inverse_operator = read_inverse_operator(inv_fn.format(cond=cond))
stc = apply_inverse(evoked[cond], inverse_operator, lambda2, inverse_method)
read_vertices_from = len(stc.vertices[0])+len(stc.vertices[1])
sub_corticals_activity = {}
for sub_cortical_ind, sub_cortical_code in enumerate(sub_corticals):
# +2 becasue the first two are the hemispheres
sub_corticals_activity[sub_cortical_code] = stc.data[
read_vertices_from: read_vertices_from + len(stc.vertices[sub_cortical_ind + 2])]
read_vertices_from += len(stc.vertices[sub_cortical_ind + 2])
if not os.path.isdir:
os.mkdir(os.path.join(SUBJECT_MEG_FOLDER, 'subcorticals'))
for sub_cortical_code, activity in sub_corticals_activity.iteritems():
sub_cortical, _ = get_numeric_index_to_label(sub_cortical_code, lut)
np.save(os.path.join(SUBJECT_MEG_FOLDER, 'subcorticals', '{}-{}-{}'.format(cond, sub_cortical, inverse_method)), activity.mean(0))
np.save(os.path.join(SUBJECT_MEG_FOLDER, 'subcorticals', '{}-{}-{}-all-vertices'.format(cond, sub_cortical, inverse_method)), activity)
msg = f'Input: {fname_evoked}, Output: {fname_fwd}'
logger.info(gen_log_message(message=msg, step=10, subject=subject,
session=session))
# Find the raw data file
trans = get_head_mri_trans(
bids_basename=(bids_basename.copy()
.update(run=config.get_runs()[0], prefix=None)),
bids_root=config.bids_root)
mne.write_trans(fname_trans, trans)
src = mne.setup_source_space(subject, spacing=config.spacing,
subjects_dir=config.get_fs_subjects_dir(),
add_dist=False)
evoked = mne.read_evokeds(fname_evoked, condition=0)
# Here we only use 3-layers BEM only if EEG is available.
if 'eeg' in config.ch_types:
model = mne.make_bem_model(subject, ico=4,
conductivity=(0.3, 0.006, 0.3),
subjects_dir=config.get_fs_subjects_dir())
else:
model = mne.make_bem_model(subject, ico=4, conductivity=(0.3,),
subjects_dir=config.get_fs_subjects_dir())
bem = mne.make_bem_solution(model)
fwd = mne.make_forward_solution(evoked.info, trans, src, bem,
mindist=config.mindist)
mne.write_forward_solution(fname_fwd, fwd, overwrite=True)
def read_vars(events_id, region, read_csd=True):
for event in events_id.keys():
forward, noise_csd, data_csd = None, None, None
if not region is None:
forward = mne.read_forward_solution(get_cond_fname(FWD_X, event, region=region)) #, surf_ori=True)
epochs = mne.read_epochs(get_cond_fname(EPO, event))
evoked = mne.read_evokeds(get_cond_fname(EVO, event), baseline=(None, 0))[0]
noise_cov = calc_cov(get_cond_fname(DATA_COV, event), event, epochs, None, 0)
data_cov = calc_cov(get_cond_fname(NOISE_COV, event), event, epochs, 0.0, 1.0)
if read_csd:
noise_csd = calc_csd(NOISE_CSD, event, epochs, -0.5, 0., mode='multitaper', fmin=6, fmax=10, overwrite=False)
data_csd = calc_csd(DATA_CSD, event, epochs, 0.0, 1.0, mode='multitaper', fmin=6, fmax=10, overwrite=False)
yield event, forward, evoked, epochs, data_cov, noise_cov, data_csd, noise_csd
See :ref:`inverse_orientation_constrains`
"""
###############################################################################
# Loading data
# ------------
# Load everything we need to perform source localization on the sample dataset.
import mne
import numpy as np
from mne.datasets import sample
from mne.minimum_norm import make_inverse_operator, apply_inverse
data_path = sample.data_path()
evokeds = mne.read_evokeds(data_path + '/MEG/sample/sample_audvis-ave.fif')
left_auditory = evokeds[0].apply_baseline()
fwd = mne.read_forward_solution(
data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif')
mne.convert_forward_solution(fwd, surf_ori=True, copy=False)
noise_cov = mne.read_cov(data_path + '/MEG/sample/sample_audvis-cov.fif')
subject = 'sample'
subjects_dir = data_path + '/subjects'
trans_fname = data_path + '/MEG/sample/sample_audvis_raw-trans.fif'
###############################################################################
# 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.
eve_fname = op.join(subject_dir, 'run_01_filt_sss-eve.fif')
epo_fname = op.join(subject_dir,
'%s_highpass-%sHz-epo.fif' % (subject, l_freq))
events = mne.read_events(eve_fname)
fig = mne.viz.plot_events(events, show=False)
fig.suptitle('Events from run 01')
epochs = mne.read_epochs(epo_fname)
epochs.plot_drop_log()
###############################################################################
# Evoked responses :ref:`sphx_glr_auto_scripts_06-make_evoked.py`
ave_fname = op.join(subject_dir,
'%s_highpass-%sHz-ave.fif' % (subject, l_freq))
evoked = mne.read_evokeds(ave_fname)
###############################################################################
# Faces
famous_evo, scrambled_evo, unfamiliar_evo, contrast_evo, faces_evo = evoked
faces_evo.plot(spatial_colors=True, gfp=True, ylim=ylim,
window_title='Faces %s' % subject)
###############################################################################
# Famous
famous_evo.plot(spatial_colors=True, gfp=True, ylim=ylim,
window_title='Famous %s' % subject)
###############################################################################
# Scrambled
scrambled_evo.plot(spatial_colors=True, gfp=True, ylim=ylim,
window_title='Scrambled %s' % subject)
# Events :ref:`sphx_glr_auto_scripts_02-extract_events.py`.
# Epochs :ref:`sphx_glr_auto_scripts_06-make_epochs.py`.
eve_fname = op.join(subject_dir, 'run_01-eve.fif')
epo_fname = op.join(subject_dir, '%s-tsss_%d-epo.fif' % (subject, st_duration))
events = mne.read_events(eve_fname)
fig = mne.viz.plot_events(events, show=False)
fig.suptitle('Events from run 01')
epochs = mne.read_epochs(epo_fname)
epochs.plot_drop_log()
###############################################################################
# Evoked responses :ref:`sphx_glr_auto_scripts_07-make_evoked.py`
ave_fname = op.join(subject_dir, '%s-tsss_%d-ave.fif' % (subject, st_duration))
evoked = mne.read_evokeds(ave_fname)
famous_evo, scrambled_evo, unfamiliar_evo, contrast_evo, faces_evo = evoked[:5]
###############################################################################
# Faces
faces_evo.plot(spatial_colors=True, gfp=True, ylim=ylim,
window_title='Faces %s' % subject)
###############################################################################
# Famous
famous_evo.plot(spatial_colors=True, gfp=True, ylim=ylim,
window_title='Famous %s' % subject)
###############################################################################
# Scrambled
scrambled_evo.plot(spatial_colors=True, gfp=True, ylim=ylim,
window_title='Scrambled %s' % subject)
def plot_all_files_graph_max(subject, baseline_fnames, event_fname, func_name, bands_names, modality, input_template,
sz_name='', sfreq=None, do_plot=False, overwrite=False):
if sz_name == '':
sz_name = utils.namebase(event_fname)
output_fol = utils.make_dir(op.join(
MMVT_DIR, subject, 'connectivity', '{}_{}'.format(modality, func_name), 'runs', sz_name))
if modality == 'ieeg':
# clip = np.load(event_fname)
t_start, t_end = -5, 5
else:
clip = mne.read_evokeds(event_fname)[0]
sfreq = clip.info['sfreq']
t_start, t_end = clip.times[0], clip.times[-1]
windows_length = 500
half_window = (1 /sfreq) * (windows_length / 2) # In seconds
scores = {}
for band_name in bands_names:
band_fol = utils.make_dir(op.join(MMVT_DIR, subject, 'connectivity', '{}_{}'.format(modality, func_name), band_name))
con_name = '{}_{}_mi'.format(modality, band_name)
figure_name = '{}_{}_{}.jpg'.format(con_name, func_name, sz_name)
output_fname = op.join(output_fol, figure_name)
# if op.isfile(output_fname) and not overwrite:
# print('{} already exist'.format(figure_name))
# continue
all_files_found = True
for fname in baseline_fnames + [event_fname]:
def get_evoked_cond(cond_name, baseline=(None, 0), apply_SSP_projection_vectors=True, add_eeg_ref=True):
evo_fname, evo_found = locating_file(EVO, '*ave.fif')
if not evo_found:
print('get_evoked_cond: No evoked file found!')
return None
if '{cond}' not in evo_fname:
try:
evoked = mne.read_evokeds(evo_fname, condition=cond_name, baseline=baseline)
except:
print('No evoked data with the condition {}'.format(cond_name))
evoked = None
else:
evo_cond = get_cond_fname(evo_fname, cond_name)
if op.isfile(evo_cond):
evoked = mne.read_evokeds(evo_cond, baseline=baseline)[0]
else:
print('No evoked file, trying to use epo file')
epo_fname, epo_found = locating_file(EPO, '*epo.fif')
if not epo_found:
print('No epochs were found!')
return None
if '{cond}' not in epo_fname:
epochs = mne.read_epochs(epo_fname, apply_SSP_projection_vectors, add_eeg_ref)
evoked = epochs[cond_name].average()
from alphacsc.utils import get_uv
from alphacsc.utils.viz import COLORS
data_path = mne.datasets.somato.data_path()
subjects_dir = op.join(data_path, 'subjects')
fname_ave = 'examples_multicsc/atom_multi_somato-ave.fif'
fname_raw = os.path.join(data_path, 'sef_raw_sss.fif')
fname_bem = op.join(subjects_dir, 'somato', 'bem', 'somato-5120-bem-sol.fif')
fname_trans = op.join(data_path, 'MEG', 'somato',
'sef_raw_sss-trans.fif')
fname_surf_lh = op.join(subjects_dir, 'somato', 'surf', 'lh.white')
atom_idx = 4
evoked = mne.read_evokeds(fname_ave, baseline=None)[atom_idx]
evoked.pick_types(meg=True, eeg=False)
epochs = load_data(epoch=True, return_epochs=True)
cov = mne.compute_covariance(epochs)
# Fit a dipole
dip = mne.fit_dipole(evoked, cov, fname_bem, fname_trans)[0]
# Plot the result in 3D brain with the MRI image.
fig = plt.figure(figsize=plt.figaspect(2.))
ax = fig.add_subplot(2, 1, 1, projection='3d')
dip.plot_locations(fname_trans, 'somato', subjects_dir, ax=ax,
mode='orthoview')
best_idx = np.argmax(dip.gof)
best_time = dip.times[best_idx]
ax.set_title('Dipole fit (Highest GOF=%0.1f%%)' % dip.gof[best_idx])