Beispiel #1
0
 def vizify(self):
     for hemi in self.hemis:
         print "visualize %s" % hemi
         
         # Bring up the beauty (the underlay)
         brain = Brain(self.subject_id, hemi, self.surf, \
                       config_opts=self.config_opts, \
                       subjects_dir=self.subjects_dir)
         
         surf_data = io.read_scalar_data(self.overlay_surf[hemi])
         if (sum(abs(surf_data)) > 0):
             # Overlay another hopeful beauty (functional overlay)
             brain.add_overlay(self.overlay_surf[hemi], name=self.overlay_name, 
                               min=self.min, max=self.max, sign=self.sign)
         
             # Update colorbar
             #brain.overlays[self.overlay_name].pos_bar.lut_mode = self.colorbar
             tmp = brain.overlays[self.overlay_name]
             lut = tmp.pos_bar.lut.table.to_array()
             lut[:,0:3] = self.colorbar
             tmp.pos_bar.lut.table = lut
         
             # Refresh
             brain.show_view("lat")
             brain.hide_colorbar()
         
         # Save the beauts
         brain.save_imageset("%s_%s" % (self.outprefix, hemi), self.views, 
                             'jpg', colorbar=None)
         
         # End a great journey, till another life
         brain.close()
     return
Beispiel #2
0
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 plot_surface(vtx_data, subject_id, subjects_dir, hemi, surface, output_dir, prefix, l, u, cmap, center, thresh):
    # Open up a brain in pysurfer
    brain = Brain(
        subject_id,
        hemi,
        surface,
        subjects_dir=subjects_dir,
        config_opts=dict(background="white", height=665, width=800),
    )

    if center:
        # Make sure the colorbar is centered
        if l ** 2 < u ** 2:
            l = u * -1
        else:
            u = l * -1

    # Create an empty brain if the values are all below threshold
    if np.max(vtx_data) < thresh:
        # Add your data to the brain
        brain.add_data(vtx_data * 0, l, u, thresh=thresh, colormap=cmap, alpha=0.0)

    # Otherwise, add the data appropriately!
    else:
        # Add your data to the brain
        brain.add_data(vtx_data, l, u, thresh=thresh, colormap=cmap, alpha=0.8)

    # Save the images for medial and lateral
    # putting a color bar on all of them
    brain.save_imageset(prefix=os.path.join(output_dir, prefix), views=views_list, colorbar=range(len(views_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()
Beispiel #5
0
def test_image():
    """Test image saving
    """
    mlab.options.backend = 'auto'
    brain = Brain(*std_args, config_opts=small_brain)
    tmp_name = mktemp() + '.png'
    brain.save_image(tmp_name)
    brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg')
    brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v')
    brain.screenshot()
Beispiel #6
0
def test_image():
    """Test image saving
    """
    mlab.options.backend = 'auto'
    brain = Brain(*std_args, config_opts=small_brain)
    tmp_name = mktemp() + '.png'
    brain.save_image(tmp_name)
    brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg')
    brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v')
    brain.screenshot()
    brain.close()
Beispiel #7
0
def save_groups_labels_figures():
    labels, groups = get_groups()
    for group in groups:
        print(group)
        if len(get_group_labels(group)) < 4:
            group_label = [l for l in labels if group in l]
            colors = get_spaced_colors(len(group_label))
        brain = Brain(subject, hemi, surf, offscreen=False)
        for label_id, label in enumerate(group_label):
            print(label)
            brain.add_label(label, color=colors[label_id])
        fol = os.path.join(subjects_dir, subject, 'label', '{}_figures'.format(aparc_name))
        if not os.path.isdir(fol):
            os.mkdir(fol)
        brain.save_imageset(os.path.join(fol, group), get_views(), 'jpg')
        brain.remove_labels()
        brain.close()
Beispiel #8
0
def test_image(tmpdir):
    """Test image saving."""
    tmp_name = tmpdir.join('temp.png')
    tmp_name = str(tmp_name)  # coerce to str to avoid PIL error

    _set_backend()
    subject_id, _, surf = std_args
    brain = Brain(subject_id, 'both', surf=surf, size=100)
    brain.add_overlay(overlay_fname, hemi='lh', min=5, max=20, sign="pos")
    brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg')
    brain.save_image(tmp_name)
    brain.save_image(tmp_name, 'rgba', True)
    brain.screenshot()
    brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v')
    brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='h')
    brain.save_montage(tmp_name, [['l', 'v'], ['m', 'f']])
    brain.close()
Beispiel #9
0
def test_image():
    """Test image saving
    """
    tmp_name = mktemp() + '.png'

    mlab.options.backend = 'auto'
    subject_id, _, surf = std_args
    brain = Brain(subject_id, 'both', surf=surf, size=100)
    brain.add_overlay(overlay_fname, hemi='lh', min=5, max=20, sign="pos")
    brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg')

    brain = Brain(*std_args, size=100)
    brain.save_image(tmp_name)
    brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v')
    brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='h')
    brain.save_montage(tmp_name, [['l', 'v'], ['m', 'f']])
    brain.screenshot()
    brain.close()
Beispiel #10
0
def test_image():
    """Test image saving."""
    tmp_name = mktemp() + '.png'

    _set_backend()
    subject_id, _, surf = std_args
    brain = Brain(subject_id, 'both', surf=surf, size=100)
    brain.add_overlay(overlay_fname, hemi='lh', min=5, max=20, sign="pos")
    brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg')

    brain = Brain(*std_args, size=100)
    brain.save_image(tmp_name)
    brain.save_image(tmp_name, 'rgba', True)
    brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v')
    brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='h')
    brain.save_montage(tmp_name, [['l', 'v'], ['m', 'f']])
    brain.screenshot()
    brain.close()
