Exemplo n.º 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
def visMontage(pathToSurface, overlay, outputPath, hemi, type='white'):
    brain = Brain(pathToSurface, hemi, type)
    brain.add_overlay(overlay, -5, 3)
    brain.save_montage(outputPath, ['l', 'm'], orientation='v')
    brain.close()

    return outputPath
Exemplo n.º 3
0
def test_overlay():
    """Test plotting of overlay
    """
    mlab.options.backend = 'test'
    # basic overlay support
    overlay_file = pjoin(data_dir, "lh.sig.nii.gz")
    brain = Brain(*std_args)
    brain.add_overlay(overlay_file)
    brain.overlays["sig"].remove()
    brain.add_overlay(overlay_file, min=5, max=20, sign="pos")
    sig1 = io.read_scalar_data(pjoin(data_dir, "lh.sig.nii.gz"))
    sig2 = io.read_scalar_data(pjoin(data_dir, "lh.alt_sig.nii.gz"))

    thresh = 4
    sig1[sig1 < thresh] = 0
    sig2[sig2 < thresh] = 0

    conjunct = np.min(np.vstack((sig1, sig2)), axis=0)
    brain.add_overlay(sig1, 4, 30, name="sig1")
    brain.overlays["sig1"].pos_bar.lut_mode = "Reds"
    brain.overlays["sig1"].pos_bar.visible = False

    brain.add_overlay(sig2, 4, 30, name="sig2")
    brain.overlays["sig2"].pos_bar.lut_mode = "Blues"
    brain.overlays["sig2"].pos_bar.visible = False

    brain.add_overlay(conjunct, 4, 30, name="conjunct")
    brain.overlays["conjunct"].pos_bar.lut_mode = "Purples"
    brain.overlays["conjunct"].pos_bar.visible = False
    brain.close()
Exemplo n.º 4
0
def load_fmri(subject, input_file, hemi="both"):
    brain = Brain(subject, hemi, "pial", curv=False)
    brain.toggle_toolbars(True)
    if hemi == "both":
        for hemi in ["rh", "lh"]:
            brain.add_overlay(input_file.format(hemi), hemi=hemi)
    else:
        brain.add_overlay(input_file.format(hemi), hemi=hemi)
Exemplo n.º 5
0
def main(subid, overlay):
    _, fname = os.path.split(overlay)
    
    hemi = fname[:2]
    brain = Brain(subid, hemi, "pial",
                  config_opts=dict(cortex="low_contrast"))
    brain.add_overlay(overlay, min=0.4, max=4, sign="pos")
    brain.show_view('m')
Exemplo n.º 6
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
Exemplo n.º 7
0
 def make_brain(subject_id,image_path):
     from surfer import Brain
     hemi = 'lh'
     surface = 'inflated'
     brain = Brain(subject_id, hemi, surface)
     brain.add_overlay(image_path,min=thr)
     outpath = os.path.join(os.getcwd(),os.path.split(image_path)[1]+'_surf.png')
     brain.save_montage(outpath)
     return outpath
Exemplo n.º 8
0
def show_fMRI_using_pysurfer(subject, input_file, hemi='both'):
    brain = Brain(subject, hemi, "pial", curv=False, offscreen=False)
    brain.toggle_toolbars(True)
    if hemi=='both':
        for hemi in ['rh', 'lh']:
            print('adding {}'.format(input_file.format(hemi=hemi)))
            brain.add_overlay(input_file.format(hemi=hemi), hemi=hemi)
    else:
        print('adding {}'.format(input_file.format(hemi=hemi)))
        brain.add_overlay(input_file.format(hemi=hemi), hemi=hemi)
