Example #1
0
def test_patch(subject, **kargs):
    from src.utils import preproc_utils as pu
    SUBJECTS_DIR, MMVT_DIR, FREESURFER_HOME = pu.get_links()

    flat_patch_cut_vertices = utils.load(op.join(MMVT_DIR, subject, 'flat_patch_cut_vertices.pkl'))
    for hemi in utils.HEMIS:
        # verts, faces = read_patch(hemi, SUBJECTS_DIR)
        # write_patch(op.join(MMVT_DIR, 'fsaverage', 'surf', '{}.flat.test.pial'.format(hemi)), verts, faces)

        # fs_verts, fs_faces = utils.read_pial('fsaverage', MMVT_DIR, hemi, surface_type='inflated')
        print('Reading inflated surf')
        fs_verts, fs_faces = nib.freesurfer.read_geometry(op.join(SUBJECTS_DIR, subject, 'surf', '{}.inflated'.format(hemi)))
        # flat_verts, flat_faces = read_patch(hemi, SUBJECTS_DIR, surface_type='inflated')
        # good_verts = set(np.unique(flat_faces))
        # bad_verts = np.setdiff1d(np.arange(0, flat_verts.shape[0]), good_verts)
        # bad_faces_inds = set(utils.flat_list_of_lists([verts_faces_lookup[hemi][v] for v in bad_verts]))
        patch_fname = op.join(SUBJECTS_DIR, subject, 'surf', '{}.inflated.patch'.format(hemi))
        print('Writing patch')
        flat_patch_cut_vertices_hemi = set(flat_patch_cut_vertices[hemi])
        write_patch(patch_fname, [(ind, v) for ind, v in enumerate(fs_verts) if ind not in flat_patch_cut_vertices_hemi], set())#flat_faces)

        print('Reading patch')
        patch_verts, patch_faces = read_patch(subject, hemi, SUBJECTS_DIR, surface_type='inflated', patch_fname=patch_fname)

        print('Writing ply')
        patch_verts *= 0.1
        utils.write_ply_file(patch_verts, patch_faces, op.join(MMVT_DIR, subject, 'surf', '{}.flat.pial.test.ply').format(hemi))
    print('Finish!')
Example #2
0
def writing_ply_files(subject, surface_type, lab, facL_lab, vtx, vtxL, labels,
                      hemi, output_fol):
    # Vertices for the current label
    nV = vtx.shape[0]
    facL_lab_flat = utils.list_flatten(facL_lab)
    if len(facL_lab_flat) == 0:
        print("Cant write {}, no vertices!".format(labels[lab]))
        return True
    vidx = list(set(facL_lab_flat))
    vtxL[lab] = vtx[vidx]
    # Reindex the faces
    tmp = np.zeros(nV, dtype=np.int)
    tmp[vidx] = np.arange(len(vidx))
    try:
        facL_lab = np.reshape(tmp[facL_lab_flat],
                              (len(facL_lab), len(facL_lab[0])))
    except:
        print(traceback.format_exc())
        dumps_fol = utils.make_dir(op.join(MMVT_DIR, subject, 'dumps'))
        utils.save((lab, facL_lab, vtx, vtxL, labels, hemi, output_fol),
                   op.join(dumps_fol,
                           'parcelate_cortex_writing_ply_files.pkl'))
        return False

    # Save the resulting surface
    label_name = '{}-{}.ply'.format(
        lu.get_label_hemi_invariant_name(labels[lab].name), hemi)
    # print('Writing {}'.format(op.join(output_fol, label_name)))
    # todo: add distance between hemis if inflated like with the activity surfaces
    if surface_type == 'inflated':
        verts_offset = 55 if hemi == 'rh' else -55
        vtxL[lab][:, 0] = vtxL[lab][:, 0] + verts_offset
    utils.write_ply_file(vtxL[lab], facL_lab, op.join(output_fol, label_name),
                         True)
    return op.isfile(op.join(output_fol, label_name))
