def project_z_map(in_file, subject, hemi, proj_frac, fsaverage_fwhm=3.):

    out_dir = path(in_file).dirname()
    out_base = path(in_file).basename()
    if out_base[-3:] == ".gz":
        out_base = out_base[:-3]
    if out_base[-4:] == ".nii":
        out_base = out_base[:-4]
    else:
        raise Exception("problem with infile name %s" % infile)

    out_file_name = out_dir / (out_base + "-projfrac-%1.2f-%s.gii"
                               % (proj_frac, hemi))
    print out_file_name
    out_file_fsaverage = out_dir / ("avg_%s-projfrac-%1.2f-%s.gii"
                                    % (out_base, proj_frac, hemi))
    print out_file_fsaverage
    out_data = project_volume_data(in_file, hemi, subject_id=subject,
                              projmeth="frac", projarg=proj_frac,
                                   projsum="point")
    out_data_avg = project_volume_data(in_file, hemi, subject_id=subject,
                                  projmeth="frac", projarg=proj_frac,
                                  target_subject="fsaverage",
                                  smooth_fwhm=fsaverage_fwhm,
                                       projsum="point")

    gii_arr = gifti.GiftiDataArray.from_array(out_data, 0)
    out_gii = gifti.GiftiImage(darrays=[gii_arr])

    gii_arr_avg = gifti.GiftiDataArray.from_array(out_data_avg, 0)
    out_gii_avg = gifti.GiftiImage(darrays=[gii_arr_avg])

    gifti.write(out_gii, out_file_name)
    gifti.write(out_gii_avg, out_file_fsaverage)
def plot_group(hub,num_nodes,hemi='lh'):
    from surfer import Brain, io
    brain = Brain("fsaverage", "%s" %(hemi), "pial",config_opts=dict(background="white"))
    if hub == 'pc' or hub =='wmd':
        image = io.project_volume_data('/home/despo/mb3152/random_nodes/%s/group_%s.nii'%(num_nodes,hub),hemi, subject_id="fsaverage", projsum = 'max', smooth_fwhm = 20)
        brain.add_data(image,colormap = "Reds", colorbar= True)
    else:
        pc_image = io.project_volume_data('/home/despo/mb3152/random_nodes/%s/group_pc.nii'%(num_nodes),hemi, subject_id="fsaverage", projsum = 'max', smooth_fwhm = 20)
        wmd_image = io.project_volume_data('/home/despo/mb3152/random_nodes/%s/group_wmd.nii'%(num_nodes),hemi, subject_id="fsaverage", projsum = 'max', smooth_fwhm = 20) 
        wmd_thresh = np.nanmean(wmd_image[wmd_image>0])
        pc_thresh = np.nanmean(pc_image[pc_image >0])
        #find connetor hub activity
        connector_hub_image = pc_image.copy()
        connector_hub_image[pc_image < pc_thresh] = 0.
        connector_hub_image[wmd_image < wmd_thresh] = 0.
        #find sattelite connector activty
        satellite_image = pc_image.copy()
        satellite_image[pc_image < pc_thresh] = 0.
        satellite_image[wmd_image > wmd_thresh] = 0.
        # find provincial hub activity
        provincial_hub_image = wmd_image.copy()
        provincial_hub_image[pc_image > pc_thresh] = 0.
        provincial_hub_image[wmd_image < wmd_thresh] = 0.

        node_image = pc_image.copy()
        node_image[provincial_hub_image > 0] = 0
        node_image[connector_hub_image > 0] = 0
        node_image[satellite_image > 0] = 0
        node_image[node_image > 0] = 1

        # brain.add_data(node_image,thresh= 0, max = 2, colormap = 'gray',hemi=hemi,smoothing_steps = 0)
        brain.add_data(connector_hub_image,thresh= np.nanmin(pc_image),max=pc_thresh + np.std(pc_image), colormap = 'Reds',hemi=hemi,smoothing_steps = 0)
        brain.add_data(satellite_image,thresh= np.nanmin(pc_image),max=pc_thresh + np.std(pc_image),colormap = 'autumn',hemi=hemi,smoothing_steps = 0)
        brain.add_data(provincial_hub_image,thresh=np.nanmin(wmd_image),max=wmd_thresh +np.std(wmd_image),colormap = 'Blues',hemi=hemi,smoothing_steps = 0)
