Esempio n. 1
0
 def dfs(filename):
     s1 = Surface()
     s1.vertices = coords
     s1.faces = faces
     s1.attributes = attributes
     # NFV.attributes = attributes
     dfsio.writedfs(filename, s1)
Esempio n. 2
0
def save2surfgord(lsurf,
                  rsurf,
                  out_dir,
                  surf_name,
                  bfp_path='.',
                  save_png=True):
    # if label is zero, black out surface, attribute should be nan
    num_vert = lsurf.vertices.shape[0]
    lab = spio.loadmat(
        os.path.join(bfp_path, 'supp_data/USCBrain_grayordinate_labels.mat'))
    labs = lab['labels'].squeeze()
    labs = sp.float64(labs)
    lsurf.attributes[labs[:num_vert] == 0] = sp.nan
    rsurf.attributes[labs[num_vert:2 * num_vert] == 0] = sp.nan
    lsurf.vColor[sp.isnan(lsurf.attributes), :] = 0
    rsurf.vColor[sp.isnan(lsurf.attributes), :] = 0

    writedfs(out_dir + '/Right_' + surf_name + '.dfs', rsurf)
    writedfs(out_dir + '/Left_' + surf_name + '.dfs', lsurf)

    if VTK_INSTALLED == 0:
        print('VTK is not installed, screenshots will not be saved.')
        save_png = False

    if save_png == True:
        # Visualize left hemisphere
        view_patch_vtk(lsurf,
                       azimuth=100,
                       elevation=180,
                       roll=90,
                       outfile=out_dir + '/LeftLateral_' + surf_name + '.png',
                       show=0)
        view_patch_vtk(lsurf,
                       azimuth=-100,
                       elevation=180,
                       roll=-90,
                       outfile=out_dir + '/LeftMedial_' + surf_name + '.png',
                       show=0)
        # Visualize right hemisphere
        view_patch_vtk(rsurf,
                       azimuth=-100,
                       elevation=180,
                       roll=-90,
                       outfile=out_dir + '/RightLateral_' + surf_name + '.png',
                       show=0)
        view_patch_vtk(rsurf,
                       azimuth=100,
                       elevation=180,
                       roll=90,
                       outfile=out_dir + '/RightMedial_' + surf_name + '.png',
                       show=0)
Esempio n. 3
0
    def save(self, outdir, outprefix, atlas_filename):
        sys.stdout.write('Saving output files...\n')
        self.adjust_for_multi_comparisons()

        s1 = dfsio.readdfs(atlas_filename)

        s1.attributes = self.pvalues
        # print s1.attributes

        if len(s1.attributes) == s1.vertices.shape[0]:
            # Also write color to the field
            s1.vColor = colormaps.Colormap.get_rgb_color_array('pvalue', s1.attributes)
            dfsio.writedfs(os.path.join(outdir, outprefix + '_atlas_pvalues.dfs'), s1)
            if len(self.pvalues_adjusted) > 0:
                s1.attributes = self.pvalues_adjusted
                # Also write color to the field
                s1.vColor = colormaps.Colormap.get_rgb_color_array('pvalue', s1.attributes)
                dfsio.writedfs(os.path.join(outdir, outprefix + '_atlas_pvalues_adjusted.dfs'), s1)
        else:
            sys.stdout.write('Error: Dimension mismatch between the p-values and the number of vertices. '
                             'Quitting without saving.\n')

        if len(self.corrvalues) > 0:
            s1.attributes = self.corrvalues
            s1.vColor = colormaps.Colormap.get_rgb_color_array('corr', s1.attributes)
            dfsio.writedfs(os.path.join(outdir, outprefix + '_corr.dfs'), s1)
            self.corrvalues[np.abs(self.pvalues_adjusted) > 0.05] = 0
            s1.attributes = self.corrvalues
            # Also write color to the field
            s1.vColor = colormaps.Colormap.get_rgb_color_array('corr', s1.attributes)
            dfsio.writedfs(os.path.join(outdir, outprefix + '_corr_adjusted.dfs'), s1)
        sys.stdout.write('Done.\n')
Esempio n. 4
0
def image_to_shape(imagefile, shapefile, outputshapefile, resample):
    NimgDataio.validatetype(imagefile)
    NimgDataio.validatetype(shapefile)

    sys.stdout.write('Reading Image file ' + imagefile + '...')
    img = nii_io.readnii(imagefile)
    sys.stdout.write('Done.\n')

    sys.stdout.write('Reading Shape file ' + shapefile + '...')
    shape = NimgDataio.read_surface(shapefile)
    sys.stdout.write('Done.\n')

    # Scale shape coordinates to image according to pixdim
    pixdim = np.asarray(img.get_header().get_zooms())
    vox_indices = np.rint(shape.vertices / pixdim)
    vox_indices = vox_indices.astype(int)
    imgdim = img.get_header().get_data_shape()
    validate_shape_dimensions(vox_indices, imgdim)

    img_data = img.get_data()
    img_data_ravel = np.ravel(img_data)

    sys.stdout.write('Resampling image values to shape...')
    # Iterate over all shape coordinates (voxel indices) to find the resampled value
    if resample == 'nearest':  # Just use the voxel value
        idx = [np.ravel_multi_index(i, imgdim) for i in vox_indices]
        shape.attributes = img_data_ravel[idx]

    if resample == 'mean':
        # For each voxel index find the voxel neighborhood
        Nbr_list = np.zeros((len(shape.attributes), 18), dtype=np.int)
        for i, v_idx in enumerate(vox_indices):
            Nbr_list[i, :] = get_vox_neighborhood_ravel_index(
                v_idx[0], v_idx[1], v_idx[2], imgdim)
            shape.attributes[i] = np.mean(img_data_ravel[Nbr_list[i, :]])

    if resample == 'max':
        # For each voxel index find the voxel neighborhood
        Nbr_list = np.zeros((len(shape.attributes), 18), dtype=np.int)
        for i, v_idx in enumerate(vox_indices):
            Nbr_list[i, :] = get_vox_neighborhood_ravel_index(
                v_idx[0], v_idx[1], v_idx[2], imgdim)
            shape.attributes[i] = np.max(img_data_ravel[Nbr_list[i, :]])

    if outputshapefile:
        dfsio.writedfs(outputshapefile, shape)
    else:
        dfsio.writedfs(shapefile, shape)
    sys.stdout.write('Done.\n')
Esempio n. 5
0
def sub(file1, file2, fileout):
    s1 = dfsio.readdfs(file1)
    s2 = dfsio.readdfs(file2)
    sout = s1
    if not s1.attributes.any() and not s2.attributes.any():
        raise excepts.AttributeMissingError(
            'Missing attributes in {0:s} and/or {1:s}'.format(
                file1,
                file2))  # TODO: Change this to a custom exception in future
    if len(s1.attributes) != len(s2.attributes):
        raise excepts.AttributeLengthError(
            'Attribute lengths of {0:s} and {1:s} do not match.\n'.format(
                file1, file2))
    sout.attributes = s1.attributes - s2.attributes
    dfsio.writedfs(fileout, sout)
