def plot_brain_color_legend(palette): from surfer import Brain from pymeg import atlas_glasser as ag from pymeg import source_reconstruction as sr labels = sr.get_labels(subject='S04', filters=['*wang*.label', '*JWDG*.label'], annotations=['HCPMMP1']) labels = sr.labels_exclude(labels=labels, exclude_filters=[ 'wang2015atlas.IPS4', 'wang2015atlas.IPS5', 'wang2015atlas.SPL', 'JWDG_lat_Unknown' ]) labels = sr.labels_remove_overlap(labels=labels, priority_filters=['wang', 'JWDG']) lc = ag.labels2clusters(labels) brain = Brain('S04', 'lh', 'inflated', views=['lat'], background='w') for cluster, labelobjects in lc.items(): if cluster in palette.keys(): color = palette[cluster] for l0 in labelobjects: if l0.hemi == 'lh': brain.add_label(l0, color=color, alpha=1) brain.save_montage( '/Users/nwilming/Dropbox/UKE/confidence_study/brain_colorbar.png', [['par', 'fro'], ['lat', 'med']]) return brain
def plot_V1V2(measure, hemi, clim): data, vert = extract_hemi_data(src_df, measure, time, hemi) brain = Brain('fsaverage', hemi, 'inflated', cortex='low_contrast', subjects_dir='mne_subjects', background='w', foreground='k') brain.add_data(data, vertices=vert, min=-clim[2], max=clim[2], time=[time], time_label=lambda t: '%d ms' % (t * 1000), colormap=morph_divergent_cmap(cmap, clim), hemi=hemi, smoothing_steps=5) labels = mne.read_labels_from_annot('fsaverage', parc='HCPMMP1', hemi=hemi, regexp='[LR]_((V1)|(V2)).*') for label in labels: brain.add_label(label, borders=True) mlab.view(*views[hemi]) return brain
def plot_distance(subject, data_dir, parcels, parcel_name='1-lh'): print('displaying brain of subject {}, distances from label {}'.format( subject, parcel_name)) data_path = 'mne_data/MNE-sample-data' # Maja subjects_dir = os.path.join(data_path, 'subjects') hemi = 'both' brain = Brain(subject, hemi, 'inflated', subjects_dir=subjects_dir, cortex='low_contrast', background='white') dist_path_lh = os.path.join(data_dir, subject + '_dist_matrix_lh.csv') dist_matrix_lh = pd.read_csv(dist_path_lh, index_col=0) dist_matrix_lh_norm = dist_matrix_lh.divide(dist_matrix_lh.max().max()) if 'lh' in parcel_name: hemi = 'lh' elif 'rh' in parcel_name: hemi = 'rh' for parcel in parcels: if parcel_name == parcel.name: brain.add_label(parcel, alpha=1, color='blue') elif hemi in parcel.name: dist = dist_matrix_lh_norm.loc[parcel_name][parcel.name] brain.add_label(parcel, alpha=1, color=str(1 - dist)) import pdb pdb.set_trace() cm = parcel.center_of_mass(subject, subjects_dir=subjects_dir) brain.add_foci(cm, coords_as_verts=True, hemi='lh', color='blue')
def drawROI(): for hemi in ["lh"]: # load data roivol = io.project_volume_data(roifile, hemi, subject_id=surfsubj, smooth_fwhm=4.0, projmeth="dist", projsum="avg", projarg=[0,6,0.1], surf="white") # create label roivol = abs(roivol) roivol[roivol < 0.33] = 0 #if max(roivol) < 1: # brain.close() # continue #else: write_label(np.asarray(np.nonzero(roivol)),"/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.label") # load brain my_fig = mlab.figure(figure="new_fig1", size=(800,800)) brain = Brain("fsaverage",hemi,"inflated",curv=True,size=[800,800],background="white",cortex=(("gist_yarg",-1.5,3.5,False)),figure=my_fig) set_mylights(my_fig,lights[hemi]) #add label brain.add_label("/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.label",borders=False,color="#ffff00",alpha=1) brain.add_label("/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.label",borders=1,color="black",alpha=0.5) brain.show_view('lat') brain.save_image("/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.tiff") brain.close()
def img2disc(data, foci_all=False, foci_dmn=False, labelfile=False, hemi='lh', filename='temp.png'): brain = Brain('fsaverage5', hemi, 'inflated', curv=False) brain.add_data(data, data.min(), data.max(), colormap="spectral", alpha=0.6) if labelfile: brain.add_label(labelfile, borders=True, color='grey') if foci_all: brain.add_foci(foci_all, coords_as_verts=True, scale_factor=.5, color='black') if foci_dmn: brain.add_foci(foci_dmn, coords_as_verts=True, scale_factor=.7, color='blue') brain.save_montage(filename, order=['lat', 'med'], orientation='h', border_size=10)
def make_brain_figures(srcdf, measure, cinfo, filepat_base, top=5): views = {'rh': ['medial', 'lateral'], 'lh': ['lateral', 'medial']} toplabels = {} for hemi in ['lh', 'rh']: brain = Brain('fsaverage', hemi, 'inflated', cortex='low_contrast', subjects_dir=sv.subjects_dir, background='w', foreground='k') sv.show_labels_as_data(srcdf, measure, brain, time_label=None, parc=parc, **cinfo) if top: ind = srcdf.index.get_level_values('label').map( lambda x: x.startswith(hemi[0].upper())) topl = srcdf[ind].abs().sort_values( measure, ascending=False).head(top) topl = ( topl[(topl[measure] != 0) & topl[measure].notna()] .index.droplevel('time')) toplabels[hemi] = topl alllabels = mne.read_labels_from_annot( 'fsaverage', parc=parc, hemi=hemi) brain.remove_labels() for label in alllabels: if label.name in topl: brain.add_label(label, borders=1, hemi=hemi, alpha=0.8, color='k') # increase font size of colorbar - this only works by increasing the # colorbar itself and setting the ratio of colorbar to text brain.data['colorbar'].scalar_bar.bar_ratio = 0.35 brain.data['colorbar'].scalar_bar_representation.position = [0.075, 0.01] brain.data['colorbar'].scalar_bar_representation.position2 = [0.85, 0.12] filepat = os.path.join(figdir, filepat_base + '_{}.png'.format(hemi)) brain.save_montage(filepat, views[hemi], colorbar=0) brain.close() infiles = [ os.path.join(figdir, filepat_base + '_{}.png'.format(hemi)) for hemi in ['lh', 'rh']] outfile = os.path.join(figdir, filepat_base + '.png') os.system("montage -tile 2x1 -geometry +0+0 {} {}".format( ' '.join(infiles), outfile)) return toplabels
def test_probabilistic_labels(): """Test plotting of probabilistic labels """ mlab.options.backend = 'test' brain = Brain("fsaverage", "lh", "inflated", config_opts=dict(cortex="low_contrast")) brain.add_label("BA1", color="darkblue") brain.add_label("BA1", color="dodgerblue", scalar_thresh=.5) brain.add_label("BA45", color="firebrick", borders=True) brain.add_label("BA45", color="salmon", borders=True, scalar_thresh=.5) label_file = pjoin(subj_dir, "fsaverage", "label", "lh.BA6.label") prob_field = np.zeros_like(brain._geo.x) ids, probs = nib.freesurfer.read_label(label_file, read_scalars=True) prob_field[ids] = probs brain.add_data(prob_field, thresh=1e-5) brain.data["colorbar"].number_of_colors = 10 brain.data["colorbar"].number_of_labels = 11 brain.close()
def test_probabilistic_labels(): """Test plotting of probabilistic labels.""" _set_backend() brain = Brain("fsaverage", "lh", "inflated", cortex="low_contrast") extra, subj_dir = _get_extra() brain.add_label("BA1" + extra, color="darkblue") brain.add_label("BA1" + extra, color="dodgerblue", scalar_thresh=.5) brain.add_label("BA45" + extra, color="firebrick", borders=True) brain.add_label("BA45" + extra, color="salmon", borders=True, scalar_thresh=.5) label_file = pjoin(subj_dir, "fsaverage", "label", "lh.BA6%s.label" % (extra, )) prob_field = np.zeros_like(brain.geo['lh'].x) ids, probs = nib.freesurfer.read_label(label_file, read_scalars=True) prob_field[ids] = probs brain.add_data(prob_field, thresh=1e-5) with warnings.catch_warnings(record=True): brain.data["colorbar"].number_of_colors = 10 brain.data["colorbar"].number_of_labels = 11 brain.close()
def inflated_surfaces(out_dir, subj, close=True): """Native inflated surfaces with cortical label.""" for hemi in ["lh", "rh"]: b = Brain(subj, hemi, "inflated", curv=False, config_opts=dict(background="white", width=800, height=500)) b.add_label("cortex", color="#6B6B6B") for view in ["lat", "med"]: b.show_view(view) mlab.view(distance=400) png = op.join(out_dir, "%s.surface_%s.png" % (hemi, view)) b.save_image(png) if close: b.close()
def plot_roi(hemi, labels, colors, view='parietal', fs_dir=os.environ['SUBJECTS_DIR']): import os subject_id = "fsaverage" surf = "inflated" brain = Brain(subject_id, hemi, surf, offscreen=True) for label, color in zip(labels, colors): label_file = os.path.join(fs_dir, subject_id, 'label', (label.replace('-rh', '.label') .replace('-lh', '.label') .replace('&', '_and_') .replace('_Havg', '') .replace('_Lateralized', ''))) brain.add_label(label_file, color=color) brain.show_view(view) return brain.screenshot()
def plot_roi( hemi, labels, color, annotation="HCPMMP1", view="parietal", fs_dir=os.environ["SUBJECTS_DIR"], subject_id="S04", surf="inflated", ): import matplotlib import os import glob from surfer import Brain from mne import Label color = np.array(matplotlib.colors.to_rgba(color)) brain = Brain(subject_id, hemi, surf, offscreen=False) labels = [label.replace("-rh", "").replace("-lh", "") for label in labels] # First select all label files label_names = glob.glob( os.path.join(fs_dir, subject_id, "label", "lh*.label")) label_names = [ label for label in label_names if any([l in label for l in labels]) ] for label in label_names: brain.add_label(label, color=color) # Now go for annotations from nibabel.freesurfer import io ids, colors, annot_names = io.read_annot( os.path.join(fs_dir, subject_id, "label", "lh.%s.annot" % annotation), orig_ids=True, ) for i, alabel in enumerate(annot_names): if any([label in alabel.decode("utf-8") for label in labels]): label_id = colors[i, -1] vertices = np.where(ids == label_id)[0] l = Label(np.sort(vertices), hemi="lh") brain.add_label(l, color=color) brain.show_view(view) return brain.screenshot()
def save_groups_labels_figures(): labels, groups = get_groups() for group in groups: print(group) if len(get_group_labels(group)) < 4: group_label = [l for l in labels if group in l] colors = get_spaced_colors(len(group_label)) brain = Brain(subject, hemi, surf, offscreen=False) for label_id, label in enumerate(group_label): print(label) brain.add_label(label, color=colors[label_id]) fol = os.path.join(subjects_dir, subject, 'label', '{}_figures'.format(aparc_name)) if not os.path.isdir(fol): os.mkdir(fol) brain.save_imageset(os.path.join(fol, group), get_views(), 'jpg') brain.remove_labels() brain.close()
def plot_src_ROI(subjects_dir=None, subject=None, parc=None): '''Plot selected frontal regions in source space.''' from surfer import Brain subject = 'fsaverage' if subject is None else subject brain = Brain(subject, 'lh', 'inflated', subjects_dir=subjects_dir, cortex='low_contrast', background='white', size=(800, 600), views='l') # brain.add_annotation('HCPMMP1_combined') labels, _ = get_frontal_labels(subjects_dir=subjects_dir, parc=parc) for lab in labels: brain.add_label(lab, borders=False, color='b') return brain
def plot_y_pred_true_parcels(subject_name, labels_pred, labels_true, colors={ 'pred': 'y', 'true': 'b', 'overlap': 'g' }): # fig_name = (subject_name + '_' + str(len(parcels_subject)) + '_' + # str(n_parcels_max)) # TODO: make the switch automatic depending on who/where it runs data_path = 'mne_data/MNE-sample-data' # Maja # mne_dir = mne.get_config('MNE_DATASETS_SAMPLE_PATH') # Alex # data_path = mne_dir + '/MNE-sample-data' subjects_dir = os.path.join(data_path, 'subjects') hemi = 'both' brain = Brain(subject_name, hemi, 'inflated', subjects_dir=subjects_dir, cortex='low_contrast', background='white') for parcel in labels_pred: brain.add_label(parcel, alpha=1, color=colors['pred']) for parcel in labels_true: brain.add_label(parcel, alpha=1, color=colors['true']) for parcel in set(labels_pred) & set(labels_true): brain.add_label(parcel, alpha=1, color=colors['overlap']) import pdb pdb.set_trace()
def plot_rois( labels, clusters, view="lat", fs_dir=os.environ["SUBJECTS_DIR"], subject_id="S04", surf="inflated", ): hemi = "lh" from surfer import Brain import seaborn as sns colors = sns.color_palette("husl", len(clusters)) brain = Brain(subject_id, hemi, surf, offscreen=False) for color, cluster in zip(colors, clusters): for label in labels[cluster]: if "rh" in label.name: continue # print(cluster, label) brain.add_label(label, color=color) brain.show_view(view) return brain, brain.screenshot()
def visualize_brain(subject, hemi, annot_name, subjects_dir, parcels_selected, fig_dir='figs', ext='.png'): # visualize the brain with the parcellations and the source of the signal if not os.path.isdir(fig_dir): os.mkdir(fig_dir) brain = Brain(subject, hemi, 'inflated', subjects_dir=subjects_dir, cortex='low_contrast', background='white', size=(800, 600)) for parcel in parcels_selected: brain.add_label(parcel, alpha=1, color=parcel.color) save_fig = os.path.join(fig_dir, 'brain_' + annot_name + ext) brain.save_image(save_fig) print('brain image saved in {}'.format(save_fig))
def plot_brains(axes, palette): lat_ax, med_ax = axes lat_color, med_color = palette b = Brain("fsaverage", "lh", "pial", background="white", size=(1200, 1200)) b.add_morphometry("curv", grayscale=True, min=-.5, max=.5, colormap="Greys", colorbar=False) b.add_label("roi_labels/lh.ifs.label", alpha=.9, color="#feb308") b.add_label("roi_labels/lh.mfc.label", alpha=.9, color="#cf6275") mlab.view(160, 70) lat_ax.imshow(crop(b.screenshot()), rasterized=True) mlab.view(15, 90) med_ax.imshow(crop(b.screenshot()), rasterized=True) b.close() for ax in axes: ax.set_axis_off()
def brain_labels(labels, names, subjects_dir, stc=None, title=None, hemi='both', view=['med'], save=False, fname='', dataset='sample_LAud'): from surfer import Brain n_support = names.shape[0] label_names = [label.name for label in labels] # Plot the selected labels in a Brain brain = Brain('sample', hemi=hemi, surf='inflated', subjects_dir=subjects_dir, title=title, views=view, background='white') for label in np.unique(names[:n_support // 2]): if hemi == 'both': # Left hemi idx = label_names.index(label) brain.add_label(labels[idx], color=labels[idx].color) # Right hemi idx = label_names.index(label[:-3] + '-rh') brain.add_label(labels[idx], color=labels[idx].color) elif hemi == 'lh': # Left hemi idx = label_names.index(label) brain.add_label(labels[idx], color=labels[idx].color) elif hemi == 'rh': # Right hemi idx = label_names.index(label[:-3] + '-rh') brain.add_label(labels[idx], color=labels[idx].color) if save: brain.save_montage('paper_figures/images/' + fname + '_' + view[0] + '_' + hemi + '.png', order=view, border_size=1)
def test_probabilistic_labels(): """Test plotting of probabilistic labels.""" mlab.options.backend = 'test' brain = Brain("fsaverage", "lh", "inflated", cortex="low_contrast") brain.add_label("BA1", color="darkblue") brain.add_label("BA1", color="dodgerblue", scalar_thresh=.5) brain.add_label("BA45", color="firebrick", borders=True) brain.add_label("BA45", color="salmon", borders=True, scalar_thresh=.5) label_file = pjoin(subj_dir, "fsaverage", "label", "lh.BA6.label") prob_field = np.zeros_like(brain._geo.x) ids, probs = nib.freesurfer.read_label(label_file, read_scalars=True) prob_field[ids] = probs brain.add_data(prob_field, thresh=1e-5) brain.data["colorbar"].number_of_colors = 10 brain.data["colorbar"].number_of_labels = 11 brain.close()
def test_probabilistic_labels(): """Test plotting of probabilistic labels.""" _set_backend() brain = Brain("fsaverage", "lh", "inflated", cortex="low_contrast") brain.add_label("BA1", color="darkblue") brain.add_label("BA1", color="dodgerblue", scalar_thresh=.5) brain.add_label("BA45", color="firebrick", borders=True) brain.add_label("BA45", color="salmon", borders=True, scalar_thresh=.5) subj_dir = utils._get_subjects_dir() label_file = pjoin(subj_dir, "fsaverage", "label", "lh.BA6.label") prob_field = np.zeros_like(brain.geo['lh'].x) ids, probs = nib.freesurfer.read_label(label_file, read_scalars=True) prob_field[ids] = probs brain.add_data(prob_field, thresh=1e-5) with warnings.catch_warnings(record=True): brain.data["colorbar"].number_of_colors = 10 brain.data["colorbar"].number_of_labels = 11 brain.close()
''' import os import glob import mne from surfer import Brain subjects_dir = '/home/uais_common/dong/freesurfer/subjects/' stcs_path = subjects_dir + '/fsaverage/conf_stc/' labels_dir = stcs_path + 'STC_ROI/merge/' subject_id = 'fsaverage' hemi = "lh" # surf = "smoothwm" surf = 'inflated' fn_list = glob.glob(labels_dir + '*') brain = Brain(subject_id, hemi, surf) color = ['#990033', '#9900CC', '#FF6600', '#FF3333', '#00CC33'] i = 0 for fn_label in fn_list: label_name = os.path.split(fn_label)[-1] # if label_name.split('_')[0] == 'sti,RRst': i = i + 1 ind = i % 5 label = mne.read_label(fn_label) if label.hemi == 'lh': brain.add_label(label) brain.add_annotation(annot='aparc', borders=True)
def drawContrast(infile,outname): for hemi in ["rh"]: # load data volpos = io.project_volume_data(infile, hemi, subject_id=surfsubj, smooth_fwhm=4.0, projmeth="dist", projsum="max", projarg=[-6,6,0.1], surf="pial") """ volneg = io.project_volume_data(rsfcfile_neg, hemi, subject_id=surfsubj, smooth_fwhm=4.0, projmeth="dist", projsum="max", projarg=[-6,6,0.1], surf="white") volneg=volneg*-1 ccvol=volpos+volneg """ # load brain my_fig = mlab.figure(figure="new_fig1", size=(800,800)) brain = Brain("fsaverage",hemi,"inflated",curv=True,size=[800,800],background="white",cortex=(("gist_yarg",-1.5,3.5,False)),figure=my_fig) set_mylights(my_fig,lights[hemi]) if outname == "fig6b": # create label labIFG = volpos labIFG[labIFG < 2.0739] = 0 write_label(np.asarray(np.nonzero(labIFG)),"fig6prep/roi_IFG.label") #brain.add_label("fig6prep/roi_IFG.label",borders=False,color="red",alpha=0.125) brain.add_label("fig6prep/roi_IFG.label",borders=2,color="#e7298a",alpha=1) if outname == "fig6d": # create label labAG = io.project_volume_data("/gablab/p/CASL/Results/Imaging/resting/zqi/conn_CASL_pre_post_training13o/results/secondlevel/ANALYSIS_01/3mohsk_all(0).3mohsk(1)/pre-training(-1).post-training(1)/anat_func_lifg_1_1/roi_AG.nii.gz", hemi, subject_id=surfsubj, smooth_fwhm=4.0, projmeth="dist", projsum="max", projarg=[-6,6,0.1], surf="pial") labAG[labAG < 0.33] = 0 write_label(np.asarray(np.nonzero(labAG)),"fig6prep/roi_AG.label") labSTGMTG = io.project_volume_data("/gablab/p/CASL/Results/Imaging/resting/zqi/conn_CASL_pre_post_training13o/results/secondlevel/ANALYSIS_01/3mohsk_all(0).3mohsk(1)/pre-training(-1).post-training(1)/anat_func_lifg_1_1/roi_STGMTG.nii.gz", hemi, subject_id=surfsubj, smooth_fwhm=4.0, projmeth="dist", projsum="max", projarg=[-6,6,0.1], surf="pial") labSTGMTG[labSTGMTG < 0.66] = 0 write_label(np.asarray(np.nonzero(labSTGMTG)),"fig6prep/roi_STGMTG.label") #brain.add_label("fig6prep/roi_AG.label",borders=False,color="black",alpha=0.125) brain.add_label("fig6prep/roi_AG.label",borders=2,color="#1b9e77",alpha=1) #brain.add_label("fig6prep/roi_STGMTG.label",borders=False,color="blue",alpha=0.125) brain.add_label("fig6prep/roi_STGMTG.label",borders=2,color="#7570b3",alpha=1) brain.add_overlay(volpos, min=2.0739, #p = 0.025 2-tailed max=5.0216, #p = 0.000025, 2-tailed sign="abs", name=outname, hemi=hemi) brain.show_view('lat') brain.save_image("fig6prep/%s.tiff"%(outname)) brain.close()
temp_frange = list(np.arange(frange[fs[0]], frange[fs[1]]) + 1) XX = X[:, :, fs[0]:fs[1], ] XX = XX.mean(axis=-1) # average over tone XX_t = XX / sem(XX, axis=0) # t by subject XXX_t = XX_t.mean(axis=0) these_data = XXX_t for cl_idx, cl in enumerate(clust_labels): hemi = cl.hemi fig, axes = plt.subplots(4, 1) mfig = mlab.figure() brain = Brain("fsaverage", hemi, "inflated", subjects_dir=subjects_dir, figure=mfig) brain.add_label(cl, color="blue", alpha=0.7) axes[0].imshow(mlab.screenshot(figure=mfig)) axes[0].axis("off") mlab.close() mfig = mlab.figure() brain = Brain("fsaverage", hemi, "inflated", subjects_dir=subjects_dir, figure=mfig, views=["med"]) brain.add_label(cl, color="blue", alpha=0.7) axes[1].imshow(mlab.screenshot(figure=mfig)) axes[1].axis("off") mlab.close() temp_mean = these_data.mean(axis=0)
continue this_con = cons["{}-rest".format(block)] con = np.hstack((this_con[bh_reg_inds], 0)) alphas = abs(con) / vmax node_n = len(node_names) con_mat = np.zeros((node_n, node_n)) con_mat[-1, ] = con pcc(con_mat, node_names, node_angles=angles, colormap="seismic", node_colors=colors, vmin=vmin, vmax=vmax, title=block, alphas=None, facecolor="white", textcolor="black") fig = mlab.figure() subjects_dir = "/home/jeff/freesurfer/subjects" brain = Brain('fsaverage', 'lh', "inflated", alpha=1, subjects_dir=subjects_dir, figure=fig) for bon_idx, bon in enumerate(bh_ordered_names): this_label = [l for l in labels if l.name == bon + "-lh"][0] brain.add_label(this_label, color=this_cm(gradient[bon_idx]))
def show(self, figure=None, color=None, opacity=1, bgcolor=(1, 1, 1), size=(600, 600), show_brain=False, brain=None, get_brain=False, fileformat='white'): """show surface Parameters ---------- figure : None | Figure object color : list(3) | None Color of the surface opacity : float | None Opacity of the surface. It's must be between 0 and 1 bgcolor : list(3) Color of the background color size : list(2) Size of the window that displays figures show_brain : Boolean If True, display regions on brain hemispheres brain : Brain surfer instance The basic hemisphere get_brain : Boolean If True, return the last Brain surfer instance fileformat : str The format of file surface hemisphere. It's used only if show_brain is True Returns ------- figure : Figure object brain : Brain surfer object It returned if show_brain is True ------- Author : Alexandre Fabre """ if figure is None: figure = mlab.figure(size=size, bgcolor=bgcolor) if show_brain: if brain is None: # NB: there is an error in sucjects_dir setting brain = Brain(self.label.subject, self.label.hemi, fileformat, subjects_dir='/hpc/comco/brovelli.a/db_mne/meg_te/', figure=figure, background='gii', curv=False, show_toolbar=True) if color is None: color = self.label.color if self.label is not None: brain.add_label(self.label, color=color) else: raise Exception('instance of Surface has not associate a label') else: if color is None: color = self.color x, y, z = np.transpose(self.pos) mesh = mlab.pipeline.triangular_mesh_source(x, y, z, self.triangles, opacity=opacity) mlab.pipeline.surface(mesh, color=color, opacity=opacity) if get_brain: return figure, brain else: return figure
to help characterize the location of your data. """ from os import environ from os.path import join import numpy as np from surfer import Brain, io brain = Brain("fsaverage", "lh", "inflated", config_opts=dict(cortex="low_contrast")) """ The easiest way to label any vertex that could be in the region is with add_label. """ brain.add_label("BA1", color="#A6BDDB") """ You can also threshold based on the probability of that region being at each vertex. """ brain.add_label("BA1", color="#2B8CBE", scalar_thresh=.5) """ It's also possible to plot just the label boundary, in case you wanted to overlay the label on an activation plot to asses whether it falls within that region. """ brain.add_label("BA45", color="#F0F8FF", borders=True, scalar_thresh=.5) brain.add_label("BA45", color="#F0F8FF", alpha=.3, scalar_thresh=.5)
def test_label(): """Test plotting of label.""" _set_backend() subject_id = "fsaverage" hemi = "lh" surf = "inflated" brain = Brain(subject_id, hemi, surf) view = get_view(brain) extra, subj_dir = _get_extra() brain.add_label("BA1" + extra) check_view(brain, view) brain.add_label("BA1" + extra, color="blue", scalar_thresh=.5) label_file = pjoin(subj_dir, subject_id, "label", "%s.MT%s.label" % (hemi, extra)) brain.add_label(label_file) brain.add_label("BA44" + extra, borders=True) brain.add_label("BA6" + extra, alpha=.7) brain.show_view("medial") brain.add_label("V1" + extra, color="steelblue", alpha=.6) brain.add_label("V2" + extra, color="#FF6347", alpha=.6) brain.add_label("entorhinal" + extra, color=(.2, 1, .5), alpha=.6) brain.set_surf('white') brain.show_view(dict(elevation=40, distance=430), distance=430) with pytest.raises(ValueError, match='!='): brain.show_view(dict(elevation=40, distance=430), distance=431) # remove labels brain.remove_labels('V1' + extra) assert 'V2' + extra in brain.labels_dict assert 'V1' + extra not in brain.labels_dict brain.remove_labels() assert 'V2' + extra not in brain.labels_dict brain.close()
---------- .. [1] Glasser MF et al. (2016) A multi-modal parcellation of human cerebral cortex. Nature 536:171-178. """ # Author: Eric Larson <*****@*****.**> # # License: BSD (3-clause) from surfer import Brain import mne subjects_dir = mne.datasets.sample.data_path() + '/subjects' mne.datasets.fetch_hcp_mmp_parcellation(subjects_dir=subjects_dir, verbose=True) labels = mne.read_labels_from_annot( 'fsaverage', 'HCPMMP1', 'lh', subjects_dir=subjects_dir) brain = Brain('fsaverage', 'lh', 'inflated', subjects_dir=subjects_dir, cortex='low_contrast', background='white', size=(800, 600)) brain.add_annotation('HCPMMP1') aud_label = [label for label in labels if label.name == 'L_A1_ROI-lh'][0] brain.add_label(aud_label, borders=False) ############################################################################### # We can also plot a combined set of labels (23 per hemisphere). brain = Brain('fsaverage', 'lh', 'inflated', subjects_dir=subjects_dir, cortex='low_contrast', background='white', size=(800, 600)) brain.add_annotation('HCPMMP1_combined')
if m == 0: ATL = my_ATL[m] else: ATL = ATL + my_ATL[m] brain = Brain('fsaverage', 'lh', 'inflated', subjects_dir=C.data_path, cortex='low_contrast', background='white', size=(400, 400)) for m in np.arange(0, len(my_ATL)): brain.add_label(my_ATL[m], borders=False) #label_ATL = ['L_MT_ROI-lh','L_MST_ROI-lh','L_V4t_ROI-lh','L_FST_ROI-lh', # 'L_LO1_ROI-lh','L_LO2_ROI-lh','L_LO3_ROI-lh','L_PH_ROI-lh'] #label_ATL = ['L_A4_ROI-lh','L_A5_ROI-lh','L_STSda_ROI-lh','L_STSdp_ROI-lh', # 'L_STSva_ROI-lh','L_STSvp_ROI-lh','L_STGa_ROI-lh','L_TA2_ROI-lh'] label_ATL = [ 'L_STSvp_ROI-lh', 'L_TPOJ1_ROI-lh', 'L_PH_ROI-lh', 'L_TE1p_ROI-lh', 'L_TE2p_ROI-lh' ] my_ATL = [] for j in np.arange(0, len(label_ATL)): my_ATL.append([label for label in labels if label.name == label_ATL[j]][0]) for m in np.arange(0, len(my_ATL)): if m == 0:
subject_id = "fsaverage" hemi = "both" #surf = "smoothwm" surf = 'inflated' brain = Brain(subject_id, hemi, surf) list_dirs = os.walk(subject_path + '/func_labels/') color = ['#990033', '#9900CC', '#FF6600', '#FF3333', '#00CC33'] for root, dirs, files in list_dirs: for f in files: label_fname = os.path.join(root, f) label = mne.read_label(label_fname) #label.values.fill(1.0) #label_morph = label.morph(subject_from='fsaverage', subject_to=subject, smooth=5, # n_jobs=1, copy=True) if label.hemi == 'lh': brain.add_label(label, color=random.choice(color)) elif label.hemi == 'rh': brain.add_label(label, color=random.choice(color)) #brain.add_foci(vertno_max, coords_as_verts=True, hemi='lh', color='blue', scale_factor=0.6) # If the label lives in the normal place in the subjects directory, # you can plot it by just using the name #ref_ROI_fname = '/home/qdong/freesurfer/subjects/fsaverage/label/lh.Auditory_82.label' #ref_label = mne.read_label(ref_ROI_fname) #brain.add_label(ref_label, color="blue") #brain.add_label("ROI1", color="blue") #brain.add_label("ROI2", color="red") #brain.add_label("ROI3", color="green") #brain.add_label("ROI4", color="blue") #brain.add_label("ROI5", color="blue") #brain.add_label("ROI6", color="blue") #brain.add_label("ROI7", color="blue")
and visual areas. Here we show several ways to visualize these labels to help characterize the location of your data. """ from os import environ from os.path import join import numpy as np from surfer import Brain, io brain = Brain("fsaverage", "lh", "inflated", config_opts=dict(cortex="low_contrast")) """ The simplest way is to use add_label. """ brain.add_label("BA1", color="darkblue") """ You can also threshold based on the probability of that region being at each vertex. """ brain.add_label("BA1", color="dodgerblue", scalar_thresh=.5) """ It's also possible to plot just the label boundary, in case you wanted to overlay the label on an activation plot to asses whether it falls within that region. """ brain.add_label("BA45", color="firebrick", borders=True) brain.add_label("BA45", color="salmon", borders=True, scalar_thresh=.5)
""" brain = Brain(subject_id, "lh", "inflated") """ First we'll get a set of stereotaxic foci in the MNI coordinate system. These might be peak activations from a volume based analysis. """ coord = [-43, 25, 24] utils.coord_to_label(subject_id, coord, label='example_data/coord', hemi='lh', n_steps=50, map_surface="white") brain.add_label('example_data/coord-lh.label') """ Now we plot the foci on the inflated surface. We will map the foci onto the surface by finding the vertex on the "white" mesh that is closest to the coordinate of the point we want to display. """ brain.add_foci([coord], map_surface="white", color="gold") """ or using a vertex index """ coord = 0 utils.coord_to_label(subject_id, coord, label='example_data/coord',
if doMorph: print 'Morphing %i labels to %i subjects...\n' % (len(labels_to_morph), len(subject_list)) for i, label_orig in enumerate(labels_to_morph): for si, subject in enumerate(subject_list): label = deepcopy(label_orig) # Important to prevent double morphing label.values.fill(1.0) morphedLabel = label.morph(subject_from=modelSubj, subject_to=subject, smooth=n_smooth, grade=src_vert_list[si], n_jobs=6, verbose=False) print(morphedLabel) labelSavePath = op.join(subjectDir, subject, 'label', morphedLabel.name[:-3] + '.label') morphedLabel.save(labelSavePath) print 'Morphing Complete' ########### # Plot ########### colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] color_hexes = ['4C0000', 'FF4D4D', 'FF0000', 'FF8080', 'FFCCCC'] if doPlot: brain = Brain(modelSubj, hemi='lh', surf='white', views=views, show_toolbar=False) for li, label in enumerate([l for l in orig_label_list if l.hemi == 'lh']): brain.add_label(label=label, color=(colors * 2)[li], alpha=0.7, hemi=label.hemi)
with a large amount of control over the visual representation. """ import os from surfer import Brain print(__doc__) subject_id = "fsaverage" hemi = "lh" surf = "smoothwm" brain = Brain(subject_id, hemi, surf) # If the label lives in the normal place in the subjects directory, # you can plot it by just using the name brain.add_label("BA1_exvivo") # Some labels have an associated scalar value at each ID in the label. # For example, they may be probabilistically defined. You can threshold # what vertices show up in the label using this scalar data brain.add_label("BA1_exvivo", color="blue", scalar_thresh=.5) # Or you can give a path to a label in an arbitrary location subj_dir = brain.subjects_dir label_file = os.path.join(subj_dir, subject_id, "label", "%s.MT_exvivo.label" % hemi) brain.add_label(label_file) # By default the label is 'filled-in', but you can # plot just the label boundaries brain.add_label("BA44_exvivo", borders=True)
""" Bring up the visualization. """ brain = Brain(subject_id, "lh", "inflated") """ First we'll get a set of stereotaxic foci in the MNI coordinate system. These might be peak activations from a volume based analysis. """ coord = [-43, 25, 24] utils.coord_to_label(subject_id, coord, label='examples/example_data/coord', hemi='lh', n_steps=50, map_surface="white") brain.add_label('examples/example_data/coord-lh.label') """ Now we plot the foci on the inflated surface. We will map the foci onto the surface by finding the vertex on the "white" mesh that is closest to the coordinate of the point we want to display. """ brain.add_foci([coord], map_surface="white", color="gold") """ or using a vertex index """ coord = 0 utils.coord_to_label(subject_id, coord, label='examples/example_data/coord',
def test_label(): """Test plotting of label """ mlab.options.backend = 'test' subject_id = "fsaverage" hemi = "lh" surf = "inflated" brain = Brain(subject_id, hemi, surf) brain.add_label("BA1") brain.add_label("BA1", color="blue", scalar_thresh=.5) label_file = pjoin(subj_dir, subject_id, "label", "%s.MT.label" % hemi) brain.add_label(label_file) brain.add_label("BA44", borders=True) brain.add_label("BA6", alpha=.7) brain.show_view("medial") brain.add_label("V1", color="steelblue", alpha=.6) brain.add_label("V2", color="#FF6347", alpha=.6) brain.add_label("entorhinal", color=(.2, 1, .5), alpha=.6) brain.close()
with a large amount of control over the visual representation. """ import os from surfer import Brain print(__doc__) subject_id = "fsaverage" hemi = "lh" surf = "smoothwm" brain = Brain(subject_id, hemi, surf) # If the label lives in the normal place in the subjects directory, # you can plot it by just using the name brain.add_label("BA1") # Some labels have an associated scalar value at each ID in the label. # For example, they may be probabilistically defined. You can threshold # what vertices show up in the label using this scalar data brain.add_label("BA1", color="blue", scalar_thresh=.5) # Or you can give a path to a label in an arbitrary location subj_dir = os.environ["SUBJECTS_DIR"] label_file = os.path.join(subj_dir, subject_id, "label", "%s.MT.label" % hemi) brain.add_label(label_file) # By default the label is 'filled-in', but you can # plot just the label boundaries brain.add_label("BA44", borders=True)
# Author: Jean-Remi King <*****@*****.**> # # Licence: BSD 3-clause """Make a plot of the selected region of interest typically associated with visual perception (i.e. ventral and dorsal stream + PFC) Used to generate Figure 2.a """ import numpy as np import matplotlib.pyplot as plt import mne from surfer import Brain rois = ['lingual', 'inferiortemporal', 'superiorparietal', 'supramarginal', 'rostralmiddlefrontal', 'precentral'] brain = Brain('fsaverage', 'split', 'inflated', background='w') labels = mne.read_labels_from_annot('fsaverage', parc='aparc') cmap = plt.get_cmap('rainbow') colors = cmap(np.linspace(0., 1., len(rois))) for roi, color in zip(rois, colors): for hemi in ['lh', 'rh']: label = [lbl for lbl in labels if lbl.name == (roi + '-' + hemi)][0] brain.add_label(label, color=color, alpha=.9, hemi=hemi)
units='m') """ First we'll identify a stereotaxic focus in the MNI coordinate system. This might be a peak activations from a volume based analysis. """ coord = [-43, 25, 24] """ Next we grow a label along the surface around the neareset vertex to this coordinate in the white surface mesh. The `n_steps` argument controls the size of the resulting label. """ utils.coord_to_label(subject_id, coord, label='example_data/coord', hemi='lh', n_steps=25, map_surface="white") brain.add_label('example_data/coord-lh.label', color="darkseagreen", alpha=.8) """ Now we plot the focus on the inflated surface at the vertex identified in the previous step. """ brain.add_foci([coord], map_surface="white", color="mediumseagreen") """ We can also do this using a vertex index, perhaps defined as the peak activation in a surface analysis. This will be more accurate than using a volume-based focus. """ coord = 0 utils.coord_to_label(subject_id, coord, label='example_data/coord',
# Load labels fslabels = mne.read_labels_from_annot('fsaverage', 'aparc_sub', 'both', surf_name='white', subjects_dir=defaults.subjects_dir) wernicke_mni = np.array([-54, -47.5, 7.5]) / 1000 dists = [np.min(np.linalg.norm(l.pos - wernicke_mni, axis=-1)) for l in fslabels] print([fslabels[idx] for idx in np.argsort(dists)[:10]]) wernicke_roi = np.array([fslabels[idx] for idx in np.argsort(dists)[:4]]).sum() broca_mni = np.array([-51, 21.7, 7.5]) / 1000 dists = [np.min(np.linalg.norm(l.pos - broca_mni, axis=-1)) for l in fslabels] print([fslabels[idx] for idx in np.argsort(dists)[:10]]) broca_roi = np.array([fslabels[idx] for idx in np.argsort(dists)[:6]]).sum() brain = Brain('fsaverage', 'lh', 'inflated', subjects_dir=defaults.subjects_dir, cortex='low_contrast', background='white', size=(800, 600)) brain.add_label(wernicke_roi + broca_roi, borders=False) picks = pd.read_csv(op.join(defaults.static, 'picks.tsv'), sep='\t') picks.drop(picks[picks.id.isin(defaults.exclude)].index, inplace=True) picks.sort_values(by='id', inplace=True) for aix, age in enumerate(defaults.ages): subjects = ['genz%s' % ss for ss in picks[picks.ag == age].id] for ix, (kk, vv) in enumerate(defaults.bands.items()): hp, lp = vv for si, subject in enumerate(subjects): bem_dir = os.path.join(defaults.subjects_dir, subject, 'bem') bem_fname = os.path.join(bem_dir, '%s-5120-bem-sol.fif' % subject) src_fname = os.path.join(bem_dir, '%s-oct-6-src.fif' % subject) subj_dir = os.path.join(defaults.megdata, subject) raw_fname = os.path.join(subj_dir, 'sss_pca_fif', '%s_rest_01_allclean_fil100_raw_sss.fif' %
b.add_morphometry(args.morphometry) # Maybe load an overlay if args.overlay is not None: if args.range is not None: args.min, args.max = args.range b.add_overlay(args.overlay, args.min, args.max, args.sign) # Maybe load an annot if args.annotation is not None: if not args.borders: args.borders = any([args.overlay, args.morphometry]) b.add_annotation(args.annotation, args.borders) # Maybe load a label if args.label is not None: if not args.borders: args.borders = any([args.overlay, args.morphometry]) b.add_label(args.label, args.borders) # Also point brain at the Brain() object brain = b # It's nice to have mlab in the namespace, but we'll import it # after the other stuff so getting usage is not interminable from enthought.mayavi import mlab # Now clean up the namespace a bit del parser, args
[0.91, 0.79, sq_size, sq_size]] print '\nPlotting...\n' for ri, roi_name in enumerate(rois): ################################### # Plot source space with roi ################################### width = 500 if ri == 2 else 1000 height = 400 if ri == 2 else 800 brain = Brain(subject_id='fsaverage', hemi=hemi, surf='inflated_pre', size=(height, width), offscreen=True, background='white') # Load corresponding label from fsaverage if roi_name == 'G_temp_sup-G_T_transv-rh.label': brain.add_label(aud_label_fsaverage, color=label_color, alpha=0.75) else: fname_load_label = op.join(struct_dir, model_subj, 'label', roi_name) temp_roi = mne.read_label(fname_load_label, subject=model_subj) brain.add_label(temp_roi, color=label_color, alpha=0.75) # Save montage as an image montage = brain.save_montage(None, order=view_dict[roi_name], orientation='v', border_size=15, colorbar=None) axes[0, ri].imshow(montage, interpolation='nearest', origin='upper', aspect='equal') brain.close() ax_coord = plt.axes(coord_ax_dims[ri], axisbg='none', projection='3d', aspect='equal')
def test_label(): """Test plotting of label.""" _set_backend() subject_id = "fsaverage" hemi = "lh" surf = "inflated" brain = Brain(subject_id, hemi, surf) brain.add_label("BA1") brain.add_label("BA1", color="blue", scalar_thresh=.5) subj_dir = utils._get_subjects_dir() label_file = pjoin(subj_dir, subject_id, "label", "%s.MT.label" % hemi) brain.add_label(label_file) brain.add_label("BA44", borders=True) brain.add_label("BA6", alpha=.7) brain.show_view("medial") brain.add_label("V1", color="steelblue", alpha=.6) brain.add_label("V2", color="#FF6347", alpha=.6) brain.add_label("entorhinal", color=(.2, 1, .5), alpha=.6) brain.set_surf('white') # remove labels brain.remove_labels('V1') assert_in('V2', brain.labels_dict) assert_not_in('V1', brain.labels_dict) brain.remove_labels() assert_not_in('V2', brain.labels_dict) brain.close()
subjects_dir = '/home/qdong/freesurfer/subjects/' subject_path = subjects_dir + 'fsaverage' labels_dir = subject_path + '/func_labels/common/' subject_id = 'fsaverage' hemi = "split" #surf = "smoothwm" surf = 'inflated' #label_fname='/home/qdong/freesurfer/subjects/101611/func_labels/new_func_temporal-lh.label' brain = Brain(subject_id, hemi, surf) list_dirs = os.walk(labels_dir) for root, dirs, files in list_dirs: for f in files: label_fname = os.path.join(root, f) label = mne.read_label(label_fname) brain.add_label(label, color='red') #if f[0:6]=='101611': # brain.add_label(label, color='green', alpha=0.5) #elif f[0:6]=='108815': # brain.add_label(label, color='yellow', alpha=0.5) #elif f[0:6]=='109925': # brain.add_label(label, color='blue', alpha=0.5) #elif f[0:6]=='110061': # brain.add_label(label, color='cyan', alpha=0.5) #elif f[0:6]=='201394': # brain.add_label(label, color='red', alpha=0.5) #elif f[0:6]=='202825': # brain.add_label(label, color='magenta', alpha=0.5) #else: # brain.add_label(label, color='red', subdir=root) #mne.gui.coregistration()
def show_labels(srcfile, measure, brain=None, r_name=None, src_df=None, transform=None, surface='white', time=0.17, labels=None): parc = re.match('source_(\w+)_allsubs_\d+_slabs_\w+.h5', srcfile).group(1) if labels is None: labels = mne.read_labels_from_annot('fsaverage', parc=parc, hemi='both') labels = {l.name: l for l in labels} file = os.path.join(bem_dir, srcfile) if srcfile.find('_slabs_') >= 0: slabsi = file.find('slabs_') r_n = file[slabsi + 6:-3] if r_name is None: r_name = r_n elif r_name != r_n: raise ValueError( "Provided source file name and name of desired " "regressor are not compatible!") if src_df is None: src_df = pd.read_hdf(file, 'second_level_src') if brain is None: brain = Brain('fsaverage', 'both', surface, cortex='low_contrast', subjects_dir=subjects_dir) else: brain.remove_labels(hemi='rh') brain.remove_labels(hemi='lh') data = src_df.loc[(slice(None), time), measure] if transform is not None: data = transform(data) vmin = 0.9 norm = matplotlib.colors.Normalize(vmin, 1, clip=True) alpha = matplotlib.colors.Normalize(vmin, (1 - vmin) / 2 + vmin, clip=True) data = data[data > vmin] cmap = matplotlib.cm.hot print(data) for index, value in data.iteritems(): if index[0].startswith('L'): hemi = 'left' else: hemi = 'right' print(index[0]) brain.add_label(labels[index[0]], color=cmap(norm(value)), alpha=alpha(value), hemi=hemi) return brain
print(__doc__) brain = Brain("fsaverage", "lh", "inflated") """ Show the morphometry with a continuous grayscale colormap. """ brain.add_morphometry("curv", colormap="binary", min=-.8, max=.8, colorbar=False) """ The easiest way to label any vertex that could be in the region is with add_label. """ brain.add_label("BA1_exvivo", color="#A6BDDB") """ You can also threshold based on the probability of that region being at each vertex. """ brain.add_label("BA1_exvivo", color="#2B8CBE", scalar_thresh=.5) """ It's also possible to plot just the label boundary, in case you wanted to overlay the label on an activation plot to asses whether it falls within that region. """ brain.add_label("BA45_exvivo", color="#F0F8FF", borders=3, scalar_thresh=.5) brain.add_label("BA45_exvivo", color="#F0F8FF", alpha=.3, scalar_thresh=.5)
""" Bring up the visualization. """ brain = Brain(subject_id, "lh", "inflated") """ First we'll get a set of stereotaxic foci in the MNI coordinate system. These might be peak activations from a volume based analysis. """ coord = [-43, 25, 24] utils.coord_to_label(subject_id, coord, label='coord', hemi='lh', n_steps=50, map_surface="white") brain.add_label('coord-lh.label') """ Now we plot the foci on the inflated surface. We will map the foci onto the surface by finding the vertex on the "white" mesh that is closest to the coordinate of the point we want to display. """ brain.add_foci([coord], map_surface="white", color="gold") """ or using a vertex index """ coord = 0 utils.coord_to_label(subject_id, coord, label='coord', hemi='lh', n_steps=50,
subjects_dir = mne.datasets.sample.data_path() + '/subjects' mne.datasets.fetch_hcp_mmp_parcellation(subjects_dir=subjects_dir, verbose=True) labels = mne.read_labels_from_annot('fsaverage', 'HCPMMP1', 'lh', subjects_dir=subjects_dir) brain = Brain('fsaverage', 'lh', 'inflated', subjects_dir=subjects_dir, cortex='low_contrast', background='white', size=(800, 600)) brain.add_annotation('HCPMMP1') aud_label = [label for label in labels if label.name == 'L_A1_ROI-lh'][0] brain.add_label(aud_label, borders=False) ############################################################################### # We can also plot a combined set of labels (23 per hemisphere). brain = Brain('fsaverage', 'lh', 'inflated', subjects_dir=subjects_dir, cortex='low_contrast', background='white', size=(800, 600)) brain.add_annotation('HCPMMP1_combined')
""" print __doc__ import os from surfer import Brain subject_id = "fsaverage" hemi = "lh" surf = "smoothwm" brain = Brain(subject_id, hemi, surf) # If the label lives in the normal place in the subjects directory, # you can plot it by just using the name brain.add_label("BA1") # Or you can give a path to a label in an arbitrary location subj_dir = os.environ["SUBJECTS_DIR"] label_file = os.path.join(subj_dir, subject_id, "label", "%s.MT.label" % hemi) brain.add_label(label_file) # By default the label is 'filled-in', but you can # plot just the label boundaries brain.add_label("BA44", borders=True) # You can also control the opacity of the label color brain.add_label("BA6", alpha=.7)
# Author: Jean-Remi King <*****@*****.**> # # Licence: BSD 3-clause """Make a plot of the selected region of interest typically associated with visual perception (i.e. ventral and dorsal stream + PFC) Used to generate Figure 2.a """ import numpy as np import matplotlib.pyplot as plt import mne from surfer import Brain rois = [ 'lingual', 'inferiortemporal', 'superiorparietal', 'supramarginal', 'rostralmiddlefrontal', 'precentral' ] brain = Brain('fsaverage', 'split', 'inflated', background='w') labels = mne.read_labels_from_annot('fsaverage', parc='aparc') cmap = plt.get_cmap('rainbow') colors = cmap(np.linspace(0., 1., len(rois))) for roi, color in zip(rois, colors): for hemi in ['lh', 'rh']: label = [lbl for lbl in labels if lbl.name == (roi + '-' + hemi)][0] brain.add_label(label, color=color, alpha=.9, hemi=hemi)
cont_result = np.expand_dims(cont_result, 0) XXX = np.vstack((XXX, cont_result)) fig, axes = plt.subplots(len(these_labels), len(temp_conds) + 1, figsize=(12, 8)) for tl_idx, this_label in enumerate(these_labels): mfig = mlab.figure() hemi = "lh" if "lh" in this_label.name else "rh" brain = Brain('fsaverage', hemi, 'inflated', subjects_dir=subjects_dir, cortex='low_contrast', size=(800, 600), figure=mfig) brain.add_label(this_label) axes[tl_idx, 0].imshow(mlab.screenshot(figure=mfig)) axes[tl_idx, 0].axis("off") mlab.close() for ax_idx, ax in enumerate(axes[tl_idx, 1:]): ax.imshow(XXX[ax_idx, :, tl_idx, v[0]:v[1]], vmin=vmin, vmax=vmax, cmap="seismic") ax.set_title(temp_conds[ax_idx]) plt.sca(ax) if ax_idx == len(temp_conds) - 1: plt.yticks(ticks=np.arange(len(subjs_t)), labels=subjs_t) ax.yaxis.tick_right() else: ax.yaxis.set_visible(False)
Display ROIs based on MNE estimates and select dipoles for causality analysis. ''' import os import glob import mne from surfer import Brain subjects_dir = os.environ['SUBJECTS_DIR'] stcs_path = subjects_dir + '/fsaverage/conf_stc/' labels_dir = stcs_path + 'STC_ROI/func/' subject_id = 'fsaverage' hemi = "split" # surf = "smoothwm" surf = 'inflated' fn_list = glob.glob(labels_dir + '*') brain = Brain(subject_id, hemi, surf) color = ['#990033', '#9900CC', '#FF6600', '#FF3333', '#00CC33'] i = 0 for fn_label in fn_list: label_name = os.path.split(fn_label)[-1] # if label_name.split('_')[0] == 'sti,RRst': i = i + 1 ind = i % 5 label = mne.read_label(fn_label) brain.add_label(label, color=color[ind], alpha=0.8) brain.add_annotation(annot='aparc', borders=True)