Exemplo n.º 9
0
def make_pysurfer_images_lh_rh(folder,suffix='cope1',hemi='lh',threshold=0.9499,coords=(),surface='inflated',fwhm=0,filename='',saveFolder=[],vmax=5.0,bsize=5):
    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",hemi,surface, 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 = io.project_volume_data(mri_file, hemi, 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, min=smin, max=vmax, name="activation", hemi=hemi)
    # brain.overlays["activation"]
    # brain.add_overlay(surf_data_rh, min=smin, max=5, name="ang_corr_rh", hemi='rh')

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

    if len(saveFolder)>0:
        folder=saveFolder
        image_out=brain.save_montage('%s/%s-%s.png' % (folder,hemi,filename),order=['l','m'],orientation='h',border_size=bsize,colorbar=None)

    else:
        image_out=brain.save_image('%s/surfaceplot.jpg' % folder)
    brain.close()
    return image_out
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
Exemplo n.º 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, 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()
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
Exemplo n.º 13
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()
Exemplo n.º 14
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()
Exemplo n.º 15
0
def surface_streamlines_map(subjects_dir, subject_id, hemi, surf, alpha,
                            coords):
    """
    Bring up the visualization.
    display a map
    """
    brain = Brain(subjects_dir=subjects_dir,
                  subject_id=subject_id,
                  hemi=hemi,
                  surf=surf,
                  alpha=alpha)

    if hemi == 'both':
        hemi_both = ['lh', 'rh']
        for hemi_index in range(len(['lh', 'rh'])):
            brain.add_overlay(
                coords[hemi_index],
                min=coords[hemi_index][coords[hemi_index] > 0].min(),
                max=coords[hemi_index].max(),
                sign='pos',
                hemi=hemi_both[hemi_index])

    elif hemi == 'lh':
        brain.add_overlay(coords[0],
                          min=coords[0][coords[0] > 0].min(),
                          max=coords[0].max(),
                          sign='pos',
                          hemi='lh',
                          name='lh')

    else:
        brain.add_overlay(coords[1],
                          min=coords[1][coords[1] > 0].min(),
                          max=coords[1].max(),
                          sign='pos',
                          hemi='rh',
                          name='rh')

    mlab.show()
Exemplo n.º 16
0
import os.path as op
from surfer import Brain

"""
Bring up the visualization
"""
brain = Brain("fsaverage", "lh", "inflated")

"""
Get a path to the overlay file.
"""
overlay_file = op.join("example_data", "lh.sig.nii.gz")

"""
Display the overlay on the surface using the defaults
to control thresholding and colorbar saturation.
These can be set through your config file.
"""
brain.add_overlay(overlay_file)

"""
You can then turn the overlay off.
"""
brain.overlays["sig"].remove()

"""
Now add the overlay again, but this time with set threshold
and showing only the positive activations
"""
brain.add_overlay(overlay_file, min=5, max=20, sign="pos")
Exemplo n.º 17
0
## AGE

"""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_age_thr2.nii.gz")

"""
You can pass this array to the add_overlay method for
a typical activation overlay (with thresholding, etc.)
"""
brain.add_overlay(cwas_file, min=1, max=3, name="tmp1")

# Update color bar

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

## 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
Exemplo n.º 18
0
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)

"""
This overlay represents resting-state correlations with a
seed in left angular gyrus. Let's plot that seed.
"""
seed_coords = (-45, -67, 36)
brain.add_foci(seed_coords, map_surface="white")
Exemplo n.º 19
0
## AGE

"""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_age_thr2.nii.gz")

"""
You can pass this array to the add_overlay method for
a typical activation overlay (with thresholding, etc.)
"""
brain.add_overlay(cwas_file, min=1, max=3, name="tmp1")

# Update color bar

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

## 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
Exemplo n.º 20
0
export SUBJECTS_DIR='/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/mri'
export QT_API=pyqt

ipython

from surfer import Brain
%gui qt

brain = Brain("fsaverage", "lh", "inflated")
overlay_file = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/fMRI/GROUPlvl_SPROJ_SJ_lh.mgz"
brain.add_overlay(overlay_file, min=3.10, max=5.80, sign="pos")

brain = Brain("fsaverage", "rh", "inflated")
overlay_file = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/fMRI/GROUPlvl_SPROJ_SJ_rh.mgz"
brain.add_overlay(overlay_file, min=3.10, max=5.80, sign="pos")