def make_pysurfer_images(folder,suffix='cope1',threshold=0.9499,coords=(),surface='inflated',fwhm=0,filename='',saveFolder=[]):
    from surfer import Brain, io
    TFCEposImg,posImg,TFCEnegImg,negImg=getFileNamesfromFolder(folder,suffix)

    pos=image.math_img("np.multiply(img1,img2)",
                         img1=image.threshold_img(TFCEposImg,threshold=threshold),img2=posImg)
    neg=image.math_img("np.multiply(img1,img2)",
                         img1=image.threshold_img(TFCEnegImg,threshold=threshold),img2=negImg)
    fw=image.math_img("img1-img2",img1=pos,img2=neg)

    if fwhm==0:
        smin=np.min(np.abs(fw.get_data()[fw.get_data()!=0]))
    else:
        smin=2

    mri_file = "%s/thresholded_posneg.nii.gz" % folder
    fw.to_filename(mri_file)

    """Bring up the visualization"""
    brain = Brain("fsaverage", "split", surface ,views=['lat', 'med'], offscreen=True , background="white")

    """Project the volume file and return as an array"""

    reg_file = os.path.join("/opt/freesurfer","average/mni152.register.dat")
    surf_data_lh = io.project_volume_data(mri_file, "lh", reg_file,smooth_fwhm=fwhm)
    surf_data_rh = io.project_volume_data(mri_file, "rh", reg_file,smooth_fwhm=fwhm)


    """
    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=smin, max=5, name="ang_corr_lh", hemi='lh')
    brain.add_overlay(surf_data_rh, min=smin, max=5, name="ang_corr_rh", hemi='rh')

    if len(coords)>0:
        if coords[0]>0:
            hemi='rh'
        else:
            hemi='lh'
        brain.add_foci(coords, map_surface="pial", color="gold",hemi=hemi)

    if len(saveFolder)>0:
        folder=saveFolder
        brain.save_image('%s/%s.png' % (folder,filename))
    else:
        brain.save_image('%s/surfaceplot.jpg' % folder)
    brain.close()
Example #4
0
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 plot_data_surf_bh(in_file, colormap='jet', thr_list=[(None, None, None)],roi_coords=(), fwhm=0):
    '''
    allows more flexible visualization than plot_rs_surf_bh
    thr_list = [(min, max, thresh)]
    colormap: matplotlib colormap (http://matplotlib.org/examples/color/colormaps_reference.html)
    '''

    # in_file .nii to be projected on surface


    import os
    from surfer import Brain, io

    out_file_list = []
    in_file_name = os.path.basename(in_file)

    reg_file = os.path.join(os.environ["FREESURFER_HOME"],"average/mni152.register.dat")
    for thr in thr_list:
        min_thr = thr[0]
        max_thr = thr[1]
        thr_thr = thr[2]


        brain = Brain("fsaverage", "split", "inflated", views=['lat', 'med'], config_opts=dict(background="white"))

        surf_data_lh = io.project_volume_data(in_file, "lh", reg_file, smooth_fwhm=fwhm)
        surf_data_rh = io.project_volume_data(in_file, "rh", reg_file, smooth_fwhm=fwhm)

        brain.add_data(surf_data_lh, min=min_thr, max=max_thr, thresh=thr_thr, colormap=colormap, hemi='lh')
        brain.add_data(surf_data_rh, min=min_thr, max=max_thr, thresh=thr_thr, colormap=colormap, hemi='rh')

        roi_str = ''
        if not(roi_coords == ()):
            if roi_coords[0] <0: #lh
                hemi_str = 'lh'
            else:
                hemi_str = 'rh'
            roi_str = '_roi_%s.%s.%s' % roi_coords

            brain.add_foci(roi_coords, map_surface="white", hemi=hemi_str, color='red', scale_factor=2)


        out_filename = os.path.join(os.getcwd(), in_file_name + roi_str + '_thr_%s' % min_thr + '.png')
        out_file_list += [out_filename]
        brain.save_image(out_filename)
        brain.close()
    return out_file_list
def plot_parcel(num_nodes=600,numbers=[1],hemi='lh'):
    from surfer import Brain, io
    for n in numbers:
        brain = Brain("fsaverage", "%s" %(hemi), "pial",config_opts=dict(background="white"))
        image = io.project_volume_data('/home/despo/mb3152/random_nodes/%s/parcel_%s.nii'%(num_nodes,n),hemi, subject_id="fsaverage", projsum = 'max', smooth_fwhm = 0)
        brain.add_data(image,thresh=1,colormap = "spectral")
        brain.save_imageset('/home/despo/mb3152/random_nodes/%s/parcel_%s' %(num_nodes,n),['med','lat'],'jpg',colorbar= None)
        brain.close()
Example #7
0
def test_data():
    """Test plotting of data
    """
    mlab.options.backend = 'test'
    brain = Brain(*std_args)
    mri_file = pjoin(data_dir, 'resting_corr.nii.gz')
    reg_file = pjoin(data_dir, 'register.dat')
    surf_data = io.project_volume_data(mri_file, "lh", reg_file)
    brain.add_data(surf_data, -.7, .7, colormap="jet", alpha=.7)
Example #8
0
def test_data():
    """Test plotting of data
    """
    mlab.options.backend = 'test'
    brain = Brain(*std_args)
    mri_file = pjoin(data_dir, 'resting_corr.nii.gz')
    reg_file = pjoin(data_dir, 'register.dat')
    surf_data = io.project_volume_data(mri_file, "lh", reg_file)
    brain.add_data(surf_data, -.7, .7, colormap="jet", alpha=.7)
    brain.close()
Example #9
0
def test_data():
    """Test plotting of data."""
    _set_backend()
    brain = Brain(*std_args)
    mri_file = pjoin(data_dir, 'resting_corr.nii.gz')
    reg_file = pjoin(data_dir, 'register.dat')
    surf_data = io.project_volume_data(mri_file, "lh", reg_file)
    brain.add_data(surf_data, -.7, .7, colormap="jet", alpha=.7)
    brain.set_surf('white')
    brain.add_data([], vertices=np.array([], int))
    brain.close()
Example #10
0
def test_data():
    """Test plotting of data."""
    _set_backend()
    brain = Brain(*std_args)
    mri_file = pjoin(data_dir, 'resting_corr.nii.gz')
    reg_file = pjoin(data_dir, 'register.dat')
    surf_data = io.project_volume_data(mri_file, "lh", reg_file)
    brain.add_data(surf_data, -.7, .7, colormap="jet", alpha=.7)
    brain.set_surf('white')
    brain.add_data([], vertices=np.array([], int))
    brain.close()
def plot_rs_surf_bh(in_file, thr_list=[(.2,1)],roi_coords=(), fwhm=0):
    # in_file .nii to be projected on surface
    # list of tuples defining min and max thr_list=[(.2,1)]
    import os
    from surfer import Brain, io

    out_file_list = []
    in_file_name = os.path.basename(in_file)

    reg_file = os.path.join(os.environ["FREESURFER_HOME"],"average/mni152.register.dat")
    for thr in thr_list:
        min_thr = thr[0]
        max_thr = thr[1]
        print(min_thr)
        print(max_thr)

        brain = Brain("fsaverage", "split", "inflated", views=['lat', 'med'], config_opts=dict(background="white"))

        surf_data_lh = io.project_volume_data(in_file, "lh", reg_file, smooth_fwhm=fwhm)
        surf_data_rh = io.project_volume_data(in_file, "rh", reg_file, smooth_fwhm=fwhm)

        brain.add_overlay(surf_data_lh, min=min_thr, max=max_thr, name="ang_corr_lh", hemi='lh')
        brain.add_overlay(surf_data_rh, min=min_thr, max=max_thr, name="ang_corr_rh", hemi='rh')

        roi_str = ''
        if not(roi_coords == ()):
            if roi_coords[0] <0: #lh
                hemi_str = 'lh'
            else:
                hemi_str = 'rh'
            roi_str = '_roi_%s.%s.%s' % roi_coords

            brain.add_foci(roi_coords, map_surface="white", hemi=hemi_str, color='red', scale_factor=2)


        out_filename = os.path.join(os.getcwd(), in_file_name + roi_str + '_thr_%s' % min_thr + '.png')
        out_file_list += [out_filename]
        brain.save_image(out_filename)
        brain.close()
    return out_file_list
Example #12
0
def read_in_data(cope1_file, cope2_file, cope4_file, subject_id, subjects_dir):
    '''
    Read in the three nifti files for each hemisphere
    and combine into one surface (for each hemisphere)
    '''
    vtx_data_dict = {}

    for hemi in ['lh', 'rh']:
        cope1 = io.project_volume_data(cope1_file, hemi, subject_id=subject_id)

        cope2 = io.project_volume_data(cope2_file, hemi, subject_id=subject_id)

        cope4 = io.project_volume_data(cope4_file, hemi, subject_id=subject_id)

        # Binarize the maps and threshold to get rid of vertices that are only
        # created from the smoothing kernel
        cope1_bin = np.copy(cope1)
        cope1_bin[cope1 > 0] = 1

        cope2_bin = np.copy(cope2)
        cope2_bin[cope2 > 0] = 2

        cope4_bin = np.copy(cope4)
        cope4_bin[cope4 > 0] = 4

        cope124_bin = cope1_bin + cope2_bin + cope4_bin

        vtx_data_dict[hemi] = cope124_bin

        # Mask the data so you are only visualising cortex
        cortex_fname = os.path.join(subjects_dir, subject_id, 'label',
                                    hemi + '.cortex.label')

        # Read the data in and mask it so that non-cortex is -99
        vtx_data_dict[hemi] = mask_vtx_data(vtx_data_dict[hemi], cortex_fname,
                                            thresh)

    return vtx_data_dict
def read_in_data(cope1_file, cope2_file, cope4_file, subject_id, subjects_dir):
    """
    Read in the three nifti files for each hemisphere
    and combine into one surface (for each hemisphere)
    """
    vtx_data_dict = {}

    for hemi in ["lh", "rh"]:
        cope1 = io.project_volume_data(cope1_file, hemi, subject_id=subject_id)

        cope2 = io.project_volume_data(cope2_file, hemi, subject_id=subject_id)

        cope4 = io.project_volume_data(cope4_file, hemi, subject_id=subject_id)

        # Binarize the maps and threshold to get rid of vertices that are only
        # created from the smoothing kernel
        cope1_bin = np.copy(cope1)
        cope1_bin[cope1 > 0] = 1

        cope2_bin = np.copy(cope2)
        cope2_bin[cope2 > 0] = 2

        cope4_bin = np.copy(cope4)
        cope4_bin[cope4 > 0] = 4

        cope124_bin = cope1_bin + cope2_bin + cope4_bin

        vtx_data_dict[hemi] = cope124_bin

        # Mask the data so you are only visualising cortex
        cortex_fname = os.path.join(subjects_dir, subject_id, "label", hemi + ".cortex.label")

        # Read the data in and mask it so that non-cortex is -99
        vtx_data_dict[hemi] = mask_vtx_data(vtx_data_dict[hemi], cortex_fname, thresh)

    return vtx_data_dict
def plot_rs_surf(in_file, thr_list=[(.2,1)],roi_coords=(), fwhm=0):
    # in_file .nii to be projected on surface
    # list of tuples defining min and max thr_list=[(.2,1)]
    import os
    import subprocess
    from surfer import Brain, io

    arch = subprocess.check_output('arch')
    if arch.startswith('x86_'): # set offscrene rendering to avoid intereference on linux
        from mayavi import mlab
        mlab.options.offscreen = True

    out_file_list = []
    in_file_name = os.path.basename(in_file)

    reg_file = os.path.join(os.environ["FREESURFER_HOME"],"average/mni152.register.dat")
    for thr in thr_list:
        min_thr = thr[0]
        max_thr = thr[1]
        print(min_thr)
        print(max_thr)

        for hemi in ['lh', 'rh']:
            brain = Brain("fsaverage", hemi, "inflated", views=['lat', 'med'], config_opts=dict(background="white"))

            surf_data = io.project_volume_data(in_file, hemi, reg_file, smooth_fwhm=fwhm)

            brain.add_overlay(surf_data, min=min_thr, max=max_thr, name="ang_corr", hemi=hemi)

            roi_str = ''
            if not(roi_coords == ()):
                if roi_coords[0] <0: #lh
                    hemi_str = 'lh'
                else:
                    hemi_str = 'rh'
                roi_str = '_roi_%s.%s.%s' % roi_coords

                if hemi_str == hemi:
                    brain.add_foci(roi_coords, map_surface="white", hemi=hemi_str, color='red', scale_factor=2)


            out_filename = os.path.join(os.getcwd(), in_file_name + roi_str + '_thr_%s' % min_thr + '_' + hemi + '.png')
            out_file_list += [out_filename]
            brain.save_image(out_filename)
            brain.close()
    return out_file_list
Example #15
0
import os
from surfer import Brain, io
subj_id = 'Bend1'
subjects_dir = "/media/BlackBook_/ERIKPETDTIFMRI/ComaSample/subjects"

os.environ['SUBJECTS_DIR'] = subjects_dir

brain = Brain(subj_id,
              "lh",
              "pial",
              subjects_dir=subjects_dir,
              config_opts=dict(background="white"))
"""Project the volume file and return as an array"""
mri_file = "petmr.nii"

surf_data = io.project_volume_data(mri_file, "lh", subject_id=subj_id)
brain.add_data(surf_data, 100, 50000, colormap="jet", alpha=.7)
Example #16
0
to the surface for improved visualization. At the moment, this
uses Freesurfer's mri_vol2surf routine.

"""
print __doc__