Example #3
0
def create_eeg_mesh(subject, excludes=[], overwrite_faces_verts=True):
    try:
        from scipy.spatial import Delaunay
        from src.utils import trig_utils
        input_file = op.join(MMVT_DIR, subject, 'eeg', 'eeg_positions.npz')
        mesh_ply_fname = op.join(MMVT_DIR, subject, 'eeg', 'eeg_helmet.ply')
        faces_verts_out_fname = op.join(MMVT_DIR, subject, 'eeg',
                                        'eeg_faces_verts.npy')
        f = np.load(input_file)
        verts = f['pos']
        excluded_inds = [np.where(f['names'] == e)[0] for e in excludes]
        # verts = np.delete(verts, excluded_inds, 0)
        verts_tup = [(x, y, z) for x, y, z in verts]
        tris = Delaunay(verts_tup)
        faces = tris.convex_hull
        areas = [
            trig_utils.poly_area(verts[poly]) for poly in tris.convex_hull
        ]
        inds = [k for k, s in enumerate(areas) if s > np.percentile(areas, 97)]
        faces = np.delete(faces, inds, 0)
        utils.write_ply_file(verts, faces, mesh_ply_fname, True)
        utils.calc_ply_faces_verts(verts, faces, faces_verts_out_fname,
                                   overwrite_faces_verts,
                                   utils.namebase(faces_verts_out_fname))
        np.savez(input_file,
                 pos=f['pos'],
                 names=f['names'],
                 tri=faces,
                 excludes=excludes)
    except:
        print('Error in create_eeg_mesh!')
        print(traceback.format_exc())
        return False
    return True
Example #4
0
def create_eeg_mesh(subject, excludes=[], overwrite_faces_verts=True):
    try:
        from scipy.spatial import Delaunay
        from src.utils import trig_utils
        input_file = op.join(MMVT_DIR, subject, 'eeg', 'eeg_positions.npz')
        mesh_ply_fname = op.join(MMVT_DIR, subject, 'eeg', 'eeg_helmet.ply')
        faces_verts_out_fname = op.join(MMVT_DIR, subject, 'eeg', 'eeg_faces_verts.npy')
        f = np.load(input_file)
        verts = f['pos']
        excluded_inds = [np.where(f['names'] == e)[0] for e in excludes]
        # verts = np.delete(verts, excluded_inds, 0)
        verts_tup = [(x, y, z) for x, y, z in verts]
        tris = Delaunay(verts_tup)
        faces = tris.convex_hull
        areas = [trig_utils.poly_area(verts[poly]) for poly in tris.convex_hull]
        inds = [k for k, s in enumerate(areas) if s > np.percentile(areas, 97)]
        faces = np.delete(faces, inds, 0)
        utils.write_ply_file(verts, faces, mesh_ply_fname, True)
        utils.calc_ply_faces_verts(verts, faces, faces_verts_out_fname, overwrite_faces_verts,
                                   utils.namebase(faces_verts_out_fname))
        np.savez(input_file, pos=f['pos'], names=f['names'], tri=faces, excludes=excludes)
    except:
        print('Error in create_eeg_mesh!')
        print(traceback.format_exc())
        return False
    return True
def create_skull_plys(subject):
    for skull_surf in ['inner_skull', 'outer_skull']:
        ply_fname = op.join(SUBJECTS_DIR, subject, 'bem',
                            '{}.ply'.format(skull_surf))
        surf_fname = op.join(SUBJECTS_DIR, subject, 'bem',
                             '{}.surf'.format(skull_surf))
        verts, faces = nib_fs.read_geometry(surf_fname)
        utils.write_ply_file(verts, faces, ply_fname, True)
Example #6
0
def transform_to_another_subject(subject, region, subjects_dir):
    colin27_xfm = tu.get_talxfm('colin27', subjects_dir)
    xfm = tu.get_talxfm('colin27', subjects_dir)
    for hemi in ['lh', 'rh']:
        verts, faces = utils.read_ply_file(op.join(MMVT_DIR, 'colin27', 'subcortical', '{}_{}.ply'.format(region, hemi)))
        verts = tu.apply_trans(colin27_xfm, verts)
        verts = tu.apply_trans(np.linalg.inv(xfm), verts)
        utils.write_ply_file(verts, faces, op.join(MMVT_DIR, subject, 'subcortical', '{}_{}.ply'.format(region, hemi)))
