def profile_meshing(profile_file, surf_mesh, save_data=True, base_name=None):

    profile_img = load_volume(profile_file)
    profile_data = profile_img.get_data()
    profile_len = profile_data.shape[3]
    hdr = profile_img.get_header()
    aff = profile_img.get_affine()

    in_coords = load_mesh_geometry(surf_mesh)['coords']
    in_faces = load_mesh_geometry(surf_mesh)['faces']

    try:
        cbstoolsjcc.initVM(initialheap='6000m', maxheap='6000m')
    except ValueError:
        pass

    mesher = cbstoolsjcc.LaminarProfileMeshing()

    mesher.setDimensions(profile_data.shape)
    zooms = [x.item() for x in hdr.get_zooms()]
    mesher.setResolutions(zooms[0], zooms[1], zooms[2])

    mesher.setProfileSurfaceImage(cbstoolsjcc.JArray('float')((profile_data.flatten('F')).astype(float)))
    mesher.setSurfacePoints(cbstoolsjcc.JArray('float')(in_coords.flatten().astype(float)))
    mesher.setSurfaceTriangles(cbstoolsjcc.JArray('int')(in_faces.flatten().astype(int)))

    mesher.execute()

    out_coords = np.zeros((in_coords.shape[0], in_coords.shape[1], profile_len))
    out_faces = np.zeros((in_faces.shape[0], in_faces.shape[1], profile_len))

    mesh_list = []
    for i in range(profile_len):
        current_mesh = {}
        current_mesh['coords'] = np.reshape(np.array(mesher.getSampledSurfacePoints(i),
                                            dtype=np.float32),in_coords.shape)
        current_mesh['faces'] =  np.reshape(np.array(mesher.getSampledSurfaceTriangles(i),
                                            dtype=np.float32),in_faces.shape)
        mesh_list.append(current_mesh)

    if save_data:
        if not base_name:
            if not isinstance(profile_file, basestring):
                base_name = os.getcwd()
                print "saving to %s"%base_name
            else:
                dir_name = os.path.dirname(intensity_img)
                base_name = os.path.basename(intensity_img)
                base_name = os.path.join(dir_name, base_name[:base_name.find('.')])

        for i in range(len(mesh_list)):
            save_mesh_geometry(base_name+'_%s.vtk'%str(i), mesh_list[i])


    return mesh_list
def surface_to_graph(mesh_fn, mask_fn, adj_fn):
    #mesh_fn='data/Structure/average/S900.L.pial_MSMAll.32k_fs_LR.surf.gii'
    #mask_fn='data/vlpfc_nodes.1D'
    #import template mesh. has fields mesh['coords'] for xyz coordinates
    # and mesh['faces'] for face indices
    mesh = io.load_mesh_geometry(mesh_fn)
    faces = mesh['faces']

    #load in mask of vertices being considered (BA44 and 45)
    mask = np.loadtxt(mask_fn, dtype=int)
    mask = mask - 1

    #Mask the faces
    masked_faces=mask_faces(mask, faces)
    #Create indices for masked vertices
    reindex = reindexing(masked_faces)
    masked_faces_ridx = np.array( [ map(lambda x : reindex[x], f) for f in masked_faces ], dtype=int)  
    #restrict mesh using the mask
    adj = mesh_to_graph(masked_faces_ridx)

    #convert to sparse matrix
    #sparse_adj = csr_matrix(adj)
#    scipy.misc.imsave('data/adjacency_matrix.png', adj, format='png')
    np.save(adj_fn, adj)
    return adj
if args.smoothing:
    fwhm = args.smoothing
else:
    fwhm = 0
if args.software:
    software=args.software
else:
    software="CIVET"

if args.subject_id:
    subject_id=args.subject_id
else:
    subject_id="fsid"

wm = io.load_mesh_geometry(str(args.white))
gm = io.load_mesh_geometry(args.gray)

n_surfs=args.n_surfs


wm_vertexareas = calculate_area(args.white, fwhm,software,surf="white", subject=subject_id)
pia_vertexareas = calculate_area(args.gray, fwhm,software,surf="pial", subject=subject_id)