Beispiel #11
0
def test_image():
    """Test image saving
    """
    tmp_name = mktemp() + '.png'

    mlab.options.backend = 'auto'
    subject_id, _, surf = std_args
    brain = Brain(subject_id, 'both', surf=surf, config_opts=small_brain)
    brain.add_overlay(overlay_fname, hemi='lh', min=5, max=20, sign="pos")
    brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg')

    brain = Brain(*std_args, config_opts=small_brain)
    brain.save_image(tmp_name)
    brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v')
    brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='h')
    brain.save_montage(tmp_name, [['l', 'v'], ['m', 'f']])
    brain.screenshot()
    brain.close()
def corr_image(resting_image,fwhm):
    """This function makes correlation image on brain surface"""
    import numpy as np
    import nibabel as nb
    import matplotlib.pyplot as plt
    from surfer import Brain, Surface
    import os

    img = nb.load(resting_image)
    corrmat = np.corrcoef(np.squeeze(img.get_data()))
    corrmat[np.isnan(corrmat)] = 0
    corrmat_npz = os.path.abspath('corrmat.npz')
    np.savez(corrmat_npz,corrmat=corrmat)

    br = Brain('fsaverage5', 'lh', 'smoothwm')

    #br.add_overlay(corrmat[0,:], min=0.2, name=0, visible=True)
    lh_aparc_annot_file = os.path.join(os.environ["FREESURFER_HOME"],'/subjects/label/lh.aparc.annot')
    values = nb.freesurfer.read_annot(lh_aparc_annot_file)

    #br.add_overlay(np.mean(corrmat[values[0]==5,:], axis=0), min=0.8, name='mean', visible=True)


    data = img.get_data()

    data = np.squeeze(img.get_data())

    #
    precuneus_signal = np.mean(data[values[0]==np.nonzero(np.array(values[2])=='precuneus')[0][0],:], axis=0)
    precuneus = np.corrcoef(precuneus_signal, data)
    #precuneus.shape

    #br.add_overlay(precuneus[0,1:], min=0.3, sign='pos', name='mean', visible=True)

    br.add_overlay(precuneus[0,1:], min=0.2, name='mean')#, visible=True)
    #br.add_overlay(precuneus[0,1:], min=0.2, name='mean')#, visible=True)
    plt.hist(precuneus[0,1:], 128)
    plt.savefig(os.path.abspath("histogram.png"))
    plt.close()

    corr_image = os.path.abspath("corr_image%s.png"%fwhm)
    br.save_montage(corr_image)
    ims = br.save_imageset(prefix=os.path.abspath('fwhm_%s'%str(fwhm)),views=['medial','lateral','caudal','rostral','dorsal','ventral'])
    br.close()
    print ims
    #precuneus[np.isnan(precuneus)] = 0
    #plt.hist(precuneus[0,1:])

    roitable = [['Region','Mean Correlation']]
    for i, roi in enumerate(np.unique(values[2])):
        roitable.append([roi,np.mean(precuneus[values[0]==np.nonzero(np.array(values[2])==roi)[0][0]])])

        #images = [corr_fimage]+ims+[os.path.abspath("histogram.png"), roitable]
    roitable=[roitable]
    histogram = os.path.abspath("histogram.png")

    return corr_image, ims, roitable, histogram, corrmat_npz