from surfer import Brain, io

"""Bring up the visualization"""
brain = Brain("fsaverage", "lh", "inflated",
              config_opts=dict(background="white"))

"""Project the volume file and return as an array"""
mri_file = "auto_examples/data/resting_corr.nii.gz"
reg_file = "auto_examples/data/register.dat"
surf_data = io.project_volume_data(mri_file, "lh", 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, min=.3, max=.7, name="ang_corr")

"""
You can also pass it to add_data for more control
over the visualzation. Here we'll plot the whole
range of correlations
"""
brain.overlays["ang_corr"].remove()
brain.add_data(surf_data, -.7, .7, colormap="jet", alpha=.7)
"""
import os
from surfer import Brain, io

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 = io.project_volume_data(mri_file, "lh", reg_file)
surf_data_rh = io.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"]:
Example #18
0
                              name=name_roi)
        text = brain.texts[name_roi]
        text.width = 0.2

        #   Projection part
        #   If reg_file if needed:
        #   surf_data = io.project_volume_data(r, "lh", reg_file)
        #   Projection parameters, see the docstring for more information
        projmeth = "frac"  # frac' method, projection on a fraction of thickness
        projsum = "max"  # the max value is projected
        projarg = [0, 1, 0.1]  # from 0 to 1 thickness fract every 0.1 step
        smooth_fwhm = 0  # no smoothing
        surf_data = io.project_volume_data(r,
                                           hemi,
                                           projmeth=projmeth,
                                           projsum=projsum,
                                           projarg=projarg,
                                           smooth_fwhm=smooth_fwhm,
                                           subject_id='fsaverage')

        # nothing to do, if all points in the projection are nul
        if surf_data.max() != 0:
            name_overlay = '{name_roi}_{hemi}'.format(name_roi=name_roi,
                                                      hemi=hemi)
            brain.add_overlay(surf_data, name=name_overlay, hemi=hemi)
            overlay_roi = brain.overlays[name_overlay]
            lut = overlay_roi.pos_bar.lut.table.to_array()
            lut[0:255, 0:3] = color_list[cpt_color]
            overlay_roi.pos_bar.lut.table = lut

            # Save in png
def plot(subject,hemi='lh',hub='pc',num_nodes=600):
    from surfer import Brain, io
    hemi = hemi
    brain = Brain("fsaverage", "%s" %(hemi), "pial",config_opts=dict(background="white"))
    image = io.project_volume_data('/home/despo/mb3152/random_nodes/%s/final_%s_%s.nii'%(num_nodes,hub,subject),hemi, subject_id="fsaverage", projsum = 'max', smooth_fwhm = 0)
    brain.add_data(image,min=1,colormap = "jet", smoothing_steps = 0, colorbar= True)
Example #20
0
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()
Example #21
0
import os


#def plot_surf(working_dir):
from surfer import Brain, io
#ecm = os.path.join(working_dir, 'STATISTICS/ECM/%s'%string)
ecm = '/scr/sambesi4/workspace/project_REST/study_a/STATISTICS/SCA/FIRST/RESIDUAL_MNI2mm_detrend_wmcsf_friston_bp_fwhm_scrubbed/randomise_baseline_tfce_corrp_tstat2.nii.gz'
reg_file = '/afs/cbs.mpg.de/software/freesurfer/5.3.0/ubuntu-precise-amd64/average/mni152.register.dat'
surf_data_lh = io.project_volume_data(ecm, "lh", reg_file)
brain = Brain("fsaverage", "lh", "pial", views=['lat', 'med'], background="black")
brain.add_data(surf_data_lh, min = 0, max = 1,   colormap="jet", hemi='lh')
# brain.save_image('/SCR/ECM_imgs/all_mean.png')
Example #22
0
from mayavi import mlab
from surfer import Brain, io
subject = 'fsaverage' # SAD_017
surface = 'pial'

br1 = Brain(subject, 'rh', surface, title='lgroup')
l_surf_data = io.project_volume_data('/mindhive/scratch/satra/sadfigures/nipype_mem/nipype-interfaces-spm-model-EstimateContrast/cf535c8b3e6380c2c8512307f3c294ad/spmT_0001.img',
                                     'rh', subject_id='fsaverage',
                                     target_subject=subject)
br1.add_overlay(l_surf_data, min=2, max=3.7, sign='pos', name='lgroup')

br2 = Brain(subject, 'rh', surface, title='hgroup')
h_surf_data = io.project_volume_data('/mindhive/scratch/satra/sadfigures/nipype_mem/nipype-interfaces-spm-model-EstimateContrast/d1fbe9c9d24038d7d1e16b16936f52ed/spmT_0001.img',
                                     'rh', subject_id='fsaverage',
                                     target_subject=subject)
br2.add_overlay(h_surf_data, min=2, max=3.7, sign='pos', name='hgroup')
mlab.sync_camera(br1._f, br2._f)
mlab.sync_camera(br2._f, br1._f)

"""
br1.save_image('lgroup.png')
br2.save_image('hgroup.png')
"""
Example #23
0
def singleNiftiHeatmap(niftiPath1, subject_id, subjects_dir):

    #for whatever reason, it seems that left and right are switched here.
    # at least this is what I infer from the nifti.  Right side niftis
    # have lower x values than left side niftis, which one wouldnt usualy
    # expect, but whatever.  It serves as the appropriate check
    niftiVol = nib.load(niftiPath1)
    niftiData = niftiVol.get_data()
    nonZeros = np.nonzero(niftiData)
    niftiDimensions = niftiData.shape
    xDim = niftiDimensions[1]
    averageXcoord = np.mean(nonZeros[0])
    if averageXcoord > xDim / 2:
        side = 'lh'
    else:
        side = 'rh'

    dirContent = os.listdir(subjects_dir + subject_id)
    fsindices = [i for i, s in enumerate(dirContent) if 'freesurfer' in s]
    fsDir = NiftiPreDir + dirContent[fsindices[0]]

    brain = Brain(subject_id='output',
                  hemi=side,
                  surf="inflated",
                  background="white",
                  subjects_dir=fsDir)

    #set this up for each system, I guess
    os.environ['FREESURFER_HOME'] = '/Applications/freesurfer/'
    os.environ['SUBJECTS_DIR'] = fsDir
    #print os.environ['SUBJECTS_DIR']

    steps = [float(i) for i in [0, 10, .1]]

    #fib1_surf_data = io.project_volume_data(filepath=niftiPath1, hemi=side,  subject_id=subject_id, projsum='max', smooth_fwhm=5, projmeth='dist',  projarg=[4])
    fib1_surf_data = io.project_volume_data(filepath=niftiPath1,
                                            hemi=side,
                                            subject_id='output',
                                            projsum='max',
                                            smooth_fwhm=5,
                                            projmeth='dist',
                                            projarg=steps)

    #thresh=max(fib1_surf_data)*.05

    fib1Max = max(fib1_surf_data)
    #        fib1Dev=np.std(fib1_surf_data[(fib1_surf_data!=0)])
    #        fib2Dev=np.std(fib2_surf_data[(fib2_surf_data!=0)])
    #        fib1Ratio=fib1Max/fib1Dev
    #        fib2Ratio=fib2Max/fib2Dev
    #        fib1mean=np.true_divide(fib1_surf_data.sum(),(fib1_surf_data!=0).sum())
    #        fib2mean=np.true_divide(fib2_surf_data.sum(),(fib2_surf_data!=0).sum())

    dataSort = fib1_surf_data
    dataSort = dataSort[dataSort > 0]
    print dataSort

    #thresh=dataSort[twentiethPrctIndx]
    thresh = 5
    print thresh

    brain.add_data(fib1_surf_data,
                   0,
                   fib1Max,
                   .333,
                   colormap="gist_rainbow",
                   alpha=.6,
                   hemi=side)

    figdir = os.path.join(subjects_dir, subject_id, 'Figures/')
    filename1 = os.path.basename(niftiPath1)
    #i have no idea why this picks the first ., but it works.
    filedotIndex1 = filename1.index('.')
    filetitle1 = filename1[0:filedotIndex1]

    if not os.path.exists(figdir):
        os.makedirs(figdir)
        #views=[(-45,27.5),(-45,90),(45,90),(-90,135),(-225,27.5),(-315,27.5),(-45,-27.5),(-135,-27.5),(-225,-27.5),(-315,-27.5),(0,0),(0,-27.5),(0,27.5)]
    if side == 'rh':
        views = [(-45, 27.5), (-45, 110), (45, 90), (-90, 135), (-315, 27.5),
                 (90, -180), (0, 27.5), (-100, 80), (-120, 105), (0, 90),
                 (90, 90)]
    else:
        views = [(-135, 27.5), (-135, 110), (135, 90), (90, -135),
                 (315, -27.5), (90, -180), (0, -27.5), (100, -80), (120, -105),
                 (0, -90), (90, 90)]

    for iviews in np.arange(len(views)):

        mayavi.mlab.view(azimuth=views[iviews][0], elevation=views[iviews][1])
        figName = filetitle1 + '_heatmap' + str(iviews) + '.png'
        curFileName = os.path.join(figdir, figName)
        brain.save_single_image(curFileName)
Example #24
0
        text = brain.add_text(0.1, pos_y, color=tuple(color), 
                       text=name_roi, name=name_roi)
        text = brain.texts[name_roi]
        text.width = 0.2

    #   Projection part
    #   If reg_file if needed: 
    #   surf_data = io.project_volume_data(r, "lh", reg_file)
    #   Projection parameters, see the docstring for more information
        projmeth = "frac" # frac' method, projection on a fraction of thickness
        projsum = "max"   # the max value is projected
        projarg = [0, 1, 0.1] # from 0 to 1 thickness fract every 0.1 step
        smooth_fwhm = 0       # no smoothing  
        surf_data = io.project_volume_data(r, hemi,
                                          projmeth=projmeth,
                                          projsum=projsum, 
                                          projarg=projarg,
                                          smooth_fwhm = smooth_fwhm,
                                          subject_id='fsaverage')


        # nothing to do, if all points in the projection are nul                              
        if surf_data.max()!=0:
            name_overlay = '{name_roi}_{hemi}'.format(name_roi=name_roi, hemi=hemi)
            brain.add_overlay(surf_data, name=name_overlay, hemi=hemi)
            overlay_roi = brain.overlays[name_overlay]
            lut = overlay_roi.pos_bar.lut.table.to_array()
            lut[0:255, 0:3] = color_list[cpt_color]
            overlay_roi.pos_bar.lut.table = lut
            
            # Save in png   
            #brain.save_imageset(save_png, ['lat'], 'png', colorbar=None)  
Example #25
0
to the surface for improved visualization. At the moment, this
uses Freesurfer's mri_vol2surf routine.

"""
print __doc__