Esempio n. 6
0
    def write_attribute_to_surface(insurface, attribute_file, outsurface):
        s1 = NimgDataio.read_surface(insurface)
        filext = splitext(attribute_file)[1]
        attributes = []
        if filext == '.txt':
            attributes = np.loadtxt(attribute_file)
        elif filext == '.mat':
            temp = loadmat(attribute_file)
            attributes = temp[temp.keys()[0]]  # Just read the first variable in the .mat file
        else:
            raise ValueError('Error: Invalid attribute file' + attribute_file +
                             '. Attribute file should have a .mat or a .txt format.\n')

        if s1.vertices.shape[0] != attributes.shape[1]:
            raise excepts.AttributeLengthError('Error: Attribute lengths of data in {0:s} and the surface {1:s} do not match.\n'.format(attribute_file, insurface))

        s1.attributes = attributes
        dfsio.writedfs(outsurface, s1)
Esempio n. 7
0
    def save(self, outdir, outprefix, atlas_filename):
        sys.stdout.write('Saving output files...\n')
        self.statsresult.adjust_for_multi_comparisons()

        s1 = dfsio.readdfs(atlas_filename)

        s1.attributes = self.statsresult.pvalues
        # print s1.attributes

        if len(s1.attributes) == s1.vertices.shape[0]:
            # Also write color to the field
            s1.vColor = colormaps.Colormap.get_rgb_color_array(
                'pvalue', s1.attributes)
            dfsio.writedfs(
                os.path.join(outdir, outprefix + '_atlas_pvalues.dfs'), s1)
            if len(self.statsresult.pvalues_adjusted) > 0:
                s1.attributes = self.statsresult.pvalues_adjusted
                # Also write color to the field
                s1.vColor = colormaps.Colormap.get_rgb_color_array(
                    'pvalue', s1.attributes)
                dfsio.writedfs(
                    os.path.join(outdir,
                                 outprefix + '_atlas_pvalues_adjusted.dfs'),
                    s1)
        else:
            sys.stdout.write(
                'Error: Dimension mismatch between the p-values and the number of vertices. '
                'Quitting without saving.\n')

        if len(self.statsresult.corrvalues) > 0:
            s1.attributes = self.statsresult.corrvalues
            s1.vColor = colormaps.Colormap.get_rgb_color_array(
                'corr', s1.attributes)
            dfsio.writedfs(os.path.join(outdir, outprefix + '_corr.dfs'), s1)
            self.statsresult.corrvalues[
                np.abs(self.statsresult.pvalues_adjusted) > 0.05] = 0
            s1.attributes = self.statsresult.corrvalues
            # Also write color to the field
            s1.vColor = colormaps.Colormap.get_rgb_color_array(
                'corr', s1.attributes)
            dfsio.writedfs(
                os.path.join(outdir, outprefix + '_corr_adjusted.dfs'), s1)
        sys.stdout.write('Done.\n')
Esempio n. 8
0

hemi = 'left'
fshemi = 'lh'
''' BCI to FS processed BCI '''
bci_bsti = readdfs('/home/ajoshi/BrainSuite19b/svreg/BCI-DNI\
_brain_atlas/BCI-DNI_brain.' + hemi + '.mid.cortex.dfs')
bci_bst = readdfs('/home/ajoshi/BrainSuite19b/svreg/BCI-DNI\
_brain_atlas/BCI-DNI_brain.' + hemi + '.inner.cortex.dfs')
bci_bst.labels = bci_bsti.labels
bci_bst.vertices[:, 0] -= 96 * 0.8
bci_bst.vertices[:, 1] -= 192 * 0.546875
bci_bst.vertices[:, 2] -= 192 * 0.546875
bci_fs.vertices, bci_fs.faces = fsio.read_geometry('/big_disk/ajoshi/data/BCI_\
DNI_Atlas/surf/' + fshemi + '.white')

fslabels, _, _ = fsio.read_annot(
    '/big_disk/ajoshi/freesurfer/subjects/BCI_DNI_Atlas/label/' + fshemi +
    '.economo.annot')
bci_fs.labels = fslabels

bci_bst = interpolate_labels(bci_fs, bci_bst)
bci_bsti.labels = bci_bst.labels
bci_bsti = patch_color_labels(bci_bsti)
view_patch_vtk(bci_bsti)

bci_bsti = smooth_patch(bci_bsti, iterations=10000)
view_patch_vtk(bci_bsti)

writedfs('BCI_DNI_economo_' + hemi + '.dfs', bci_bsti)
bci_freq = reduce3_to_bci_rh(bci_bst.attributes)

bci_bst = readdfs(
    '/big_disk/ajoshi/data/BCI-DNI_brain_atlas/BCI-DNI_brain.right.\
mid.cortex.dfs')
bci_bst_sm = readdfs('/big_disk/ajoshi/data/BCI-DNI_brain_atlas/BCI-DNI_brain.\
right.mid.cortex_smooth10.dfs')
bci_bst.vertices = bci_bst_sm.vertices

bci_bst.labels = bci_labs
bci_bst.attributes = bci_freq

bci_bst = patch_color_labels(bci_bst, cmap='Paired')
view_patch_vtk(bci_bst, show=1)
writedfs(
    '/big_disk/ajoshi/data/BCI-DNI_brain_atlas/BCI-DNI_brain.right.\
mid.cortex_refined_labs_uncorr.dfs', bci_bst)

bci_bst = patch_color_labels(bci_bst, freq=bci_bst.attributes, cmap='Paired')
# bci_bst = smooth_patch(bci_bst, iterations=90, relaxation=10.8)
view_patch_vtk(bci_bst, show=1)
writedfs(
    '/big_disk/ajoshi/data/BCI-DNI_brain_atlas/BCI-DNI_brain.right.\
mid.cortex_refined_labs_mod_freq_uncorr.dfs', bci_bst)

surfname = '/big_disk/ajoshi/data/BCI-DNI_brain_atlas/BCI-DNI_brain.right.\
mid.cortex_refined_labs_uncorr.dfs'

sub_out = '/big_disk/ajoshi/data/BCI-DNI_brain_atlas/BCI-DNI_brain.right.\
mid.cortex_refined_labs_out.dfs'
Esempio n. 10
0
USCBrainbaseLatest = '/ImagePTE1/ajoshi/code_farm/hybridatlas/USCBrain_9_8'

eng = meng.start_matlab()
eng.addpath(eng.genpath('/ImagePTE1/ajoshi/code_farm/svreg/MEX_Files'))
eng.addpath(eng.genpath('/ImagePTE1/ajoshi/code_farm/svreg/3rdParty'))
eng.addpath(eng.genpath('/ImagePTE1/ajoshi/code_farm/svreg/src'))
xmlf = USCBrainbaseLatest + '/brainsuite_labeldescription.xml'

