本文整理汇总了Python中mne.label.read_labels_from_annot函数的典型用法代码示例。如果您正苦于以下问题:Python read_labels_from_annot函数的具体用法?Python read_labels_from_annot怎么用?Python read_labels_from_annot使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了read_labels_from_annot函数的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_stc_methods
def test_stc_methods():
"""Test stc methods lh_data, rh_data, bin, center_of_mass, resample"""
stc = read_source_estimate(fname_stc)
# lh_data / rh_data
assert_array_equal(stc.lh_data, stc.data[:len(stc.lh_vertno)])
assert_array_equal(stc.rh_data, stc.data[len(stc.lh_vertno):])
# bin
bin = stc.bin(.12)
a = np.array((1,), dtype=stc.data.dtype)
a[0] = np.mean(stc.data[0, stc.times < .12])
assert a[0] == bin.data[0, 0]
assert_raises(ValueError, stc.center_of_mass, 'sample')
assert_raises(TypeError, stc.center_of_mass, 'sample',
subjects_dir=subjects_dir, surf=1)
stc.lh_data[:] = 0
vertex, hemi, t = stc.center_of_mass('sample', subjects_dir=subjects_dir)
assert_true(hemi == 1)
# XXX Should design a fool-proof test case, but here were the results:
assert_equal(vertex, 124791)
assert_equal(np.round(t, 2), 0.12)
stc = read_source_estimate(fname_stc)
stc.subject = 'sample'
label_lh = read_labels_from_annot('sample', 'aparc', 'lh',
subjects_dir=subjects_dir)[0]
label_rh = read_labels_from_annot('sample', 'aparc', 'rh',
subjects_dir=subjects_dir)[0]
label_both = label_lh + label_rh
for label in (label_lh, label_rh, label_both):
assert_true(isinstance(stc.shape, tuple) and len(stc.shape) == 2)
stc_label = stc.in_label(label)
if label.hemi != 'both':
if label.hemi == 'lh':
verts = stc_label.vertices[0]
else: # label.hemi == 'rh':
verts = stc_label.vertices[1]
n_vertices_used = len(label.get_vertices_used(verts))
assert_equal(len(stc_label.data), n_vertices_used)
stc_lh = stc.in_label(label_lh)
assert_raises(ValueError, stc_lh.in_label, label_rh)
label_lh.subject = 'foo'
assert_raises(RuntimeError, stc.in_label, label_lh)
stc_new = deepcopy(stc)
o_sfreq = 1.0 / stc.tstep
# note that using no padding for this STC reduces edge ringing...
stc_new.resample(2 * o_sfreq, npad=0, n_jobs=2)
assert_true(stc_new.data.shape[1] == 2 * stc.data.shape[1])
assert_true(stc_new.tstep == stc.tstep / 2)
stc_new.resample(o_sfreq, npad=0)
assert_true(stc_new.data.shape[1] == stc.data.shape[1])
assert_true(stc_new.tstep == stc.tstep)
assert_array_almost_equal(stc_new.data, stc.data, 5)
示例2: test_stc_methods
def test_stc_methods():
"""Test stc methods lh_data, rh_data, bin(), resample()."""
stc_ = read_source_estimate(fname_stc)
# Make a vector version of the above source estimate
x = stc_.data[:, np.newaxis, :]
yz = np.zeros((x.shape[0], 2, x.shape[2]))
vec_stc_ = VectorSourceEstimate(
np.concatenate((x, yz), 1),
stc_.vertices, stc_.tmin, stc_.tstep, stc_.subject
)
for stc in [stc_, vec_stc_]:
# lh_data / rh_data
assert_array_equal(stc.lh_data, stc.data[:len(stc.lh_vertno)])
assert_array_equal(stc.rh_data, stc.data[len(stc.lh_vertno):])
# bin
binned = stc.bin(.12)
a = np.mean(stc.data[..., :np.searchsorted(stc.times, .12)], axis=-1)
assert_array_equal(a, binned.data[..., 0])
stc = read_source_estimate(fname_stc)
stc.subject = 'sample'
label_lh = read_labels_from_annot('sample', 'aparc', 'lh',
subjects_dir=subjects_dir)[0]
label_rh = read_labels_from_annot('sample', 'aparc', 'rh',
subjects_dir=subjects_dir)[0]
label_both = label_lh + label_rh
for label in (label_lh, label_rh, label_both):
assert (isinstance(stc.shape, tuple) and len(stc.shape) == 2)
stc_label = stc.in_label(label)
if label.hemi != 'both':
if label.hemi == 'lh':
verts = stc_label.vertices[0]
else: # label.hemi == 'rh':
verts = stc_label.vertices[1]
n_vertices_used = len(label.get_vertices_used(verts))
assert_equal(len(stc_label.data), n_vertices_used)
stc_lh = stc.in_label(label_lh)
pytest.raises(ValueError, stc_lh.in_label, label_rh)
label_lh.subject = 'foo'
pytest.raises(RuntimeError, stc.in_label, label_lh)
stc_new = deepcopy(stc)
o_sfreq = 1.0 / stc.tstep
# note that using no padding for this STC reduces edge ringing...
stc_new.resample(2 * o_sfreq, npad=0, n_jobs=2)
assert (stc_new.data.shape[1] == 2 * stc.data.shape[1])
assert (stc_new.tstep == stc.tstep / 2)
stc_new.resample(o_sfreq, npad=0)
assert (stc_new.data.shape[1] == stc.data.shape[1])
assert (stc_new.tstep == stc.tstep)
assert_array_almost_equal(stc_new.data, stc.data, 5)
示例3: test_spatial_inter_hemi_connectivity
def test_spatial_inter_hemi_connectivity():
"""Test spatial connectivity between hemispheres"""
# trivial cases
conn = spatial_inter_hemi_connectivity(fname_src_3, 5e-6)
assert_equal(conn.data.size, 0)
conn = spatial_inter_hemi_connectivity(fname_src_3, 5e6)
assert_equal(conn.data.size, np.prod(conn.shape) // 2)
# actually interesting case (1cm), should be between 2 and 10% of verts
src = read_source_spaces(fname_src_3)
conn = spatial_inter_hemi_connectivity(src, 10e-3)
conn = conn.tocsr()
n_src = conn.shape[0]
assert_true(n_src * 0.02 < conn.data.size < n_src * 0.10)
assert_equal(conn[:src[0]['nuse'], :src[0]['nuse']].data.size, 0)
assert_equal(conn[-src[1]['nuse']:, -src[1]['nuse']:].data.size, 0)
c = (conn.T + conn) / 2. - conn
c.eliminate_zeros()
assert_equal(c.data.size, 0)
# check locations
upper_right = conn[:src[0]['nuse'], src[0]['nuse']:].toarray()
assert_equal(upper_right.sum(), conn.sum() // 2)
good_labels = ['S_pericallosal', 'Unknown', 'G_and_S_cingul-Mid-Post',
'G_cuneus']
for hi, hemi in enumerate(('lh', 'rh')):
has_neighbors = src[hi]['vertno'][np.where(np.any(upper_right,
axis=1 - hi))[0]]
labels = read_labels_from_annot('sample', 'aparc.a2009s', hemi,
subjects_dir=subjects_dir)
use_labels = [l.name[:-3] for l in labels
if np.in1d(l.vertices, has_neighbors).any()]
assert_true(set(use_labels) - set(good_labels) == set())
示例4: convert_label2label
def convert_label2label(annot_fname, subjects_list, srcsubject='fsaverage',
subjects_dir=None, freesurfer_home=None):
'''
Python wrapper for Freesurfer mri_label2label function.
Converts all labels in annot_fname from source subject to target subject
given the subjects directory. Both hemispheres are considered.
The registration method used it surface.
Parameters
----------
annot_fname: str
The name of the annotation (or parcellation).
subjects_list: list or str
Subject names to which the labels have to be transformed to (the target subjects).
Can be provided as a list or a string.
srcsubject: str
The name of the source subject to be used. The source subject should
contain the labels in the correct folders already. Default - fsaverage.
subjects_dir: str
The subjects directory, if not provided, then the
environment value is used.
freesurfer_home: str
The freeesurfer home path, if not provided, the
environment value is used.
Reference:
https://surfer.nmr.mgh.harvard.edu/fswiki/mri_label2label
'''
if subjects_list:
subjects_list = get_files_from_list(subjects_list)
else:
raise RuntimeError('No subjects are specified.')
subjects_dir = check_env_variables(subjects_dir, key='SUBJECTS_DIR')
freesurfer_home = check_env_variables(freesurfer_home, key='FREESURFER_HOME')
freesurfer_bin = os.path.join(freesurfer_home, 'bin', '')
# obtain the names of labels in parcellation
from mne.label import read_labels_from_annot
labels = read_labels_from_annot(srcsubject, parc=annot_fname)
lnames = [l.name.rsplit('-')[0] if l.hemi is 'lh' else '' for l in labels]
lnames = filter(None, lnames) # remove empty strings
# convert the labels from source subject to target subject
from subprocess import call
for subj in subjects_list:
# the target subject is subj provided
print 'Converting labels from %s to %s' % (srcsubject, subj)
for label in lnames:
for hemi in ['lh', 'rh']:
srclabel = os.path.join(subjects_dir, srcsubject, 'label', hemi + '.' + label + '.label')
trglabel = os.path.join(subjects_dir, subj, 'label', hemi + '.' + label + '.label')
retcode = call([freesurfer_bin + 'mri_label2label', '--srclabel', srclabel, '--srcsubject', srcsubject,
'--trglabel', trglabel, '--trgsubject', subj, '--regmethod', 'surface', '--hemi', hemi])
if retcode != 0:
retcode_error('mri_label2label')
continue
print 'Labels for %d subjects have been transformed from source %s' %(len(subjects_list), srcsubject)
示例5: test_expand
def test_expand():
"""Test stc expansion
"""
stc = read_source_estimate(fname, 'sample')
assert_true('sample' in repr(stc))
labels_lh = read_labels_from_annot('sample', 'aparc', 'lh',
subjects_dir=subjects_dir)
stc_limited = stc.in_label(labels_lh[0] + labels_lh[1])
stc_new = stc_limited.copy()
stc_new.data.fill(0)
for label in labels_lh[:2]:
stc_new += stc.in_label(label).expand(stc_limited.vertno)
# make sure we can't add unless vertno agree
assert_raises(ValueError, stc.__add__, stc.in_label(labels_lh[0]))
示例6: test_stc_methods
def test_stc_methods():
"""Test stc methods lh_data, rh_data, bin(), center_of_mass(), resample()
"""
fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg')
stc = read_source_estimate(fname)
# lh_data / rh_data
assert_array_equal(stc.lh_data, stc.data[:len(stc.lh_vertno)])
assert_array_equal(stc.rh_data, stc.data[len(stc.lh_vertno):])
# bin
bin = stc.bin(.12)
a = np.array((1,), dtype=stc.data.dtype)
a[0] = np.mean(stc.data[0, stc.times < .12])
assert a[0] == bin.data[0, 0]
assert_raises(ValueError, stc.center_of_mass, 'sample')
stc.lh_data[:] = 0
vertex, hemi, t = stc.center_of_mass('sample', subjects_dir=subjects_dir)
assert_true(hemi == 1)
# XXX Should design a fool-proof test case, but here were the results:
assert_true(vertex == 90186)
assert_true(np.round(t, 3) == 0.123)
stc = read_source_estimate(fname)
label = read_labels_from_annot('sample', 'aparc', 'lh',
subjects_dir=subjects_dir)[0]
stc_label = stc.in_label(label)
n_vertices_used = len(label.get_vertices_used(stc_label.vertno[0]))
assert_equal(len(stc_label.data), n_vertices_used)
stc_new = deepcopy(stc)
o_sfreq = 1.0 / stc.tstep
# note that using no padding for this STC reduces edge ringing...
stc_new.resample(2 * o_sfreq, npad=0, n_jobs=2)
assert_true(stc_new.data.shape[1] == 2 * stc.data.shape[1])
assert_true(stc_new.tstep == stc.tstep / 2)
stc_new.resample(o_sfreq, npad=0)
assert_true(stc_new.data.shape[1] == stc.data.shape[1])
assert_true(stc_new.tstep == stc.tstep)
assert_array_almost_equal(stc_new.data, stc.data, 5)
示例7: test_expand
def test_expand():
"""Test stc expansion."""
stc_ = read_source_estimate(fname_stc, 'sample')
vec_stc_ = VectorSourceEstimate(np.zeros((stc_.data.shape[0], 3,
stc_.data.shape[1])),
stc_.vertices, stc_.tmin, stc_.tstep,
stc_.subject)
for stc in [stc_, vec_stc_]:
assert ('sample' in repr(stc))
labels_lh = read_labels_from_annot('sample', 'aparc', 'lh',
subjects_dir=subjects_dir)
new_label = labels_lh[0] + labels_lh[1]
stc_limited = stc.in_label(new_label)
stc_new = stc_limited.copy()
stc_new.data.fill(0)
for label in labels_lh[:2]:
stc_new += stc.in_label(label).expand(stc_limited.vertices)
pytest.raises(TypeError, stc_new.expand, stc_limited.vertices[0])
pytest.raises(ValueError, stc_new.expand, [stc_limited.vertices[0]])
# make sure we can't add unless vertno agree
pytest.raises(ValueError, stc.__add__, stc.in_label(labels_lh[0]))
示例8: test_extract_label_time_course
def test_extract_label_time_course():
"""Test extraction of label time courses from stc
"""
n_stcs = 3
n_times = 50
src = read_inverse_operator(fname_inv)['src']
vertices = [src[0]['vertno'], src[1]['vertno']]
n_verts = len(vertices[0]) + len(vertices[1])
# get some labels
labels_lh = read_labels_from_annot('sample', hemi='lh',
subjects_dir=subjects_dir)
labels_rh = read_labels_from_annot('sample', hemi='rh',
subjects_dir=subjects_dir)
labels = list()
labels.extend(labels_lh[:5])
labels.extend(labels_rh[:4])
n_labels = len(labels)
label_means = np.arange(n_labels)[:, None] * np.ones((n_labels, n_times))
label_maxs = np.arange(n_labels)[:, None] * np.ones((n_labels, n_times))
# compute the mean with sign flip
label_means_flipped = np.zeros_like(label_means)
for i, label in enumerate(labels):
label_means_flipped[i] = i * np.mean(label_sign_flip(label, src))
# generate some stc's with known data
stcs = list()
for i in range(n_stcs):
data = np.zeros((n_verts, n_times))
# set the value of the stc within each label
for j, label in enumerate(labels):
if label.hemi == 'lh':
idx = np.intersect1d(vertices[0], label.vertices)
idx = np.searchsorted(vertices[0], idx)
elif label.hemi == 'rh':
idx = np.intersect1d(vertices[1], label.vertices)
idx = len(vertices[0]) + np.searchsorted(vertices[1], idx)
data[idx] = label_means[j]
this_stc = SourceEstimate(data, vertices, 0, 1)
stcs.append(this_stc)
# test some invalid inputs
assert_raises(ValueError, extract_label_time_course, stcs, labels,
src, mode='notamode')
# have an empty label
empty_label = labels[0].copy()
empty_label.vertices += 1000000
assert_raises(ValueError, extract_label_time_course, stcs, empty_label,
src, mode='mean')
# but this works:
with warnings.catch_warnings(record=True): # empty label
tc = extract_label_time_course(stcs, empty_label, src, mode='mean',
allow_empty=True)
for arr in tc:
assert_true(arr.shape == (1, n_times))
assert_array_equal(arr, np.zeros((1, n_times)))
# test the different modes
modes = ['mean', 'mean_flip', 'pca_flip', 'max']
for mode in modes:
label_tc = extract_label_time_course(stcs, labels, src, mode=mode)
label_tc_method = [stc.extract_label_time_course(labels, src,
mode=mode) for stc in stcs]
assert_true(len(label_tc) == n_stcs)
assert_true(len(label_tc_method) == n_stcs)
for tc1, tc2 in zip(label_tc, label_tc_method):
assert_true(tc1.shape == (n_labels, n_times))
assert_true(tc2.shape == (n_labels, n_times))
assert_true(np.allclose(tc1, tc2, rtol=1e-8, atol=1e-16))
if mode == 'mean':
assert_array_almost_equal(tc1, label_means)
if mode == 'mean_flip':
assert_array_almost_equal(tc1, label_means_flipped)
if mode == 'max':
assert_array_almost_equal(tc1, label_maxs)
# test label with very few vertices (check SVD conditionals)
label = Label(vertices=src[0]['vertno'][:2], hemi='lh')
x = label_sign_flip(label, src)
assert_true(len(x) == 2)
label = Label(vertices=[], hemi='lh')
x = label_sign_flip(label, src)
assert_true(x.size == 0)