def plot_lv(lv): import matplotlib.pyplot as plt fig1 = mlab.figure() cor = surfer.Brain('mni', 'rh', 'cortex', curv=False, figure=fig1) cor.add_data(saliences[:, lv], vertices=my_cor_vertices) useTrans = len(my_cor_vertices) != saliences.shape[0] cor.scale_data_colormap(np.min(saliences[:, lv]), 0, np.max(saliences[:, lv]), useTrans) fig2 = mlab.figure() cor = surfer.Brain('mni', 'rh', 'cortex', curv=False, figure=fig2) cor.add_data(saliences[:, lv], vertices=my_cor_vertices) useTrans = len(my_cor_vertices) != saliences.shape[0] cor.scale_data_colormap(np.min(saliences[:, lv]), 0, np.max(saliences[:, lv]), useTrans) ind = np.arange(num_comps) # the x locations for the groups width = 0.15 # the width of the bars: can also be len(x) sequence fig = plt.figure() ax = plt.subplot(111) # colors = ['r', 'g', 'b', 'y', 'k'] from random import random colors = [ 'red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple', 'white', 'black', 'grey', 'brown' ] # legend = ['mediodorsal', 'pulvinar', 'LGB', 'MGB', 'LP', 'LD', 'VPLc', 'VPL', 'VLO', 'VA', 'anterior'] # colors = [(1,1,1)] + [(random(),random(),random()) for i in xrange(patterns.shape[0])] rects = [ plt.bar(i, patterns[i, lv], color=colors[i], label=label_names[i]) for i in range(patterns.shape[0] / 2) ] rects = rects + [ plt.bar(i + 1, patterns[i, lv], color=colors[i - len(label_names)]) for i in range(len(label_names), patterns.shape[0]) ] plt.ylim([-1, 1]) # rects = [] # for c, color in enumerate(colors): # rects.append(pl.bar(ind + c * width, patterns[c, lv], width, color=color)) # plt.ylabel('Saliences') # plt.title('Saliences by seed-voxel') # plt.xticks(ind + width / 2., ['LV' + str(i + 1) for i in range(num_comps)]) # plt.plot(plt.xlim(), [0, 0], 'k') # plt.legend(rects, [str(i + 1) for i in my_sub_vertices], loc=0) # Shink current axis by 20% box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) # Put a legend to the right of the current axis ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) # plt.legend(rects, legend, loc=0) plt.show(block=False)
def plot_distance(stc_est, stc_signal, D, surface='inflated'): """Plots the distance to the peak estimated signal, along with the true signal location""" peak = stc_est.get_peak(vert_as_index=True)[0] peak_hemi = 0 if peak < len(stc_est.vertices[0]) else 1 true_hemi = config.signal_hemi est_vert = np.hstack(stc_est.vertices)[peak] true_vert = stc_signal.vertices[true_hemi][0] brain = surfer.Brain('sample', hemi='both', surf=surface) brain.add_data(D[peak, :len(stc_est.vertices[0])], vertices=stc_est.vertices[0], hemi='lh', transparent=True) brain.add_data(D[peak, len(stc_est.vertices[0]):], vertices=stc_est.vertices[1], hemi='rh', transparent=True) brain.add_foci([est_vert], coords_as_verts=True, hemi='lh' if peak_hemi == 0 else 'rh', color='red') brain.add_foci([true_vert], coords_as_verts=True, hemi='lh' if true_hemi == 0 else 'rh', color='green') return brain
def surfplot_2x2(nodeData,atlas,savedir,ttl='',clim_type='all',cmap='plasma'): # INPUTS: # nodeData: Nx1 data for N nodes # atlas: string specifiying atlas of node data # ttl: title to go above entire plot # savedir: where to output temporary files which will be deleted # clim_type: optional limit for color axis, symmetric about 0. # 'all' (default) means set color scales based on all values in nodeData # a numeric input will be set as the color limit if clim_type == 'all': clim = np.round(np.max(np.abs(nodeData)),decimals=2) print('color limits:' +str(clim)) if clim ==0: clim = 0.2 print('setting clim to 0.2 by default') else: clim = clim_type hemis = ['lh','rh'] views = ['lat','med'] thrsh = -10 subject_id = 'fsaverage' surf = 'pial' cbar = False for hemi in hemis: ntv = node_to_vertex(annot_path='data/annot/',node_data=nodeData) vtx_data = ntv.getvertdata(atlas,hemi=hemi) for view in views: fig = my.mlab.figure(size=(340,340)) fig = my.mlab.gcf() brain = surfer.Brain(subject_id, hemi, surf,figure=fig,views=view,background='white', alpha = 1) brain.add_data(vtx_data, min = -clim, max = clim, thresh = thrsh, colormap=cmap, alpha=.8,colorbar=cbar,time_label=None) fname = 'nodeData' + view + hemi + '.png' my.mlab.savefig(figure=fig,filename=opj(savedir,fname),magnification=1) my.mlab.close(all=True) #Arrange brains into grid arial = {'fontname':'Arial'} plt.figure(figsize = [1.7,1.7]) for H,hemi in enumerate(hemis): for V, view in enumerate(views): #Arrange brains into grid fname = opj(savedir,'nodeData' + view + hemi + '.png') img = mpimg.imread(fname) plt.subplot(2,2,(H + 2*V+1)) imgplot = plt.imshow(img,aspect='auto') plt.axis('off') plt.subplots_adjust(hspace=0, wspace=0.05) plt.suptitle(ttl,family='arial',size=8,weight='bold') #delete intermediate files [os.remove(f) for f in glob(opj(savedir,'nodeData*.png'))] return(plt.gcf())
def build_surface(self, subjects_dir=None, subject=None): ''' creates a pysurfer surface and plots it specify subject, subjects_dir or these are taken from the environment Returns ------- brain | surfer.viz.Brain Pysurfer brain object figure | mlab.scene Mayavi scene object ''' if subjects_dir == None: subjects_dir = os.environ['SUBJECTS_DIR'] if subject == None: subject = os.environ['SUBJECT'] self.brain = surfer.Brain(subject, hemi='both', surf='pial', figure=self.scene.mayavi_scene, subjects_dir=subjects_dir, curv=False) #self.scene = self.brain._figures[0][0] self.brain.toggle_toolbars(True) #set the surface unpickable for srf in self.brain.brains: srf._geo_surf.actor.actor.pickable = False srf._geo_surf.actor.property.opacity = self.opacity return self.brain
''' Script to show the picked point in the surface on the screen''' import surfer from mayavi import mlab import numpy as np fig = mlab.figure() tha = surfer.Brain('mni', 'rh', 'thalamus', curv=False, figure=fig) Y = np.array(range(3108)) tha.add_data(Y) def picker_callback(picker_obj): print picker_obj.point_id fig.on_mouse_pick(picker_callback) mlab.show()
continue if sensor_type == 'joint' and use_noise_cov == False: continue # Add row to the HTML table html_table += '<tr><td>' + '</td><td>'.join([str(s) for s in setting]) + '</td>' try: if len(sel) < 1000: raise RuntimeError('not enough vertices') # Create the brain plots mlab.figure(1, size=(600, 500)) vertices = fwd['src'][1]['vertno'][sel['vertex']] brain = surfer.Brain('sample', hemi='rh', surf='white', figure=1) brain.add_data(sel['dist'], vertices=vertices, smoothing_steps=5) brain.scale_data_colormap(0, 0.075, 0.15, transparent=False) mlab.view(0, 90, 250, [33, -10, 35]) mlab.savefig('html/lcmv/%03d_dist_out.png' % i) mlab.view(-180, 90, 300, [33, -10, 35]) mlab.savefig('html/lcmv/%03d_dist_in.png' % i) mlab.close(1) mlab.figure(1, size=(600, 500)) vertices = fwd['src'][1]['vertno'][sel['vertex']] brain = surfer.Brain('sample', hemi='rh', surf='white', figure=1) brain.add_data(sel['eval'], vertices=vertices, smoothing_steps=5) brain.scale_data_colormap(0, 0.001, 0.002, transparent=False) mlab.view(0, 90, 250, [33, -10, 35]) mlab.savefig('html/lcmv/%03d_eval_out.png' % i)
m + '-sig.mgh') # p = nib.freesurfer.mghformat.load('data/Sunetal2018_Fig1Maps/left-CT-sig.mgh') b = np.squeeze(np.asarray( b.get_data()[:, :, :, 1])) # select 22q-control predictor betas p = np.squeeze(np.asarray(p.get_data())) data_plot = -b clim = np.abs(b).max() cmax = b.max() cmin = b.min() fig = my.mlab.figure(size=(340, 340)) fig = my.mlab.gcf() brain = surfer.Brain(subject_id, hemi, surf, figure=fig, views=view, background='white', alpha=1) brain.add_data(data_plot, min=cmin, max=cmax, mid=0, thresh=thrsh, colormap=cmap, alpha=1, colorbar=cbar) my.mlab.savefig(figure=fig, filename=opj('data', 'Sunetal2018_Fig1Maps', view + m + subject_id + 'Betas.png'), magnification=1)
def brain_plot(roi_data, parcel_names, parc_file, fig_str, subject_id='fsaverage', hemi='lh', surf='inflated', color='coolwarm', center_anchor=0, showcolorbar=False): vtx_data, plot_min, plot_max = roi_to_vtx(roi_data, parcel_names, parc_file) if np.all(vtx_data == -1000) == False: if color == 'coolwarm': if center_anchor == 0: if abs(plot_max) > abs(plot_min): center_anchor = abs(plot_max) elif abs(plot_max) < abs(plot_min): center_anchor = abs(plot_min) else: center_anchor = abs(plot_max) if center_anchor == -1000: center_anchor = 1 print(center_anchor) if center_anchor != 0: view = 'lat' fname1 = view + '_' + fig_str + '.png' fig = my.mlab.figure(size=(1000, 1000)) fig = my.mlab.gcf() brain = surfer.Brain(subject_id, hemi, surf, figure=fig, views=view, background='white', alpha=1) if subject_id == 'fsaverage': brain.add_morphometry("avg_sulc", colormap="binary", min=-3, max=3, colorbar=False) elif subject_id == 'lausanne125': brain.add_morphometry("avg_curv", colormap="binary", min=-.5, max=.5, colorbar=False) brain.add_data(vtx_data, max=center_anchor, center=0, thresh=-999, colormap=color, alpha=1, colorbar=showcolorbar) brain.add_annotation(parc_file, hemi=hemi, borders=True, alpha=.25, color='lightsteelblue') my.mlab.savefig(figure=fig, filename=fname1) my.mlab.close() view = 'med' fname2 = view + '_' + fig_str + '.png' fig = my.mlab.figure(size=(1000, 1000)) fig = my.mlab.gcf() brain = surfer.Brain(subject_id, hemi, surf, figure=fig, views=view, background='white', alpha=1) if subject_id == 'fsaverage': brain.add_morphometry("avg_sulc", colormap="binary", min=-3, max=3, colorbar=False) elif subject_id == 'lausanne125': brain.add_morphometry("avg_curv", colormap="binary", min=-.5, max=.5, colorbar=False) brain.add_data(vtx_data, max=center_anchor, center=0, thresh=-999, colormap=color, alpha=1, colorbar=showcolorbar) brain.add_annotation(parc_file, hemi=hemi, borders=True, alpha=.25, color='lightsteelblue') my.mlab.savefig(figure=fig, filename=fname2) my.mlab.close() view = 'ventral' fname2 = view + '_' + fig_str + '.png' fig = my.mlab.figure(size=(1000, 1000)) fig = my.mlab.gcf() brain = surfer.Brain(subject_id, hemi, surf, figure=fig, views=view, background='white', alpha=1) if subject_id == 'fsaverage': brain.add_morphometry("avg_sulc", colormap="binary", min=-3, max=3, colorbar=False) elif subject_id == 'lausanne125': brain.add_morphometry("avg_curv", colormap="binary", min=-.5, max=.5, colorbar=False) brain.add_data(vtx_data, max=center_anchor, center=0, thresh=-999, colormap=color, alpha=1, colorbar=showcolorbar) brain.add_annotation(parc_file, hemi=hemi, borders=True, alpha=.25, color='lightsteelblue') my.mlab.savefig(figure=fig, filename=fname2) my.mlab.close() else: print('There' 's nothing to plot...') elif color == 'viridis' or color == 'viridis_r': view = 'lat' fname1 = view + '_' + fig_str + '.png' fig = my.mlab.figure(size=(1000, 1000)) fig = my.mlab.gcf() brain = surfer.Brain(subject_id, hemi, surf, figure=fig, views=view, background='white', alpha=1) if subject_id == 'fsaverage': brain.add_morphometry("avg_sulc", colormap="binary", min=-3, max=3, colorbar=False) elif subject_id == 'lausanne125': brain.add_morphometry("avg_curv", colormap="binary", min=-.5, max=.5, colorbar=False) brain.add_data(vtx_data, max=plot_max, min=plot_min, thresh=-999, colormap=color, alpha=1, colorbar=showcolorbar) brain.add_annotation(parc_file, hemi=hemi, borders=True, alpha=.25, color='lightsteelblue') my.mlab.savefig(figure=fig, filename=fname1) my.mlab.close() view = 'med' fname2 = view + '_' + fig_str + '.png' fig = my.mlab.figure(size=(1000, 1000)) fig = my.mlab.gcf() brain = surfer.Brain(subject_id, hemi, surf, figure=fig, views=view, background='white', alpha=1) if subject_id == 'fsaverage': brain.add_morphometry("avg_sulc", colormap="binary", min=-3, max=3, colorbar=False) elif subject_id == 'lausanne125': brain.add_morphometry("avg_curv", colormap="binary", min=-.5, max=.5, colorbar=False) brain.add_data(vtx_data, max=plot_max, min=plot_min, thresh=-999, colormap=color, alpha=1, colorbar=showcolorbar) brain.add_annotation(parc_file, hemi=hemi, borders=True, alpha=.25, color='lightsteelblue') my.mlab.savefig(figure=fig, filename=fname2) my.mlab.close() elif color == 'hot': if center_anchor != 0: plot_max = center_anchor view = 'lat' fname1 = view + '_' + fig_str + '.png' fig = my.mlab.figure(size=(1000, 1000)) fig = my.mlab.gcf() brain = surfer.Brain(subject_id, hemi, surf, figure=fig, views=view, background='white', alpha=1) if subject_id == 'fsaverage': brain.add_morphometry("avg_sulc", colormap="binary", min=-3, max=3, colorbar=False) elif subject_id == 'lausanne125': brain.add_morphometry("avg_curv", colormap="binary", min=-.5, max=.5, colorbar=False) brain.add_data(vtx_data, min=0, max=plot_max, thresh=-999, colormap=color, alpha=1, colorbar=showcolorbar) brain.add_annotation(parc_file, hemi=hemi, borders=True, alpha=.25, color='lightsteelblue') my.mlab.savefig(figure=fig, filename=fname1) my.mlab.close() view = 'med' fname2 = view + '_' + fig_str + '.png' fig = my.mlab.figure(size=(1000, 1000)) fig = my.mlab.gcf() brain = surfer.Brain(subject_id, hemi, surf, figure=fig, views=view, background='white', alpha=1) if subject_id == 'fsaverage': brain.add_morphometry("avg_sulc", colormap="binary", min=-3, max=3, colorbar=False) elif subject_id == 'lausanne125': brain.add_morphometry("avg_curv", colormap="binary", min=-.5, max=.5, colorbar=False) brain.add_data(vtx_data, min=0, max=plot_max, thresh=-999, colormap=color, alpha=1, colorbar=showcolorbar) brain.add_annotation(parc_file, hemi=hemi, borders=True, alpha=.25, color='lightsteelblue') my.mlab.savefig(figure=fig, filename=fname2) my.mlab.close() else: my_cmap = list() for i in np.arange(0, int(plot_max)): my_cmap.append(get_cmap(color)(i)) view = 'lat' fname1 = view + '_' + fig_str + '.png' fig = my.mlab.figure(size=(1000, 1000)) fig = my.mlab.gcf() brain = surfer.Brain(subject_id, hemi, surf, figure=fig, views=view, background='white', alpha=1) if subject_id == 'fsaverage': brain.add_morphometry("avg_sulc", colormap="binary", min=-3, max=3, colorbar=False) elif subject_id == 'lausanne125': brain.add_morphometry("avg_curv", colormap="binary", min=-.5, max=.5, colorbar=False) brain.add_data(vtx_data, min=plot_min, max=plot_max, thresh=-999, colormap=my_cmap, alpha=1, colorbar=showcolorbar) brain.add_annotation(parc_file, hemi=hemi, borders=True, alpha=.25, color='lightsteelblue') my.mlab.savefig(figure=fig, filename=fname1) my.mlab.close() view = 'med' fname2 = view + '_' + fig_str + '.png' fig = my.mlab.figure(size=(1000, 1000)) fig = my.mlab.gcf() brain = surfer.Brain(subject_id, hemi, surf, figure=fig, views=view, background='white', alpha=1) if subject_id == 'fsaverage': brain.add_morphometry("avg_sulc", colormap="binary", min=-3, max=3, colorbar=False) elif subject_id == 'lausanne125': brain.add_morphometry("avg_curv", colormap="binary", min=-.5, max=.5, colorbar=False) brain.add_data(vtx_data, min=plot_min, max=plot_max, thresh=-999, colormap=my_cmap, alpha=1, colorbar=showcolorbar) brain.add_annotation(parc_file, hemi=hemi, borders=True, alpha=.25, color='lightsteelblue') my.mlab.savefig(figure=fig, filename=fname2) my.mlab.close() else: view = 'lat' fname1 = view + '_' + fig_str + '.png' fig = my.mlab.figure(size=(1000, 1000)) fig = my.mlab.gcf() brain = surfer.Brain(subject_id, hemi, surf, figure=fig, views=view, background='white', alpha=1) if subject_id == 'fsaverage': brain.add_morphometry("avg_sulc", colormap="binary", min=-3, max=3, colorbar=False) elif subject_id == 'lausanne125': brain.add_morphometry("avg_curv", colormap="binary", min=-.5, max=.5, colorbar=False) brain.add_annotation(parc_file, hemi=hemi, borders=True, alpha=.25, color='lightsteelblue') my.mlab.savefig(figure=fig, filename=fname1) my.mlab.close() view = 'med' fname2 = view + '_' + fig_str + '.png' fig = my.mlab.figure(size=(1000, 1000)) fig = my.mlab.gcf() brain = surfer.Brain(subject_id, hemi, surf, figure=fig, views=view, background='white', alpha=1) if subject_id == 'fsaverage': brain.add_morphometry("avg_sulc", colormap="binary", min=-3, max=3, colorbar=False) elif subject_id == 'lausanne125': brain.add_morphometry("avg_curv", colormap="binary", min=-.5, max=.5, colorbar=False) brain.add_annotation(parc_file, hemi=hemi, borders=True, alpha=.25, color='lightsteelblue') my.mlab.savefig(figure=fig, filename=fname2) my.mlab.close()
import glob from os.path import join #Enter directory with the mgh files General_Directory = '' Hemisphere = 'lh' Viewpoint = ["lateral", "medial", "parietal", "ventral"] C1_Col = 'Reds' C2_Col = 'Greens' C3_Col = 'Wistia' brain = surfer.Brain('fsaverage', '{}'.format(Hemisphere), 'inflated', config_opts={ 'cortex': 'bone', 'background': 'white' }) light_settings = [{ 'elevation': 0, 'azimuth': 0, 'intensity': 0.7 }, { 'elevation': 0, 'azimuth': -90, 'intensity': 0.7 }, { 'elevation': 0, 'azimuth': 90, 'intensity': 0.7
def surfplot_2xK(nodeData,hemi,atlas,ttls,savedir,clim_type='each',cbar_yn=True,cmap = 'plasma'): # INPUTS: # nodeData: NxK data for N nodes and K activation maps # hemi: hemisphere to plot # atlas: string specifiying atlas of node data # ttls: length K list of plot titles # savedir: where to output temporary files which will be deleted # clim_type: optional limit for color axis, symmetric about 0. # 'each' (default) means each map is scaled independently # 'all' means set color scales based on all values in nodeData # a numeric input will be set as the color limit # cbar_yn: if True, put a colorbar on the bottom row of plots views=['lat','med'] thrsh = -10 subject_id = 'fsaverage' surf = 'pial' tmp = 'TEMP_BRAIN' N,K = nodeData.shape ntv = node_to_vertex(annot_path='../data/annot/',node_data=nodeData) vtx_data = ntv.getvertdata(atlas,hemi=hemi) img=dict() for act_map in range(K): data_plot = vtx_data[:,act_map] if clim_type == 'each': clim = np.max(np.abs(data_plot[data_plot>-999])) elif clim_type == 'all': clim = np.max(np.abs(vtx_data[vtx_data > -999])) else: clim = clim_type print('color limits:' +str(clim)) for view in views: cbar = False if view == 'med': cbar = cbar_yn fig = my.mlab.figure(size=(340,340)) fig = my.mlab.gcf() brain = surfer.Brain(subject_id, hemi, surf,figure=fig,views=view,background='white', alpha = 1) brain.add_data(data_plot, min = -clim, max = clim, thresh = thrsh, colormap= cmap,alpha=1,colorbar=cbar) fname = tmp + str(act_map) + view + hemi + '.png' #img[str(act_map)+view] = my.mlab.screenshot(figure=fig, mode='rgba', antialiased=True) my.mlab.savefig(figure=fig,filename=opj(savedir,fname),magnification=1) my.mlab.close(all=True) fig = plt.figure(figsize = [K,2]) arial = {'fontname':'Arial'} for view in np.arange(1,len(views)+1): for act_map in np.arange(K): fname = tmp + str(act_map) + views[view-1] + hemi + '.png' img = mpimg.imread(opj(savedir,fname)) plt.subplot(2,K,1+act_map + K*(view-1)) #imgplot = plt.imshow(img[str(act_map)+views[view-1]],aspect='auto') imgplot = plt.imshow(img,aspect='auto') if view == 1: ttl = ttls[act_map] plt.title(ttl,fontsize=8,fontweight='bold',**arial) plt.axis('off') plt.subplots_adjust(hspace=0, wspace=0.05) [os.remove(f) for f in glob(opj(savedir,tmp + '*' + hemi + '.png'))] return(plt.gcf())