for hemi in {'left', 'right'}:

    mid = USCBrainbaseLatest + '/BCI-DNI_brain.' + hemi + '.mid.cortex.dfs'
    eng.recolor_by_label(mid, '', xmlf, nargout=0)

    s = readdfs(mid)
    sin = readdfs(USCBrainbaseLatest + '/BCI-DNI_brain.' + hemi +
                  '.inner.cortex.dfs')
    spial = readdfs(USCBrainbaseLatest + '/BCI-DNI_brain.' + hemi +
                    '.pial.cortex.dfs')

    sin.vColor = s.vColor
    sin.labels = s.labels
    writedfs(
        USCBrainbaseLatest + '/BCI-DNI_brain.' + hemi + '.inner.cortex.dfs',
        sin)

    spial.vColor = s.vColor
    spial.labels = s.labels
    writedfs(
        USCBrainbaseLatest + '/BCI-DNI_brain.' + hemi + '.pial.cortex.dfs',
        spial)
    vrest, _, _ = normalizeData(vrest)
    vrest, Rot = brainSync(X=vsub, Y=vrest)
    t = sp.sum(vrest*vsub, axis=0)
#    print('rho(%d)=%g' % (ind1, sp.mean(t)), end=' ')
    print 'rho(%d)=%g' % (ind1, sp.mean(t))

    rho_sub[ind1, :] = t
    
    
# %%
# Hypothesis test

rho_sub1 = sp.mean(rho_sub, axis=0)
pval = sp.mean(rho_sub1 > rho_null, axis=0)
r, corrPval,_,_ = multipletests(pvals=pval, alpha=0.05, method='fdr_bh')


sl = readdfs(os.path.join(BFPPATH, 'bci32kleft.dfs'))
sl.attributes = corrPval[:sl.vertices.shape[0]]
sl = patch_color_attrib(sl, clim=[0, 1])

sr = readdfs(os.path.join(BFPPATH, 'bci32kright.dfs'))
sr.attributes = corrPval[sl.vertices.shape[0]:2*sl.vertices.shape[0]]
sr = patch_color_attrib(sr, clim=[0, 1])

writedfs('right_pval_sn7915.dfs',sr);
writedfs('left_pval_sn7915.dfs',sl);

view_patch_vtk(sl, azimuth=90, elevation=180, roll=90, show=1)
view_patch_vtk(sl, azimuth=-90, elevation=180, roll=-90, show=1)
    bci = readdfs(BCIbase + '/BCI-DNI_brain.left.mid.cortex.dfs')

    error_indicator1 = check_uscbrain_bci(uscbrain.labels.flatten(),
                                          uscbrain_dict, bci.labels.flatten(),
                                          bci_dict)

    error_indicator2 = check_bci_uscbrain(uscbrain.labels.flatten(),
                                          uscbrain_dict, bci.labels.flatten(),
                                          bci_dict)

    error_surf.vertices = bci.vertices
    error_surf.faces = bci.faces
    error_surf.attributes = 255.0 * error_indicator1
    error_surf.labels = error_indicator1

    writedfs('error_left.dfs', error_surf)

    out_surf = surf_lab_match_bci_uscbrain(uscbrain, uscbrain_dict, bci,
                                           bci_dict, error_indicator1)

    writedfs(
        USCBrainbaseLatest +
        '/BCI-DNI_brain.left.mid.cortex_bci_consistent.dfs', out_surf)

    print('Tiny region overlaps: %d or %d ' %
          (np.sum(error_indicator1), np.sum(error_indicator2)))
    # Right hemisphere surface
    print('=====Checking Right Hemisphere Surface=====')

    uscbrain = readdfs(USCBrainbaseLatest +
                       '/BCI-DNI_brain.right.mid.cortex.dfs')
s = r
s.vColor = sp.zeros(s.vertices.shape)
label_vert, lab_count = sp.stats.mode(labs_all.T)
colr = get_cmap(nClusters + 1)
lab_count = sp.float32(lab_count.squeeze())
s.vColor = s.vColor + 1

for i in range(len(s.vertices)):
    #        print i, (lab_count[i]/sp.amax(lab_count)), colr(label_vert[0,i])[:3], (lab_count[i]/sp.amax(lab_count)), 0.55*sp.array(colr(label_vert[0,i])[:3])
    if label_vert[0, i] > 0:
        freq = ((lab_count[i] / sp.amax(lab_count)) -
                1.0 / nClusters) * (sp.float32(nClusters) / (nClusters - 1.0))
        s.vColor[i, ] = (1 -
                         freq) + freq * sp.array(colr(label_vert[0, i])[:3])

view_patch(s)
view_patch_vtk(s)
writedfs('outclustering_pc.dfs', s)
#    view_patch(r,r.labels)
#mesh = mlab.triangular_mesh(r.vertices[:,0], r.vertices[:,1], r.vertices[:,2], r.faces, representation='surface',
#                            opacity=1,scalars=np.float64(r.labels))
#    #mlab.pipeline.surface(mesh)
#mlab.gcf().scene.parallel_projection = True
#mlab.view(azimuth=0, elevation=-90)
#mlab.show()
#mlab.savefig(filename = 'dict_learning_1.png')
#mlab.view(azimuth=0, elevation=90)
#mlab.savefig(filename = 'dict_learning_2.png')
#mlab.close()
Esempio n. 14
0
view_patch_vtk(h)
''' native FS ref to native FS BCI'''
g_surf = nib.load('/data_disk/HCP5-fMRI-NLM/reference/100307/MNINon\
Linear/Native/100307.R.sphere.reg.native.surf.gii')
s.vertices = g_surf.darrays[0].data
s.faces = g_surf.darrays[1].data
s.labels = h.labels
''' map to bc sphere'''
bs.vertices, bs.faces = fsio.read_geometry(
    '/big_disk/ajoshi/fs_sub/BCI_DNI_Atlas/surf/rh.sphere.reg')
bs = interpolate_labels(s, bs)
bci.vertices, bci.faces = fsio.read_geometry(
    '/big_disk/ajoshi/fs_sub/BCI_DNI_Atlas/surf/rh.white')
bci.labels = bs.labels
writedfs('BCI_orig_rh.dfs', bci)

bci.vertices, bci.faces = fsio.read_geometry(
    '/big_disk/ajoshi/fs_sub/BCI_DNI_Atlas/surf/rh.inflated')
bci = patch_color_labels(bci)
view_patch_vtk(bci)

writedfs('BCI_pial_rh.dfs.', bci)

bci.vertices, bci.faces = fsio.read_geometry(
    '/big_disk/ajoshi/fs_sub/BCI_DNI_Atlas/surf/rh.white')
writedfs('BCI_white_rh.dfs.', bci)

bci.vertices[:, 0] += 96 * 0.8
bci.vertices[:, 1] += 192 * 0.546875
bci.vertices[:, 2] += 192 * 0.546875
Esempio n. 15
0
''' native FS ref to native FS BCI'''
g_surf = gread('/home/ajoshi/data/HCP_data/reference/100307/MNINonLinear/Nativ\
e/100307.R.sphere.reg.native.surf.gii')
s.vertices = g_surf.darrays[0].data
s.faces = g_surf.darrays[1].data
s.labels = h.labels