Example #7
0
def transform_to_another_subject(subject, region, subjects_dir):
    colin27_xfm = tu.get_talxfm('colin27', subjects_dir)
    xfm = tu.get_talxfm('colin27', subjects_dir)
    for hemi in ['lh', 'rh']:
        verts, faces = utils.read_ply_file(op.join(MMVT_DIR, 'colin27', 'subcortical', '{}_{}.ply'.format(region, hemi)))
        verts = tu.apply_trans(colin27_xfm, verts)
        verts = tu.apply_trans(np.linalg.inv(xfm), verts)
        utils.write_ply_file(verts, faces, op.join(MMVT_DIR, subject, 'subcortical', '{}_{}.ply'.format(region, hemi)))
Example #8
0
def obj_to_ply():
    fol = '/homes/5/npeled/space1/Angelique/Lionel Recon/blender/objs'
    files = glob.glob(op.join(fol, '*.obj'))
    for f in files:
        print(f)
        verts, faces = utils.read_obj_file(f)
        ply_fname = utils.change_fname_extension(f, 'ply')
        utils.write_ply_file(verts, faces, ply_fname, True)
Example #9
0
def convert(subject, surfaces_fnames):
    for surf_fname in surfaces_fnames:
        ply_fname = op.join(SUBJECTS_DIR, subject, 'surf',
                            '{}.ply'.format(utils.namebase(surf_fname)))
        if op.isfile(ply_fname):
            continue
        verts, faces = nib_fs.read_geometry(surf_fname)
        utils.write_ply_file(verts, faces, ply_fname)
Example #10
0
def create_eeg_mesh_from_obj(subject, obj_fname):
    mesh_ply_fname = op.join(MMVT_DIR, subject, 'eeg', 'eeg_helmet.ply')
    # mesh = obj.Obj(obj_fname)
    # verts, faces = mesh.vertices, mesh.faces
    verts, faces = utils.read_obj_file(obj_fname)
    utils.write_ply_file(verts, faces, mesh_ply_fname)
    faces_verts_out_fname = op.join(MMVT_DIR, subject, 'eeg', 'eeg_faces_verts.npy')
    utils.calc_ply_faces_verts(verts, faces, faces_verts_out_fname, True,
                               utils.namebase(faces_verts_out_fname))
Example #11
0
def transform_to_another_subject(subject, region, subjects_dir):
    import mne.source_space
    import mne.transforms
    colin27_xfm = mne.source_space._read_talxfm('colin27', subjects_dir, 'nibabel')
    xfm = mne.source_space._read_talxfm(subject, subjects_dir, 'nibabel')
    for hemi in ['lh', 'rh']:
        verts, faces = utils.read_ply_file(op.join(MMVT_DIR, 'colin27', 'subcortical', '{}_{}.ply'.format(region, hemi)))
        verts = apply_trans(colin27_xfm['trans'], verts)
        verts = apply_trans(np.linalg.inv(xfm['trans']), verts)
        utils.write_ply_file(verts, faces, op.join(MMVT_DIR, subject, 'subcortical', '{}_{}.ply'.format(region, hemi)))
Example #12
0
def writing_ply_files_parallel(p):
    facL_lab, vtxL_lab, vidx, nV, label_name, hemi, output_fol = p
    # Reindex the faces
    tmp = np.zeros(nV, dtype=np.int)
    tmp[vidx] = np.arange(len(vidx))
    facL_lab_flat = utils.list_flatten(facL_lab)
    facL_lab = np.reshape(tmp[facL_lab_flat], (len(facL_lab), len(facL_lab[0])))
    # Save the resulting surface
    label_name = '{}-{}.ply'.format(lu.get_label_hemi_invariant_name(label_name), hemi)
    # print('Writing {}'.format(op.join(output_fol, label_name)))
    utils.write_ply_file(vtxL_lab, facL_lab, op.join(output_fol, label_name), True)