brain = Brain("fsaverage", "rh", "inflated")
overlay_file = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/fMRI/GROUPlvl_SPROJ_SJ_rh.mgz"
brain.add_overlay(overlay_file, min=2.34, max=5.50, sign="pos")
    Get a path to the overlay file.
    """
    mri_file = '/Users/jamalw/Desktop/PNI/music_event_structures/data/best_k_map_z' + str(
        z) + '.nii.gz'
    reg_file = '/Applications/freesurfer/average/mni152.register.dat'

    data = nib.load(mri_file)
    minval = 0
    maxval = np.max(data.get_data())

    surf_data_lh = project_volume_data(mri_file, "lh", reg_file)
    surf_data_rh = project_volume_data(mri_file, "rh", reg_file)

    brain.add_overlay(surf_data_lh,
                      min=minval,
                      max=maxval,
                      name="thirty_sec_lh",
                      hemi='lh')
    brain.add_overlay(surf_data_rh,
                      min=minval,
                      max=maxval,
                      name="thirty_sec_rh",
                      hemi='rh')

    for overlay in brain.overlays_dict["thirty_sec_lh"]:
        overlay.remove()
    for overlay in brain.overlays_dict["thirty_sec_rh"]:
        overlay.remove()

    brain.add_data(surf_data_lh,
                   0,
surf_data = io.project_volume_data(mri_file, "rh", reg_file)

"""Load the output data and get maximum value"""
img = nib.load(mri_file)
data = img.get_data()
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_rh" % "only_age"), 
                    ['med', 'lat', 'ros', 'caud'], 'jpg')

brain.close()


## Age with motion as covariate

print "age with motion"
Exemplo n.º 23
0
def surfer(hemi, overlay, annot='Yeo2011_7Networks_N1000'):
    brain = Brain("fsaverage", hemi, "inflated")
    brain.add_annotation(annot, borders=False, alpha=0.3)
    brain.add_overlay(overlay, min=1.66, max=4)
    return brain
Exemplo n.º 24
0
        """Project the volume file and return as an array"""
        orig_file = path.join(mdmr_dir, "clust_logp_%s.nii.gz" % factor)
        """Load the output data and get maximum value"""
        img = nib.load(orig_file)
        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 some images
Exemplo n.º 25
0
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.
"""
seed_coords = (-45, -67, 36)
brain.add_foci(seed_coords, map_surface="white")
Exemplo n.º 26
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()
Exemplo n.º 27
0
def surfer(hemi, overlay, annot='Yeo2011_7Networks_N1000'):
    brain = Brain("fsaverage", hemi, "inflated")
    brain.add_annotation(annot, borders=False, alpha=0.3)
    brain.add_overlay(overlay, min=1.66, max=4)
    return brain
Exemplo n.º 28
0
sig2[sig2 < thresh] = 0

"""
A conjunction is defined as the minimum significance
value between the two maps at each vertex.
"""
conjunct = np.min(np.vstack((sig1, sig2)), axis=0)


"""
Now load the numpy array as an overlay.
Use a high saturation point so that the
blob will largely be colored with lower
values from the lookup table.
"""
brain.add_overlay(sig1, 4, 30, name="sig1")

"""
A pointer to the overlay's color manager
gets stored in the overlays dictionary.
Change the lookup table to "Reds" and turn the
color bar itself off, as otherwise the bars
for the three maps will get confusingly stacked.
"""
brain.overlays["sig1"].pos_bar.lut_mode = "Reds"
brain.overlays["sig1"].pos_bar.visible = False

"""
Now load the other two maps and again change
the lookup table and turn off the color bar itself.
"""
Exemplo n.º 29
0
Alternatively, if your data are already in register with the Freesurfer
anatomy, you can provide project_volume_data with the subject ID, avoiding the
need to specify a registration file.

By default, 3mm of smoothing is applied on the surface to clean up the overlay
a bit, although the extent of smoothing can be controlled.
"""
zstat = project_volume_data(volume_file,
                            "lh",
                            subject_id="fsaverage",
                            smooth_fwhm=0.5)
"""
Once you have the statistical data loaded into Python, you can simply pass it
to the `add_overlay` method of the Brain object.
"""
brain.add_overlay(zstat, min=2, max=12)
"""
It can also be a good idea to plot the inverse of the mask that was used in the
analysis, so you can be clear about areas that were not included.