''' map to bc sphere'''
bs.vertices, bs.faces = fsio.read_geometry('/home/ajoshi/data/BCI_DNI_Atlas/su\
rf/rh.sphere.reg')
bs = interpolate_labels(s, bs)
bci.vertices, bci.faces = fsio.read_geometry('/home/ajoshi/data/BCI_DNI_A\
tlas/surf/rh.white')
bci.labels = bs.labels
writedfs('BCI_orig_rh.dfs', bci)


bci.vertices, bci.faces = fsio.read_geometry('/home/ajoshi/data/BCI_DNI_A\
tlas/surf/rh.inflated')
view_patch(bci, bci.labels)

writedfs('BCI_pial_rh.dfs.', bci)

bci.vertices, bci.faces = fsio.read_geometry('/home/ajoshi/data/BCI_DNI_Atla\
s/surf/rh.white')
writedfs('BCI_white_rh.dfs.', bci)


bci.vertices[:, 0] += 96*0.8
bci.vertices[:, 1] += 192*0.546875
Esempio n. 16
0
xx = np.arange(vol_lab.shape[0]) * xres
yy = np.arange(vol_lab.shape[1]) * yres
zz = np.arange(vol_lab.shape[2]) * zres

sl.labels = interpn((xx, yy, zz), vol_img, sl.vertices, method='nearest')
sr.labels = interpn((xx, yy, zz), vol_img, sr.vertices, method='nearest')

sl = smooth_patch(sl, iterations=3000, relaxation=.5)
sr = smooth_patch(sr, iterations=3000, relaxation=.5)

patch_color_labels(sl)
view_patch_vtk(sl)
patch_color_labels(sr)
view_patch_vtk(sr)
writedfs(outmidl, sl)
writedfs(outmidr, sr)

eng = matlab.engine.start_matlab()
eng.addpath(eng.genpath('/ImagePTE1/ajoshi/code_farm/svreg/src'))
eng.addpath(eng.genpath('/ImagePTE1/ajoshi/code_farm/svreg/3rdParty'))
eng.addpath(eng.genpath('/ImagePTE1/ajoshi/code_farm/svreg/MEX_Files'))

eng.mni152_to_bci(atlas_name, nargout=0)
eng.exit()

