Esempio n. 1
0
def init(subject, atlas, n_jobs):
    from src.utils import geometry_utils as gu
    if not utils.both_hemi_files_exist(
            op.join(SUBJECTS_DIR, subject, 'label', '{}.{}.annot'.format(
                '{hemi}', atlas))):
        anat.create_annotation(subject, atlas)
        if not utils.both_hemi_files_exist(
                op.join(SUBJECTS_DIR, subject, 'label', '{}.{}.annot'.format(
                    '{hemi}', atlas))):
            raise Exception(
                'Can\'t find the cortical atlas {} for subject {}'.format(
                    atlas, subject))
    labels_vertices = find_rois.read_labels_vertices(SUBJECTS_DIR, subject,
                                                     atlas, n_jobs)
    labels = lu.read_labels(subject, SUBJECTS_DIR, atlas)
    labels_names = [l.name for l in labels]
    aseg_atlas_fname = op.join(SUBJECTS_DIR, subject, 'mri', 'aseg.mgz')
    aseg_data = nib.load(aseg_atlas_fname).get_data()
    lut = fu.import_freesurfer_lut()
    pia_verts = {}
    for hemi in ['rh', 'lh']:
        pia_verts[hemi], _ = gu.read_surface(
            op.join(SUBJECTS_DIR, subject, 'surf', '{}.pial'.format(hemi)))
        # pia_verts[hemi], _ = nib.freesurfer.read_geometry(
        #     op.join(SUBJECTS_DIR, subject, 'surf', '{}.pial'.format(hemi)))
    subs_center_of_mass, subs_names = calc_subcorticals_pos(
        subject, aseg_data, lut)
    labels_center_of_mass = lu.calc_center_of_mass(labels, ret_mat=True) * 1000
    regions_center_of_mass = np.concatenate(
        (labels_center_of_mass, subs_center_of_mass))
    regions_names = labels_names + subs_names
    # save_com_as_elecs(subject, regions_center_of_mass, regions_names, atlas)
    # save_com_as_elecs(subject, subs_center_of_mass, subs_names, atlas)
    return labels_vertices, regions_center_of_mass, regions_names, aseg_data, lut, pia_verts,
Esempio n. 2
0
def read_surface(subject, subjects_dir, surf_type='pial'):
    from src.utils import geometry_utils as gu
    verts, faces = {}, {}
    for hemi in utils.HEMIS:
        surf_fname = op.join(subjects_dir, subject, 'surf', '{}.{}'.format(hemi, surf_type))
        if not op.isfile(surf_fname):
            print('{} does not exist!'.format(surf_fname))
            return None, None
        # verts[hemi], faces[hemi] = nib.freesurfer.read_geometry(surf_fname)
        verts[hemi], faces[hemi] = gu.read_surface(surf_fname)
    return verts, faces
Esempio n. 3
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
Esempio n. 4
0
def read_surface(subject, subjects_dir, surf_type='pial'):
    from src.utils import geometry_utils as gu
    verts, faces = {}, {}
    surf_found = True
    for hemi in utils.HEMIS:
        surf_fname = op.join(subjects_dir, subject, 'surf', '{}.{}'.format(hemi, surf_type))
        if op.isfile(surf_fname):
            verts[hemi], faces[hemi] = gu.read_surface(surf_fname)
        elif not op.isfile(surf_fname):
            surf_fname = op.join(
                MMVT_DIR, subject, 'subcortical', '{}-{}.npz'.format('Left' if hemi=='lh' else 'Right', surf_type))
            if op.isfile(surf_fname):
                d = np.load(surf_fname)
                verts[hemi], faces[hemi] = d['verts'], d['faces']
        if not op.isfile(surf_fname):
            print('{} does not exist!'.format(surf_fname))
            return None, None
    return verts, faces
