def labels_to_annot(subject, labels, subjects_dir, atlas='laus125', overwrite=True): subject_dir = op.join(subjects_dir, subject) annot_files_exist = both_hemi_files_exist( op.join(subject_dir, 'label', '{}.{}.annot'.format('{hemi}', atlas))) if annot_files_exist and not overwrite: return True if len(labels) == 0: labels_files = glob.glob( op.join(subject_dir, 'label', atlas, '*.label')) if len(labels_files) == 0: raise Exception('labels_to_annot: No labels files!') for label_file in labels_files: if 'unknown' in namebase(label_file): continue label = mne.read_label(label_file) labels.append(label) labels.sort(key=lambda l: l.name) mne.write_labels_to_annot(subject=subject, labels=labels, parc=atlas, overwrite=overwrite, subjects_dir=subjects_dir) return both_hemi_files_exist( op.join(subject_dir, 'label', '{}.{}.annot'.format('{hemi}', atlas)))
def morph_labels_from_fsaverage(mri_sub): parcellations = ['aparc_sub', 'HCPMMP1_combined', 'HCPMMP1'] if not isfile(join(mri_sub.subjects_dir, 'fsaverage/label', 'lh.' + parcellations[0] + '.annot')): mne.datasets.fetch_hcp_mmp_parcellation(subjects_dir=mri_sub.subjects_dir, verbose=True) mne.datasets.fetch_aparc_sub_parcellation(subjects_dir=mri_sub.subjects_dir, verbose=True) else: print('You\'ve already downloaded the parcellations, splendid!') if not isfile(join(mri_sub.subjects_dir, mri_sub.name, 'label', 'lh.' + parcellations[0] + '.annot')): for pc in parcellations: labels = mne.read_labels_from_annot('fsaverage', pc, hemi='both') m_labels = mne.morph_labels(labels, mri_sub.name, 'fsaverage', mri_sub.subjects_dir, surf_name='pial') mne.write_labels_to_annot(m_labels, subject=mri_sub.name, parc=pc, subjects_dir=mri_sub.subjects_dir, overwrite=True) else: print(f'{parcellations} already exist')
def test_fetch_parcellations(tmpdir): """Test fetching parcellations.""" this_subjects_dir = str(tmpdir) os.mkdir(op.join(this_subjects_dir, 'fsaverage')) os.mkdir(op.join(this_subjects_dir, 'fsaverage', 'label')) os.mkdir(op.join(this_subjects_dir, 'fsaverage', 'surf')) for hemi in ('lh', 'rh'): shutil.copyfile( op.join(subjects_dir, 'fsaverage', 'surf', '%s.white' % hemi), op.join(this_subjects_dir, 'fsaverage', 'surf', '%s.white' % hemi)) # speed up by prenteding we have one of them with open(op.join(this_subjects_dir, 'fsaverage', 'label', 'lh.aparc_sub.annot'), 'wb'): pass datasets.fetch_aparc_sub_parcellation(subjects_dir=this_subjects_dir) with ArgvSetter(('--accept-hcpmmp-license',)): datasets.fetch_hcp_mmp_parcellation(subjects_dir=this_subjects_dir) for hemi in ('lh', 'rh'): assert op.isfile(op.join(this_subjects_dir, 'fsaverage', 'label', '%s.aparc_sub.annot' % hemi)) # test our annot round-trips here kwargs = dict(subject='fsaverage', hemi='both', sort=False, subjects_dir=this_subjects_dir) labels = read_labels_from_annot(parc='HCPMMP1', **kwargs) write_labels_to_annot( labels, parc='HCPMMP1_round', table_name='./left.fsaverage164.label.gii', **kwargs) orig = op.join(this_subjects_dir, 'fsaverage', 'label', 'lh.HCPMMP1.annot') first = hashfunc(orig) new = orig[:-6] + '_round.annot' second = hashfunc(new) assert first == second
def morph_labels(subject_from, subject_to, parc, surf_name='pial', smooth=2, overwrite=True): ''' mne_morph_labels --from fsaverage --to mg79 --labeldir /homes/5/npeled/space3/subjects/fsaverage/label/laus500_labels --smooth 5 ''' # brain = Brain(subject_from, 'both', surf_name, curv=False) labels = mne.read_labels_from_annot(subject_from, parc, 'both', surf_name) morphed_labels = [] for ind, label in enumerate(labels): try: print('label {}/{}'.format(ind, len(labels))) label.values.fill(1.0) morphed_label = label.morph(subject_from, subject_to, smooth) morphed_labels.append(morphed_label) except: print('cant morph label {}'.format(label.name)) print(sys.exc_info()[1]) print('{} labels were morphed succefully.'.format(len(morphed_labels))) mne.write_labels_to_annot(morphed_labels, subject_to, parc, overwrite, hemi='both')
def labels_to_annot(subject, fol, parc, overwrite=True): for hemi in ["lh", "lr"]: labels = [] for label_file in glob.glob(os.path.join(fol, "*{}.label".format(hemi))): label = mne.read_label(label_file) labels.append(label) print("write {} labels to annot file".format(hemi)) mne.write_labels_to_annot(labels, subject, parc, overwrite, hemi=hemi)
def labels_to_annot(subject, fol, parc, overwrite=True): for hemi in ['lh', 'lr']: labels = [] for label_file in glob.glob(os.path.join(fol, '*{}.label'.format(hemi))): label = mne.read_label(label_file) labels.append(label) print('write {} labels to annot file'.format(hemi)) mne.write_labels_to_annot(labels, subject, parc, overwrite, hemi=hemi)
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)))
def save_annot(self, overwrite=False): """ """ if not self.labels: raise Exception('To save annot, you must fit first') mne.write_labels_to_annot( self.labels, subject=self.subject, hemi=self.hemi, parc=self.name, subjects_dir=self.subjects_dir, overwrite=overwrite)
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)
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)))
def morph_labels(subject_from, subject_to, parc, surf_name="pial", smooth=2, overwrite=True): """ mne_morph_labels --from fsaverage --to mg79 --labeldir /homes/5/npeled/space3/subjects/fsaverage/label/laus500_labels --smooth 5 """ # brain = Brain(subject_from, 'both', surf_name, curv=False) labels = mne.read_labels_from_annot(subject_from, parc, "both", surf_name) morphed_labels = [] for ind, label in enumerate(labels): try: print("label {}/{}".format(ind, len(labels))) label.values.fill(1.0) morphed_label = label.morph(subject_from, subject_to, smooth) morphed_labels.append(morphed_label) except: print("cant morph label {}".format(label.name)) print(sys.exc_info()[1]) print("{} labels were morphed succefully.".format(len(morphed_labels))) mne.write_labels_to_annot(morphed_labels, subject_to, parc, overwrite, hemi="both")
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)
def write_aparc_sub(subjid=None, subjects_dir=None): '''Check for fsaverage and aparc_sub and download Morph fsaverage aparc_sub labels to single subject data https://mne.tools/stable/auto_examples/visualization/plot_parcellation.html ''' mne.datasets.fetch_fsaverage(verbose='ERROR') #True requires TQDM mne.datasets.fetch_aparc_sub_parcellation(subjects_dir=subjects_dir, verbose='ERROR') sub_labels = mne.read_labels_from_annot('fsaverage', parc='aparc_sub', subjects_dir=subjects_dir) subject_labels = mne.morph_labels(sub_labels, subject_to=subjid, subjects_dir=subjects_dir) mne.write_labels_to_annot(subject_labels, subject=subjid, parc='aparc_sub', subjects_dir=subjects_dir, overwrite=True)
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)
def make_random_parcellation(path_annot, n, hemi, subjects_dir, random_state, subject, remove_corpus_callosum=False): parcels = random_parcellation(subject, n, hemi, subjects_dir=subjects_dir, surface='white', random_state=random_state) if remove_corpus_callosum: corpus_callosum = find_corpus_callosum(subject, subjects_dir, hemi=hemi) # instead of removing all the overlapping parcels we will remove only # the vertices which belong to corpus callosum to_remove = [] for idx, parcel in enumerate(parcels): cc_free = set(parcel.vertices) - set(corpus_callosum.vertices) parcel.vertices = np.array(list(cc_free)) if len(parcel.vertices) == 0: to_remove.append(idx) # remove all the parcels which after removing corpus callosum now # have 0 indices [parcels.pop(idc) for idc in to_remove[::-1]] write_labels_to_annot(parcels, subjects_dir=subjects_dir, subject=subject, annot_fname=path_annot, overwrite=True)
def plot(res, ds, out_dir, match, subjects_dir, surf=None, hemi=None, pmin=None): ''' Plot Timecourse, Brain, and Barplot of signidicant clusters from an eelbrain ANOVA/t-test results object. Parameters ------------- res : eelbrain ANOVA or t-test result object ds: eelbrain.Dataset Dataset containing stcs and condidion labels needs to be specified out_dir : str Output directory, ends with "/" surf : 'inflated' | 'pial' | 'smoothwm' | 'sphere' | 'white' surfer.Brain surface to use as brain geometry. Default = 'white' match : str | None Match cases for a repeated measures design in pairwsie t-test for barplots. hemi: 'lh' | 'rh' Hemisphere. Defaults to 'lh' subjects_dir : str subjects directory associated with the source space dimension. pmin: float permutation p-value (threshold) ''' if surf == None: surf = 'white' if hemi == None: hemi = 'lh' if pmin == None: pmin = 0.05 reset_stc = ds['stc'] mask_sign_clusters = np.where(res.clusters['p'] <= pmin, True, False) sign_clusters = res.clusters[mask_sign_clusters] if sign_clusters.n_cases != None: #check for significant clusters for i in range(sign_clusters.n_cases): cluster_nb = i + 1 cluster = sign_clusters[i]['cluster'] tstart = sign_clusters[i]['tstart'] tstop = sign_clusters[i]['tstop'] effect = sign_clusters[i]['effect'] effect = effect.replace( ' x ', '%') # Changing format of string for interaction effects. # save significant cluster as a temporary label for plotting. ds['stc'] = reset_stc label = eelbrain.labels_from_clusters(cluster) label[0].name = 'TempLabel-%s' % hemi mne.write_labels_to_annot(label, subject='fsaverage', parc='workspace', subjects_dir=subjects_dir, overwrite=True) ds['stc'].source.set_parc('workspace') ds['stc'] = ds['stc'].sub(source='TempLabel-%s' % hemi) timecourse = ds['stc'].mean('source') #Plot # 1)Timecourse activation = eelbrain.plot.UTSStat( timecourse, effect, ds=ds, title='Effect = %s, cluster #%s' % (effect, cluster_nb)) activation.add_vspan(xmin=tstart, xmax=tstop, color='lightgrey', zorder=-50) activation.save(out_dir + 'Cluster #%s, Effect = %s - Timecourse.png' % (cluster_nb, effect)) activation.close() # 2) Brain brain = eelbrain.plot.brain.cluster(cluster.mean(time=(tstart, tstop)), subjects_dir=subjects_dir, surf=surf, colorbar=True) brain.save_image(out_dir + 'Cluster #%s, Effect = %s - Brain.png' % (cluster_nb, effect)) brain.close() # 3) Bars ds['average_source_activation'] = timecourse.mean(time=(tstart, tstop)) bar = eelbrain.plot.Barplot(ds['average_source_activation'], X=effect, ds=ds, match=match) bar.save(out_dir + 'Cluster #%s, Effect = %s - Bars.png' % (cluster_nb, effect)) bar.close() ds['stc'] = reset_stc # resets ds['stc'] before exiting the loop. Otherwise, returns an errror if run again.
def test_write_labels_to_annot(): """Test writing FreeSurfer parcellation from labels""" tempdir = _TempDir() labels = read_labels_from_annot('sample', subjects_dir=subjects_dir) # write left and right hemi labels: fnames = ['%s/%s-myparc' % (tempdir, hemi) for hemi in ['lh', 'rh']] for fname in fnames: write_labels_to_annot(labels, annot_fname=fname) # read it back labels2 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[0]) labels22 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[1]) labels2.extend(labels22) names = [label.name for label in labels2] for label in labels: idx = names.index(label.name) assert_labels_equal(label, labels2[idx]) # same with label-internal colors for fname in fnames: write_labels_to_annot(labels, annot_fname=fname, overwrite=True) labels3 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[0]) labels33 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[1]) labels3.extend(labels33) names3 = [label.name for label in labels3] for label in labels: idx = names3.index(label.name) assert_labels_equal(label, labels3[idx]) # make sure we can't overwrite things assert_raises(ValueError, write_labels_to_annot, labels, annot_fname=fnames[0]) # however, this works write_labels_to_annot(labels, annot_fname=fnames[0], overwrite=True) # label without color labels_ = labels[:] labels_[0] = labels_[0].copy() labels_[0].color = None write_labels_to_annot(labels_, annot_fname=fnames[0], overwrite=True) # duplicate color labels_[0].color = labels_[2].color assert_raises(ValueError, write_labels_to_annot, labels_, annot_fname=fnames[0], overwrite=True) # invalid color inputs labels_[0].color = (1.1, 1., 1., 1.) assert_raises(ValueError, write_labels_to_annot, labels_, annot_fname=fnames[0], overwrite=True) # overlapping labels labels_ = labels[:] cuneus_lh = labels[6] precuneus_lh = labels[50] labels_.append(precuneus_lh + cuneus_lh) assert_raises(ValueError, write_labels_to_annot, labels_, annot_fname=fnames[0], overwrite=True) # unlabeled vertices labels_lh = [label for label in labels if label.name.endswith('lh')] write_labels_to_annot(labels_lh[1:], 'sample', annot_fname=fnames[0], overwrite=True, subjects_dir=subjects_dir) labels_reloaded = read_labels_from_annot('sample', annot_fname=fnames[0], subjects_dir=subjects_dir) assert_equal(len(labels_lh), len(labels_reloaded)) label0 = labels_lh[0] label1 = labels_reloaded[-1] assert_equal(label1.name, "unknown-lh") assert_true(np.all(in1d(label0.vertices, label1.vertices)))
def test_write_labels_to_annot(): """Test writing FreeSurfer parcellation from labels""" tempdir = _TempDir() labels = read_labels_from_annot("sample", subjects_dir=subjects_dir) # create temporary subjects-dir skeleton surf_dir = op.join(subjects_dir, "sample", "surf") temp_surf_dir = op.join(tempdir, "sample", "surf") os.makedirs(temp_surf_dir) shutil.copy(op.join(surf_dir, "lh.white"), temp_surf_dir) shutil.copy(op.join(surf_dir, "rh.white"), temp_surf_dir) os.makedirs(op.join(tempdir, "sample", "label")) # test automatic filenames dst = op.join(tempdir, "sample", "label", "%s.%s.annot") write_labels_to_annot(labels, "sample", "test1", subjects_dir=tempdir) assert_true(op.exists(dst % ("lh", "test1"))) assert_true(op.exists(dst % ("rh", "test1"))) # lh only for label in labels: if label.hemi == "lh": break write_labels_to_annot([label], "sample", "test2", subjects_dir=tempdir) assert_true(op.exists(dst % ("lh", "test2"))) assert_true(op.exists(dst % ("rh", "test2"))) # rh only for label in labels: if label.hemi == "rh": break write_labels_to_annot([label], "sample", "test3", subjects_dir=tempdir) assert_true(op.exists(dst % ("lh", "test3"))) assert_true(op.exists(dst % ("rh", "test3"))) # label alone assert_raises(TypeError, write_labels_to_annot, labels[0], "sample", "test4", subjects_dir=tempdir) # write left and right hemi labels with filenames: fnames = ["%s/%s-myparc" % (tempdir, hemi) for hemi in ["lh", "rh"]] for fname in fnames: write_labels_to_annot(labels, annot_fname=fname) # read it back labels2 = read_labels_from_annot("sample", subjects_dir=subjects_dir, annot_fname=fnames[0]) labels22 = read_labels_from_annot("sample", subjects_dir=subjects_dir, annot_fname=fnames[1]) labels2.extend(labels22) names = [label.name for label in labels2] for label in labels: idx = names.index(label.name) assert_labels_equal(label, labels2[idx]) # same with label-internal colors for fname in fnames: write_labels_to_annot(labels, annot_fname=fname, overwrite=True) labels3 = read_labels_from_annot("sample", subjects_dir=subjects_dir, annot_fname=fnames[0]) labels33 = read_labels_from_annot("sample", subjects_dir=subjects_dir, annot_fname=fnames[1]) labels3.extend(labels33) names3 = [label.name for label in labels3] for label in labels: idx = names3.index(label.name) assert_labels_equal(label, labels3[idx]) # make sure we can't overwrite things assert_raises(ValueError, write_labels_to_annot, labels, annot_fname=fnames[0]) # however, this works write_labels_to_annot(labels, annot_fname=fnames[0], overwrite=True) # label without color labels_ = labels[:] labels_[0] = labels_[0].copy() labels_[0].color = None write_labels_to_annot(labels_, annot_fname=fnames[0], overwrite=True) # duplicate color labels_[0].color = labels_[2].color assert_raises(ValueError, write_labels_to_annot, labels_, annot_fname=fnames[0], overwrite=True) # invalid color inputs labels_[0].color = (1.1, 1.0, 1.0, 1.0) assert_raises(ValueError, write_labels_to_annot, labels_, annot_fname=fnames[0], overwrite=True) # overlapping labels labels_ = labels[:] cuneus_lh = labels[6] precuneus_lh = labels[50] labels_.append(precuneus_lh + cuneus_lh) assert_raises(ValueError, write_labels_to_annot, labels_, annot_fname=fnames[0], overwrite=True) # unlabeled vertices labels_lh = [label for label in labels if label.name.endswith("lh")] write_labels_to_annot(labels_lh[1:], "sample", annot_fname=fnames[0], overwrite=True, subjects_dir=subjects_dir) labels_reloaded = read_labels_from_annot("sample", annot_fname=fnames[0], subjects_dir=subjects_dir) assert_equal(len(labels_lh), len(labels_reloaded)) label0 = labels_lh[0] label1 = labels_reloaded[-1] assert_equal(label1.name, "unknown-lh") assert_true(np.all(in1d(label0.vertices, label1.vertices)))
def test_write_labels_to_annot(): """Test writing FreeSurfer parcellation from labels""" tempdir = _TempDir() labels = read_labels_from_annot('sample', subjects_dir=subjects_dir) # create temporary subjects-dir skeleton surf_dir = op.join(subjects_dir, 'sample', 'surf') temp_surf_dir = op.join(tempdir, 'sample', 'surf') os.makedirs(temp_surf_dir) shutil.copy(op.join(surf_dir, 'lh.white'), temp_surf_dir) shutil.copy(op.join(surf_dir, 'rh.white'), temp_surf_dir) os.makedirs(op.join(tempdir, 'sample', 'label')) # test automatic filenames dst = op.join(tempdir, 'sample', 'label', '%s.%s.annot') write_labels_to_annot(labels, 'sample', 'test1', subjects_dir=tempdir) assert_true(op.exists(dst % ('lh', 'test1'))) assert_true(op.exists(dst % ('rh', 'test1'))) # lh only for label in labels: if label.hemi == 'lh': break write_labels_to_annot([label], 'sample', 'test2', subjects_dir=tempdir) assert_true(op.exists(dst % ('lh', 'test2'))) assert_true(op.exists(dst % ('rh', 'test2'))) # rh only for label in labels: if label.hemi == 'rh': break write_labels_to_annot([label], 'sample', 'test3', subjects_dir=tempdir) assert_true(op.exists(dst % ('lh', 'test3'))) assert_true(op.exists(dst % ('rh', 'test3'))) # label alone assert_raises(TypeError, write_labels_to_annot, labels[0], 'sample', 'test4', subjects_dir=tempdir) # write left and right hemi labels with filenames: fnames = [op.join(tempdir, hemi + '-myparc') for hemi in ['lh', 'rh']] with warnings.catch_warnings(record=True): # specify subject_dir param for fname in fnames: write_labels_to_annot(labels, annot_fname=fname) # read it back labels2 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[0]) labels22 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[1]) labels2.extend(labels22) names = [label.name for label in labels2] for label in labels: idx = names.index(label.name) assert_labels_equal(label, labels2[idx]) # same with label-internal colors for fname in fnames: write_labels_to_annot(labels, 'sample', annot_fname=fname, overwrite=True, subjects_dir=subjects_dir) labels3 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[0]) labels33 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[1]) labels3.extend(labels33) names3 = [label.name for label in labels3] for label in labels: idx = names3.index(label.name) assert_labels_equal(label, labels3[idx]) # make sure we can't overwrite things assert_raises(ValueError, write_labels_to_annot, labels, 'sample', annot_fname=fnames[0], subjects_dir=subjects_dir) # however, this works write_labels_to_annot(labels, 'sample', annot_fname=fnames[0], overwrite=True, subjects_dir=subjects_dir) # label without color labels_ = labels[:] labels_[0] = labels_[0].copy() labels_[0].color = None write_labels_to_annot(labels_, 'sample', annot_fname=fnames[0], overwrite=True, subjects_dir=subjects_dir) # duplicate color labels_[0].color = labels_[2].color assert_raises(ValueError, write_labels_to_annot, labels_, 'sample', annot_fname=fnames[0], overwrite=True, subjects_dir=subjects_dir) # invalid color inputs labels_[0].color = (1.1, 1., 1., 1.) assert_raises(ValueError, write_labels_to_annot, labels_, 'sample', annot_fname=fnames[0], overwrite=True, subjects_dir=subjects_dir) # overlapping labels labels_ = labels[:] cuneus_lh = labels[6] precuneus_lh = labels[50] labels_.append(precuneus_lh + cuneus_lh) assert_raises(ValueError, write_labels_to_annot, labels_, 'sample', annot_fname=fnames[0], overwrite=True, subjects_dir=subjects_dir) # unlabeled vertices labels_lh = [label for label in labels if label.name.endswith('lh')] write_labels_to_annot(labels_lh[1:], 'sample', annot_fname=fnames[0], overwrite=True, subjects_dir=subjects_dir) labels_reloaded = read_labels_from_annot('sample', annot_fname=fnames[0], subjects_dir=subjects_dir) assert_equal(len(labels_lh), len(labels_reloaded)) label0 = labels_lh[0] label1 = labels_reloaded[-1] assert_equal(label1.name, "unknown-lh") assert_true(np.all(in1d(label0.vertices, label1.vertices))) # unnamed labels labels4 = labels[:] labels4[0].name = None assert_raises(ValueError, write_labels_to_annot, labels4, annot_fname=fnames[0])
def test_write_labels_to_annot(): """Test writing FreeSurfer parcellation from labels""" tempdir = _TempDir() labels = read_labels_from_annot('sample', subjects_dir=subjects_dir) # create temporary subjects-dir skeleton surf_dir = op.join(subjects_dir, 'sample', 'surf') temp_surf_dir = op.join(tempdir, 'sample', 'surf') os.makedirs(temp_surf_dir) shutil.copy(op.join(surf_dir, 'lh.white'), temp_surf_dir) shutil.copy(op.join(surf_dir, 'rh.white'), temp_surf_dir) os.makedirs(op.join(tempdir, 'sample', 'label')) # test automatic filenames dst = op.join(tempdir, 'sample', 'label', '%s.%s.annot') write_labels_to_annot(labels, 'sample', 'test1', subjects_dir=tempdir) assert_true(op.exists(dst % ('lh', 'test1'))) assert_true(op.exists(dst % ('rh', 'test1'))) # lh only for label in labels: if label.hemi == 'lh': break write_labels_to_annot([label], 'sample', 'test2', subjects_dir=tempdir) assert_true(op.exists(dst % ('lh', 'test2'))) assert_true(op.exists(dst % ('rh', 'test2'))) # rh only for label in labels: if label.hemi == 'rh': break write_labels_to_annot([label], 'sample', 'test3', subjects_dir=tempdir) assert_true(op.exists(dst % ('lh', 'test3'))) assert_true(op.exists(dst % ('rh', 'test3'))) # label alone assert_raises(TypeError, write_labels_to_annot, labels[0], 'sample', 'test4', subjects_dir=tempdir) # write left and right hemi labels with filenames: fnames = [op.join(tempdir, hemi + '-myparc') for hemi in ['lh', 'rh']] with warnings.catch_warnings(record=True): # specify subject_dir param for fname in fnames: write_labels_to_annot(labels, annot_fname=fname) # read it back labels2 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[0]) labels22 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[1]) labels2.extend(labels22) names = [label.name for label in labels2] for label in labels: idx = names.index(label.name) assert_labels_equal(label, labels2[idx]) # same with label-internal colors for fname in fnames: write_labels_to_annot(labels, 'sample', annot_fname=fname, overwrite=True, subjects_dir=subjects_dir) labels3 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[0]) labels33 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[1]) labels3.extend(labels33) names3 = [label.name for label in labels3] for label in labels: idx = names3.index(label.name) assert_labels_equal(label, labels3[idx]) # make sure we can't overwrite things assert_raises(ValueError, write_labels_to_annot, labels, 'sample', annot_fname=fnames[0], subjects_dir=subjects_dir) # however, this works write_labels_to_annot(labels, 'sample', annot_fname=fnames[0], overwrite=True, subjects_dir=subjects_dir) # label without color labels_ = labels[:] labels_[0] = labels_[0].copy() labels_[0].color = None write_labels_to_annot(labels_, 'sample', annot_fname=fnames[0], overwrite=True, subjects_dir=subjects_dir) # duplicate color labels_[0].color = labels_[2].color assert_raises(ValueError, write_labels_to_annot, labels_, 'sample', annot_fname=fnames[0], overwrite=True, subjects_dir=subjects_dir) # invalid color inputs labels_[0].color = (1.1, 1., 1., 1.) assert_raises(ValueError, write_labels_to_annot, labels_, 'sample', annot_fname=fnames[0], overwrite=True, subjects_dir=subjects_dir) # overlapping labels labels_ = labels[:] cuneus_lh = labels[6] precuneus_lh = labels[50] labels_.append(precuneus_lh + cuneus_lh) assert_raises(ValueError, write_labels_to_annot, labels_, 'sample', annot_fname=fnames[0], overwrite=True, subjects_dir=subjects_dir) # unlabeled vertices labels_lh = [label for label in labels if label.name.endswith('lh')] write_labels_to_annot(labels_lh[1:], 'sample', annot_fname=fnames[0], overwrite=True, subjects_dir=subjects_dir) labels_reloaded = read_labels_from_annot('sample', annot_fname=fnames[0], subjects_dir=subjects_dir) assert_equal(len(labels_lh), len(labels_reloaded)) label0 = labels_lh[0] label1 = labels_reloaded[-1] assert_equal(label1.name, "unknown-lh") assert_true(np.all(np.in1d(label0.vertices, label1.vertices))) # unnamed labels labels4 = labels[:] labels4[0].name = None assert_raises(ValueError, write_labels_to_annot, labels4, annot_fname=fnames[0])
def test_write_labels_to_annot(): """Test writing FreeSurfer parcellation from labels""" labels = read_labels_from_annot('sample', subjects_dir=subjects_dir) # write left and right hemi labels: fnames = ['%s/%s-myparc' % (tempdir, hemi) for hemi in ['lh', 'rh']] for fname in fnames: write_labels_to_annot(labels, annot_fname=fname) # read it back labels2 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[0]) labels22 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[1]) labels2.extend(labels22) names = [label.name for label in labels2] for label in labels: idx = names.index(label.name) assert_labels_equal(label, labels2[idx]) # same with label-internal colors for fname in fnames: write_labels_to_annot(labels, annot_fname=fname, overwrite=True) labels3 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[0]) labels33 = read_labels_from_annot('sample', subjects_dir=subjects_dir, annot_fname=fnames[1]) labels3.extend(labels33) names3 = [label.name for label in labels3] for label in labels: idx = names3.index(label.name) assert_labels_equal(label, labels3[idx]) # make sure we can't overwrite things assert_raises(ValueError, write_labels_to_annot, labels, annot_fname=fnames[0]) # however, this works write_labels_to_annot(labels, annot_fname=fnames[0], overwrite=True) # label without color labels_ = labels[:] labels_[0] = labels_[0].copy() labels_[0].color = None write_labels_to_annot(labels_, annot_fname=fnames[0], overwrite=True) # duplicate color labels_[0].color = labels_[2].color assert_raises(ValueError, write_labels_to_annot, labels_, annot_fname=fnames[0], overwrite=True) # invalid color inputs labels_[0].color = (1.1, 1., 1., 1.) assert_raises(ValueError, write_labels_to_annot, labels_, annot_fname=fnames[0], overwrite=True) # overlapping labels labels_ = labels[:] cuneus_lh = labels[6] precuneus_lh = labels[50] labels_.append(precuneus_lh + cuneus_lh) assert_raises(ValueError, write_labels_to_annot, labels_, annot_fname=fnames[0], overwrite=True) # unlabeled vertices labels_lh = [label for label in labels if label.name.endswith('lh')] write_labels_to_annot(labels_lh[1:], 'sample', annot_fname=fnames[0], overwrite=True, subjects_dir=subjects_dir) labels_reloaded = read_labels_from_annot('sample', annot_fname=fnames[0], subjects_dir=subjects_dir) assert_equal(len(labels_lh), len(labels_reloaded)) label0 = labels_lh[0] label1 = labels_reloaded[-1] assert_equal(label1.name, "unknown-lh") assert_true(np.all(in1d(label0.vertices, label1.vertices)))