Beispiel #13
0
def corr_image(resting_image,fwhm):
    """This function makes correlation image on brain surface"""
    import numpy as np
    import nibabel as nb
    import matplotlib.pyplot as plt
    from surfer import Brain, Surface
    import os

    img = nb.load(resting_image)
    corrmat = np.corrcoef(np.squeeze(img.get_data()))
    corrmat[np.isnan(corrmat)] = 0
    corrmat_npz = os.path.abspath('corrmat.npz')
    np.savez(corrmat_npz,corrmat=corrmat)

    br = Brain('fsaverage5', 'lh', 'smoothwm')

    #br.add_overlay(corrmat[0,:], min=0.2, name=0, visible=True)
    lh_aparc_annot_file = os.path.join(os.environ["FREESURFER_HOME"],'/subjects/label/lh.aparc.annot')
    values = nb.freesurfer.read_annot(lh_aparc_annot_file)

    #br.add_overlay(np.mean(corrmat[values[0]==5,:], axis=0), min=0.8, name='mean', visible=True)


    data = img.get_data()

    data = np.squeeze(img.get_data())

    #
    precuneus_signal = np.mean(data[values[0]==np.nonzero(np.array(values[2])=='precuneus')[0][0],:], axis=0)
    precuneus = np.corrcoef(precuneus_signal, data)
    #precuneus.shape

    #br.add_overlay(precuneus[0,1:], min=0.3, sign='pos', name='mean', visible=True)

    br.add_overlay(precuneus[0,1:], min=0.2, name='mean')#, visible=True)
    #br.add_overlay(precuneus[0,1:], min=0.2, name='mean')#, visible=True)
    plt.hist(precuneus[0,1:], 128)
    plt.savefig(os.path.abspath("histogram.png"))
    plt.close()

    corr_image = os.path.abspath("corr_image%s.png"%fwhm)
    br.save_montage(corr_image)
    ims = br.save_imageset(prefix=os.path.abspath('fwhm_%s'%str(fwhm)),views=['medial','lateral','caudal','rostral','dorsal','ventral'])
    br.close()
    print ims
    #precuneus[np.isnan(precuneus)] = 0
    #plt.hist(precuneus[0,1:])

    roitable = [['Region','Mean Correlation']]
    for i, roi in enumerate(np.unique(values[2])):
        roitable.append([roi,np.mean(precuneus[values[0]==np.nonzero(np.array(values[2])==roi)[0][0]])])

        #images = [corr_fimage]+ims+[os.path.abspath("histogram.png"), roitable]
    roitable=[roitable]
    histogram = os.path.abspath("histogram.png")

    return corr_image, ims, roitable, histogram, corrmat_npz
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/final_group_%s.nii'%(num_nodes,hub),hemi, subject_id="fsaverage", projsum = 'max', smooth_fwhm = 20)
        brain.add_data(image,thresh = np.nanmin(image[image>0]),colormap = "jet", colorbar= True)
        brain.save_imageset('/home/despo/mb3152/random_nodes/%s/final_%s' %(num_nodes,hub),['med','lat'],'jpg',colorbar= None)
    else:
        pc_image = io.project_volume_data('/home/despo/mb3152/random_nodes/%s/final_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/final_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 = max(wmd_image), colormap = 'Blues',alpha= .65,hemi=hemi,smoothing_steps = 0)
        # brain.add_data(connector_hub_image,thresh=pc_thresh,max=np.nanmax(pc_image), colormap = 'Purples',alpha= .65,hemi=hemi,smoothing_steps = 0)
        # brain.add_data(satellite_image,thresh= pc_thresh,max=np.nanmax(pc_image),colormap = 'Reds',alpha= .65,hemi=hemi,smoothing_steps = 0)
        # brain.add_data(provincial_hub_image,thresh=wmd_thresh,max=np.nanmax(wmd_image),colormap = 'Blues',alpha= .65,hemi=hemi,smoothing_steps = 0)

        brain.add_data(node_image,thresh= 0, max = max(wmd_image), colormap = 'Blues',hemi=hemi,smoothing_steps = 0)
        brain.add_data(connector_hub_image,thresh=pc_thresh,max=np.nanmax(pc_image), colormap = 'Purples',hemi=hemi,smoothing_steps = 0)
        brain.add_data(satellite_image,thresh= pc_thresh,max=np.nanmax(pc_image),colormap = 'Reds',hemi=hemi,smoothing_steps = 0)
        brain.add_data(provincial_hub_image,thresh=wmd_thresh,max=np.nanmax(wmd_image),colormap = 'Blues',hemi=hemi,smoothing_steps = 0)
        brain.save_imageset('/home/despo/mb3152/random_nodes/%s/final_combined' %(num_nodes),['med','lat'],'jpg',colorbar= None)
Beispiel #15
0
def plot_surface(vtx_data, subject_id, subjects_dir, hemi, surface, output_dir,
                 prefix, l, u, cmap, center, thresh):
    # Open up a brain in pysurfer
    # brain = Brain(subject_id, hemi, surface,
    #               subjects_dir = subjects_dir,
    #               config_opts=dict(background="white",
    #                                height=665,
    #                                width=800))
    brain = Brain(subject_id,
                  hemi,
                  surface,
                  subjects_dir=subjects_dir,
                  background="white")

    if center:
        # Make sure the colorbar is centered
        if l**2 < u**2:
            l = u * -1
        else:
            u = l * -1

    # Create an empty brain if the values are all below threshold
    if np.max(vtx_data) < thresh:
        # Add your data to the brain
        brain.add_data(vtx_data * 0,
                       l,
                       u,
                       thresh=thresh,
                       colormap=cmap,
                       alpha=0.0)

    # Otherwise, add the data appropriately!
    else:
        # Add your data to the brain
        brain.add_data(vtx_data, l, u, thresh=thresh, colormap=cmap, alpha=.8)

    # Save the images for medial and lateral
    # putting a color bar on all of them
    brain.save_imageset(prefix=os.path.join(output_dir, prefix),
                        views=views_list,
                        colorbar=range(len(views_list)))
Beispiel #16
0
def test_image():
    """Test image saving."""
    tmp_name = mktemp() + '.png'

    _set_backend()
    subject_id, _, surf = std_args
    brain = Brain(subject_id, 'both', surf=surf, size=100)
    brain.add_overlay(overlay_fname, hemi='lh', min=5, max=20, sign="pos")
    brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg')
    brain.close()

    brain = Brain(*std_args, size=100)
    brain.save_image(tmp_name)
    brain.save_image(tmp_name, 'rgba', True)
    brain.screenshot()
    if not os.getenv('TRAVIS', 'false') == 'true':
        # for some reason these fail on Travis sometimes
        brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v')
        brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='h')
        brain.save_montage(tmp_name, [['l', 'v'], ['m', 'f']])
    brain.close()