def beta(alpha, aw, ap):
    """Compute euclidean distance fraction, beta, that will yield the desired
    volume fraction, alpha, given vertex areas in the white matter surface, aw,
    and on the pial surface, ap.

    A surface with `alpha` fraction of the cortical volume below it and
#generate a mid surface that is close to pia in sulci and white in gyri to avoid self intersections

import numpy as np
import subprocess
import io_mesh

surfdir='/data1/users/kwagstyl/bigbrain/NeuralNetworks/surfdir/'

hemis=['right', 'left']
for hemi in hemis:
#subprocess.call('depth_potential -depth_potential -alpha 0.05 mid_'+hemi+'_327680.obj depth_'+hemi+'.txt', shell=True)
    subprocess.call('depth_potential -mean_curvature -alpha 0.05 '+surfdir+'mid_'+hemi+'_327680.obj '+surfdir+'curvature_'+hemi+'.txt', shell=True)
    subprocess.call('depth_potential -smooth 1 '+surfdir+'curvature_'+hemi+'.txt '+surfdir+'mid_'+hemi+'_327680.obj '+surfdir+'smcurvature_'+hemi+'.txt', shell=True)
    #depth = np.loadtxt('depth_'+hemi+'.txt')
#normalise values between 0 and 1
    curv = np.loadtxt(''+surfdir+'smcurvature_'+hemi+'.txt')
    min_value=np.mean(curv)-2*np.std(curv)
    curv = (curv - min_value)
    max_value=np.mean(curv)+2*np.std(curv)
    curv = np.array([curv/max_value]).T
    np.clip(curv, 0,1,out=curv)
#load in surfaces
    g=io_mesh.load_mesh_geometry(''+surfdir+'gray_' + hemi + '_327680.obj')
    w=io_mesh.load_mesh_geometry(''+surfdir+'white_' + hemi + '_327680.obj')
    mid = g['coords']*(1-curv) + w['coords']*curv
    g['coords'] = mid
    io_mesh.save_mesh_geometry(''+surfdir+'weighted_mid_' + hemi + '_327680.obj',g)

def profile_meshing(profile_file, surf_mesh, save_data=True, base_name=None):

    profile_img = load_volume(profile_file)
    profile_data = profile_img.get_data()
    profile_len = profile_data.shape[3]
    hdr = profile_img.get_header()
    aff = profile_img.get_affine()

    in_coords = load_mesh_geometry(surf_mesh)['coords']
    in_faces = load_mesh_geometry(surf_mesh)['faces']

    try:
        cbstoolsjcc.initVM(initialheap='6000m', maxheap='6000m')
    except ValueError:
        pass

    mesher = cbstoolsjcc.LaminarProfileMeshing()

    mesher.setDimensions(profile_data.shape)
    zooms = [x.item() for x in hdr.get_zooms()]
    mesher.setResolutions(zooms[0], zooms[1], zooms[2])

    mesher.setProfileSurfaceImage(
        cbstoolsjcc.JArray('float')((profile_data.flatten('F')).astype(float)))
    mesher.setSurfacePoints(
        cbstoolsjcc.JArray('float')(in_coords.flatten().astype(float)))
    mesher.setSurfaceTriangles(
        cbstoolsjcc.JArray('int')(in_faces.flatten().astype(int)))

    mesher.execute()

    out_coords = np.zeros(
        (in_coords.shape[0], in_coords.shape[1], profile_len))
    out_faces = np.zeros((in_faces.shape[0], in_faces.shape[1], profile_len))

    mesh_list = []
    for i in range(profile_len):
        current_mesh = {}
        current_mesh['coords'] = np.reshape(
            np.array(mesher.getSampledSurfacePoints(i), dtype=np.float32),
            in_coords.shape)
        current_mesh['faces'] = np.reshape(
            np.array(mesher.getSampledSurfaceTriangles(i), dtype=np.float32),
            in_faces.shape)
        mesh_list.append(current_mesh)

    if save_data:
        if not base_name:
            if not isinstance(profile_file, basestring):
                base_name = os.getcwd()
                print "saving to %s" % base_name
            else:
                dir_name = os.path.dirname(intensity_img)
                base_name = os.path.basename(intensity_img)
                base_name = os.path.join(dir_name,
                                         base_name[:base_name.find('.')])

        for i in range(len(mesh_list)):
            save_mesh_geometry(base_name + '_%s.vtk' % str(i), mesh_list[i])

    return mesh_list
Esempio n. 6
0
def get_neighbours(surfname):
    """return neighbours from surface filename"""
    surf = io_mesh.load_mesh_geometry(surfname)
    neighbours = get_neighbours_from_tris(surf['faces'])
    return neighbours
Esempio n. 7
0
def create_weighted_midsurface(gray, white, surfdir):
    import tempfile
    tmpdir = os.path.join(tempfile.gettempdir(),
                          'tmp_{}'.format(str(np.random.randint(1000))))
    os.mkdir(tmpdir)
    from vast import io_mesh
    """ create mid surface weighted by the curvature so that it is on the outside of 
         gyri and inside of sulci to prevent self-intersection and correspondence problems
    inputs : gray_surface filename
              white surface filename
              """
    if 'left' in gray:
        hemi = 'left'
    else:
        hemi = 'right'
    if 'rsl' in gray:
        flag = 'rsl'
    else:
        flag = 'native'
    if os.path.isfile(
            os.path.join(surfdir,
                         'weighted_mid_' + hemi + '_' + flag + '.obj')):
        m = io_mesh.load_mesh_geometry(
            os.path.join(surfdir,
                         'weighted_mid_' + hemi + '_' + flag + '.obj'))
        return m['coords']
    else:
        try:
            subprocess.call('{} {} {}'.format(
                os.path.join(civet_path, 'average_objects'),
                os.path.join(tmpdir, 'mid.obj'), gray, white),
                            shell=True)
            subprocess.call('{} -mean_curvature -alpha 0.05 {} {}'.format(
                os.path.join(civet_path, 'depth_potential'),
                os.path.join(tmpdir, 'mid.obj '),
                os.path.join(tmpdir, 'curvature.txt')),
                            shell=True)
            subprocess.call('{} -smooth 3 {} {} {}'.format(
                os.path.join(civet_path, 'depth_potential'),
                os.path.join(tmpdir, 'curvature.txt '),
                os.path.join(tmpdir, 'mid.obj '),
                os.path.join(tmpdir, 'smcurvature.txt')),
                            shell=True)
            #normalise values between 0 and 1
            curv = np.loadtxt(os.path.join(tmpdir, 'smcurvature.txt'))
            min_value = np.mean(curv) - 2 * np.std(curv)
            curv = (curv - min_value)
            max_value = np.mean(curv) + 2 * np.std(curv)
            curv = np.array([curv / max_value]).T
            np.clip(curv, 0, 1, out=curv)
            #load in surfaces
            g = io_mesh.load_mesh_geometry(gray)
            w = io_mesh.load_mesh_geometry(white)
            mid = g['coords'] * (curv) + w['coords'] * (1 - curv)
            g['coords'] = mid
            io_mesh.save_mesh_geometry(
                os.path.join(surfdir, 'mid_' + hemi + '_' + flag + '.obj'), g)
        except OSError:
            print(
                'Error in creating create_weighted_midsurface, likely due to difficulties finding CIVET'
            )
            raise
        return mid
import numpy as np
import os
from cortex.polyutils import Surface
from perpendicular_path import perpendicular_scalar_func
import io_mesh as io
from neighbours import get_neighbours

surf_io = io.load_mesh_geometry('icbm_avg_mid_sym_mc_left_hires.obj')
surf = Surface(surf_io['coords'], surf_io['faces'])

atlas = np.loadtxt('icbm_avg_mid_sym_mc_atlas_left.txt')
lobule = np.loadtxt('lobule.txt')
medial = (atlas == 0).astype(int)
medial[lobule == 1] = 1
mask = np.where(medial == 1)[0]
dists = surf.geodesic_distance(mask, m=5)

max_start = np.argmax(dists)
#np.savetxt('dists.txt',dists)

inv_dists = surf.geodesic_distance(max_start, m=5)
filtered = inv_dists.copy()
filtered[medial == 0] = 500
#np.savetxt('invdists.txt',inv_dists)
#filtered=filtered*0
#filtered[max_start]=1
#np.savetxt('start.txt',filtered)

start_vert = np.argmax(dists)
end_vert = np.argmin(filtered)
#print end_vert
    """
    if alpha == 0:
        return np.zeros_like(aw)
    elif alpha == 1:
        return np.ones_like(aw)
    else:
        return 1 - (1 / (ap - aw) *
                    (-aw + np.sqrt((1 - alpha) * ap**2 + alpha * aw**2)))