It's good to change some parameters of the sampling to account for the fact
that you are projecting binary (0, 1) data.
"""
mask_file = "example_data/mask.nii.gz"
mask = project_volume_data(mask_file,
                           "lh",
                           subject_id="fsaverage",
                           smooth_fwhm=0,
                           projsum="max").astype(bool)
mask = ~mask
brain.add_data(mask,
Exemplo n.º 30
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)
    values = nb.freesurfer.read_annot(
        '/software/Freesurfer/5.1.0/subjects/fsaverage5/label/lh.aparc.annot')

    #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
mri_file = path.join(mdmr_dir, "mni305_log_fdr_pvals_age.nii.gz")
reg_file = path.join(mdmr_dir, "mni305_log_fdr_pvals_age.nii.gz.reg")
surf_data = io.project_volume_data(mri_file, "lh", reg_file)
"""Load the output data and get maximum value"""
img = nib.load(mri_file)
data = img.get_data()
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"
Exemplo n.º 32
0
def test_overlay():
    """Test plotting of overlay."""
    _set_backend()
    # basic overlay support
    overlay_file = pjoin(data_dir, "lh.sig.nii.gz")
    brain = Brain(*std_args)
    brain.add_overlay(overlay_file)
    brain.overlays["sig"].remove()
    brain.add_overlay(overlay_file, min=5, max=20, sign="pos")
    sig1 = io.read_scalar_data(pjoin(data_dir, "lh.sig.nii.gz"))
    sig2 = io.read_scalar_data(pjoin(data_dir, "lh.alt_sig.nii.gz"))

    # two-sided overlay
    brain.add_overlay(sig1, 4, 30, name="two-sided")
    overlay = brain.overlays_dict.pop('two-sided')[0]
    assert_array_equal(overlay.pos_bar.data_range, [4, 30])
    assert_array_equal(overlay.neg_bar.data_range, [-30, -4])
    assert_equal(overlay.pos_bar.reverse_lut, True)
    assert_equal(overlay.neg_bar.reverse_lut, False)
    overlay.remove()

    thresh = 4
    sig1[sig1 < thresh] = 0
    sig2[sig2 < thresh] = 0

    conjunct = np.min(np.vstack((sig1, sig2)), axis=0)
    brain.add_overlay(sig1, 4, 30, name="sig1")
    brain.overlays["sig1"].pos_bar.lut_mode = "Reds"
    brain.overlays["sig1"].pos_bar.visible = False

    brain.add_overlay(sig2, 4, 30, name="sig2")
    brain.overlays["sig2"].pos_bar.lut_mode = "Blues"
    brain.overlays["sig2"].pos_bar.visible = False

    brain.add_overlay(conjunct, 4, 30, name="conjunct")
    brain.overlays["conjunct"].pos_bar.lut_mode = "Purples"
    brain.overlays["conjunct"].pos_bar.visible = False

    brain.set_surf('white')

    brain.close()
Alternatively, if your data are already in register with the Freesurfer
anatomy, you can provide project_volume_data with the subject ID, avoiding the
need to specify a registration file.

By default, 3mm of smoothing is applied on the surface to clean up the overlay a
bit, although the extent of smoothing can be controlled.
"""
zstat = project_volume_data(volume_file, "lh",
                            subject_id="fsaverage", smooth_fwhm=0.5)

"""
Once you have the statistical data loaded into Python, you can simply pass it
to the `add_overlay` method of the Brain object.
"""
brain.add_overlay(zstat, min=2, max=12)

"""
It can also be a good idea to plot the inverse of the mask that was used in the
analysis, so you can be clear about areas that were not included.

It's good to change some parameters of the sampling to account for the fact that
you are projecting binary (0, 1) data.
"""
mask_file = "example_data/mask.nii.gz"
mask = project_volume_data(mask_file, "lh", subject_id="fsaverage",
                           smooth_fwhm=0, projsum="max").astype(bool)
mask = ~mask
brain.add_data(mask, min=0, max=10, thresh=.5,
               colormap="bone", alpha=.6, colorbar=False)
                time=str(time), subid=subid))

############################################
# Visualize accuracy (for given subject)
############################################

from surfer import Brain, project_volume_data
tr_shift_test_list = [0, 2, 4, 6, 8, 10,
                      12]  # seconds to shift onset forward by

