def plot_ctx(): # Visualize the left or right hemisphere activation map per run with Yeo 2011 overlay of functional connectivity maps # State path to statistical mask files generated by freesurfer processes path = "/home/lauri/Documents/temp/" statpath = os.listdir(path) statfile = [] hemispheres = ['lh','rh'] # Creates a function to grab all cortical statistical files for h in hemispheres: for s in statpath: if s.startswith(h) and s.endswith("gz"): statfile.append(s) print('Making images for:') statfile.sort() print(statfile) # Create the image using pysurfer with backend function initialized for h in hemispheres: for f in statfile: sig = os.path.join(path,f) sub = "fsaverage" hemi = h surf = "inflated" view_types = ['lat','med'] brain = Brain(sub, hemi, surf, cortex=None, background="midnightblue", views=view_types) overlay_file = sig brain.add_overlay(sig, min=1, max=3, name="ovrlay") # To change colour of activations: note replace pos or neg: brain.overlays["ovrlay"].neg_bar.lut_mode = "winter" subjects_dir = os.environ["SUBJECTS_DIR"] annot_path = os.path.join(subjects_dir, sub, "label", "lh.Yeo2011_7Networks_N1000.annot") brain.add_annotation(annot_path, hemi=h, borders=False, alpha=.33) brain.save_image(os.path.join(path,f + ".jpeg"))
def montage_plot(parameter, in_dir, task, fdr_correct=True, hemi='lh', input_hemisphere='', annot=None): ''' Make plots for parameter on the cortical surface using pysurf module - Arguments: a) parameter b) output directory c) task (inference or instructed) d) FDR correction (boolean) ''' out_dir = join(in_dir, 'pysurf_plots') slu.mkdir_p(out_dir) fsaverage = "fsaverage" surf = "inflated" t_data, p_data, str_names, labels = get_data(task, in_dir, input_hemisphere, hemi) if fdr_correct is True: data = fdr_filter(t_data, p_data, parameter) else: data = t_data[parameter].values data = data[labels] brain = Brain(fsaverage, hemi, surf, background="white", title=parameter + task) brain.add_data(data, -10, 10, thresh=None, colormap="RdBu_r", alpha=.8) if annot is not None: brain.add_annotation(annot, color='white', alpha=1) brain.save_imageset(join(out_dir, parameter + '_' + task + input_hemisphere), ['lateral', 'medial', 'par'], colorbar=None)
def test_annot(): """Test plotting of annot """ mlab.options.backend = 'test' annots = ['aparc', 'aparc.a2005s'] borders = [True, False] alphas = [1, 0.5] brain = Brain(*std_args) for a, b, p in zip(annots, borders, alphas): brain.add_annotation(a, b, p)
def test_annot(): """Test plotting of annot.""" mlab.options.backend = 'test' annots = ['aparc', 'aparc.a2005s'] borders = [True, False, 2] alphas = [1, 0.5] brain = Brain(*std_args) for a, b, p in zip(annots, borders, alphas): brain.add_annotation(a, b, p) assert_raises(ValueError, brain.add_annotation, 'aparc', borders=-1) brain.close()
def test_annot(): """Test plotting of annot """ mlab.options.backend = 'test' annots = ['aparc', 'aparc.a2005s'] borders = [True, False] alphas = [1, 0.5] brain = Brain(*std_args) for a, b, p in zip(annots, borders, alphas): brain.add_annotation(a, b, p) brain.close()
def test_annot(): """Test plotting of annot.""" _set_backend() annots = ['aparc', 'aparc.a2005s'] borders = [True, False, 2] alphas = [1, 0.5] brain = Brain(*std_args) view = get_view(brain) for a, b, p in zip(annots, borders, alphas): brain.add_annotation(a, b, p, opacity=0.8) check_view(brain, view) brain.set_surf('white') with pytest.raises(ValueError): brain.add_annotation('aparc', borders=-1) subj_dir = utils._get_subjects_dir() annot_path = pjoin(subj_dir, subject_id, 'label', 'lh.aparc.a2009s.annot') labels, ctab, names = nib.freesurfer.read_annot(annot_path) brain.add_annotation((labels, ctab)) brain.add_annotation('aparc', color="red", remove_existing=True) surf = brain.annot["surface"] ctab = surf.module_manager.scalar_lut_manager.lut.table for color in ctab: assert color[:3] == (255, 0, 0) brain.close()
def test_annot(): """Test plotting of annot.""" _set_backend() annots = ['aparc', 'aparc.a2005s'] borders = [True, False, 2] alphas = [1, 0.5] brain = Brain(*std_args) for a, b, p in zip(annots, borders, alphas): brain.add_annotation(a, b, p) brain.set_surf('white') assert_raises(ValueError, brain.add_annotation, 'aparc', borders=-1) subj_dir = utils._get_subjects_dir() annot_path = pjoin(subj_dir, subject_id, 'label', 'lh.aparc.a2009s.annot') labels, ctab, names = nib.freesurfer.read_annot(annot_path) brain.add_annotation((labels, ctab)) brain.close()
hemi = "both" surface = "inflated" view = "frontal" """ Bring up the visualization """ brain = Brain(subject_id, hemi, surface, views=view, config_opts={"cortex": "bone", "background": "ivory"}) """ Display the 'aparc' parcellation borders. To use annotations that live in your subject's label directory, just use the annot name. """ brain.add_annotation("aparc") """ You can also display the regions with "filled in" colors """ brain.add_annotation("aparc", borders=False) """ You may also provide a full path to an annotation file at an arbitray location on the disc. You can also plot things separately for the left and right hemispheres. """ subjects_dir = os.environ["SUBJECTS_DIR"] annot_path = pjoin(subjects_dir, subject_id, "label", "lh.aparc.annot") brain.add_annotation(annot_path, hemi="lh", borders=False) annot_path = pjoin(subjects_dir, subject_id, "label", "rh.aparc.a2009s.annot")
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)
def source_recon(subject): global report from mayavi import mlab clean_path = op.join(rest_dir, subject, 'meg_clean', 'clean_raw.fif') empty_room_path = op.join( 'G:\OpenSource_data\CAM-CAN\cc700\meg\pipeline\\release004\emptyroom', subject[4:], 'emptyroom_' + subject[4:] + '.fif') if not os.path.exists(clean_path): return raw_clean = read_raw_fif(clean_path, preload=True) raw_empty_room = read_raw_fif(empty_room_path, preload=True) trans = mne.read_trans( op.join(rest_dir, subject, 'meg_clean', '_trans.fif')) pick_meg = mne.pick_types(raw_clean.info, meg=True, eeg=False, stim=False, ref_meg=False) ## Noise covariance raw_empty_room.filter(1., 200, fir_design='firwin', phase='zero') noise_cov = mne.compute_raw_covariance(raw_empty_room, tmin=0, tmax=None, picks=pick_meg) data_cov = mne.compute_raw_covariance(raw_clean, picks=pick_meg) ## Surface mesh src = mne.read_source_spaces( op.join(rest_dir, subject, 'meg_clean', '_oct6-src.fif')) ## Forward solution fwd = mne.read_forward_solution( op.join(rest_dir, subject, 'meg_clean', '_fwd.fif')) ## Inverse model method = 'beam' filters = mne.beamformer.make_lcmv(raw_clean.info, fwd, data_cov, noise_cov=noise_cov) stc = mne.beamformer.apply_lcmv_raw(raw_clean, filters) if (len(src[0]['vertno']) != len(stc.vertices[0])) | (len( src[1]['vertno']) != len(stc.vertices[1])): logFile.write( "Subject " + subject + ": Number of vertices of src and stc does not match, src[0] = " + str(len(src[0]['vertno'])) + ", src[1] = " + str(len(src[1]['vertno'])) + ", stc[0] = " + str(len(stc.vertices[0])) + ", stc[1] = " + str(len(stc.vertices[1])) + ".\n") vertno = [src[0]['vertno'], src[1]['vertno']] stc.expand(vertno) stc.save(op.join(rest_dir, subject, 'meg_clean', '_' + method + '_inv')) _, peak_time = stc.get_peak(hemi='lh') brain = stc.plot(initial_time=peak_time, hemi='lh', subjects_dir=subjects_dir) report.add_figs_to_section(brain._figures[0], captions=subject + ' => stc plot', section='Source reconstruction') ## Extract time series from cortical parcellations parcellations = ['Yeo_7Network', 'Yeo_17Network', 'aparc.a2009s' ] # parcellations to use, e.g., 'aparc' 'aparc.a2009s' for parc in parcellations: brain = Brain(subject, 'lh', 'inflated', subjects_dir=subjects_dir, cortex='low_contrast', background='white', size=(800, 600)) brain.add_annotation(parc) report.add_figs_to_section(brain._figures[0], captions=subject + ' => ' + parc, section='Parcellations') labels_parc = mne.read_labels_from_annot( subject, parc=parc, subjects_dir=subjects_dir ) # Get labels from FreeSurfer's cortical parcellation try: label_ts = mne.extract_label_time_course([stc], labels_parc, src, mode='mean_flip', allow_empty=False, return_generator=False) label_ts = np.squeeze( np.asarray(label_ts)) # convert list to numpy array np.save( op.join(rest_dir, subject, 'meg_clean', 'ts' + '-' + method + '-' + parc + '.npy'), label_ts) except: logFile.write("Subject " + subject + " : Parcellation " + parc + " failed.\n")
#Run with ipython --gui=wx from os import environ from os.path import join import numpy as np from surfer import Brain, io import os import os.path as op import numpy.random as random subject_id = 'fsaverage' hemi = "rh" surf = "pial" bkrnd = "white" brain = Brain(subject_id, hemi, surf, config_opts=dict(background=bkrnd)) brain.add_annotation(op.abspath("%s.Lausanne1015_fsavg.annot" % hemi), borders=False)
# Maybe load some morphometry if args.morphometry is not None: 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
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')
data_path = mne.datasets.sample.data_path() subjects_dir = data_path + '/subjects' subject = 'sample' # read forward solution fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif' fwd = mne.read_forward_solution(fname_fwd) # read inverse solution fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' inv = mne.minimum_norm.read_inverse_operator(fname_inv) # create and save parcellation parc = AdaptiveParcellation('simoparc', subject=subject, subjects_dir=subjects_dir, hemi='both') parc.fit(fwd, inv) parc.save_annot(overwrite=True) # create brain for plotting brain = Brain(subject, 'both', 'inflated', subjects_dir=subjects_dir, alpha=0.999) # add all labels to plot in one go from annotation file brain.add_annotation('simoparc')
#stc.plot(initial_time=0.1, hemi='split', views=['lat', 'med'], subjects_dir=shared_dir,subject=mri_partic) #stc = mne.read_source_estimate(shared_dir+'\\examplestc-rh.stc') # Labels # ============================================================================= #potential atlas: 'aparc', 'aparc.a2009s' (smallest), 'aparc.DKTatlas' parc='aparc.a2009s' labels = mne.read_labels_from_annot(subject=mri_partic,parc=parc,subjects_dir=shared_dir) ## DKTatlas40 or a2009s if len(parc)>5 and parc[-2]=='9': label_oi='S_temporal_transverse-rh' else: label_oi='transversetemporal-rh' aud_label = [label for label in labels if label.name == label_oi][0] if plot_steps_source==True: brain = Brain(subject_id=mri_partic,subjects_dir=shared_dir,surf='orig',hemi='rh', background='white', size=(800, 600)) brain.add_annotation(parc) brain.add_label(aud_label, borders=False,color=[1, 0, 0]) #plot label_oi & sources normals = src[1]['nn'][src[1]['vertno']] brain = Brain(hemi='rh', surf='inflated', subjects_dir=shared_dir,subject_id=mri_partic) surf = brain.geo['rh'] mlab.quiver3d(surf.x[src[1]['vertno']], surf.y[src[1]['vertno']],surf.z[src[1]['vertno']], normals[:, 0], normals[:, 1], normals[:, 2], color=(0.0, 0.0, 0.0) ,scale_factor=1.5) brain.add_label(aud_label, borders=False,color=[1, 0, 0]) mean_rh = stc.extract_label_time_course(aud_label, inverse_operator['src'], mode='mean') plt.plot(stc.times,mean_rh.T) a=1 mean_rh=mean_rh.T np.savetxt(shared_dir+'\\mean_rh.txt',mean_rh,fmt='%s') np.savetxt(shared_dir+'\\mean_rh_time.txt',stc.times,fmt='%s')
mne.datasets.fetch_aparc_sub_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')
import os import os.path as op from surfer import Brain, io from coma.datasets import sample data_path = sample.data_path() subjects_dir = op.join(data_path, "subjects") os.environ['SUBJECTS_DIR'] = subjects_dir subject_id = "Bend1" hemi = "lh" surf = "pial" bgcolor = 'w' brain = Brain(subject_id, hemi, surf, config_opts={'background': bgcolor}, subjects_dir=subjects_dir) annot_path = op.join(subjects_dir, subject_id, "label", "%s.aparc.annot" % hemi) assert(op.exists(annot_path)) brain.add_annotation(annot_path, borders=False) image = brain.save_montage("Example_FreesurferRegions.png", ['l', 'd', 'm'], orientation='v') brain.close()
def plot_MMP(data, save_file=None, minmax=None, thresh=None, cmap='inferno', alpha=1, add_border=False, bp=3, title=None): """ Plots arbitrary array of data onto MMP parcellation """ ## Folloing this tutorial # https://github.com/nipy/PySurfer/blob/master/examples/plot_parc_values.py # I assume I will always be using this parcellation, at least for now subjects_dir = mne.datasets.sample.data_path() + '/subjects' annot_file = subjects_dir + '/fsaverage/label/lh.HCPMMP1.annot' mmp_labels, ctab, names = ni.freesurfer.read_annot(annot_file) if len(names) - len(data) == 1: # short one label cuz 0 is unassigned in the data, fill with big negative number data_app = np.hstack((-1e6, data)) vtx_data = data_app[mmp_labels] else: vtx_data = data[mmp_labels] vtx_data[mmp_labels < 1] = -1e6 # plot brain brain = Brain('fsaverage', 'lh', 'inflated', subjects_dir=subjects_dir, cortex=None, background='white', size=800, show_toolbar=False, offscreen=True) if add_border: brain.add_annotation( (mmp_labels, np.array([[0, 0, 0, c[3], c[4]] for c in ctab]))) if minmax is None: minmax = [np.min(data), np.max(data)] # add data if thresh is None: thresh = minmax[0] brain.add_data(vtx_data, minmax[0], minmax[1], colormap=cmap, alpha=alpha, colorbar=False, thresh=thresh) # plot brain views brainviews = brain.save_imageset(None, ['lat', 'med']) # merge brainviews and plot horizontally plt.imshow(np.concatenate(brainviews, axis=1), cmap=cmap) despine(bottom=True, left=True) plt.xticks([]) plt.yticks([]) cbaxes = inset_axes(plt.gca(), width="50%", height="4%", loc=8, borderpad=bp) plt.colorbar(cax=cbaxes, orientation='horizontal') plt.clim(minmax[0], minmax[1]) plt.tight_layout() if title is not None: plt.title(title) if save_file: plt.savefig(save_file, bbox_inches='tight')
subject_id = 'fsaverage' hemi = 'lh' surface = 'inflated' """ Bring up the visualization """ brain = Brain(subject_id, hemi, surface, config_opts={ "cortex": "bone", "background": "ivory" }) """ Display the 'aparc' parcellation borders. To use annotations that live in your subject's label directory, just use the annot name. """ brain.add_annotation("aparc") """ You can also display the regions with "filled in" colors """ brain.add_annotation("aparc", borders=False) """ You may also provide a full path to an annotation file at an arbitray location on the disc. """ subjects_dir = os.environ["SUBJECTS_DIR"] annot_path = pjoin(subjects_dir, subject_id, "label", "lh.aparc.annot") brain.add_annotation(annot_path)
snr = C.snr lambda2 = C.lambda2 mne.datasets.fetch_hcp_mmp_parcellation(subjects_dir=C.data_path, verbose=True) labels = mne.read_labels_from_annot('fsaverage', 'HCPMMP1', 'both',\ subjects_dir=C.data_path) brain = Brain('fsaverage', 'lh', 'inflated', subjects_dir=C.data_path, cortex='low_contrast', background='white', size=(400, 400)) brain.add_annotation('HCPMMP1') # label_ATL = ['L_TGd_ROI-lh','L_TGv_ROI-lh','L_TF_ROI-lh','L_TE2a_ROI-lh','L_TE2p_ROI-lh' ,'L_TE1a_ROI-lh','L_TE1m_ROI-lh'] label_ATL = [ 'L_TGd_ROI-lh', 'L_TGv_ROI-lh', 'L_TE2a_ROI-lh', 'L_TE1a_ROI-lh', 'L_TE1m_ROI-lh' ] #label_ATL = ['L_TE2a_ROI-lh','L_TE1a_ROI-lh','L_TE1m_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)):
right_df = pd.DataFrame({ 'col': [ key.replace('rh_', '').replace('.', '-').replace('_thickness_D', '') for key, val in right_count.items() ], 'val': [val for key, val in right_count.items()] }) label_dir = '/cm/shared/openmind/freesurfer/5.3.0/subjects/fsaverage/label' left_label_file = 'lh.aparc.a2009s.annot' right_label_file = 'rh.aparc.a2009s.annot' lh_aparc_file = os.path.join(label_dir, left_label_file) rh_aparc_file = os.path.join(label_dir, right_label_file) lh_labels, lh_ctab, lh_names = nb.freesurfer.read_annot(lh_aparc_file) rh_labels, rh_ctab, rh_names = nb.freesurfer.read_annot(rh_aparc_file) left_df = left_df.set_index('col').loc[lh_names].reset_index().fillna(0) right_df = right_df.set_index('col').loc[rh_names].reset_index().fillna(0) vtx_lh = left_df.val.values[lh_labels] vtx_lh[lh_labels == -1] = 0 vtx_rh = right_df.val.values[rh_labels] vtx_rh[rh_labels == -1] = 0 brain.add_data(vtx_lh, 0, 400, colormap="Reds", alpha=.8, hemi='lh') brain.add_annotation(lh_aparc_file, hemi='lh') brain.add_data(vtx_rh, 0, 400, colormap="Reds", alpha=.8, hemi='rh') brain.add_annotation(rh_aparc_file, hemi='rh', remove_existing=False) save_name = "../images/{}_brain.png".format(save_name) brain.save_image(save_name)
import os import os.path as op from surfer import Brain, io from coma.datasets import sample data_path = sample.data_path() subjects_dir = op.join(data_path, "subjects") os.environ['SUBJECTS_DIR'] = subjects_dir subject_id = "Bend1" hemi = "lh" surf = "pial" bgcolor = 'w' brain = Brain(subject_id, hemi, surf, config_opts={'background': bgcolor}, subjects_dir=subjects_dir) annot_path = op.join(subjects_dir, subject_id, "label", "%s.aparc.annot" % hemi) assert (op.exists(annot_path)) brain.add_annotation(annot_path, borders=False) image = brain.save_montage("Example_FreesurferRegions.png", ['l', 'd', 'm'], orientation='v') brain.close()
Of particular relevance: "I will acknowledge the use of WU-Minn HCP data and data derived from WU-Minn HCP data when publicly presenting any results or algorithms that benefitted from their use." References ---------- .. [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)
import mne subjects_dir = mne.datasets.sample.data_path() + '/subjects' mne.datasets.fetch_hcp_mmp_parcellation(subjects_dir=subjects_dir, verbose=True) mne.datasets.fetch_aparc_sub_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') ############################################################################### # We can add another custom parcellation brain = Brain('fsaverage', 'lh', 'inflated', subjects_dir=subjects_dir, cortex='low_contrast', background='white', size=(800, 600))
def surfer(hemi, overlay, annot='Yeo2011_7Networks_N1000'): brain = Brain("fsaverage", hemi, "inflated") brain.add_annotation(annot, borders=False, alpha=0.3) brain.add_overlay(overlay, min=1.66, max=4) return brain
""" Adapted from: https://pysurfer.github.io/examples/plot_parc_values.html """ import numpy as np import nibabel as nib from surfer import Brain subject_id = "fsaverage" hemi "lh" surface = "inflated" brain = Brain(subject_id, hemi, surface, background="white") surface = "inflated" aparc_file = "/home/jelman/data_VETSA2/fsurf/fsaverage/label/lh.aparc.annot" labels, ctab, names = nib.freesurfer.read_annot(aparc_file) dat = np.genfromtxt('/home/jelman/test/ROI_data.csv',delimiter=",",skip_header=1) roi_data = dat[:,1] vtx_data = roi_data[labels] brain = Brain('fsaverage', 'lh', 'orig', cortex='low_contrast') brain.add_annotation("aparc") brain.add_data(vtx_data, .4, .7, colormap="Reds", hemi='lh',thresh=.1, alpha=.8) brain = Brain('fsaverage', 'split', 'inflated', views=['lat', 'med'])
subject_id = 'fsaverage' hemi = 'lh' surface = 'inflated' """ Bring up the visualization """ brain = Brain(subject_id, hemi, surface) """ Display the 'aparc' parcellation borders. To use annotations that live in your subject's label directory, just use the annot name. """ brain.add_annotation("aparc") """ You can also display the regions with "filled in" colors """ brain.add_annotation("aparc", borders=False) """ You may also provide a full path to an annotation file at an arbitray location on the disc. """ subjects_dir = os.environ["SUBJECTS_DIR"] annot_path = pjoin(subjects_dir, subject_id, "label", "lh.aparc.annot") brain.add_annotation(annot_path)
# In[5]: stcs = dict() stcs_path = 'stcs' stcs_sub_files = os.listdir(stcs_path) for stc_sub in stcs_sub_files: stcs[stc_sub] = mne_pp.load_stcs(stcs_path, stc_sub) # In[6]: stc_cp = mne_pp.apply_cortical_parcellation_event_stcs(stcs, src, save=False, gen_mode=False) # In[7]: stc_cp['N1_stc'].shape # In[8]: from surfer import Brain brain = Brain(mne_pp.subject, hemi='both', surf='inflated' ,subjects_dir=mne_pp.subjects_dir, offscreen=False) brain.add_annotation('aparc')
rh_aparc_file = os.path.join(label_dir, right_label_file) lh_labels, lh_ctab, lh_names = nb.freesurfer.read_annot(lh_aparc_file) rh_labels, rh_ctab, rh_names = nb.freesurfer.read_annot(rh_aparc_file) left_df = left_df.set_index('col').loc[lh_names].reset_index().fillna(0) right_df = right_df.set_index('col').loc[rh_names].reset_index().fillna(0) vtx_lh = left_df.val.values[lh_labels] vtx_lh[lh_labels == -1] = 0 vtx_rh = right_df.val.values[rh_labels] vtx_rh[rh_labels == -1] = 0 brain.add_data(vtx_lh, 0, 400, colormap="Reds", alpha=.8, hemi='lh') brain.add_annotation(lh_aparc_file, hemi='lh') brain.add_data(vtx_rh, 0, 400, colormap="Reds", alpha=.8, hemi='rh') brain.add_annotation(rh_aparc_file, hemi='rh', remove_existing=False) save_name = "../images/{}_brain.png".format(save_name) brain.save_image(save_name)
grade = 3 annot = "aparc_sub" subject = "fsaverage" subjects_dir = config.get_subjects_dir_subj("sample") ground_metric = np.load("data/ground_metric.npy") hemi = "lh" label_index = 0 labels = mne.read_labels_from_annot(subject, annot, hemi, subjects_dir=subjects_dir) labels = [label.morph(subject_to=subject, subject_from=subject, grade=grade, subjects_dir=subjects_dir) for label in labels] distances = np.zeros(642) label_vertices = labels[label_index].vertices for ii, label_i in enumerate(labels): v_i = label_i.vertices distances[v_i] = ground_metric[0][ii] f = mlab.figure(size=(700, 600)) brain = Brain(subject, hemi, "inflated", subjects_dir=subjects_dir, figure=f, background="white", foreground='black') vertices = np.arange(642) brain.add_annotation('aparc_sub', alpha=0.2) brain.add_data(distances, vertices=vertices, hemi="lh", transparent=True, smoothing_steps=5, colormap="hot", alpha=0.95, mid=40) brain.save_image("data/ground_metric.png")
view = 'frontal' """ Bring up the visualization """ brain = Brain(subject_id, hemi, surf, views=view, cortex="bone", background="ivory") """ Display the 'aparc' parcellation borders. To use annotations that live in your subject's label directory, just use the annot name. """ brain.add_annotation("aparc") """ You can also display the regions with "filled in" colors """ brain.add_annotation("aparc", borders=False) """ You may also provide a full path to an annotation file at an arbitray location on the disc. You can also plot things separately for the left and right hemispheres. """ subjects_dir = os.environ["SUBJECTS_DIR"] annot_path = pjoin(subjects_dir, subject_id, "label", "lh.aparc.annot") brain.add_annotation(annot_path, hemi='lh', borders=False, alpha=.75) annot_path = pjoin(subjects_dir, subject_id, "label", "rh.aparc.a2009s.annot") brain.add_annotation(annot_path, hemi='rh', borders=2, remove_existing=False)
def plot_mixn(sub, mne_evoked_time, parcellation): trans = sub.load_transformation() dipole_dict = sub.load_mixn_dipoles() for trial in dipole_dict: dipoles = dipole_dict[trial] # Plot Dipole Amplitues (derived from Source Code with added legend) colors = plt.cm.get_cmap(name='hsv', lut=len(dipoles) + 1) fig1, ax = plt.subplots(1, 1) xlim = [np.inf, -np.inf] for i, dip in enumerate(dipoles): ax.plot(dip.times, dip.amplitude * 1e9, color=colors(i), linewidth=1.5, label=f'dipole {i + 1}') xlim[0] = min(xlim[0], dip.times[0]) xlim[1] = max(xlim[1], dip.times[-1]) ax.set(xlim=xlim, xlabel='Time (s)', ylabel='Amplitude (nAm)') ax.legend() fig1.suptitle(f'Dipoles Amplitudes', fontsize=16) fig1.show(warn=False) plot_save(sub, 'mixed-norm-estimate', subfolder='dipoles', trial=trial, matplotlib_figure=fig1) for idx, dipole in enumerate(dipoles): # Assumption right in Head Coordinates? if dipole.pos[0, 0] < 0: side = 'left' hemi = 'lh' else: side = 'right' hemi = 'rh' fig2 = mne.viz.plot_dipole_locations(dipole, trans=trans, subject=sub.subtomri, subjects_dir=sub.subjects_dir, coord_frame='mri') fig2.suptitle(f'Dipole {idx + 1} {side}', fontsize=16) plot_save(sub, 'mixed-norm-estimate', subfolder='dipoles', trial=trial, idx=idx, matplotlib_figure=fig2) brain = Brain(sub.subtomri, hemi=hemi, surf='pial', views='lat') dip_loc = mne.head_to_mri(dipole.pos, sub.subtomri, trans, subjects_dir=sub.subjects_dir) brain.add_foci(dip_loc[0]) brain.add_annotation(parcellation) # Todo: Comparision with label plot_save(sub, 'mixed-norm-estimate', subfolder='dipoles', trial=trial, idx=idx, brain=brain) stcs = sub.load_mixn_source_estimates() brain_plot(sub, stcs, 'mixed-norm-estimate/stc', sub.subtomri, mne_evoked_time)
''' 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 plot_annotation(mri_sub, parcellation): brain = Brain(mri_sub.name, hemi='lh', surf='inflated', views='lat') brain.add_annotation(parcellation) plot_save(mri_sub, 'Labels', brain=brain)
---------- .. [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')
class plotting_points(object): def __init__(self, points, hemi='both', surf='pial', map_surface=None, annot=None, map_to_annot=None, show_skin=True, show_roi=False, show_name=False, name_scale=1, name_color=(0, 0, 0), show_directions=False, background='white', show_average=False, opacity=1, scale_factor=.5, color=np.array([(1, 0, 0)]), use_default=True): self.points = copy.deepcopy(points) self.subject = points.subject self.freesurfer_dir = points.freesurfer_dir self.hemi = hemi self.surf = surf self.background = background self.map_surface = map_surface self.annot = annot self.map_to_annot = map_to_annot self.show_skin = show_skin self.show_roi = show_roi self.scale_factor = scale_factor self.show_directions = show_directions self.show_name = show_name self.show_average = show_average self.opacity = opacity self.color = color self.scale_factor = scale_factor self.use_default = use_default self.name_scale = name_scale self.name_color = name_color self._set_config() self._plot() def _set_config(self): if not hasattr(self.points, 'color'): if self.color.shape[0] == 1: self.points.add_trait( 'color', np.repeat(self.color, self.points.npoints, axis=0)) elif self.color.shape[0] == self.points.npoints: self.points.add_trait('color', self.color) else: raise 'Color size is incorrect' if not hasattr(self.points, 'scale_factor'): self.points.add_trait( 'scale_factor', np.ones(self.points.npoints) * self.scale_factor) if not hasattr(self.points, 'opacity'): self.points.add_trait('opacity', np.ones(self.points.npoints) * self.opacity) def _plot(self): ## plot self.brain = Brain(hemi=self.hemi, surf=self.surf, subject_id=self.subject, subjects_dir=self.freesurfer_dir, background=self.background, offset=False) if self.show_skin: self._show_skin() if self.annot: self._show_annot() self._add_points() if self.show_average: self._show_average() def show(self): mlab.show() def _add_points(self): if self.map_surface: temp = self.points.map_to_surface(self.map_surface) mapped_vertices, mapped_coords_ras_tkr = temp['vertices'], temp[ 'ras_tkr_coord'] mapped_coords = mapped_coords_ras_tkr ### FreesurferCoords.map_to_annot requires map_surface to be set ( set to white by default). Here, we use map_surface if it has been set, otherwise use 'white' by default. if self.map_to_annot: if self.map_surface: self.points.name, self.points.color = self.points.map_to_annot( self.map_to_annot, map_surface=self.map_surface) else: self.points.name, self.points.color = self.points.map_to_annot( self.map_to_annot, map_surface='white') for i in range(self.points.npoints): point = self.points[i] if point.hemi == self.hemi or self.hemi == 'both': if self.map_surface: self.brain.add_foci(mapped_coords[i, :], hemi=point.hemi, color=point.color, scale_factor=point.scale_factor, alpha=point.opacity) else: self.brain.add_foci(point.ras_tkr_coord, hemi=point.hemi, color=point.color, scale_factor=point.scale_factor, alpha=point.opacity) if self.show_roi and hasattr(point, 'roi'): self.brain.add_label(point.roi, hemi=point.hemi, color=point.roi.color) if self.show_name and hasattr(point, 'name'): mlab.text3d(point.ras_tkr_coord[0], point.ras_tkr_coord[1], point.ras_tkr_coord[2], point.name, scale=self.name_scale, color=self.name_color) if self.show_directions and hasattr(point, 'direction'): origin = point.ras_tkr_coord.flatten().tolist() X, Y, Z = zip(origin, origin, origin) p0 = point.direction[0:3] p1 = point.direction[3:6] p2 = point.direction[6:9] U, W, V = zip(p0, p1, p2) plot_directions(X, Y, Z, U, W, V) def _show_skin(self): ## create head model under freesurfer_dir/{subject}/bem (if none existing!) anat_img = os.path.join(self.points.freesurfer_dir, self.points.subject, 'mri', 'rawavg.mgz') out_dir = os.path.join(self.points.freesurfer_dir, self.points.subject, 'bem') make_head_model(anat_img, out_dir) skin_surf = Surf( '{freesurfer_dir}/{subject}/bem/outer_skin_surface'.format( freesurfer_dir=self.freesurfer_dir, subject=self.subject)) mlab.triangular_mesh(skin_surf.vertices[:, 0], skin_surf.vertices[:, 1], skin_surf.vertices[:, 2], skin_surf.faces, opacity=0.2, color=(1, 1, 0)) def _show_annot(self): if self.hemi in ['lh', 'rh']: self.brain.add_annotation(self.annot, hemi=self.hemi, borders=False) elif self.hemi == 'both': self.brain.add_annotation(self.annot, hemi='lh', borders=False) self.brain.add_annotation(self.annot, hemi='rh', borders=False, remove_existing=False) def _show_average(self, scale_factor=6, color=(0, 0, 1)): avg_coord = np.mean(self.points.coordinates['ras_tkr_coord'], axis=0) mlab.points3d(avg_coord[0], avg_coord[1], avg_coord[2], color=color, scale_factor=scale_factor) def save_image(self, out_dir, views=['lat', 'med', 'dor', 'ros', 'caud'], prefix='', filetype='jpg'): if not os.path.exists(out_dir): os.makedirs(out_dir) prefix = out_dir + '/' + prefix self.brain.save_imageset(prefix=prefix, views=views, filetype=filetype) mlab.close() fig, ax = plt.subplots(1, len(views), figsize=(15, 8)) for i, view in enumerate(views): img_name = prefix + '_' + view + '.' + filetype img = plt.imread(img_name) ax[i].imshow(img) ax[i].set_axis_off() os.remove(img_name) fig.savefig(prefix + '.png', bbox_inches='tight', dpi=600) plt.close() ## return saved image path return prefix + '.png'
hemi = 'both' surface = 'inflated' view = 'frontal' """ Bring up the visualization """ brain = Brain(subject_id, hemi, surface, views=view, cortex="bone", background="ivory") """ Display the 'aparc' parcellation borders. To use annotations that live in your subject's label directory, just use the annot name. """ brain.add_annotation("aparc") """ You can also display the regions with "filled in" colors """ brain.add_annotation("aparc", borders=False) """ You may also provide a full path to an annotation file at an arbitray location on the disc. You can also plot things separately for the left and right hemispheres. """ subjects_dir = os.environ["SUBJECTS_DIR"] annot_path = pjoin(subjects_dir, subject_id, "label", "lh.aparc.annot") brain.add_annotation(annot_path, hemi='lh', borders=False, alpha=.75) annot_path = pjoin(subjects_dir, subject_id, "label", "rh.aparc.a2009s.annot")