os.mkdir('output_surfaces')
out_dir = os.path.join(os.getcwd(), 'output_surfaces')

for hemisphere in ("rh", "lh"):

    wm = io.load_mesh_geometry(
        os.path.join('/tmp', str(sys.argv[2]), hemisphere + ".white"))
    gm = io.load_mesh_geometry(
        os.path.join('/tmp', str(sys.argv[2]), hemisphere + ".pial"))

    wm_vertexareas = io.load_mgh(
        os.path.join('/tmp', str(sys.argv[2]),
                     '%s_white_area.mgh' % hemisphere))
    pia_vertexareas = io.load_mgh(
        os.path.join('/tmp', str(sys.argv[2]),
                     '%s_pial_area.mgh' % hemisphere))

    vectors = wm['coords'] - gm['coords']
    tmpsurf = copy.deepcopy(gm)
    #create mask where vertex coordinates match
    mask = vectors.sum(axis=1) != 0
import io_mesh as io
import numpy as np

#import template mesh. has fields mesh['coords'] for xyz coordinates
# and mesh['faces'] for face indices
mesh = io.load_mesh_geometry(
    'Structure/average/S900.L.pial_MSMAll.32k_fs_LR.surf.gii')

#load in mask of vertices being considered (BA44 and 45)
mask = np.loadtxt('vlpfc_nodes.1D', dtype=int)

#restrict mesh using the mask