def create_surf(subject, subcortical_code, subcortical_name):
    aseg = nib.load(op.join(SUBJECTS_DIR, subject, 'mri',
                            'aseg.mgz')).get_data()
    t1_header = nib.load(op.join(SUBJECTS_DIR, subject, 'mri',
                                 'T1.mgz')).header
    aseg[aseg != subcortical_code] = 255
    aseg[aseg == subcortical_code] = 10
    aseg = np.array(aseg, dtype=np.float)
    aseg_smooth = scipy.ndimage.gaussian_filter(aseg, sigma=1)
    verts_vox, faces, _, _ = measure.marching_cubes(aseg_smooth, 100)
    # Doesn't seem to fix the normals directions that should be out...
    faces = measure.correct_mesh_orientation(aseg_smooth, verts_vox, faces)
    verts = utils.apply_trans(t1_header.get_vox2ras_tkr(), verts_vox)
    fol = utils.make_dir(op.join(MMVT_DIR, subject, 'subcortical_test'))
    ply_file_name = op.join(fol, '{}.ply'.format(subcortical_name))
    utils.write_ply_file(verts, faces, ply_file_name, False)
Example #14
0
def aseg_to_srf(subject,
                subjects_dir,
                output_fol,
                region_id,
                lookup,
                mask_fname,
                norm_fname,
                overwrite_subcortical_objs=False,
                **kargs):
    from src.utils import geometry_utils as gu
    ret = True
    tmp_fol = op.join(subjects_dir, subject, 'tmp', utils.rand_letters(6))
    utils.make_dir(tmp_fol)
    rs = utils.partial_run_script(locals())
    # output_fname = op.join(output_fol, '{}.srf'.format(region_id))
    # tmp_output_fname = op.join(tmp_fol, '{}.asc'.format(region_id))
    # if overwrite_subcortical_objs:
    #     utils.remove_file(output_fname)
    try:
        rs(mri_pretess)
        rs(mri_tessellate)
        rs(mris_smooth)
        fs_file = op.join(tmp_fol, '{}_smooth'.format(region_id))
        verts, faces = gu.read_surface(fs_file)
        # verts, faces = nib_fs.read_geometry(fs_file)
        num = int(op.basename(fs_file).split('_')[0])
        if num not in lookup:
            print('Error in the subcorticals lookup table!')
            return False
        new_name = lookup.get(num, '')
        utils.write_ply_file(verts, faces,
                             op.join(output_fol, '{}.ply'.format(new_name)),
                             True)
        # mris_convert = 'mris_convert {tmp_fol}/{region_id}_smooth {tmp_fol}/{region_id}.asc'
        # rs(mris_convert)
        # if op.isfile(tmp_output_fname):
        #     shutil.move(tmp_output_fname, output_fname)
        if op.isdir(tmp_fol):
            shutil.rmtree(tmp_fol)
        else:
            ret = False
    except:
        print('Error in aseg_to_srf! subject: {}'.format(subject))
        print(traceback.format_exc())
        ret = False

    return ret
Example #15
0
def convert_perecelated_cortex(subject, aparc_name, surf_type='pial', overwrite_ply_files=False, hemi='both'):
    lookup = {}
    for hemi in utils.get_hemis(hemi):
        lookup[hemi] = create_labels_lookup(subject, hemi, aparc_name)
        if len(lookup[hemi]) == 0:
            continue
        srf_fol = op.join(SUBJECTS_DIR, subject,'{}.{}.{}'.format(aparc_name, surf_type, hemi))
        ply_fol = op.join(SUBJECTS_DIR, subject,'{}_{}_{}_ply'.format(aparc_name, surf_type, hemi))
        blender_fol = op.join(MMVT_DIR, subject,'{}.{}.{}'.format(aparc_name, surf_type, hemi))
        utils.convert_srf_files_to_ply(srf_fol, overwrite_ply_files)
        rename_cortical(lookup, srf_fol, ply_fol)
        if surf_type == 'inflated':
            for ply_fname in glob.glob(op.join(ply_fol, '*.ply')):
                verts, faces = utils.read_ply_file(ply_fname)
                verts_offset = 5.5 if hemi == 'rh' else -5.5
                verts[:, 0] = verts[:, 0] + verts_offset
                utils.write_ply_file(verts, faces, ply_fname)
        utils.rmtree(blender_fol)
        shutil.copytree(ply_fol, blender_fol)
    return lookup