# for subid in subj_info.subid:
subid = 'ap101'
for time in tr_shift_test_list:
    brain = Brain(subid,
                  "split",
                  "inflated",
                  views=['lat', 'med', 'ven'],
                  background="white")
    volume_file = '/Volumes/group/awagner/sgagnon/AP/analysis/mvpa_raw/searchlight_test/sourcehit_time{time}_acc_{subid}.nii.gz'.format(
        time=str(time), subid=subid)

    for hemi in ['lh', 'rh']:
        zstat = project_volume_data(volume_file,
                                    hemi,
                                    subject_id=subid,
                                    smooth_fwhm=0.5)
        brain.add_overlay(zstat, hemi=hemi, min=.333)
    brain.save_image(
        '/Volumes/group/awagner/sgagnon/AP/analysis/mvpa_raw/searchlight_test/sourcehit_time{time}_acc_{subid}.png'
        .format(time=str(time), subid=subid))
Exemplo n.º 35
0
def test_overlay():
    """Test plotting of overlay."""
    _set_backend()
    # basic overlay support
    overlay_file = pjoin(data_dir, "lh.sig.nii.gz")
    brain = Brain(*std_args)
    brain.add_overlay(overlay_file)
    brain.overlays["sig"].remove()
    brain.add_overlay(overlay_file, min=5, max=20, sign="pos")
    sig1 = io.read_scalar_data(pjoin(data_dir, "lh.sig.nii.gz"))
    sig2 = io.read_scalar_data(pjoin(data_dir, "lh.alt_sig.nii.gz"))

    # two-sided overlay
    brain.add_overlay(sig1, 4, 30, name="two-sided")
    overlay = brain.overlays_dict.pop('two-sided')[0]
    assert_array_equal(overlay.pos_bar.data_range, [4, 30])
    assert_array_equal(overlay.neg_bar.data_range, [-30, -4])
    assert_equal(overlay.pos_bar.reverse_lut, True)
    assert_equal(overlay.neg_bar.reverse_lut, False)
    overlay.remove()

    thresh = 4
    sig1[sig1 < thresh] = 0
    sig2[sig2 < thresh] = 0

    conjunct = np.min(np.vstack((sig1, sig2)), axis=0)
    brain.add_overlay(sig1, 4, 30, name="sig1")
    brain.overlays["sig1"].pos_bar.lut_mode = "Reds"
    brain.overlays["sig1"].pos_bar.visible = False

    brain.add_overlay(sig2, 4, 30, name="sig2")
    brain.overlays["sig2"].pos_bar.lut_mode = "Blues"
    brain.overlays["sig2"].pos_bar.visible = False

    brain.add_overlay(conjunct, 4, 30, name="conjunct")
    brain.overlays["conjunct"].pos_bar.lut_mode = "Purples"
    brain.overlays["conjunct"].pos_bar.visible = False

    brain.set_surf('white')

    brain.close()
Exemplo n.º 36
0
import os.path as op
import numpy as np
from surfer import io


########################## TJ - SJ #########################"
brain = Brain("fsaverage", "lh", "pial", config_opts={"cortex":"low_contrast","background":"black"})
sig1 = np.nan_to_num(io.read_scalar_data("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/fMRI/GROUPlvl_TJ-SJ_lh.mgz"))
sig2 = np.nan_to_num(io.read_scalar_data('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/fMRI/GROUPlvl_SJ-TJ_lh.mgz'))

thresh = 1
sig1[sig1 < thresh] = 0
sig2[sig2 < thresh] = 0
conjunct = np.min(np.vstack((sig1, sig2)), axis=0)
brain.add_overlay(sig1, 1, 8, name="sig1")
brain.overlays["sig1"].pos_bar.lut_mode = "Reds"
brain.overlays["sig1"].pos_bar.visible = False
brain.add_overlay(sig2, 1, 8, name="sig2")
brain.overlays["sig2"].pos_bar.lut_mode = "Blues"
brain.overlays["sig2"].pos_bar.visible = False

################### CONJ[TJ-CTRL SJ- CTRL] #####################
################## WHITE #######################################
###################### LH #######################
brain = Brain("fsaverage", "lh", "white", config_opts={"cortex":"low_contrast","background":"black"})
overlay_file = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/fMRI/GROUPlvl_CONJTASK_lh_projfrac05.mgz"
brain.add_overlay(overlay_file, min=1, max=10, sign="pos")
mayavi.mlab.view(azimuth=-33, elevation=None, distance=None, focalpoint=None,
     roll=None, reset_roll=True, figure=None)
