本文整理汇总了Python中mne.read_labels_from_annot函数的典型用法代码示例。如果您正苦于以下问题:Python read_labels_from_annot函数的具体用法?Python read_labels_from_annot怎么用?Python read_labels_from_annot使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了read_labels_from_annot函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_combination_label
def test_combination_label():
"Test combination label creation"
labels = {l.name: l for l in
mne.read_labels_from_annot('fsaverage', subjects_dir=subjects_dir)}
# standard
l = combination_label('temporal', "superiortemporal + middletemporal + inferiortemporal", labels)
lh = labels['superiortemporal-lh'] + labels['middletemporal-lh'] + labels['inferiortemporal-lh']
rh = labels['superiortemporal-rh'] + labels['middletemporal-rh'] + labels['inferiortemporal-rh']
eq_(len(l), 2)
eq_(l[0].name, 'temporal-lh')
eq_(l[1].name, 'temporal-rh')
assert_array_equal(l[0].vertices, lh.vertices)
assert_array_equal(l[1].vertices, rh.vertices)
# only rh
l = combination_label('temporal-rh', "superiortemporal + middletemporal + inferiortemporal", labels)
eq_(len(l), 1)
eq_(l[0].name, 'temporal-rh')
assert_array_equal(l[0].vertices, rh.vertices)
# names with .
labels = {l.name: l for l in
mne.read_labels_from_annot('fsaverage', 'PALS_B12_Brodmann', subjects_dir=subjects_dir)}
l = combination_label('Ba38-lh', "Brodmann.38", labels)[0]
assert_array_equal(l.vertices, labels['Brodmann.38-lh'].vertices)
示例2: test_morph_labels
def test_morph_labels():
"""Test morph_labels."""
# Just process the first 5 labels for speed
parc_fsaverage = read_labels_from_annot(
'fsaverage', 'aparc', subjects_dir=subjects_dir)[:5]
parc_sample = read_labels_from_annot(
'sample', 'aparc', subjects_dir=subjects_dir)[:5]
parc_fssamp = morph_labels(
parc_fsaverage, 'sample', subjects_dir=subjects_dir)
for lf, ls, lfs in zip(parc_fsaverage, parc_sample, parc_fssamp):
assert lf.hemi == ls.hemi == lfs.hemi
assert lf.name == ls.name == lfs.name
perc_1 = np.in1d(lfs.vertices, ls.vertices).mean() * 100
perc_2 = np.in1d(ls.vertices, lfs.vertices).mean() * 100
# Ideally this would be 100%, but we do not use the same algorithm
# as FreeSurfer ...
assert perc_1 > 92
assert perc_2 > 88
with pytest.raises(ValueError, match='wrong and fsaverage'):
morph_labels(parc_fsaverage, 'sample', subjects_dir=subjects_dir,
subject_from='wrong')
with pytest.raises(RuntimeError, match='Number of surface vertices'):
_load_vert_pos('sample', subjects_dir, 'white', 'lh', 1)
for label in parc_fsaverage:
label.subject = None
with pytest.raises(ValueError, match='subject_from must be provided'):
morph_labels(parc_fsaverage, 'sample', subjects_dir=subjects_dir)
示例3: test_read_labels_from_annot
def test_read_labels_from_annot():
"""Test reading labels from FreeSurfer parcellation
"""
# test some invalid inputs
assert_raises(ValueError, read_labels_from_annot, 'sample', hemi='bla',
subjects_dir=subjects_dir)
assert_raises(ValueError, read_labels_from_annot, 'sample',
annot_fname='bla.annot', subjects_dir=subjects_dir)
# read labels using hemi specification
labels_lh = read_labels_from_annot('sample', hemi='lh',
subjects_dir=subjects_dir)
for label in labels_lh:
assert_true(label.name.endswith('-lh'))
assert_true(label.hemi == 'lh')
# XXX fails on 2.6 for some reason...
if sys.version_info[:2] > (2, 6):
assert_is_not(label.color, None)
# read labels using annot_fname
annot_fname = op.join(subjects_dir, 'sample', 'label', 'rh.aparc.annot')
labels_rh = read_labels_from_annot('sample', annot_fname=annot_fname,
subjects_dir=subjects_dir)
for label in labels_rh:
assert_true(label.name.endswith('-rh'))
assert_true(label.hemi == 'rh')
# XXX doesn't work on py26 for some reason
if sys.version_info[:2] > (2, 6):
assert_is_not(label.color, None)
# combine the lh, rh, labels and sort them
labels_lhrh = list()
labels_lhrh.extend(labels_lh)
labels_lhrh.extend(labels_rh)
names = [label.name for label in labels_lhrh]
labels_lhrh = [label for (name, label) in sorted(zip(names, labels_lhrh))]
# read all labels at once
labels_both = read_labels_from_annot('sample', subjects_dir=subjects_dir)
# we have the same result
_assert_labels_equal(labels_lhrh, labels_both)
# aparc has 68 cortical labels
assert_true(len(labels_both) == 68)
# test regexp
label = read_labels_from_annot('sample', parc='aparc.a2009s',
regexp='Angu', subjects_dir=subjects_dir)[0]
assert_true(label.name == 'G_pariet_inf-Angular-lh')
# silly, but real regexp:
label = read_labels_from_annot('sample', 'aparc.a2009s',
regexp='.*-.{4,}_.{3,3}-L',
subjects_dir=subjects_dir)[0]
assert_true(label.name == 'G_oc-temp_med-Lingual-lh')
assert_raises(RuntimeError, read_labels_from_annot, 'sample', parc='aparc',
annot_fname=annot_fname, regexp='JackTheRipper',
subjects_dir=subjects_dir)
示例4: test_read_labels_from_annot
def test_read_labels_from_annot():
"""Test reading labels from FreeSurfer parcellation
"""
# test some invalid inputs
assert_raises(ValueError, read_labels_from_annot, "sample", hemi="bla", subjects_dir=subjects_dir)
assert_raises(ValueError, read_labels_from_annot, "sample", annot_fname="bla.annot", subjects_dir=subjects_dir)
# read labels using hemi specification
labels_lh = read_labels_from_annot("sample", hemi="lh", subjects_dir=subjects_dir)
for label in labels_lh:
assert_true(label.name.endswith("-lh"))
assert_true(label.hemi == "lh")
# XXX fails on 2.6 for some reason...
if sys.version_info[:2] > (2, 6):
assert_is_not(label.color, None)
# read labels using annot_fname
annot_fname = op.join(subjects_dir, "sample", "label", "rh.aparc.annot")
labels_rh = read_labels_from_annot("sample", annot_fname=annot_fname, subjects_dir=subjects_dir)
for label in labels_rh:
assert_true(label.name.endswith("-rh"))
assert_true(label.hemi == "rh")
assert_is_not(label.color, None)
# combine the lh, rh, labels and sort them
labels_lhrh = list()
labels_lhrh.extend(labels_lh)
labels_lhrh.extend(labels_rh)
names = [label.name for label in labels_lhrh]
labels_lhrh = [label for (name, label) in sorted(zip(names, labels_lhrh))]
# read all labels at once
labels_both = read_labels_from_annot("sample", subjects_dir=subjects_dir)
# we have the same result
_assert_labels_equal(labels_lhrh, labels_both)
# aparc has 68 cortical labels
assert_true(len(labels_both) == 68)
# test regexp
label = read_labels_from_annot("sample", parc="aparc.a2009s", regexp="Angu", subjects_dir=subjects_dir)[0]
assert_true(label.name == "G_pariet_inf-Angular-lh")
# silly, but real regexp:
label = read_labels_from_annot("sample", "aparc.a2009s", regexp=".*-.{4,}_.{3,3}-L", subjects_dir=subjects_dir)[0]
assert_true(label.name == "G_oc-temp_med-Lingual-lh")
assert_raises(
RuntimeError,
read_labels_from_annot,
"sample",
parc="aparc",
annot_fname=annot_fname,
regexp="JackTheRipper",
subjects_dir=subjects_dir,
)
示例5: test_annot_io
def test_annot_io():
"""Test I/O from and to *.annot files."""
# copy necessary files from fsaverage to tempdir
tempdir = _TempDir()
subject = 'fsaverage'
label_src = os.path.join(subjects_dir, 'fsaverage', 'label')
surf_src = os.path.join(subjects_dir, 'fsaverage', 'surf')
label_dir = os.path.join(tempdir, subject, 'label')
surf_dir = os.path.join(tempdir, subject, 'surf')
os.makedirs(label_dir)
os.mkdir(surf_dir)
shutil.copy(os.path.join(label_src, 'lh.PALS_B12_Lobes.annot'), label_dir)
shutil.copy(os.path.join(label_src, 'rh.PALS_B12_Lobes.annot'), label_dir)
shutil.copy(os.path.join(surf_src, 'lh.white'), surf_dir)
shutil.copy(os.path.join(surf_src, 'rh.white'), surf_dir)
# read original labels
with pytest.raises(IOError, match='\nPALS_B12_Lobes$'):
read_labels_from_annot(subject, 'PALS_B12_Lobesey',
subjects_dir=tempdir)
labels = read_labels_from_annot(subject, 'PALS_B12_Lobes',
subjects_dir=tempdir)
# test saving parcellation only covering one hemisphere
parc = [l for l in labels if l.name == 'LOBE.TEMPORAL-lh']
write_labels_to_annot(parc, subject, 'myparc', subjects_dir=tempdir)
parc1 = read_labels_from_annot(subject, 'myparc', subjects_dir=tempdir)
parc1 = [l for l in parc1 if not l.name.startswith('unknown')]
assert_equal(len(parc1), len(parc))
for l1, l in zip(parc1, parc):
assert_labels_equal(l1, l)
# test saving only one hemisphere
parc = [l for l in labels if l.name.startswith('LOBE')]
write_labels_to_annot(parc, subject, 'myparc2', hemi='lh',
subjects_dir=tempdir)
annot_fname = os.path.join(tempdir, subject, 'label', '%sh.myparc2.annot')
assert os.path.isfile(annot_fname % 'l')
assert not os.path.isfile(annot_fname % 'r')
parc1 = read_labels_from_annot(subject, 'myparc2',
annot_fname=annot_fname % 'l',
subjects_dir=tempdir)
parc_lh = [l for l in parc if l.name.endswith('lh')]
for l1, l in zip(parc1, parc_lh):
assert_labels_equal(l1, l)
# test that the annotation is complete (test Label() support)
rr = read_surface(op.join(surf_dir, 'lh.white'))[0]
label = sum(labels, Label(hemi='lh', subject='fsaverage')).lh
assert_array_equal(label.vertices, np.arange(len(rr)))
示例6: find_clusters_overlapped_labeles
def find_clusters_overlapped_labeles(subject, clusters, contrast, atlas, hemi, verts, load_from_annotation=True,
n_jobs=1):
cluster_labels = []
annot_fname = op.join(SUBJECTS_DIR, subject, 'label', '{}.{}.annot'.format(hemi, atlas))
if load_from_annotation and op.isfile(annot_fname):
labels = mne.read_labels_from_annot(subject, annot_fname=annot_fname, surf_name='pial')
else:
# todo: read only the labels from the current hemi
labels = utils.read_labels_parallel(subject, SUBJECTS_DIR, atlas, n_jobs)
labels = [l for l in labels if l.hemi == hemi]
if len(labels) == 0:
print('No labels!')
return None
for cluster in clusters:
x = contrast[cluster]
cluster_max = np.min(x) if abs(np.min(x)) > abs(np.max(x)) else np.max(x)
inter_labels, inter_labels_tups = [], []
for label in labels:
overlapped_vertices = np.intersect1d(cluster, label.vertices)
if len(overlapped_vertices) > 0:
if 'unknown' not in label.name:
inter_labels_tups.append((len(overlapped_vertices), label.name))
# inter_labels.append(dict(name=label.name, num=len(overlapped_vertices)))
inter_labels_tups = sorted(inter_labels_tups)[::-1]
for inter_labels_tup in inter_labels_tups:
inter_labels.append(dict(name=inter_labels_tup[1], num=inter_labels_tup[0]))
if len(inter_labels) > 0:
# max_inter = max([(il['num'], il['name']) for il in inter_labels])
cluster_labels.append(dict(vertices=cluster, intersects=inter_labels, name=inter_labels[0]['name'],
coordinates=verts[cluster], max=cluster_max, hemi=hemi, size=len(cluster)))
else:
print('No intersected labels!')
return cluster_labels
示例7: test_read_labels_from_annot_annot2labels
def test_read_labels_from_annot_annot2labels():
"""Test reading labels from parc. by comparing with mne_annot2labels
"""
def _mne_annot2labels(subject, subjects_dir, parc):
"""Get labels using mne_annot2lables"""
label_dir = _TempDir()
cwd = os.getcwd()
try:
os.chdir(label_dir)
env = os.environ.copy()
env['SUBJECTS_DIR'] = subjects_dir
cmd = ['mne_annot2labels', '--subject', subject, '--parc', parc]
run_subprocess(cmd, env=env)
label_fnames = glob.glob(label_dir + '/*.label')
label_fnames.sort()
labels = [read_label(fname) for fname in label_fnames]
finally:
del label_dir
os.chdir(cwd)
return labels
labels = read_labels_from_annot('sample', subjects_dir=subjects_dir)
labels_mne = _mne_annot2labels('sample', subjects_dir, 'aparc')
# we have the same result, mne does not fill pos, so ignore it
_assert_labels_equal(labels, labels_mne, ignore_pos=True)
示例8: annotation_to_labels
def annotation_to_labels():
fol = os.path.join(subjects_dir, subject, 'label', aparc_name)
if not(os.path.isdir(fol)):
os.mkdir(fol)
labels = mne.read_labels_from_annot(subject, parc=aparc_name, hemi='both', surf_name='pial')
for label in labels:
label.save(os.path.join(fol, label.name))
示例9: create_annot_csv
def create_annot_csv(subject, parc, hemi, source_file, surf_name):
labels = mne.read_labels_from_annot(subject, parc, hemi, surf_name)
old, brain = get_hemi_data(source_file, hemi, surf_name)
colors = np.zeros((old.mlab_data.shape[0], 3)) # arrToColors(old.mlab_data, colorsMap='RdBu_r')[:, :3]
brain.toggle_toolbars(True)
for label_ind, label in enumerate(labels):
# label = labels[46]
brain.add_label(label)
print(label)
示例10: calc_fsaverage_labels_indices
def calc_fsaverage_labels_indices(surf_name='pial', labels_from_annot=False, labels_fol='', parc='aparc250', subjects_dir=''):
labels_fol = os.path.join(subjects_dir, 'fsaverage', 'label', parc) if labels_fol=='' else labels_fol
if (labels_from_annot):
labels = mne.read_labels_from_annot('fsaverage', parc=parc, hemi='both', surf_name=surf_name)
else:
labels = utils.read_labels(labels_fol)
fsave_vertices = [np.arange(10242), np.arange(10242)]
labels_vertices, labels_names = utils.get_labels_vertices(labels, fsave_vertices)
np.savez(op.join(LOCAL_ROOT_DIR, 'fsaverage_labels_indices'), labels_vertices=labels_vertices, labels_names=labels_names)
示例11: test_read_labels_from_annot_annot2labels
def test_read_labels_from_annot_annot2labels():
"""Test reading labels from parc. by comparing with mne_annot2labels."""
label_fnames = glob.glob(label_dir + '/*.label')
label_fnames.sort()
labels_mne = [read_label(fname) for fname in label_fnames]
labels = read_labels_from_annot('sample', subjects_dir=subjects_dir)
# we have the same result, mne does not fill pos, so ignore it
_assert_labels_equal(labels, labels_mne, ignore_pos=True)
示例12: test_annot_io
def test_annot_io():
"""Test I/O from and to *.annot files"""
# copy necessary files from fsaverage to tempdir
tempdir = _TempDir()
subject = 'fsaverage'
label_src = os.path.join(subjects_dir, 'fsaverage', 'label')
surf_src = os.path.join(subjects_dir, 'fsaverage', 'surf')
label_dir = os.path.join(tempdir, subject, 'label')
surf_dir = os.path.join(tempdir, subject, 'surf')
os.makedirs(label_dir)
os.mkdir(surf_dir)
shutil.copy(os.path.join(label_src, 'lh.PALS_B12_Lobes.annot'), label_dir)
shutil.copy(os.path.join(label_src, 'rh.PALS_B12_Lobes.annot'), label_dir)
shutil.copy(os.path.join(surf_src, 'lh.white'), surf_dir)
shutil.copy(os.path.join(surf_src, 'rh.white'), surf_dir)
# read original labels
assert_raises(IOError, read_labels_from_annot, subject, 'PALS_B12_Lobesey',
subjects_dir=tempdir)
labels = read_labels_from_annot(subject, 'PALS_B12_Lobes',
subjects_dir=tempdir)
# test saving parcellation only covering one hemisphere
parc = [l for l in labels if l.name == 'LOBE.TEMPORAL-lh']
write_labels_to_annot(parc, subject, 'myparc', subjects_dir=tempdir)
parc1 = read_labels_from_annot(subject, 'myparc', subjects_dir=tempdir)
parc1 = [l for l in parc1 if not l.name.startswith('unknown')]
assert_equal(len(parc1), len(parc))
for l1, l in zip(parc1, parc):
assert_labels_equal(l1, l)
# test saving only one hemisphere
parc = [l for l in labels if l.name.startswith('LOBE')]
write_labels_to_annot(parc, subject, 'myparc2', hemi='lh',
subjects_dir=tempdir)
annot_fname = os.path.join(tempdir, subject, 'label', '%sh.myparc2.annot')
assert_true(os.path.isfile(annot_fname % 'l'))
assert_false(os.path.isfile(annot_fname % 'r'))
parc1 = read_labels_from_annot(subject, 'myparc2',
annot_fname=annot_fname % 'l',
subjects_dir=tempdir)
parc_lh = [l for l in parc if l.name.endswith('lh')]
for l1, l in zip(parc1, parc_lh):
assert_labels_equal(l1, l)
示例13: create_annot_dic
def create_annot_dic(subject, parc, hemi, surf_name, obj_positions):
labels = mne.read_labels_from_annot(subject, parc, hemi, surf_name)
for label in [labels[161]]:
print(len(label.pos), len(obj_positions))
for label_pos, obj_pos in zip(label.pos, obj_positions):
label_pos = round_arr(label_pos * 1000)
obj_pos = round_arr(obj_pos)
eq = np.all(label_pos == obj_pos)
if not eq:
print(label_pos, obj_pos)
示例14: save_labels_from_annotation
def save_labels_from_annotation(subject, parc, surf_name, fol=""):
brain = Brain(subject, "both", surf_name, curv=False)
labels = mne.read_labels_from_annot(subject, parc, "both", surf_name)
if fol == "":
fol = os.path.join(os.environ["SUBJECTS_DIR"], os.environ["SUBJECT"], "label", "{}_labels".format(parc))
if not os.path.isdir(fol):
os.mkdir(fol)
for ind, label in enumerate(labels):
print("label {}/{}".format(ind, len(labels)))
label.save(os.path.join(fol, label.name))
示例15: test_label_center_of_mass
def test_label_center_of_mass():
"""Test computing the center of mass of a label."""
stc = read_source_estimate(stc_fname)
stc.lh_data[:] = 0
vertex_stc = stc.center_of_mass('sample', subjects_dir=subjects_dir)[0]
assert_equal(vertex_stc, 124791)
label = Label(stc.vertices[1], pos=None, values=stc.rh_data.mean(axis=1),
hemi='rh', subject='sample')
vertex_label = label.center_of_mass(subjects_dir=subjects_dir)
assert_equal(vertex_label, vertex_stc)
labels = read_labels_from_annot('sample', parc='aparc.a2009s',
subjects_dir=subjects_dir)
src = read_source_spaces(src_fname)
# Try a couple of random ones, one from left and one from right
# Visually verified in about the right place using mne_analyze
for label, expected in zip([labels[2], labels[3], labels[-5]],
[141162, 145221, 55979]):
label.values[:] = -1
pytest.raises(ValueError, label.center_of_mass,
subjects_dir=subjects_dir)
label.values[:] = 0
pytest.raises(ValueError, label.center_of_mass,
subjects_dir=subjects_dir)
label.values[:] = 1
assert_equal(label.center_of_mass(subjects_dir=subjects_dir), expected)
assert_equal(label.center_of_mass(subjects_dir=subjects_dir,
restrict_vertices=label.vertices),
expected)
# restrict to source space
idx = 0 if label.hemi == 'lh' else 1
# this simple nearest version is not equivalent, but is probably
# close enough for many labels (including the test ones):
pos = label.pos[np.where(label.vertices == expected)[0][0]]
pos = (src[idx]['rr'][src[idx]['vertno']] - pos)
pos = np.argmin(np.sum(pos * pos, axis=1))
src_expected = src[idx]['vertno'][pos]
# see if we actually get the same one
src_restrict = np.intersect1d(label.vertices, src[idx]['vertno'])
assert_equal(label.center_of_mass(subjects_dir=subjects_dir,
restrict_vertices=src_restrict),
src_expected)
assert_equal(label.center_of_mass(subjects_dir=subjects_dir,
restrict_vertices=src),
src_expected)
# degenerate cases
pytest.raises(ValueError, label.center_of_mass, subjects_dir=subjects_dir,
restrict_vertices='foo')
pytest.raises(TypeError, label.center_of_mass, subjects_dir=subjects_dir,
surf=1)
pytest.raises(IOError, label.center_of_mass, subjects_dir=subjects_dir,
surf='foo')