Example #16
0
def convert_perecelated_cortex(subject, aparc_name, surf_type='pial', overwrite_ply_files=False, hemi='both'):
    lookup = {}
    for hemi in utils.get_hemis(hemi):
        lookup[hemi] = create_labels_lookup(subject, hemi, aparc_name)
        if len(lookup[hemi]) == 0:
            continue
        srf_fol = op.join(SUBJECTS_DIR, subject,'{}.{}.{}'.format(aparc_name, surf_type, hemi))
        ply_fol = op.join(SUBJECTS_DIR, subject,'{}_{}_{}_ply'.format(aparc_name, surf_type, hemi))
        blender_fol = op.join(MMVT_DIR, subject,'{}.{}.{}'.format(aparc_name, surf_type, hemi))
        utils.convert_srf_files_to_ply(srf_fol, overwrite_ply_files)
        rename_cortical(lookup, srf_fol, ply_fol)
        if surf_type == 'inflated':
            for ply_fname in glob.glob(op.join(ply_fol, '*.ply')):
                verts, faces = utils.read_ply_file(ply_fname)
                verts_offset = 5.5 if hemi == 'rh' else -5.5
                verts[:, 0] = verts[:, 0] + verts_offset
                utils.write_ply_file(verts, faces, ply_fname)
        utils.rmtree(blender_fol)
        shutil.copytree(ply_fol, blender_fol)
    return lookup
Example #17
0
def mat_to_ply():
    fol = '/homes/5/npeled/space1/Angelique/Lionel Recon/'
    files = glob.glob(op.join(fol, 'Iso*.mat'))
    avg_fname = op.join(fol, 'blender', 'mean_vertices.npy')
    if not op.isfile(avg_fname):
        vertices_avg = []
        for f in files:
            print(f)
            m = utils.read_mat_file_into_bag(f)
            vertices_avg.append(np.mean(m.vertices.T / 10, 0))
            m.clear()
        vertices_avg = np.mean(vertices_avg)
        np.save(avg_fname, vertices_avg)
    else:
        vertices_avg = np.load(avg_fname)

    for f in files:
        print(f)
        m = utils.read_mat_file_into_bag(f)
        ply_fname = utils.change_fname_extension(f, 'ply')
        utils.write_ply_file(m.vertices.T / 10.0 - vertices_avg , m.faces.T, ply_fname, True)
        m.clear()
Example #18
0
def convert_to_ply(srf_fname, ply_fname, org_vox2ras_tkr, shifter_vox2tk_ras):
    verts, faces, verts_num, faces_num = utils.read_srf_file(srf_fname)
    verts = tu.apply_trans(np.linalg.inv(org_vox2ras_tkr), verts)
    verts = tu.apply_trans(shifter_vox2tk_ras, verts)
    utils.write_ply_file(verts, faces, ply_fname)
Example #19
0
import glob
import re

from src.utils import utils

fol = '/home/npeled/Angelique/Niles'
tar_fol = ' '
npz_files = glob.glob(op.join(fol, 'npzs_center', '*.npz'))
utils.make_dir(op.join(fol, 'plys'))
electrodes_coords, electrodes_names = [], []
for npz_fname in npz_files:
    d = np.load(npz_fname)
    vertices, faces = d['vertices'], d['faces']
    ply_fname = op.join(fol, 'plys',
                        '{}.ply'.format(utils.namebase(npz_fname)))
    if op.isfile(ply_fname):
        os.remove(ply_fname)
    if faces.ndim == 1:
        print('{} is an electrode'.format(ply_fname))
        name = utils.namebase(npz_fname).replace('Electrode', '')
        num = re.sub('\D', ',', name).split(',')[-1]
        if not '.' in name and num == '':
            continue
        electrodes_coords.append(np.mean(vertices, 0))
        electrodes_names.append(name)
    else:
        print('Writing {}'.format(ply_fname))
        utils.write_ply_file(vertices, faces, ply_fname, False)
np.savez(op.join(fol, 'electrodes.npz'),
         pos=electrodes_coords,
         names=electrodes_names)
Example #20
0
def convert_to_ply(srf_fname, ply_fname, org_vox2ras_tkr, shifter_vox2tk_ras):
    verts, faces, verts_num, faces_num = utils.read_srf_file(srf_fname)
    verts = apply_trans(np.linalg.inv(org_vox2ras_tkr), verts)
    verts = apply_trans(shifter_vox2tk_ras, verts)
    utils.write_ply_file(verts, faces, ply_fname)