Beispiel #17
0
def test_image(tmpdir):
    """Test image saving."""
    tmp_name = tmpdir.join('temp.png')
    tmp_name = str(tmp_name)  # coerce to str to avoid PIL error

    _set_backend()
    subject_id, _, surf = std_args
    brain = Brain(subject_id, 'both', surf=surf, size=100)
    brain.add_overlay(overlay_fname, hemi='lh', min=5, max=20, sign="pos")
    brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg')
    brain.close()

    brain = Brain(*std_args, size=100)
    brain.save_image(tmp_name)
    brain.save_image(tmp_name, 'rgba', True)
    brain.screenshot()
    if os.getenv('TRAVIS', '') != 'true':
        # for some reason these fail on Travis sometimes
        brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v')
        brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='h')
        brain.save_montage(tmp_name, [['l', 'v'], ['m', 'f']])
    brain.close()
Beispiel #18
0
    def vizify(self):
        for hemi in self.hemis:
            print "visualize %s" % hemi

            # Bring up the beauty (the underlay)
            brain = Brain(self.subject_id, hemi, self.surf, \
                          config_opts=self.config_opts, \
                          subjects_dir=self.subjects_dir)

            surf_data = io.read_scalar_data(self.overlay_surf[hemi])
            if (sum(abs(surf_data)) > 0):
                # Overlay another hopeful beauty (functional overlay)
                brain.add_overlay(self.overlay_surf[hemi],
                                  name=self.overlay_name,
                                  min=self.min,
                                  max=self.max,
                                  sign=self.sign)

                # Update colorbar
                #brain.overlays[self.overlay_name].pos_bar.lut_mode = self.colorbar
                tmp = brain.overlays[self.overlay_name]
                lut = tmp.pos_bar.lut.table.to_array()
                lut[:, 0:3] = self.colorbar
                tmp.pos_bar.lut.table = lut

                # Refresh
                brain.show_view("lat")
                brain.hide_colorbar()

            # Save the beauts
            brain.save_imageset("%s_%s" % (self.outprefix, hemi),
                                self.views,
                                'jpg',
                                colorbar=None)

            # End a great journey, till another life
            brain.close()
        return
Beispiel #19
0
def test_image(tmpdir):
    """Test image saving."""
    tmp_name = tmpdir.join('temp.png')
    tmp_name = str(tmp_name)  # coerce to str to avoid PIL error

    _set_backend()
    subject_id, _, surf = std_args
    brain = Brain(subject_id, 'both', surf=surf, size=100)
    brain.add_overlay(overlay_fname, hemi='lh', min=5, max=20, sign="pos")
    brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg')
    brain.close()

    brain = Brain(*std_args, size=100)
    if sys.platform == 'darwin' and os.getenv('TRAVIS', '') == 'true':
        raise SkipTest('image saving on OSX travis is not supported')
    brain.save_image(tmp_name)
    brain.save_image(tmp_name, 'rgba', True)
    brain.screenshot()
    if os.getenv('TRAVIS', '') != 'true':
        # for some reason these fail on Travis sometimes
        brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v')
        brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='h')
        brain.save_montage(tmp_name, [['l', 'v'], ['m', 'f']])
    brain.close()
data_max = data.max()
if data_max == 0:
    data_min = 0
else:
    data_min = 1.3
"""
You can pass this array to the add_overlay method for
a typical activation overlay (with thresholding, etc.)
"""
brain.add_overlay(surf_data, min=data_min, max=data_max, name="ang_corr")
"""
Save some images
"""
odir = "/home/data/Projects/CWAS/development+motion/viz"
brain.save_imageset(
    path.join(odir, "zpics_glm_regress_surface_%s_lh" % "only_age"),
    ['med', 'lat', 'ros', 'caud'], 'jpg')

brain.close()

## Age with motion as covariate

print "age with motion"

mdmr_dir = "/home2/data/Projects/CWAS/development+motion/cwas_regress_motion/rois_random_k3200/age+motion_sex+tr.mdmr"
"""Bring up the visualization"""
brain = Brain("fsaverage",
              "lh",
              "inflated",
              config_opts=dict(background="white"))
"""Project the volume file and return as an array"""
Beispiel #21
0
                                          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)  
            
            # Color cpt
            cpt_color += 1
            
            # If you just want one roi by one  
            # Remove for the next roi
            # for overlay in brain.overlays_dict[name_overlay]:
            #    overlay.remove() 
    
    #   Save in png  
    save_png = os.path.join(datadir, "all_rois")  
    brain.save_imageset(save_png, ['lat'], 'png', colorbar=None) 
    brain.close()
Beispiel #22
0
tmp1 = brain.overlays["%s_rh" % factor]
lut = tmp1.pos_bar.lut.table.to_array()

## update color scheme
lut[:,0:3] = cols
tmp1.pos_bar.lut.table = lut

## refresh view
brain.show_view("lat")
brain.hide_colorbar()

"""
Save some images
"""
odir = "/home/data/Projects/CWAS/development+motion/viz"
brain.save_imageset(path.join(odir, "zpics_surface_%s_rh" % "only_age"), 
                    ['med', 'lat', 'ros', 'caud'], 'jpg')

brain.close()


## Age with motion as covariate

print "age with motion"