mayavi.mlab.savefig("/neurospin/unicog/protocols/IRMf/MentalTravel_Martin_2014/BAPTISTE_FOLDER/PICTURES/MOD40/GROUPlvl_CONJTASK_lh_projfrac05_face1.png", size=None, figure=None, magnification='auto')
Exemplo n.º 37
0
"""Bring up the visualization"""
brain = Brain("fsaverage", "split", "inflated",
              views=['lat', 'med'], background="white")

"""Project the volume file and return as an array"""
mri_file = "example_data/resting_corr.nii.gz"
reg_file = os.path.join(os.environ["FREESURFER_HOME"],
                        "average/mni152.register.dat")
surf_data_lh = project_volume_data(mri_file, "lh", reg_file)
surf_data_rh = project_volume_data(mri_file, "rh", reg_file)

"""
You can pass this array to the add_overlay method for a typical activation
overlay (with thresholding, etc.).
"""
brain.add_overlay(surf_data_lh, min=.3, max=.7, name="ang_corr_lh", hemi='lh')
brain.add_overlay(surf_data_rh, min=.3, max=.7, name="ang_corr_rh", hemi='rh')

"""
You can also pass it to add_data for more control
over the visualization. Here we'll plot the whole
range of correlations
"""
for overlay in brain.overlays_dict["ang_corr_lh"]:
    overlay.remove()
for overlay in brain.overlays_dict["ang_corr_rh"]:
    overlay.remove()