from surfer import Brain, io
"""Bring up the visualization"""
brain = Brain("fsaverage",
              "lh",
              "inflated",
              config_opts=dict(background="white"))
"""Project the volume file and return as an array"""
mri_file = "example_data/resting_corr.nii.gz"
reg_file = "example_data/register.dat"
surf_data = io.project_volume_data(mri_file, "lh", 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, min=.3, max=.7, name="ang_corr")
"""
You can also pass it to add_data for more control
over the visualzation. Here we'll plot the whole
range of correlations
"""
brain.overlays["ang_corr"].remove()
brain.add_data(surf_data, -.7, .7, colormap="jet", alpha=.7)
"""
This overlay represents resting-state correlations with a
seed in left angular gyrus. Let's plot that seed.
import os
from surfer import Brain, io
subj_id = 'Bend1'
subjects_dir = "/media/BlackBook_/ERIKPETDTIFMRI/ComaSample/subjects"

os.environ['SUBJECTS_DIR'] = subjects_dir

brain = Brain(subj_id, "lh", "pial", subjects_dir=subjects_dir,
              config_opts=dict(background="white"))

"""Project the volume file and return as an array"""
mri_file = "petmr.nii"

surf_data = io.project_volume_data(mri_file, "lh", subject_id=subj_id)
brain.add_data(surf_data, 100, 50000, colormap="jet", alpha=.7)
def MultiNiftiOverlap(niftiPath1, niftiPath2, subject_id, subjects_dir):

    #for whatever reason, it seems that left and right are switched here.
    # at least this is what I infer from the nifti.  Right side niftis
    # have lower x values than left side niftis, which one wouldnt usualy
    # expect, but whatever.  It serves as the appropriate check
    niftiVol = nib.load(niftiPath1)
    niftiData = niftiVol.get_data()
    nonZeros = np.nonzero(niftiData)
    niftiDimensions = niftiData.shape
    xDim = niftiDimensions[1]
    averageXcoord = np.mean(nonZeros[0])
    if averageXcoord > xDim / 2:
        side = 'lh'
    else:
        side = 'rh'

    brain = Brain(subject_id=subject_id,
                  hemi=side,
                  surf="white",
                  background="white",
                  subjects_dir=subjects_dir)

    #set this up for each system, I guess
    os.environ['FREESURFER_HOME'] = '/Applications/freesurfer/'
    os.environ['SUBJECTS_DIR'] = subjects_dir
    #print os.environ['SUBJECTS_DIR']

    #NOTE: There is also another optional variable that you can put in here, projarg=steps where steps= [float(i) for i in [0,8,.1]]
    # what this will do is specify how deep into the cortex it is going to look for data.  If your plots are coming out kind of sparse, feel free to try this
    fib1_surf_data = io.project_volume_data(filepath=niftiPath1,
                                            hemi=side,
                                            subject_id=subject_id,
                                            projsum='max',
                                            smooth_fwhm=5)
    fib2_surf_data = io.project_volume_data(filepath=niftiPath2,
                                            hemi=side,
                                            subject_id=subject_id,
                                            projsum='max',
                                            smooth_fwhm=5)

    #Here we are setting the maximum color value for the color map
    fib1Max = max(fib1_surf_data)
    fib2Max = max(fib2_surf_data)

    #here we are setting the lower bound threshold for this plotting instance.  Anything lower than this is zeroed out on the plot
    thresh1 = fib1Max * .005
    thresh2 = fib2Max * .005

    #note the value that preceeds the fiber max.  This stretches the color map so that more striking colors are used
    brain.add_data(fib1_surf_data,
                   -fib1Max * .75,
                   fib1Max,
                   thresh2,
                   colormap="Reds",
                   alpha=.5,
                   hemi=side)

    brain.add_data(fib2_surf_data,
                   -fib2Max * .75,
                   fib2Max,
                   thresh1,
                   colormap="Blues",
                   alpha=.5,
                   hemi=side)

    #sets the figure directory
    figdir = os.path.join(subjects_dir, subject_id, 'Figures/')
    filename1 = os.path.basename(niftiPath1)
    filename2 = os.path.basename(niftiPath2)
    #i have no idea why this picks the first ., but it works.
    filedotIndex1 = filename1.index('.')
    filedotIndex2 = filename2.index('.')
    filetitle1 = filename1[0:filedotIndex1]
    filetitle2 = filename2[0:filedotIndex2]

    if not os.path.exists(figdir):
        os.makedirs(figdir)

    #changes the views depending on the hemisphere used
    if side == 'rh':
        views = [(-45, 27.5), (-45, 110), (45, 90), (-90, 135), (-315, 27.5),
                 (90, -180), (0, 27.5), (-100, 80), (-120, 105), (0, 90),
                 (90, 90)]
    else:
        views = [(-135, 27.5), (-135, 110), (135, 90), (90, -135),
                 (315, -27.5), (90, -180), (0, -27.5), (100, -80), (120, -105),
                 (0, -90), (90, 90)]

    #iterates through views and saves down
    for iviews in np.arange(len(views)):
        #this mayavi bit is why this won't work on clusters.  It needs an interactive window
        #to manipulate in order to generate and iterate through images
        mayavi.mlab.view(azimuth=views[iviews][0], elevation=views[iviews][1])
        figName = filetitle1 + '_to_' + filetitle2 + str(iviews) + '.png'
        curFileName = os.path.join(figdir, figName)
        brain.save_single_image(curFileName)
Example #28
0
def MultiNiftiOverlap(niftiPath1, coordsPath, subject_id, subjects_dir):

    #for whatever reason, it seems that left and right are switched here.
    # at least this is what I infer from the nifti.  Right side niftis
    # have lower x values than left side niftis, which one wouldnt usualy
    # expect, but whatever.  It serves as the appropriate check
    niftiVol = nib.load(niftiPath1)
    niftiData = niftiVol.get_data()
    nonZeros = np.nonzero(niftiData)
    niftiDimensions = niftiData.shape
    xDim = niftiDimensions[1]
    averageXcoord = np.mean(nonZeros[0])
    if averageXcoord < xDim / 2:
        side = 'lh'
    else:
        side = 'rh'

    print(niftiPath1)

    brain = Brain(subject_id=subject_id,
                  hemi=side,
                  surf="inflated",
                  background="white",
                  subjects_dir=subjects_dir)

    #set this up for each system, I guess
    os.environ['FREESURFER_HOME'] = '/Applications/freesurfer/'
    os.environ['SUBJECTS_DIR'] = subjects_dir
    #print os.environ['SUBJECTS_DIR']

    steps = [float(i) for i in [0, 8, .1]]

    #NOTE:  FIBER 2 IS ACTUALLY THE ECOG PLOT HERE.

    epi_img = nib.load(niftiPath1)
    epi_img_data = epi_img.get_fdata()
    np.unique(epi_img_data.data)

    #unique, counts = np.unique(epi_img_data.data, return_counts=True)
    #dict(zip(unique, counts))

    fib1_surf_data = io.project_volume_data(filepath=niftiPath1,
                                            hemi=side,
                                            subject_id=subject_id,
                                            projsum='max',
                                            smooth_fwhm=5,
                                            projmeth='dist',
                                            projarg=steps)
    #fib1_surf_data = io.project_volume_data(filepath=niftiPath1, hemi=side,  subject_id=subject_id, projsum='max', smooth_fwhm=5)

    #Just scale the data I guess?  Something is being messed with in the data.

    #fib1Max=max(fib1_surf_data)

    #thresh1=np.median(fib1_surf_data[np.nonzero(fib1_surf_data)])
    #print(thresh1)
    #coords2=[]
    coords = readcsv(coordsPath)
    #padCoord=np.zeros((1,3))
    #coords2=np.concatenate((coords,padCoord),axis=0)

    fsPath = subjects_dir + subject_id + '/'
    interpolatedCoords = interpolate_coords_to_GM(fsPath, coords)
    #interpolatedCoords=rewarp_coords(fsPath,coords)

    brain.add_data(fib1_surf_data,
                   0,
                   1000,
                   150,
                   colormap="hsv",
                   alpha=.68,
                   hemi=side)

    #        colorwords=['red',
    #                     'blue',
    #                     'green',
    #                     'black',
    #                     'purple',
    #                     'cyan',
    #                     'yellow',
    #                     'pink'
    #                     'orange']

    #
    #        coordsSize=interpolatedCoords.shape
    #
    #        print(interpolatedCoords)

    #        for iCoords in range(coordsSize[0]):
    brain.add_foci(interpolatedCoords,
                   map_surface='white',
                   color="black",
                   scale_factor=.5)
    #            print(interpolatedCoords[iCoords])
    #            print(colorwords[iCoords])
    #            brain.add_foci(interpolatedCoords[iCoords], map_surface='white', color=colorwords[iCoords], scale_factor=.5)

    figdir = os.path.join(subjects_dir, subject_id, 'Figures/')
    filename1 = os.path.basename(niftiPath1)

    #i have no idea why this picks the first ., but it works.
    filedotIndex1 = filename1.index('.')

    coordName = os.path.basename(coordsPath)
    coordName = coordName.replace('.csv', '')

    filetitle1 = filename1[0:filedotIndex1] + '_' + coordName

    if not os.path.exists(figdir):
        os.makedirs(figdir)
        #views=[(-45,27.5),(-45,90),(45,90),(-90,135),(-225,27.5),(-315,27.5),(-45,-27.5),(-135,-27.5),(-225,-27.5),(-315,-27.5),(0,0),(0,-27.5),(0,27.5)]
    if side == 'rh':
        views = [(-45, 27.5), (-45, 110), (45, 90), (-90, 135), (-315, 27.5),
                 (90, -180), (0, 27.5), (-100, 80), (-120, 105), (0, 90),
                 (90, 90)]
    else:
        views = [(-135, 27.5), (-135, 110), (135, 90), (90, -135),
                 (315, -27.5), (90, -180), (0, -27.5), (100, -80), (120, -105),
                 (0, -90), (90, 90)]

    for iviews in np.arange(len(views)):

        mayavi.mlab.view(azimuth=views[iviews][0], elevation=views[iviews][1])
        figName = filetitle1 + str(iviews) + '.png'
        curFileName = os.path.join(figdir, figName)
        brain.save_single_image(curFileName)