mdmr_dir = "/home2/data/Projects/CWAS/development+motion/cwas/rois_random_k3200/age+motion_sex+tr.mdmr"
factor = "age"

"""Bring up the visualization"""
brain = Brain("fsaverage_copy", "rh", "iter8_inflated",
              config_opts=dict(background="white"), 
              subjects_dir="/home2/data/PublicProgram/freesurfer")
def plot_surface(vtx_data, subject_id, hemi, surface, subjects_dir, output_dir, prefix, l, u, cmap, thresh, thresh2=None, cmap2='autumn', cortex_style='classic'):
    """
    This function needs more documentation, but for now
    it is sufficient to know this one important fact:
	For the variable "cmap":
	    If you pass a word that defines a matplotlib
	      colormap (eg: jet, Rd_Bu etc) then the code
	      will use that for the color scheme.
	    If you pass a **list** of colors then you'll
	      just loop through those colors instead. 
    """
    if cortex_style.count('_') == 2: 
        cortex_style_list = cortex_style.split('_')
        cortex_name = cortex_style_list[0]
        cortex_min = np.float(cortex_style_list[1])
        cortex_max = np.float(cortex_style_list[2])
            
        cortex_style = ( cortex_name, cortex_min, cortex_max, False )
    
    # Open up a brain in pysurfer
    brain = Brain(subject_id, hemi, surface,
                      subjects_dir = subjects_dir,
                      background="white",
                      size=(800, 665),
                      cortex=cortex_style)

    # Create an empty brain if the values are all below threshold
    if np.max(vtx_data) < thresh:
        # Add your data to the brain
        brain.add_data(vtx_data*0,
                        l, 
                        u,
                        thresh = thresh,
                        colormap=cmap,
                        alpha=0.0)
    
    # If you only have one threshold
    # then add the data!
    elif not thresh2:
        # Add your data to the brain
        brain.add_data(vtx_data,
                        l, 
                        u,
                        thresh = thresh,
                        colormap=cmap,
                        alpha=.8)
    
    else:
        # Plot the data twice for the two
        # different settings
        vtx_data1 = np.copy(vtx_data)
        vtx_data1[vtx_data1>thresh2] = 0
        brain.add_data(vtx_data1,
                        l, 
                        u,
                        thresh = thresh,
                        colormap = cmap,
                        alpha = .8)
                        
        brain.add_data(vtx_data,
                        l, 
                        u,
                        thresh = thresh2,
                        colormap = cmap2,
                        alpha = .8)
        
    # Save the images for medial and lateral
    # putting a color bar on all of them
    brain.save_imageset(prefix = os.path.join(output_dir, prefix),
                        views = views_list, 
                        colorbar = range(len(views_list)) )
## update color scheme
single = [251, 154, 143]
overlap = [227, 26, 28]
lut[0:85,0:3] = single
lut[85:170,0:3] = single
lut[170:256,0:3] = overlap
tmp1.pos_bar.lut.table = lut

## refresh view
brain.show_view("lat")
brain.hide_colorbar()

"""Save Pictures"""
odir = "/home/data/Projects/CWAS/age+gender/03_robustness/viz_cwas/pysurfer"
brain.save_imageset(path.join(odir, "zpics_overlap_age_surface_rh"), 
                    ['med', 'lat', 'ros', 'caud'], 'jpg')

brain.close()


## SEX

"""Bring up the visualization"""
brain = Brain("fsaverage_copy", "rh", "iter8_inflated",
              config_opts=dict(background="white"), 
              subjects_dir="/home2/data/PublicProgram/freesurfer")

"""Project the volume file and return as an array"""
cwas_file = path.join(overlap_dir, "surf_rh_fdr_logp_sex_thr2.nii.gz")

"""
Beispiel #25
0
"""
Handle vertices that are not defined in the annotation.
"""
vtx_data[labels == -1] = -1000
"""
Display these values on the brain. Use a sequential colormap (assuming
these data move from low to high values), and add an alpha channel so the
underlying anatomy is visible. 
See: https://pysurfer.github.io/generated/surfer.Brain.html#surfer.Brain.add_data
"""
brain.add_data(vtx_data,
               0,
               thresh=0,
               colormap="YlOrRd",
               alpha=1,
               transparent=True,
               colorbar=True)

#Save  images

brain.save_imageset(analysis_name, ['med', 'lat'], 'jpg')
# other views
#brain.show_view('lateral')
#brain.show_view('m')
#brain.show_view('rostral')
#brain.show_view('caudal')
#brain.show_view('ve')
#brain.show_view('frontal')
#brain.show_view('par')
#brain.show_view('dor')
Beispiel #26
0
brain = Brain(sub, hemi, surf)

###############################################################################
# show all views
brain.show_view('lateral')
brain.show_view('m')
brain.show_view('rostral')
brain.show_view('caudal')
brain.show_view('dor')
brain.show_view('ve')
brain.show_view('frontal')
brain.show_view('par')

###############################################################################
# save some images
brain.show_view('lat')
brain.save_image("%s_lat.png" % sub)

brain.save_imageset(sub, ['med', 'lat', 'ros', 'caud'], 'jpg')

###############################################################################
# More advanced parameters
brain.show_view({'distance': 375})
# with great power comes great responsibility
brain.show_view({'azimuth': 20, 'elevation': 30}, roll=20)

###############################################################################
# Save a set of images as a montage
brain.save_montage('fsaverage_h_montage.png', ['l', 'v', 'm'], orientation='h')
brain.save_montage('fsaverage_v_montage.png', ['l', 'v', 'm'], orientation='v')
Beispiel #27
0
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'
            data_min = data[data.nonzero()].min()
        """
        You can pass this array to the add_overlay method for
        a typical activation overlay (with thresholding, etc.)
        """
        brain.add_overlay(cwas_file,
                          min=data_min,
                          max=data_max,
                          name="%s_rh" % factor)

        ## get overlay and color bar
        tmp1 = brain.overlays["%s_rh" % factor]
        lut = tmp1.pos_bar.lut.table.to_array()

        ## update color scheme
        lut[:, 0:3] = cols
        tmp1.pos_bar.lut.table = lut

        ## refresh view
        brain.show_view("lat")
        brain.hide_colorbar()
        """
        Save some images
        """
        odir = "/home/data/Projects/CWAS/%s/viz" % study
        brain.save_imageset(
            path.join(odir, "zpics_surface_%s_rh" % onames[i][j]),
            ['med', 'lat', 'ros', 'caud'], 'jpg')

        brain.close()
Beispiel #29
0
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jul  9 13:22:37 2019

@author: kwn500
"""