"""
We want to use an appropriate color map for these data: a divergent map that
is centered on 0, which is a meaningful transition-point as it marks the change
Exemplo n.º 38
0
def surface_roi_contour(subjects_dir, subject_id, hemi, surf, alpha, coords,
                        region):
    """
    Bring up the visualization.
    Add the contour of region.
    """
    brain = Brain(subjects_dir=subjects_dir,
                  subject_id=subject_id,
                  hemi=hemi,
                  surf=surf,
                  alpha=alpha)

    if hemi == 'both':
        brain.add_contour_overlay(region[0],
                                  min=region[0].min(),
                                  max=region[0].max(),
                                  n_contours=2,
                                  line_width=1.5,
                                  colormap="YlOrRd_r",
                                  hemi='lh',
                                  remove_existing=True,
                                  colorbar=False)
        brain.add_overlay(coords[0],
                          min=coords[0][coords[0] > 0].min(),
                          max=coords[0].max(),
                          sign='pos',
                          hemi='lh',
                          name='lh')
        brain.add_contour_overlay(region[1],
                                  min=region[1].min(),
                                  max=region[1].max(),
                                  n_contours=2,
                                  line_width=1.5,
                                  colormap="YlOrRd_r",
                                  hemi='rh',
                                  remove_existing=False,
                                  colorbar=False)
        brain.add_overlay(coords[1],
                          min=coords[1][coords[1] > 0].min(),
                          max=coords[1].max(),
                          sign='pos',
                          hemi='rh',
                          name='rh')
    elif hemi == 'lh':
        brain.add_contour_overlay(region[0],
                                  min=region[0].min(),
                                  max=region[0].max(),
                                  n_contours=2,
                                  line_width=1.5,
                                  colormap="YlOrRd_r",
                                  hemi='lh',
                                  remove_existing=True,
                                  colorbar=False)
        brain.add_overlay(coords[0],
                          min=coords[0][coords[0] > 0].min(),
                          max=coords[0].max(),
                          sign='pos',
                          hemi='lh',
                          name='lh')
    else:
        brain.add_contour_overlay(region[1],
                                  min=region[1].min(),
                                  max=region[1].max(),
                                  n_contours=2,
                                  line_width=1.5,
                                  colormap="YlOrRd_r",
                                  hemi='rh',
                                  remove_existing=True,
                                  colorbar=False)
        brain.add_overlay(coords[1],
                          min=coords[1][coords[1] > 0].min(),
                          max=coords[1].max(),
                          sign='pos',
                          hemi='rh',
                          name='rh')

    mlab.show()
Exemplo n.º 39
0
data = nib.load(mri_file)
minval = 0.2
maxval = np.max(data.get_data()) 

surf_data_lh = project_volume_data(mri_file,"lh",reg_file)
surf_data_rh = project_volume_data(mri_file,"rh",reg_file)

qmri_file = '/Users/jamalw/Desktop/PNI/music_event_structures/qstats_map.nii.gz'

qdata_lh = project_volume_data(qmri_file,"lh",reg_file)
surf_data_lh[np.logical_or(qdata_lh>0.005,surf_data_lh<0)] = 0

qdata_rh = project_volume_data(qmri_file,"rh",reg_file)
surf_data_rh[np.logical_or(qdata_rh>0.005, surf_data_rh<0)] = 0

brain.add_overlay(surf_data_lh,min=minval,max=maxval,name="thirty_sec_lh", hemi='lh',sign="pos")
brain.add_overlay(surf_data_rh,min=minval,max=maxval,name="thirty_sec_rh", hemi='rh',sign="pos")
#
#for overlay in brain.overlays_dict["thirty_sec_lh"]:
#    overlay.remove()
#for overlay in brain.overlays_dict["thirty_sec_rh"]:
#    overlay.remove()
#
#brain.add_data(surf_data_lh, minval,maxval, colormap="CMRmap", alpha=1,
#               hemi='lh')
#brain.add_data(surf_data_rh, minval,maxval, colormap="CMRmap", alpha=1,
#               hemi='rh')
#
brain.save_image("zstats_human_bounds_srm_k30.png")
#
mlab.show()
Exemplo n.º 40
0
        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)  
            
            # 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() 
Exemplo n.º 41
0
        mdmr_dir = path.join(
            basedir, "%s_rois_random_k3200/age+gender_15k.mdmr" % sample)
        """Bring up the visualization"""
        brain = Brain("fsaverage_copy",
                      "rh",
                      "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_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(
Exemplo n.º 42
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()
Exemplo n.º 43
0
config_opts = dict([(k, v) for k, v in argdict.items() if k in confkeys and v])

# Load  up the figure and underlying brain object
b = Brain(args.subject_id, args.hemi, args.surf, args.curv,
          args.title, config_opts=config_opts)

# Maybe load some morphometry
if args.morphometry is not None:
    b.add_morphometry(args.morphometry)

# Maybe load an overlay
if args.overlay is not None:
    if args.range is not None:
        args.min, args.max = args.range

    b.add_overlay(args.overlay, args.min, args.max, args.sign)

# Maybe load an annot
if args.annotation is not None:
    if not args.borders:
        args.borders = any([args.overlay, args.morphometry])
    b.add_annotation(args.annotation, args.borders)

# Maybe load a label
if args.label is not None:
    if not args.borders:
        args.borders = any([args.overlay, args.morphometry])
    b.add_label(args.label, args.borders)

# Also point brain at the Brain() object
brain = b
Exemplo n.º 44
0
def load_and_show_npy(subject, npy_file, hemi):
    x = np.load(npy_file)
    brain = Brain(subject, hemi, "pial", curv=False, offscreen=False)
    brain.toggle_toolbars(True)
    brain.add_overlay(x[:, 0], hemi=hemi)
Exemplo n.º 45
0
def load_and_show_npy(subject, npy_file, hemi):
    x = np.load(npy_file)
    brain = Brain(subject, hemi, "pial", curv=False, offscreen=False)
    brain.toggle_toolbars(True)
    brain.add_overlay(x[:, 0], hemi=hemi)
Exemplo n.º 46
0
        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)

            # 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()
Exemplo n.º 47
0
brain = Brain("fsaverage", hemi, surf,
              views=views, background="white")

"""Project the volume file and return as an array"""
mri_file = "example_data/resting_corr.nii.gz"
reg_file = os.path.join(os.environ["FREESURFER_HOME"],
                        "average/mni152.register.dat")
surf_data_lh = project_volume_data(mri_file, "lh", reg_file)
surf_data_rh = project_volume_data(mri_file, "rh", reg_file)

"""
You can pass this array to the add_overlay method for a typical activation
overlay (with thresholding, etc.).
"""
brain.add_overlay(surf_data_lh, min=.3, max=.7, name="ang_corr_lh", hemi='lh')
brain.add_overlay(surf_data_rh, min=.3, max=.7, name="ang_corr_rh", hemi='rh')

"""
You can also pass it to add_data for more control
over the visualization. Here we'll plot the whole
range of correlations
"""
for overlay in brain.overlays_dict["ang_corr_lh"]:
    overlay.remove()
for overlay in brain.overlays_dict["ang_corr_rh"]:
    overlay.remove()

"""
We want to use an appropriate color map for these data: a divergent map that
is centered on 0, which is a meaningful transition-point as it marks the change
from surfer import Brain, io