s = readdfs('BCI-' + atlas_name + '.left.mid.cortex.dfs')
s = smooth_patch(s, iterations=3000, relaxation=.5)
view_patch_vtk(s)
writedfs('BCI-' + atlas_name + '.left.mid.cortex.dfs', s)
def main(argv):
    try:
        opts, args = getopt.getopt(argv, "hf:a:", ["ifile=", "ofile="])
    except getopt.GetoptError:
        print('python freesurfer_label_USCBrain.py -f <freesurfer_sub>\
-a <USCBrain>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('python freesurfer_label_USCBrain.py -f \
<freesurfer_sub> -a <USCBrain>')
            sys.exit()
        elif opt in ("-f", "--ffile"):
            subbasename = arg
        elif opt in ("-a", "--afile"):
            USCBrainpath = arg
    print('FreeSurfer subid is :' + subbasename)
    print('USCBrain dir is :' + USCBrainpath)
    hemi = 'right'
    fshemi = 'rh'

    class s:
        pass

    class bci:
        pass

    for hi in range(2):
        if hi == 0:
            hemi = 'right'
            fshemi = 'rh'
        else:
            hemi = 'left'
            fshemi = 'lh'

        ''' USCBrain to FS processed BCI '''
        bci_bsti = readdfs(USCBrainpath +
                           '/BCI-DNI_brain.' + hemi + '.mid.cortex.dfs')
        bci_bst = readdfs(USCBrainpath + '/BCI-DNI_brain.' +
                          hemi + '.inner.cortex.dfs')
        bci_bst.labels = bci_bsti.labels
        bci_bst.vertices[:, 0] -= 96*0.8
        bci_bst.vertices[:, 1] -= 192*0.546875
        bci_bst.vertices[:, 2] -= 192*0.546875
        bci.vertices, bci.faces = fsio.read_geometry(fshemi + '.white')
        bci = interpolate_labels_colors(bci_bst, bci)

        ''' FS_BCI to FS BCI Sphere'''
        bci.vertices, bci.faces = fsio.read_geometry(fshemi + '.sphere.reg')

        ''' FS BCI Sphere to SUB FS Sphere'''
        s.vertices, s.faces = fsio.read_geometry(subbasename +
                                                 '/surf/' + fshemi +
                                                 '.sphere.reg')
        s = interpolate_labels_colors(bci, s)
        fslabels, _, _ = fsio.read_annot(subbasename +
                                         '/label/' + fshemi + '.aparc.annot')
        s.labels = s.labels * sp.int16(fslabels > 0)
        s.vColor[fslabels <= 0, :] = 0.5
        s.vertices, _ = fsio.read_geometry(subbasename + '/surf/' +
                                           fshemi + '.pial')
        so, _ = fsio.read_geometry(subbasename + '/surf/' + fshemi + '.white')
        s.vertices = (s.vertices + so)/2.0
        s.faces = s.faces[:, (0, 2, 1)]
        outfilename = subbasename + '/' + hemi + '.mid.cortex.fs.dfs'
        writedfs(outfilename, s)
        print('output file is : ' + outfilename)
bci_bst.vertices[:, 1] -= 192 * 0.546875
bci_bst.vertices[:, 2] -= 192 * 0.546875
bci.vertices, bci.faces = fsio.read_geometry(
    '/home/ajoshi/data/BCI_DNI_Atlas/surf/rh.white')
bci = interpolate_labels(bci_bst, bci)
''' FS_BCI to FS BCI Sphere'''
bci.vertices, bci.faces = fsio.read_geometry(
    '/home/ajoshi/data/BCI_DNI_Atlas/surf/rh.sphere.reg')
''' FS BCI Sphere to ref FS Sphere'''
g_surf = gread(
    '/big_disk/ajoshi/HCP_data/reference/100307/MNINonLinear/Native/100307.R.sphere.reg.native.surf.gii'
)
s.vertices = g_surf.darrays[0].data
s.faces = g_surf.darrays[1].data
s = interpolate_labels(bci, s)
''' ref BCI Sphere to FS very inflated '''
g_surf = gread(
    '/big_disk/ajoshi/HCP_data/reference/100307/MNINonLinear/Native/100307.R.very_inflated.native.surf.gii'
)
bci.vertices = g_surf.darrays[0].data
bci.faces = g_surf.darrays[1].data
bci.labels = s.labels
''' FS very inflated to reduce3 '''
dfs = readdfs(
    '/big_disk/ajoshi/HCP_data/reference/100307.aparc.a2009s.32k_fs.reduce3.very_smooth.right.dfs'
)
dfs = interpolate_labels(bci, dfs, skipzero=1)

view_patch(dfs, dfs.labels, colormap='prism')
writedfs('100307.reduce3.very_smooth.right.refined.dfs', dfs)
bci_freq[ind] = 1  #maybe

oldids = sp.floor(bci_bst.labels / 10)
ind = ((oldids == 150) | (oldids == 151))

bci_bst.labels[ind] = bci_labs[ind]

bci_freq1 = readdfs('/big_disk/ajoshi/coding_ground/hbci_atlas/BCI-DNI_brain_\
atlas_refined_4_11_2017/BCI-DNI_brain.left.mid.cortex.mod.dfs')

bci_bst.attributes = bci_freq1.attributes
bci_bst.attributes[ind] = bci_freq[ind]

bci_bst = patch_color_labels(bci_bst, cmap='Paired')
view_patch_vtk(bci_bst, show=1)
writedfs('../tmp/BCI-DNI_brain.left.\
mid.cortex_refined_labs_uncorr.dfs', bci_bst)

bci_bst = patch_color_labels(bci_bst, freq=bci_bst.attributes, cmap='Paired')
# bci_bst = smooth_patch(bci_bst, iterations=90, relaxation=10.8)
view_patch_vtk(bci_bst, show=1)
writedfs(
    '../tmp/BCI-DNI_brain.left.\
mid.cortex_refined_labs_mod_freq_uncorr.dfs', bci_bst)

surfname = '../tmp/BCI-DNI_brain.left.\
mid.cortex_refined_labs_uncorr.dfs'

sub_out = '../tmp/BCI-DNI_brain.left.\
mid.cortex_refined_labs_corr.dfs'

eng = meng.start_matlab()
    pass

class r:
    pass

''' HCP32k data'''
labs = nib.load('/home/ajoshi/data/Glasser_et_al_2016_HCP_MMP1.0_RVVG/HCP_PhaseTwo/Q1-Q6_RelatedParcellation210/MNINonLinear/fsaverage_LR32k/Q1-Q6_RelatedParcellation210.R.CorticalAreas_dil_Colors.32k_fs_LR.dlabel.nii')

cifti = etree.XML(labs.header.extensions[0].get_content())
idxs=np.array(cifti[0][2][0][0].text.split(' ')).astype(np.int)

labels = sp.squeeze(labs.get_data())
g_surf = nib.load('/home/ajoshi/data/Glasser_et_al_2016_HCP_MMP1.0_RVVG/HCP_PhaseTwo/Q1-Q6_RelatedParcellation210/MNINonLinear/fsaverage_LR32k/Q1-Q6_RelatedParcellation210.R.inflated_MSMAll_2_d41_WRN_DeDrift.32k_fs_LR.surf.gii')
s.vertices = g_surf.darrays[0].data; s.faces = g_surf.darrays[1].data
s.labels=sp.zeros(s.vertices.shape[0])
s.labels[idxs] = labels
view_patch(s, s.labels,colormap='Paired')


''' ref BCI Sphere to FS very inflated '''
g_surf = nib.load('/home/ajoshi/data/HCP_data/reference/100307/MNINonLinear/fsaverage_LR32k/100307.R.very_inflated.32k_fs_LR.surf.gii')
r.vertices = g_surf.darrays[0].data; r.faces = g_surf.darrays[1].data
r.labels=s.labels
''' FS very inflated to reduce3 '''
dfs = readdfs('/home/ajoshi/data/HCP_data/reference/100307.aparc.a2009s.32k_fs.reduce3.very_smooth.right.dfs')
dfs = interpolate_labels(r,dfs, skipzero=1)

view_patch(dfs,dfs.labels, colormap='Paired')
writedfs('100307.reduce3.Glasser.right.dfs', dfs)

_brain_atlas_refined/BCI-DNI_brain.right.inner.cortex.dfs')
bci_bst.labels = bci_bsti.labels
bci_bst.vertices[:, 0] -= 96 * 0.8
bci_bst.vertices[:, 1] -= 192 * 0.546875
bci_bst.vertices[:, 2] -= 192 * 0.546875
bci.vertices, bci.faces = fsio.read_geometry('/big_disk/ajoshi/data/BCI_\
DNI_Atlas/surf/rh.white')
bci = interpolate_labels(bci_bst, bci)
''' FS_BCI to FS BCI Sphere'''
bci.vertices, bci.faces = fsio.read_geometry('/big_disk/ajoshi/data/BCI_\
DNI_Atlas/surf/rh.sphere.reg')
''' FS BCI Sphere to ref FS Sphere'''
g_surf = gread('/big_disk/ajoshi/HCP_data/reference/100307/MNINon\
Linear/Native/100307.R.sphere.reg.native.surf.gii')
s.vertices = g_surf.darrays[0].data
s.faces = g_surf.darrays[1].data
s = interpolate_labels(bci, s)
''' ref BCI Sphere to FS very inflated '''
g_surf = gread('/big_disk/ajoshi/HCP_data/reference/100307/MNINon\
Linear/Native/100307.R.very_inflated.native.surf.gii')
bci.vertices = g_surf.darrays[0].data
bci.faces = g_surf.darrays[1].data
bci.labels = s.labels
''' FS very inflated to reduce3 '''
dfs = readdfs('/big_disk/ajoshi/HCP_data/reference/100307.aparc.a\
2009s.32k_fs.reduce3.very_smooth.right.dfs')
dfs = interpolate_labels(bci, dfs, skipzero=1)

# view_patch(dfs, dfs.labels, colormap='prism')
writedfs('BCI_refined_reduce3.very_smooth.right.dfs', dfs)
Esempio n. 22
0
g_surf = gread('/home/ajoshi/data/HCP_data/reference/100307/MNINonLinear/fsaverage_LR32k/100307.L.very_inflated.32k_fs_LR.surf.gii')
vert = g_surf.darrays[0].data
face = g_surf.darrays[1].data
hcp32k.vertices = vert; hcp32k.faces=face

a = s.vertices;
b = hcp32k.vertices

tree = cKDTree(a)

d, ind = tree.query(b)
hcp32k.labels=s.labels[ind]
view_patch(hcp32k,hcp32k.labels)

writedfs('lh.Yeo2011_17Networks_N1000.dfs',hcp32k)

#ind = sp.logical_or.reduce(sp.logical_and.reduce(a == b[:,None], axis=2))
#vert2=a[ind]

#g_surf = gread('/home/ajoshi/HCP_data/reference/100307/MNINonLinear/Native/100307.L.sphere.reg.native.surf.gii')
#vert = g_surf.darrays[0].data
#face = g_surf.darrays[1].data
#s.faces=

#hcp32k = gread('/home/ajoshi/HCP_data/reference/100307/MNINonLinear/fsaverage_LR32k/100307.L.sphere.32k_fs_LR.surf.gii')
#vert = hcp32k.darrays[0].data
#face = hcp32k.darrays[1].data
#hcp32k.vertices=vert; hcp32k.faces=face

    data2[data1 == rois1[ids]] = rois2[ids]
    data2[data1 == rois2[ids]] = rois1[ids]
    left_labs[sp.where(left_mid.labels == rois1[ids])] = rois2[ids]
    left_labs[sp.where(left_mid.labels == rois2[ids])] = rois1[ids]
    right_labs[sp.where(right_mid.labels == rois1[ids])] = rois2[ids]
    right_labs[sp.where(right_mid.labels == rois2[ids])] = rois1[ids]

vm = image.new_img_like(v_lab, data2)
vm.to_filename('/big_disk/ajoshi/coding_ground/svreg-matlab/\
BCI-DNI_brain_atlas_refined/BCI-DNI_brain.label.corr.nii.gz')

left_mid.labels = left_labs
right_mid.labels = right_labs

writedfs(
    '/big_disk/ajoshi/coding_ground/svreg-matlab/BCI-DNI_brain_atlas_\
refined/BCI-DNI_brain.left.mid.cortex.corr.dfs', left_mid)
writedfs(
    '/big_disk/ajoshi/coding_ground/svreg-matlab/BCI-DNI_brain_atlas_\
refined/BCI-DNI_brain.right.mid.cortex.corr.dfs', right_mid)

left_inner = readdfs('/big_disk/ajoshi/coding_ground/svreg-matlab/\
/BCI-DNI_brain_atlas_refined/BCI-DNI_brain.left.inner.cortex.dfs')
left_inner.labels = left_labs
writedfs(
    '/big_disk/ajoshi/coding_ground/svreg-matlab/BCI-DNI_brain_atlas_\
refined/BCI-DNI_brain.left.inner.cortex.corr.dfs', left_inner)

left_pial = readdfs('/big_disk/ajoshi/coding_ground/svreg-matlab/\
/BCI-DNI_brain_atlas_refined/BCI-DNI_brain.left.pial.cortex.dfs')
left_pial.labels = left_labs
Esempio n. 24
0
    outfile = 'BCI-DNI_Perirhinal' + '.' + hemi + '.mid.cortex.dfs'
    ''' BCI to FS processed BCI '''
    bci_bsti = readdfs(
        '/home/ajoshi/BrainSuite19b/svreg/BCI-DNI_brain_atlas/BCI-DNI_brain.' +
        hemi + '.inner.cortex.dfs')
    bci_bst_mid = readdfs(
        '/home/ajoshi/BrainSuite19b/svreg/BCI-DNI_brain_atlas/BCI-DNI_brain.' +
        hemi + '.mid.cortex.dfs')

    bci_bsti.vertices[:, 0] -= 96 * 0.8
    bci_bsti.vertices[:, 1] -= 192 * 0.546875
    bci_bsti.vertices[:, 2] -= 192 * 0.546875
    bci.vertices, bci.faces = fsio.read_geometry(
        '/big_disk/ajoshi/data/BCI_DNI_Atlas/surf/' + fshemi + '.white')
    bci.labels = np.zeros(bci.vertices.shape[0])
    for i in range(len(broadmann)):
        labind = fsio.read_label('/big_disk/ajoshi/data/BCI_DNI_Atlas/label/' +
                                 fshemi + '.' + broadmann[i] + '.label')
        bci.labels[labind] = i + 1

    bci = patch_color_labels(bci)
    view_patch_vtk(bci)

    bci_bsti = interpolate_labels(bci, bci_bsti)
    bci_bst_mid.labels = bci_bsti.labels
    bci_bst_mid = smooth_patch(bci_bst_mid, iterations=3000, relaxation=.5)
    bci_bst_labels = patch_color_labels(bci_bst_mid)
    view_patch_vtk(bci_bst_labels)
    writedfs(outfile, bci_bst_labels)
Esempio n. 25
0
brain = get_sphere([0, 0, 0], radius=.06000, res=150)
skull = get_sphere([0, 0, 0], radius=.12000, res=50)

# brain = readdfs(brain_name)
# brain=smooth_patch(brain,100)
# brain = reducepatch(brain,.9,0)
# brain=smooth_patch(brain,10)

# skull = readdfs(skull_name)
# skull = reducepatch(skull,.9,0)
brain = add_normals(brain)
# brain.normals=brain.vertices/5.0
skull = add_normals(skull)
# view_patch(brain)
# view_patch(skull)
writedfs('brain.dfs', brain)
writedfs('skull.dfs', skull)
print "# vertices in Brain: " + str(brain.vertices.shape[0])
print "# vertices in Skull: " + str(skull.vertices.shape[0])
m = mean_curvature(brain)
# m = smooth_surf_function(brain, m, 10, 100)
br = view_patch(brain, attrib=m, opacity=1, show=0)
view_patch(skull, opacity=.1, fig=br, show=1)
Tri = face_v_conn(brain)

Q = 1.0 + sp.zeros((brain.faces.shape[0], 1))
Q = (1.0 / 3.0) * Tri * Q
Q = Q[:, 0]
br_face_area = face_areas(brain)
Q = 1.0 + sp.zeros(brain.vertices.shape[0])
# Q=0.0*Q
g32k.faces = g32ktmp.get_arrays_from_intent('NIFTI_INTENT_TRIANGLE')[0].data
g32k.vColor = sp.ones(g32k.vertices.shape)

bci.vertices, bci.faces = fsio.read_geometry('/big_disk/ajoshi/data/BCI_\
DNI_Atlas/surf/rh.sphere.reg')
bci.labels = fsio.read_annot('/big_disk/ajoshi/data/BCI_DNI_Atlas/label/rh\
.BA.thresh.annot')[0]

g32k = interpolate_labels(fromsurf=bci, tosurf=g32k)
g32ktmp = gread('/big_disk/ajoshi/HCP_data/32k_ConteAtlas_v2/Conte69.R\
.very_inflated.32k_fs_LR.surf.gii')
g32k.vertices = g32ktmp.get_arrays_from_intent('NIFTI_INTENT_POINTSET')[0].data
g32k = patch_color_labels(g32k)
view_patch_vtk(g32k)

writedfs('Boradmann_32k_right.dfs', g32k)
''' Left Hemisphere '''

g32ktmp = gread('/big_disk/ajoshi/data/standard_mesh_atlases/resample\
_fsaverage/fs_LR-deformed_to-fsaverage.L.sphere.32k_fs_LR.surf.gii')
g32k.vertices = g32ktmp.get_arrays_from_intent('NIFTI_INTENT_POINTSET')[0].data
g32k.faces = g32ktmp.get_arrays_from_intent('NIFTI_INTENT_TRIANGLE')[0].data
g32k.vColor = sp.ones(g32k.vertices.shape)

bci.vertices, bci.faces = fsio.read_geometry('/big_disk/ajoshi/data/BCI_\
DNI_Atlas/surf/lh.sphere.reg')
bci.labels = fsio.read_annot('/big_disk/ajoshi/data/BCI_DNI_Atlas/label/lh\
.BA.thresh.annot')[0]

g32k = interpolate_labels(fromsurf=bci, tosurf=g32k)
g32ktmp = gread('/big_disk/ajoshi/HCP_data/32k_ConteAtlas_v2/Conte69.L\
Esempio n. 27
0
# -*- coding: utf-8 -*-
"""
Created on Fri May 12 17:35:03 2017

@author: ajoshi
"""

from dfsio import readdfs, writedfs

so = readdfs(
    '/big_disk/ajoshi/coding_ground/svreg/BCI-DNI_brain_atlas/BCI-DNI_brain.right.pial.cortex.dfs'
)
s = readdfs(
    '/big_disk/ajoshi/coding_ground/svreg/USCBrain/BCI-DNI_brain.right.pial.cortex.dfs'
)
s.vertices = so.vertices
writedfs(
    '/big_disk/ajoshi/coding_ground/svreg/USCBrain/BCI-DNI_brain.right.pial.cortex.corr.dfs',
    s)

so = readdfs(
    '/big_disk/ajoshi/coding_ground/svreg/BCI-DNI_brain_atlas/BCI-DNI_brain.left.pial.cortex.dfs'
)
s = readdfs(
    '/big_disk/ajoshi/coding_ground/svreg/USCBrain/BCI-DNI_brain.left.pial.cortex.dfs'
)
s.vertices = so.vertices
writedfs(
    '/big_disk/ajoshi/coding_ground/svreg/USCBrain/BCI-DNI_brain.left.pial.cortex.corr.dfs',
    s)
Esempio n. 28
0
vol_lab = image.load_img(outvol)
vol_lab = image.new_img_like(vol_lab, np.int16(vol_lab.get_fdata()))
vol_lab.to_filename(outvol)

vol_img = vol_lab.get_fdata()

xres = vol_lab.header['pixdim'][1]
yres = vol_lab.header['pixdim'][2]
zres = vol_lab.header['pixdim'][3]

sl = readdfs(lmid)
sr = readdfs(rmid)

xx = np.arange(vol_lab.shape[0]) * xres
yy = np.arange(vol_lab.shape[1]) * yres
zz = np.arange(vol_lab.shape[2]) * zres

sl.labels = interpn((xx, yy, zz), vol_img, sl.vertices, method='nearest')
sr.labels = interpn((xx, yy, zz), vol_img, sr.vertices, method='nearest')

sl = smooth_patch(sl, iterations=3000, relaxation=.5)
sr = smooth_patch(sr, iterations=3000, relaxation=.5)

patch_color_labels(sl)
view_patch_vtk(sl)
patch_color_labels(sr)
view_patch_vtk(sr)
writedfs(outmidl, sl)
writedfs(outmidr, sr)
               elevation=180,
               roll=90,
               outfile='before2_seg1to2_1.png')
view_patch_vtk(dfs_ref,
               azimuth=-90,
               elevation=180,
               roll=-90,
               outfile='before2_seg1to2_2.png')

_, Rot12 = rot_sub_data(ref=sub2seg2, sub=sub1seg1)

sub1seg1rot = sp.dot(sub1seg1, Rot12.T)

rho_after = sp.sum(sub1seg1rot * sub1seg2, axis=1) / sub2seg2.shape[1]
dfs_ref = patch_color_attrib(dfs_ref, rho_after, clim=[0, .7])
writedfs('temp.dfs', dfs_ref)
view_patch_vtk(dfs_ref,
               azimuth=90,
               elevation=180,
               roll=90,
               outfile='after2_seg1to2_1.png')
view_patch_vtk(dfs_ref,
               azimuth=-90,
               elevation=180,
               roll=-90,
               outfile='after2_seg1to2_2.png')
rho_direct22 = sp.sum(sub1seg2 * sub2seg2, axis=1) / sub2seg2.shape[1]
dfs_ref = patch_color_attrib(dfs_ref, rho_direct22, clim=[0, .7])

view_patch_vtk(dfs_ref,
               azimuth=90,
Esempio n. 30
0
    def save_surface(self, atlas_filename):

        s1 = dfsio.readdfs(atlas_filename)
        if self.mask_idx.any():
            pvalues = np.ones(s1.vertices.shape[0])
            pvalues[self.mask_idx] = self.statsresult.pvalues
            self.statsresult.pvalues = pvalues
            tvalues = np.zeros(s1.vertices.shape[0])
            tvalues[self.mask_idx] = self.statsresult.tvalues
            self.statsresult.tvalues = tvalues
        s1.attributes = self.statsresult.pvalues
        # print s1.attributes

        if len(s1.attributes) == s1.vertices.shape[0]:
            # Also write color to the field
            self.statsresult.pvalues = log10_transform(
                self.statsresult.pvalues)
            s1.vColor, pex, cmap = colormaps.Colormap.log_pvalues_to_rgb(
                self.statsresult.pvalues)
            s1.attributes = self.statsresult.pvalues
            dfsio.writedfs(
                os.path.join(self.outdir,
                             self.outprefix + '_atlas_log_pvalues.dfs'), s1)
            colormaps.Colormap.save_colorbar(file=os.path.join(
                self.outdir, self.outprefix + '_atlas_log_pvalues_cbar.pdf'),
                                             cmap=cmap,
                                             vmin=-1 * pex,
                                             vmax=pex,
                                             labeltxt='Unadjusted p-values')
            s1.attributes = self.statsresult.tvalues
            s1.vColor, tmin, tmax, cmap_tvalues = colormaps.Colormap.tvalues_to_rgb(
                self.statsresult.tvalues)
            dfsio.writedfs(
                os.path.join(self.outdir,
                             self.outprefix + '_atlas_tvalues_all.dfs'), s1)
            colormaps.Colormap.save_colorbar(file=os.path.join(
                self.outdir, self.outprefix + '_atlas_tvalues_all_cbar.pdf'),
                                             cmap=cmap_tvalues,
                                             vmin=tmin,
                                             vmax=tmax,
                                             labeltxt='t-values (all)')
            self.statsresult.tvalues[np.abs(self.statsresult.pvalues) <= -1 *
                                     np.log10(0.05)] = 0
            s1.vColor, tmin, tmax, cmap_tvalues = colormaps.Colormap.tvalues_to_rgb(
                self.statsresult.tvalues)
            s1.attributes = self.statsresult.tvalues
            dfsio.writedfs(
                os.path.join(self.outdir,
                             self.outprefix + '_atlas_tvalues.dfs'), s1)
            colormaps.Colormap.save_colorbar(file=os.path.join(
                self.outdir, self.outprefix + '_atlas_tvalues_cbar.pdf'),
                                             cmap=cmap_tvalues,
                                             vmin=tmin,
                                             vmax=tmax,
                                             labeltxt='t-values (unadjusted)')
            LUT = cmap_tvalues._lut[0:256, 0:3]
            colormaps.Colormap.exportBrainSuiteLUT(
                os.path.join(self.outdir,
                             self.outprefix + '_atlas_tvalues_cbar.lut'), LUT)

            with open(
                    os.path.join(
                        self.outdir,
                        self.outprefix + '_unadjusted_pvalue_range.txt'),
                    "wt") as text_file:
                text_file.write("Log P-value range: -{0:s} to +{1:s}\n".format(
                    str(pex), str(pex)))
                text_file.write("P-value range: {0:s} to +{1:s}\n".format(
                    str(-1 * 10**(-1 * pex)), str(10**(-1 * pex))))

            if len(self.statsresult.pvalues_adjusted) > 0:
                if self.mask_idx.any():
                    pvalues = np.ones(s1.vertices.shape[0])
                    pvalues[self.mask_idx] = self.statsresult.pvalues_adjusted
                    self.statsresult.pvalues_adjusted = pvalues

                s1.attributes = self.statsresult.pvalues_adjusted
                self.statsresult.pvalues_adjusted = log10_transform(
                    self.statsresult.pvalues_adjusted)
                s1.vColor, pex, cmap = colormaps.Colormap.log_pvalues_to_rgb(
                    self.statsresult.pvalues_adjusted)
                s1.attributes = self.statsresult.pvalues_adjusted
                dfsio.writedfs(
                    os.path.join(
                        self.outdir,
                        self.outprefix + '_atlas_log_pvalues_adjusted.dfs'),
                    s1)
                colormaps.Colormap.save_colorbar(file=os.path.join(
                    self.outdir,
                    self.outprefix + '_atlas_log_pvalues_adjusted_cbar.pdf'),
                                                 cmap=cmap,
                                                 vmin=-1 * pex,
                                                 vmax=pex,
                                                 labeltxt='Adjusted p-values')
                self.statsresult.tvalues[
                    np.abs(self.statsresult.pvalues_adjusted) < -1 *
                    np.log10(0.05)] = 0
                s1.vColor, tmin, tmax, cmap_tvalues = colormaps.Colormap.tvalues_to_rgb(
                    self.statsresult.tvalues)
                s1.attributes = self.statsresult.tvalues
                dfsio.writedfs(
                    os.path.join(
                        self.outdir,
                        self.outprefix + '_atlas_tvalues_adjusted.dfs'), s1)
                colormaps.Colormap.save_colorbar(
                    file=os.path.join(
                        self.outdir,
                        self.outprefix + '_atlas_tvalues_adjusted_cbar.pdf'),
                    cmap=cmap_tvalues,
                    vmin=tmin,
                    vmax=tmax,
                    labeltxt='t-values (adjusted)')
                LUT = cmap_tvalues._lut[0:256, 0:3]
                colormaps.Colormap.exportBrainSuiteLUT(
                    os.path.join(
                        self.outdir,
                        self.outprefix + '_atlas_tvalues_adjusted_cbar.lut'),
                    LUT)

                with open(
                        os.path.join(
                            self.outdir,
                            self.outprefix + '_adjusted_pvalue_range.txt'),
                        "wt") as text_file:
                    text_file.write(
                        "Log P-value range: -{0:s} to +{1:s}\n".format(
                            str(pex), str(abs(pex))))
                    text_file.write("P-value range: {0:s} to +{1:s}\n".format(
                        str(-1 * 10**(-1 * pex)), str(10**(-1 * pex))))
        else:
            sys.stdout.write(
                'Error: Dimension mismatch between the p-values and the number of vertices. '
                'Quitting without saving.\n')

        if len(self.statsresult.corrvalues) > 0:
            if self.mask_idx.any():
                corrvalues = np.zeros(s1.vertices.shape[0])
                corrvalues[self.mask_idx] = self.statsresult.corrvalues
                self.statsresult.corrvalues = corrvalues

            s1.attributes = self.statsresult.corrvalues
            s1.vColor, cex, cmap = colormaps.Colormap.correlation_to_rgb(
                self.statsresult.corrvalues)
            dfsio.writedfs(
                os.path.join(self.outdir, self.outprefix + '_corr.dfs'), s1)
            colormaps.Colormap.save_colorbar(
                file=os.path.join(self.outdir,
                                  self.outprefix + '_corr_cbar.pdf'),
                cmap=cmap,
                vmin=-1 * cex,
                vmax=cex,
                labeltxt='Correlations (unadjusted)')
            with open(
                    os.path.join(self.outdir,
                                 self.outprefix + '_corr_range.txt'),
                    "wt") as text_file:
                text_file.write(
                    "Correlation values range: -{0:s} to +{1:s}\n".format(
                        str(cex), str(cex)))

            # Also write color to the field
            self.statsresult.corrvalues[np.abs(
                self.statsresult.pvalues_adjusted) < -1 * np.log10(0.05)] = 0
            s1.attributes = self.statsresult.corrvalues
            s1.vColor, cex, cmap = colormaps.Colormap.correlation_to_rgb(
                self.statsresult.corrvalues)
            dfsio.writedfs(
                os.path.join(self.outdir,
                             self.outprefix + '_corr_adjusted.dfs'), s1)
            colormaps.Colormap.save_colorbar(
                file=os.path.join(self.outdir,
                                  self.outprefix + '_corr_adjusted_cbar.pdf'),
                cmap=cmap,
                vmin=-1 * cex,
                vmax=cex,
                labeltxt='Correlations (adjusted)')
            with open(
                    os.path.join(self.outdir,
                                 self.outprefix + '_adjusted_corr_range.txt'),
                    "wt") as text_file:
                text_file.write(
                    "Adjusted Correlation values range: {0:s} to +{1:s}\n".
                    format(str(cex), str(cex)))

        sys.stdout.write('Done.\n')
Esempio n. 31
0
view_patch_vtk(h)
''' native FS ref to native FS BCI'''
g_surf = nib.load('/data_disk/HCP5-fMRI-NLM/reference/100307/MNINon\
Linear/Native/100307.L.sphere.reg.native.surf.gii')
s.vertices = g_surf.darrays[0].data
s.faces = g_surf.darrays[1].data
s.labels = h.labels
''' map to bc sphere'''
bs.vertices, bs.faces = fsio.read_geometry(
    '/big_disk/ajoshi/fs_sub/BCI_DNI_Atlas/surf/lh.sphere.reg')
bs = interpolate_labels(s, bs)
bci.vertices, bci.faces = fsio.read_geometry(
    '/big_disk/ajoshi/fs_sub/BCI_DNI_Atlas/surf/lh.white')
bci.labels = bs.labels
writedfs('BCI_orig_lh.dfs', bci)

bci.vertices, bci.faces = fsio.read_geometry(
    '/big_disk/ajoshi/fs_sub/BCI_DNI_Atlas/surf/lh.inflated')
bci = patch_color_labels(bci)
view_patch_vtk(bci)

writedfs('BCI_pial_lh.dfs.', bci)

bci.vertices, bci.faces = fsio.read_geometry(
    '/big_disk/ajoshi/fs_sub/BCI_DNI_Atlas/surf/lh.white')
writedfs('BCI_white_lh.dfs.', bci)

bci.vertices[:, 0] += 96 * 0.8
bci.vertices[:, 1] += 192 * 0.546875
bci.vertices[:, 2] += 192 * 0.546875