from surfer import Brain
import os

subject_id = 'fsaverage'
hemi = 'lh'
surf = 'inflated'
cope_filepath = '/scratch/groups/Projects/P1361/fMRI/fsl_output/level3/freesurfer/'
cope_output = cope_filepath + 'output/'
cope_file = 'shape_versus_passive_zstat_lh'

os.environ['SUBJECTS_DIR'] = "/usr/share/freesurfer-data/subjects"
brain = Brain(subject_id, hemi, surf)
brain.add_overlay(cope_filepath + cope_file + '.mgh', 2.3, 8)

brain.save_imageset(
    cope_output + cope_file,
    ['medial', 'lateral', 'rostral', 'caudal', 'dorsal', 'ventral'], 'png',
    [1, 2, 3, 4, 5, 6])
brain.close()
Beispiel #30
0
                                           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)

            # Color cpt
            cpt_color += 1

            # If you just want one roi by one
            # Remove for the next roi
            # for overlay in brain.overlays_dict[name_overlay]:
            #    overlay.remove()

    #   Save in png
    save_png = os.path.join(datadir, "all_rois")
    brain.save_imageset(save_png, ['lat'], 'png', colorbar=None)
    brain.close()
Beispiel #31
0
    data_min = 0
else:
    data_min = data[data.nonzero()].min()

"""
You can pass this array to the add_overlay method for
a typical activation overlay (with thresholding, etc.)
"""
brain.add_overlay(cwas_file, min=data_min, max=data_max, name="%s_lh" % factor)

## get overlay and color bar
tmp1 = brain.overlays["%s_lh" % factor]
lut = tmp1.pos_bar.lut.table.to_array()

## update color scheme
lut[:,0:3] = cols
tmp1.pos_bar.lut.table = lut

## refresh view
brain.show_view("lat")
brain.hide_colorbar()

"""
Save images
"""
odir = "/home/data/Projects/CWAS/ldopa/viz"
brain.save_imageset(path.join(odir, "zpics_surface_lh"), 
                    ['med', 'lat', 'ros', 'caud'], 'jpg')
brain.close()

Beispiel #32
0
def plot_surface(vtx_data,
                 subject_id,
                 hemi,
                 surface,
                 subjects_dir,
                 output_dir,
                 prefix,
                 l,
                 u,
                 cmap,
                 thresh,
                 thresh2=None,
                 cmap2='autumn',
                 cortex_style='classic'):
    """
    This function needs more documentation, but for now
    it is sufficient to know this one important fact:
	For the variable "cmap":
	    If you pass a word that defines a matplotlib
	      colormap (eg: jet, Rd_Bu etc) then the code
	      will use that for the color scheme.
	    If you pass a **list** of colors then you'll
	      just loop through those colors instead.
    """
    if cortex_style.count('_') == 2:
        cortex_style_list = cortex_style.split('_')
        cortex_name = cortex_style_list[0]
        cortex_min = np.float(cortex_style_list[1])
        cortex_max = np.float(cortex_style_list[2])

        cortex_style = (cortex_name, cortex_min, cortex_max, False)

    # Open up a brain in pysurfer
    brain = Brain(subject_id,
                  hemi,
                  surface,
                  subjects_dir=subjects_dir,
                  background="white",
                  size=(800, 665),
                  cortex=cortex_style)

    # Create an empty brain if the values are all below threshold
    if np.max(vtx_data) < thresh:
        # Add your data to the brain
        brain.add_data(vtx_data * 0,
                       l,
                       u,
                       thresh=thresh,
                       colormap=cmap,
                       alpha=0.0)

    # If you only have one threshold
    # then add the data!
    elif not thresh2:
        # Add your data to the brain
        brain.add_data(vtx_data, l, u, thresh=thresh, colormap=cmap, alpha=.8)

    else:
        # Plot the data twice for the two
        # different settings
        vtx_data1 = np.copy(vtx_data)
        vtx_data1[vtx_data1 > thresh2] = 0
        brain.add_data(vtx_data1, l, u, thresh=thresh, colormap=cmap, alpha=.8)

        brain.add_data(vtx_data,
                       l,
                       u,
                       thresh=thresh2,
                       colormap=cmap2,
                       alpha=.8)

    # Save the images for medial and lateral
    # putting a color bar on all of them
    brain.save_imageset(prefix=os.path.join(output_dir, prefix),
                        views=views_list,
                        colorbar=range(len(views_list)))