"""Bring up the visualization"""
brain = Brain("fsaverage", "split", "inflated", views=["lat", "med"], 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_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=0.3, max=0.7, name="ang_corr_lh", hemi="lh")
brain.add_overlay(surf_data_rh, min=0.3, max=0.7, name="ang_corr_rh", hemi="rh")

"""
You can also pass it to add_data for more control
over the visualzation. Here we'll plot the whole
range of correlations
"""
for overlay in brain.overlays_dict["ang_corr_lh"]:
    overlay.remove()
for overlay in brain.overlays_dict["ang_corr_rh"]:
    overlay.remove()
brain.add_data(surf_data_lh, -0.7, 0.7, colormap="jet", alpha=0.7, hemi="lh")
brain.add_data(surf_data_rh, -0.7, 0.7, colormap="jet", alpha=0.7, hemi="rh")

"""
Exemplo n.º 49
0
orig_file = path.join(mdmr_dir, "clust_logp_%s.nii.gz" % factor)

"""Load the output data and get maximum value"""
img = nib.load(orig_file)
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 some images
Exemplo n.º 50
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')
"""
Exemplo n.º 51
0
    
        mdmr_dir = path.join(basedir, "%s_rois_random_k3200/age+gender_15k.mdmr" % sample)
    
        """Bring up the visualization"""
        brain = Brain("fsaverage_copy", "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)), 
#%gui qt
%gui wx
from surfer import Brain
import mayavi
from numpy import array

import os.path as op
import numpy as np
from surfer import io

################### TJ-CTRL #####################
###################### LH #######################
brain = Brain("fsaverage", "lh", "inflated", config_opts={"cortex":"low_contrast","background":"black"})
overlay_file = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/fMRI/GROUPlvl_TJ_CTRL_tT_extT_lh_projfrac05.mgz"
brain.add_overlay(overlay_file, min=3.11, max=10, sign="pos")
mayavi.mlab.view(azimuth=315, elevation=None, distance=None, focalpoint=None,
     roll=None, reset_roll=True, figure=None)
mayavi.mlab.savefig("/neurospin/unicog/protocols/IRMf/BENOIT_MT/BAPTISTE_FOLDER/PICTURES/MOD30-2/GROUPlvl_TJ_CTRL_tT_extT_lh_projfrac05_face1.png", size=None, figure=None, magnification='auto')
mayavi.mlab.view(azimuth=135, elevation=None, distance=None, focalpoint=None,
     roll=None, reset_roll=True, figure=None)
mayavi.mlab.savefig("/neurospin/unicog/protocols/IRMf/BENOIT_MT/BAPTISTE_FOLDER/PICTURES/MOD30-2/GROUPlvl_TJ_CTRL_tT_extT_lh_projfrac05_face2.png", size=None, figure=None, magnification='auto')
mayavi.mlab.view(azimuth=225, elevation=None, distance=None, focalpoint=None,
     roll=None, reset_roll=True, figure=None)
mayavi.mlab.savefig("/neurospin/unicog/protocols/IRMf/BENOIT_MT/BAPTISTE_FOLDER/PICTURES/MOD30-2/GROUPlvl_TJ_CTRL_tT_extT_lh_projfrac05_face3.png", size=None, figure=None, magnification='auto')
###################### RH #######################
brain = Brain("fsaverage", "rh", "inflated", config_opts={"cortex":"low_contrast","background":"black"})
overlay_file = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/fMRI/GROUPlvl_TJ_CTRL_tT_extT_rh_projfrac05.mgz"
brain.add_overlay(overlay_file, min=3.11, max=10, sign="pos")
mayavi.mlab.view(azimuth=225, elevation=None, distance=None, focalpoint=None,
     roll=None, reset_roll=True, figure=None)