def display_coactivation(brain, niftis, colormap=None, reduce_alpha_step=0, **kwargs): args = {'thresh': 0.001, 'alpha': 0.85, 'colorbar': False, 'min': 0} if kwargs != {}: args.update(kwargs) if colormap is None: colormap = sns.color_palette('Set1', len(niftis)) for i, image in enumerate(niftis): with tempfile.NamedTemporaryFile(suffix='.nii.gz') as f: nib.save(image, f.name) l_roi_surf = project_volume_data(f.name, "lh", subject_id="fsaverage", smooth_fwhm=2) r_roi_surf = project_volume_data(f.name, "rh", subject_id="fsaverage", smooth_fwhm=2) args['remove_existing'] = i == 0 color = sns.light_palette(colormap[i], n_colors=10)[5:] if l_roi_surf.sum() > 0: brain.add_data(l_roi_surf, hemi='lh', colormap=color, **args) if r_roi_surf.sum() > 0: brain.add_data(r_roi_surf, hemi='rh', colormap=color, **args) args['alpha'] -= reduce_alpha_step
def project_surface(result_file, hemi): ''' VERY helpfully taken from the Pysurfer example gallery http://pysurfer.github.io/examples/plot_fmri_activation_volume.html Parameters ---------- result_file : str 3D volume that has continuous values eg: thresh_zstat1.nii.gz hemi : {'lh', 'rh'} string indicating left or right hemisphere Returns ---------- zstat : pysurfer surface Surface projection of result_file to fsaverage brain ''' import os from surfer import project_volume_data reg_file = os.path.join(os.environ["FREESURFER_HOME"], "average/mni152.register.dat") zstat = project_volume_data(result_file, hemi, reg_file) return zstat
def project_surface(result_file, hemi): ''' VERY helpfully taken from the Pysurfer example gallery http://pysurfer.github.io/examples/plot_fmri_activation_volume.html Parameters ---------- result_file : str 3D volume that has continuous values eg: thresh_zstat1.nii.gz hemi : {'lh', 'rh'} string indicating left or right hemisphere Returns ---------- zstat : pysurfer surface Surface projection of result_file to fsaverage brain ''' import os from surfer import project_volume_data reg_file = os.path.join(os.environ["FREESURFER_HOME"], "average/mni152.register.dat") zstat = project_volume_data(result_file, hemi, reg_file) return zstat
def make_surface_mask(img, thresh=None, hemi='lh', use_nans=True): """Convert ROI mask to surface array""" surface_data = project_volume_data(img, 'lh', subject_id='fsaverage') if use_nans: mask = np.where(surface_data > thresh, 1, np.nan) else: mask = np.where(surface_data > thresh, 1, 0) return mask
def vis_ers_comp(group=None,phase=None,surf=None,cmap=None,split='lh'): mri_file = f'/mnt/c/Users/ACH/Desktop/ers_comps/{group}_{phase}/{group}_{phase}_ClusterEffEst.nii.gz' #find the file containing stats surf_data_lh = project_volume_data(mri_file, "lh", reg_file, projarg=[0, 1, .01], smooth_fwhm=1) #project to lh _max = .55 if phase == 'acquisition' else .3 for view in ['med','lat']: #lateral and medial views brain = Brain('MNI2009c', split, surf, cortex='low_contrast',size=1000, views=view, background='white', foreground=None) #initialize the brain object brain.add_data(surf_data_lh, 0, _max, center=None, hemi='lh', thresh=None, colorbar=False, colormap=cmap, transparent=True) #add lh data for vert, color in zip([115262,135014],['white','black']): #add focal ROIs brain.add_foci(vert,coords_as_verts=True,color=color,alpha=1) fname = f'/mnt/c/Users/ACH/Documents/gPPI/paper/pysurfer/{group}_{phase}_{view}.png' os.system(f'rm {fname}') brain.save_image(fname,antialiased=True)
""" import os from surfer import Brain, project_volume_data print(__doc__) """Bring up the visualization""" brain = Brain("fsaverage", "split", "inflated", views=['lat', 'med'], background="white") """Project the volume file and return as an array""" mri_file = "example_data/resting_corr.nii.gz" reg_file = os.path.join(os.environ["FREESURFER_HOME"], "average/mni152.register.dat") surf_data_lh = project_volume_data(mri_file, "lh", reg_file) surf_data_rh = project_volume_data(mri_file, "rh", reg_file) """ You can pass this array to the add_overlay method for a typical activation overlay (with thresholding, etc.). """ brain.add_overlay(surf_data_lh, min=.3, max=.7, name="ang_corr_lh", hemi='lh') brain.add_overlay(surf_data_rh, min=.3, max=.7, name="ang_corr_rh", hemi='rh') """ You can also pass it to add_data for more control over the visualization. Here we'll plot the whole range of correlations """ for overlay in brain.overlays_dict["ang_corr_lh"]:
def project_volume(work_dir, subject, do_bbr=True): # first find the session where T1w and T2w files could be ref_file = sorted( glob.glob( os.path.join(work_dir, subject, 'ses-*', 'anat', '*-highres_T1w.nii*')))[-1] # session = ref_file.split('/')[-3] anat_dir = os.path.dirname(ref_file) write_dir = os.path.join(anat_dir, 'analysis') if not os.path.exists(write_dir): os.mkdir(write_dir) os.environ['SUBJECTS_DIR'] = anat_dir data = {} for modality in ['T1w', 'T2w']: if modality == ['T1w']: image = ref_file else: image = sorted( glob.glob( os.path.join(work_dir, subject, 'ses-*', 'anat', '*-highres_T2w.nii*')))[-1] image_ = closing(image) # -------------------------------------------------------------------- # run the projection using freesurfer print("image", image) basename = os.path.basename(image).split('.')[0] if modality == 'T1w': bbreg = BBRegister(subject_id=subject, source_file=image, init='header', contrast_type='t1') else: # use BBR registration to finesse the coregistration bbreg = BBRegister(subject_id=subject, source_file=image, init='header', contrast_type='t2') regheader = os.path.join(anat_dir, basename + '_bbreg_%s.dat' % subject) bbreg.run() if 1: # output names # the .gii files will be put in the same directory as the input left_tex = os.path.join(write_dir, basename + '_lh.gii') right_tex = os.path.join(write_dir, basename + '_rh.gii') # run freesrufer command for projection os.system( '$FREESURFER_HOME/bin/mri_vol2surf --src %s --o %s ' '--out_type gii --srcreg %s --hemi lh --projfrac-avg 0 1 0.1' % (image_, left_tex, regheader)) os.system( '$FREESURFER_HOME/bin/mri_vol2surf --src %s --o %s ' '--out_type gii --srcreg %s --hemi rh --projfrac-avg 0 1 0.1' % (image_, right_tex, regheader)) # resample to fsaverage left_smooth_tex = os.path.join(write_dir, basename + '_fsaverage_lh.gii') right_smooth_tex = os.path.join(write_dir, basename + '_fsaverage_rh.gii') os.system('$FREESURFER_HOME/bin/mri_surf2surf --srcsubject %s ' '--srcsurfval %s --trgsurfval %s --trgsubject ico ' '--trgicoorder 7 --hemi lh' % (subject, left_tex, left_smooth_tex)) os.system('$FREESURFER_HOME/bin/mri_surf2surf --srcsubject %s ' '--srcsurfval %s --trgsubject ico --trgicoorder 7 ' '--trgsurfval %s --hemi rh' % (subject, right_tex, right_smooth_tex)) data[modality] = { 'lh': nib.load(left_smooth_tex).darrays[0].data, 'rh': nib.load(right_smooth_tex).darrays[0].data } else: from surfer import project_volume_data data[modality] = {} for hemi in ['lh', 'rh']: data_ = project_volume_data(image_, hemi, regheader, projarg=[0, 1., .1], smooth_fwhm=0) data[modality][hemi] = data_ # reset subject_dir to set fsaverage os.environ['SUBJECTS_DIR'] = os.path.join(work_dir, subject, 'ses-00', 'anat') for hemi in ['lh', 'rh']: ratio = data['T1w'][hemi] / data['T2w'][hemi] from nibabel.gifti import write, GiftiImage, GiftiDataArray as gda file_ratio = os.path.join(write_dir, 't1_t2_ratio_%s.gii' % hemi) write(GiftiImage(darrays=[gda(data=ratio.astype('float32'))]), file_ratio) """
#os.environ['SUBJECTS_DIR'] = expanduser('/Volumes/rmasis/MemPal/data/BIDS/derivatives/freesurfer/') os.environ['FREESURFER_HOME'] = expanduser('/Applications/freesurfer/') # #reg_file = os.environ['FREESURFER_HOME'] os.environ['SUBJECTS_DIR'] = expanduser('/Applications/freesurfer/subjects') #mri_file = '/Volumes/norman/rmasis/MemPal/analysis/PythonData/' + 'testMNIpathvideoNii.nii.gz' mri_file = '/Volumes/norman/rmasis/MemPal/analysis/PythonData/troubleshoot/' + 'PV1_isc' + '.nii.gz' reg_file = '/Applications/freesurfer/average/mni152.register.dat' data = nib.load(mri_file) brain = Brain(subject_id, hemi, surf, background="white") minval = 0.0 #np.min(data.get_data()) maxval = np.max(data.get_data()) surf_data_lh = project_volume_data(mri_file,"lh", reg_file) #uses freesurfers mri_vol2surf surf_data_rh = project_volume_data(mri_file,"rh", reg_file) brain.add_overlay(surf_data_lh,min=minval,max=maxval,name="thirty_sec_lh", hemi='lh',sign="pos") brain.add_overlay(surf_data_rh,min=minval,max=maxval,name="thirty_sec_rh", hemi='rh',sign="pos") mlab.show()
time=str(time), subid=subid)) ############################################ # Visualize accuracy (for given subject) ############################################ from surfer import Brain, project_volume_data tr_shift_test_list = [0, 2, 4, 6, 8, 10, 12] # seconds to shift onset forward by # for subid in subj_info.subid: subid = 'ap101' for time in tr_shift_test_list: brain = Brain(subid, "split", "inflated", views=['lat', 'med', 'ven'], background="white") volume_file = '/Volumes/group/awagner/sgagnon/AP/analysis/mvpa_raw/searchlight_test/sourcehit_time{time}_acc_{subid}.nii.gz'.format( time=str(time), subid=subid) for hemi in ['lh', 'rh']: zstat = project_volume_data(volume_file, hemi, subject_id=subid, smooth_fwhm=0.5) brain.add_overlay(zstat, hemi=hemi, min=.333) brain.save_image( '/Volumes/group/awagner/sgagnon/AP/analysis/mvpa_raw/searchlight_test/sourcehit_time{time}_acc_{subid}.png' .format(time=str(time), subid=subid))
""" volume_file = "example_data/zstat.nii.gz" """ There are two options for specifying the registration between the volume and the surface you want to plot on. The first is to give a path to a Freesurfer-style linear transformation matrix that will align the statistical volume with the Freesurfer anatomy. Most of the time you will be plotting data that are in MNI152 space on the fsaverage brain. For this case, Freesurfer actually ships a registration matrix file to align your data with the surface. """ reg_file = os.path.join(os.environ["FREESURFER_HOME"], "average/mni152.register.dat") zstat = project_volume_data(volume_file, "lh", reg_file) """ Note that the contours of the fsaverage surface don't perfectly match the MNI brain, so this will only approximate the location of your activation (although it generally does a pretty good job). A more accurate way to visualize data would be to run the MNI152 brain through the recon-all pipeline. Alternatively, if your data are already in register with the Freesurfer anatomy, you can provide project_volume_data with the subject ID, avoiding the need to specify a registration file. By default, 3mm of smoothing is applied on the surface to clean up the overlay a bit, although the extent of smoothing can be controlled. """ zstat = project_volume_data(volume_file, "lh",
# cb2 = mpl.colorbar.ColorbarBase(ax[1], cmap=mpl.cm.Greens, # norm=norm, orientation='horizontal') # cb1.set_label('CS+ - CS- reinstatement') # fig.show() """ This overlay represents resting-state correlations with a seed in left angular gyrus. Let's plot that seed. """ seed_coords = (-45, -67, 36) brain.add_foci(seed_coords, map_surface="white", hemi='lh') ''' a priori rois for paper ''' mri_file = f'{HOME}/Desktop/standard/vmPFC_mask.nii.gz' surf_data_lh = project_volume_data(mri_file, "lh", reg_file, projarg=[0, 1, .5], smooth_fwhm=1) surf_data_rh = project_volume_data(mri_file, "rh", reg_file, projarg=[0, 1, .5], smooth_fwhm=1) minval = np.min([np.min(surf_data_lh[np.nonzero(surf_data_lh)]),np.min(surf_data_rh[np.nonzero(surf_data_rh)])]) for view in ['med','lat']: brain = Brain('fsaverage', 'split', surf, cortex='low_contrast',size=(400,400), views=view, background='white', foreground=None) brain.add_data(surf_data_lh, 0, .5, center=None, hemi='lh', thresh=minval, colorbar=False, colormap=cmap) brain.add_data(surf_data_rh, 0, .5, center=None, hemi='rh',thresh=minval, colorbar=False, colormap=cmap) dACC_coords = (1, 21, 27) brain.add_foci(dACC_coords, map_surface='pial', hemi='rh',color='orange')
def display_bilateral(brain, nifti, colormap=None, spatial_mask=None, level_mask=None, discrete=True, **kwargs): args = { 'thresh': 0.001, 'alpha': 0.33, 'colorbar': False, 'remove_existing': True, 'min': 1 } if kwargs != {}: args.update(kwargs) if spatial_mask is None: args['alpha'] = .8 if colormap is None: n_clusters = int(nifti.get_data().max()) colormap = sns.color_palette('husl', n_clusters) if level_mask is not None: nifti = deepcopy(nifti) data = nifti.get_data() unique = np.unique(data[data.nonzero()]) for val in unique: if not val in level_mask: data[data == val] = float(0) unique = np.unique(data[data.nonzero()]) colormap = [v for i, v in enumerate(colormap) if i + 1 in unique] compress_values(nifti.get_data()) with tempfile.NamedTemporaryFile(suffix='.nii.gz') as f: nib.save(nifti, f.name) l_roi_surf = project_volume_data(f.name, "lh", subject_id="fsaverage", projsum='max', smooth_fwhm=0) r_roi_surf = project_volume_data(f.name, "rh", subject_id="fsaverage", projsum='max', smooth_fwhm=0) if discrete == True: l_cols = [colormap[int(c - 1)] for c in np.unique(l_roi_surf)[1:]] if len(l_cols) < 2: l_cols = l_cols + [(0, 0, 0)] r_cols = [colormap[int(c - 1)] for c in np.unique(r_roi_surf)[1:]] if len(r_cols) < 2: r_cols = r_cols + [(0, 0, 0)] else: l_cols = colormap r_cols = colormap brain.add_data(l_roi_surf, hemi='lh', colormap=colormap, **args) brain.add_data(r_roi_surf, hemi='rh', colormap=r_cols, **args) if spatial_mask is not None: spatial_masked_nifti = mask_nifti(nifti, spatial_mask) with tempfile.NamedTemporaryFile(suffix='.nii.gz') as f: nib.save(spatial_masked_nifti, f.name) args['remove_existing'] = False args['alpha'] = .7 l_roi_surf = project_volume_data(f.name, "lh", subject_id="fsaverage", projsum='max', smooth_fwhm=0) r_roi_surf = project_volume_data(f.name, "rh", subject_id="fsaverage", projsum='max', smooth_fwhm=0) l_cols = [colormap[int(c - 1)] for c in np.unique(l_roi_surf)[1:]] if len(l_cols) < 2: l_cols = l_cols + [(0, 0, 0)] r_cols = [colormap[int(c - 1)] for c in np.unique(r_roi_surf)[1:]] if len(r_cols) < 2: r_cols = r_cols + [(0, 0, 0)] brain.add_data(l_roi_surf, hemi='lh', colormap=l_cols, **args) brain.add_data(r_roi_surf, hemi='rh', colormap=r_cols, **args)
# load DMN ROI and plot with pysurfer import os from surfer import Brain, project_volume_data print(__doc__) brain = Brain("fsaverage", "lh", "inflated") volume_file = '/Volumes/norman/amennen/prettymouth_fmriprep2/ROI/TOM_large_resampled_maskedbybrain.nii.gz' reg_file = os.path.join(os.environ["FREESURFER_HOME"], "average/mni152.register.dat") zstat = project_volume_data(volume_file, "lh", reg_file).astype(bool) brain.add_data(zstat, min=0, max=1,colormap="bone", alpha=.6, colorbar=False) brain.show_view("medial")
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) volume_file = op.abspath("example_fspet/corrected_pet_to_t1/_subject_id_Bend1/r_volume_MGRousset_flirt.nii") pet = project_volume_data(volume_file, hemi, subject_id=subject_id) brain.add_data(pet, min=250, max=12000, colormap="jet", alpha=.6, colorbar=True) image = brain.save_montage("Example_FDG-PET.png", ['l', 'd', 'm'], orientation='v') brain.close() ############################################################################### # View created image import pylab as pl fig = pl.figure(figsize=(5, 3), facecolor=bgcolor) ax = pl.axes(frameon=False) ax.imshow(image, origin='upper') pl.draw()
Get a path to the volume file. """ volume_file = "example_data/zstat.nii.gz" """ There are two options for specifying the registration between the volume and the surface you want to plot on. The first is to give a path to a Freesurfer-style linear transformation matrix that will align the statistical volume with the Freesurfer anatomy. Most of the time you will be plotting data that are in MNI152 space on the fsaverage brain. For this case, Freesurfer actually ships a registration matrix file to align your data with the surface. """ reg_file = os.path.join(os.environ["FREESURFER_HOME"], "average/mni152.register.dat") zstat = project_volume_data(volume_file, "lh", reg_file) """ Note that the contours of the fsaverage surface don't perfectly match the MNI brain, so this will only approximate the location of your activation (although it generally does a pretty good job). A more accurate way to visualize data would be to run the MNI152 brain through the recon-all pipeline. Alternatively, if your data are already in register with the Freesurfer anatomy, you can provide project_volume_data with the subject ID, avoiding the need to specify a registration file. By default, 3mm of smoothing is applied on the surface to clean up the overlay a bit, although the extent of smoothing can be controlled. """ zstat = project_volume_data(volume_file, "lh",
title='Z=' + str(z), cortex='low_contrast', views=['lat', 'med'], background="white") """ Get a path to the overlay file. """ mri_file = '/Users/jamalw/Desktop/PNI/music_event_structures/data/best_k_map_z' + str( z) + '.nii.gz' reg_file = '/Applications/freesurfer/average/mni152.register.dat' data = nib.load(mri_file) minval = 0 maxval = np.max(data.get_data()) surf_data_lh = project_volume_data(mri_file, "lh", reg_file) surf_data_rh = project_volume_data(mri_file, "rh", reg_file) brain.add_overlay(surf_data_lh, min=minval, max=maxval, name="thirty_sec_lh", hemi='lh') brain.add_overlay(surf_data_rh, min=minval, max=maxval, name="thirty_sec_rh", hemi='rh') for overlay in brain.overlays_dict["thirty_sec_lh"]: overlay.remove()
## script to visualizee volume results in surcace, using pysurfer import os from surfer import Brain, project_volume_data import numpy as np ### script to visualize cognitive components subject_id = "fsaverage" subjects_dir = os.environ["SUBJECTS_DIR"] brain = Brain("fsaverage", "lh", "inflated", views=['lat'], background="white") overlay_file = "/Volumes/neuro/Rest/ROIs/Yeo_12.nii.gz" reg_file = os.path.join(os.environ["FREESURFER_HOME"], "average/mni152.register.dat") zstat = project_volume_data(overlay_file, "lh", reg_file) zstat = project_volume_data(overlay_file, "lh", subject_id="fsaverage", smooth_fwhm=4) brain.add_data(zstat, min=1, max=5, thresh=1, colormap="hot", colorbar=False) brain.show_view("medial") #load data to visualize #mask_file = "Cortical_CI.nii.gz" ### to visualize ROI's CI assignment #load coordinates subject_id = "fsaverage" subjects_dir = os.environ["SUBJECTS_DIR"] brain = Brain("fsaverage", "rh", "inflated", views=['lat', 'med'], background="white") #brain = Brain("fsaverage", "rh", "inflated", background="white") coords = np.loadtxt('/Volumes/neuro/Rest/ROIs/Gordon_coordinates') CIs = np.loadtxt('/Volumes/neuro/Rest/ROIs/Gordon_consensus_CI') colors = {1:'red', 2:'purple', 3:'green', 4:'yellow', 5:'cyan', 6:'blue', 7:'brown', 8:'pink', 9:'teal', 12:'pink'}