Esempio n. 5
0
def parcelate(subject, atlas, hemi, surface_type, vertices_labels_ids_lookup=None,
              overwrite_vertices_labels_lookup=False):
    output_fol = op.join(MMVT_DIR, subject, 'labels', '{}.{}.{}'.format(atlas, surface_type, hemi))
    utils.make_dir(output_fol)
    # vtx, fac = utils.read_ply_file(op.join(MMVT_DIR, subject, 'surf', '{}.{}.ply'.format(hemi, surface_type)))
    vtx, fac = gu.read_surface(op.join(SUBJECTS_DIR, subject, 'surf', '{}.{}'.format(hemi, surface_type)))
    if vertices_labels_ids_lookup is None or overwrite_vertices_labels_lookup:
        vertices_labels_ids_lookup = lu.create_vertices_labels_lookup(
            subject, atlas, True, overwrite_vertices_labels_lookup)[hemi]
    labels = lu.read_labels(subject, SUBJECTS_DIR, atlas, hemi=hemi)
    if 'unknown-{}'.format(hemi) not in [l.name for l in labels]:
        labels.append(lu.Label([], name='unknown-{}'.format(hemi), hemi=hemi))

    nV = vtx.shape[0]
    nF = fac.shape[0]
    nL = len(labels)
    # print('The number of unique labels is {}'.format(nL))

    vtxL = [[] for _ in range(nL)]
    facL = [[] for _ in range(nL)]

    now = time.time()
    for f in range(nF):
        utils.time_to_go(now, f, nF, runs_num_to_print=50000)
        # Current face & labels
        Cfac = fac[f]
        Cidx = [vertices_labels_ids_lookup[vert_ind] for vert_ind in Cfac]
        # Depending on how many vertices of the current face
        # are in different labels, behave differently
        # nuCidx = len(np.unique(Cidx))
        # if nuCidx == 1: # If all vertices share same label
        # same_label = utils.all_items_equall(Cidx)
        # if same_label:
        if Cidx[0] == Cidx[1] == Cidx[2]:
            # Add the current face to the list of faces of the
            # respective label, and don't create new faces
            facL[Cidx[0]] += [Cfac.tolist()]
        else: # If 2 or 3 vertices are in different labels
            # Create 3 new vertices at the midpoints of the 3 edges
            vtxCfac = vtx[Cfac]
            vtxnew = (vtxCfac + vtxCfac[[1, 2, 0]]) / 2
            vtx = np.concatenate((vtx, vtxnew))
            # Define 4 new faces, with care preserve normals (all CCW)
            facnew = [
                [Cfac[0], nV, nV + 2],
                [nV,  Cfac[1], nV + 1],
                [nV + 2,  nV + 1, Cfac[2]],
                [nV, nV + 1, nV + 2]]
            # Update nV for the next loop
            nV = vtx.shape[0]
            # Add the new faces to their respective labels
            facL[Cidx[0]] += [facnew[0]]
            facL[Cidx[1]] += [facnew[1]]
            facL[Cidx[2]] += [facnew[2]]
            freq_Cidx = mode(Cidx)
            facL[freq_Cidx] += [facnew[3]] # central face
    # Having defined new faces and assigned all faces to labels, now
    # select the vertices and redefine faces to use the new vertex indices
    # Also, create the file for the indices
    # fidx = fopen(sprintf('%s.index.csv', srfprefix), 'w');

    # params = []
    # for lab in range(nL):
    #     facL_lab = facL[lab]
    #     facL_lab_flat = utils.list_flatten(facL_lab)
    #     vidx = list(set(facL_lab_flat))
    #     vtxL_lab = vtx[vidx]
    #     params.append((facL_lab, vtxL_lab, vidx, nV, labels[lab].name, hemi, output_fol))
    # utils.run_parallel(writing_ply_files_parallel, params, njobs=n_jobs)
    #
    ret = True
    for lab in range(nL):
        ret = ret and writing_ply_files(subject, surface_type, lab, facL[lab], vtx, vtxL, labels, hemi, output_fol)
    return ret