Beispiel #33
0
## update color scheme
single = [251, 154, 143]
overlap = [227, 26, 28]
lut[0:85,0:3] = single
lut[85:170,0:3] = single
lut[170:256,0:3] = overlap
tmp1.pos_bar.lut.table = lut

## refresh view
brain.show_view("lat")
brain.hide_colorbar()

"""Save Pictures"""
odir = "/home/data/Projects/CWAS/age+gender/03_robustness/viz_cwas/pysurfer"
brain.save_imageset(path.join(odir, "zpics_overlap_age_surface_lh"), 
                    ['med', 'lat', 'ros', 'caud'], 'jpg')

brain.close()


## SEX

"""Bring up the visualization"""
brain = Brain("fsaverage_copy", "lh", "iter8_inflated",
              config_opts=dict(background="white"), 
              subjects_dir="/home2/data/PublicProgram/freesurfer")

"""Project the volume file and return as an array"""
cwas_file = path.join(overlap_dir, "surf_lh_fdr_logp_sex_thr2.nii.gz")

"""
Beispiel #34
0
"""
===================
Save a set of views
===================

Save some views in png files.

"""
print(__doc__)

from surfer import Brain

sub = 'fsaverage'
hemi = 'lh'
surf = 'inflated'

brain = Brain(sub, hemi, surf)

###############################################################################
# save 1 image
brain.show_view('lat')
brain.save_image("%s_lat.png" % sub)

###############################################################################
# save some images
brain.save_imageset(sub, ['med', 'lat', 'ros', 'caud'], 'jpg')
Beispiel #35
0
                      config_opts=dict(background="white"),
                      subjects_dir="/home2/data/PublicProgram/freesurfer")
        """Get the volume => surface file"""
        cwas_file = path.join(mdmr_dir, "surf_rh_fdr_logp_%s.nii.gz" % factor)
        """
        You can pass this array to the add_overlay method for
        a typical activation overlay (with thresholding, etc.)
        """
        brain.add_overlay(cwas_file,
                          min=2,
                          max=max_zvals[i],
                          name="%s_rh" % factor)

        ## get overlay and color bar
        tmp1 = brain.overlays["%s_rh" % factor]
        lut = tmp1.pos_bar.lut.table.to_array()

        ## update color scheme
        lut[:, 0:3] = cols
        tmp1.pos_bar.lut.table = lut

        ## refresh view
        brain.show_view("lat")
        brain.hide_colorbar()
        """Save Pictures"""
        brain.save_imageset(
            path.join(odir, "zpics_%s_%s_surface_rh" % (sample, factor)),
            ['med', 'lat', 'ros', 'caud'], 'jpg')

        brain.close()
Beispiel #36
0
            "lh",
            "iter8_inflated",
            config_opts=dict(background="white"),
            subjects_dir="/home2/data/PublicProgram/freesurfer",
        )
        """Get the volume => surface file"""
        cwas_file = path.join(mdmr_dir, "surf_lh_fdr_logp_%s.nii.gz" % factor)
        """
        You can pass this array to the add_overlay method for
        a typical activation overlay (with thresholding, etc.)
        """
        brain.add_overlay(cwas_file, min=2, max=max_zvals[i], name="%s_lh" % factor)

        ## get overlay and color bar
        tmp1 = brain.overlays["%s_lh" % factor]
        lut = tmp1.pos_bar.lut.table.to_array()

        ## update color scheme
        lut[:, 0:3] = cols
        tmp1.pos_bar.lut.table = lut

        ## refresh view
        brain.show_view("lat")
        brain.hide_colorbar()
        """Save Pictures"""
        brain.save_imageset(
            path.join(odir, "zpics_%s_%s_surface_lh" % (sample, factor)), ["med", "lat", "ros", "caud"], "jpg"
        )

        brain.close()
            l = u*-1
    else:
        cmap = "jet"
        
    """
    Make a vector containing the data point at each vertex.
    """
    vtx_data = roi_data[labels]
    
    """
    Display these values on the brain.
    """
    ### MEAN
    brain = Brain(subject_id, hemi, surface,
                  subjects_dir = subjects_dir,
                  config_opts=dict(background="white"))

    
    brain.add_data(vtx_data,
                    l, 
                    u,
                    thresh = -98,
                    colormap=cmap,
                    alpha=.8)
    
    views_list = [ 'medial', 'lateral' ]
    prefix = '_'.join([data_file.strip('.csv'), surface, hemi])
    brain.save_imageset(prefix = os.path.join(fs_rois_dir, prefix),
                        views = views_list, 
                        colorbar = range(len(views_list)) )
                        
Beispiel #38
0
        if l**2 < u**2:
            l = u * -1
        else:
            u = l * -1

        brain.add_data(vtx_data_r,
                       -0.35,
                       0.35,
                       thresh=-98,
                       colormap="RdBu_r",
                       alpha=.8)

        views_list = ['medial', 'lateral']
        prefix = '_'.join([measure1, hemi, surface, 'r', measure2])
        brain.save_imageset(prefix=os.path.join(fs_rois_dir, parc, prefix),
                            views=views_list,
                            colorbar=range(len(views_list)))

        ### SIGNIFICANCE w AGE
        brain = Brain(subject_id,
                      hemi,
                      surface,
                      subjects_dir=subjects_dir,
                      config_opts=dict(background="white"))

        l = roi_data_p[roi_data_mean > -99].min()
        u = roi_data_p[roi_data_mean > -99].max()
        l = np.floor(l * 20) / 20.0
        u = np.ceil(u * 20) / 20.0

        brain.add_data(vtx_data_p,
data = img.get_data()
data_max = data.max()
if data_max == 0:
    data_min = 0
else:
    data_min = data[data.nonzero()].min()
"""
You can pass this array to the add_overlay method for
a typical activation overlay (with thresholding, etc.)
"""
brain.add_overlay(cwas_file, min=data_min, max=data_max, name="%s_rh" % factor)

## get overlay and color bar
tmp1 = brain.overlays["%s_rh" % factor]
lut = tmp1.pos_bar.lut.table.to_array()

## update color scheme
lut[:, 0:3] = cols
tmp1.pos_bar.lut.table = lut

## refresh view
brain.show_view("lat")
brain.hide_colorbar()
"""
Save images
"""
odir = "/home/data/Projects/CWAS/ldopa/viz"
brain.save_imageset(path.join(odir, "zpics_surface_rh"),
                    ['med', 'lat', 'ros', 'caud'], 'jpg')
brain.close()
Beispiel #40
0
def visOverlay(pathToSurface, overlay, outputPath, hemi, type='white'):
    brain = Brain(pathToSurface, hemi, type)
    brain.add_overlay(overlay, -1, 1)
    brain.show_view('lateral')
    brain.save_imageset(outputPath, ['med', 'lat'], 'png')
    brain.close()
Beispiel #41
0
surf = "pial"
subjects_dir = os.environ.get('SUBJECTS_DIR', '/home/noam/subjects/mri')

# x=range(15)
# cm = plt.get_cmap('jet')
# cNorm = matplotlib.colors.Normalize(vmin=min(x) vmax=max(x))
# return cmx.ScalarMappable(norm=cNorm, cmap=cm)


def get_spaced_colors(n):
    HSV_tuples = [(x * 1.0 / n, 0.5, 0.5) for x in range(n)]
    RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples)
    return RGB_tuples


labels = glob.glob(
    os.path.join(subjects_dir, subject_id, 'label', 'aparc250',
                 '*{}.label'.format(hemi)))
groups = set([l.split('/')[-1].split('_')[0] for l in labels])
brain = Brain(subject_id, hemi, surf, offscreen=True)
for group in groups:
    group_label = [l for l in labels if group in l]
    colors = get_spaced_colors(len(group_label))
    for label_id, label in enumerate(group_label):
        print(label)
        brain.add_label(label, color=colors[label_id])
    brain.save_imageset('{}-{}'.format(subject_id, group),
                        ['med', 'lat', 'ros', 'caud'], 'jpg')
    break
brain.remove_labels()
print('sdf')
Beispiel #42
0
            data_min = 0
        else:
            data_min = data[data.nonzero()].min()

        """
        You can pass this array to the add_overlay method for
        a typical activation overlay (with thresholding, etc.)
        """
        brain.add_overlay(cwas_file, min=data_min, max=data_max, name="%s_rh" % factor)

        ## get overlay and color bar
        tmp1 = brain.overlays["%s_rh" % factor]
        lut = tmp1.pos_bar.lut.table.to_array()

        ## update color scheme
        lut[:,0:3] = cols
        tmp1.pos_bar.lut.table = lut

        ## refresh view
        brain.show_view("lat")
        brain.hide_colorbar()

        """
        Save some images
        """
        odir = "/home/data/Projects/CWAS/%s/viz" % study
        brain.save_imageset(path.join(odir, "zpics_surface_%s_rh" % onames[i][j]), 
                            ['med', 'lat', 'ros', 'caud'], 'jpg')

        brain.close()
Beispiel #43
0
                      config_opts=dict(background="white"), 
                      subjects_dir="/home2/data/PublicProgram/freesurfer")
    
        """Get the volume => surface file"""
        cwas_file = path.join(mdmr_dir, "surf_lh_fdr_logp_%s.nii.gz" % factor)

        """
        You can pass this array to the add_overlay method for
        a typical activation overlay (with thresholding, etc.)
        """
        brain.add_overlay(cwas_file, min=2, max=max_zvals[i], name="%s_lh" % factor)

        ## get overlay and color bar
        tmp1 = brain.overlays["%s_lh" % factor]
        lut = tmp1.pos_bar.lut.table.to_array()

        ## update color scheme
        lut[:,0:3] = cols
        tmp1.pos_bar.lut.table = lut

        ## refresh view
        brain.show_view("lat")
        brain.hide_colorbar()

        """Save Pictures"""
        brain.save_imageset(path.join(odir, "zpics_%s_%s_surface_lh" % (sample, factor)), 
                            ['med', 'lat', 'ros', 'caud'], 'jpg')

        brain.close()

Beispiel #44
0
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')