Пример #1
0
def create_unknown_labels(subject, atlas):
    labels_fol = op.join(SUBJECTS_DIR, subject, 'label', atlas)
    utils.make_dir(labels_fol)
    unknown_labels_fname_template = op.join(
        labels_fol, 'unknown-{}.label'.format('{hemi}'))
    if utils.both_hemi_files_exist(unknown_labels_fname_template):
        unknown_labels = {
            hemi:
            mne.read_label(unknown_labels_fname_template.format(hemi=hemi),
                           subject)
            for hemi in utils.HEMIS
        }
        return unknown_labels

    unknown_labels = {}
    for hemi in utils.HEMIS:
        labels = read_labels(subject, SUBJECTS_DIR, atlas, hemi=hemi)
        unknown_label_name = 'unknown-{}'.format(hemi)
        labels_names = [l.name for l in labels]
        if unknown_label_name not in labels_names:
            verts, _ = utils.read_pial(subject, MMVT_DIR, hemi)
            unknown_verts = set(range(verts.shape[0]))
            for label in labels:
                unknown_verts -= set(label.vertices)
            unknown_verts = np.array(sorted(list(unknown_verts)))
            unknown_label = mne.Label(unknown_verts,
                                      hemi=hemi,
                                      name=unknown_label_name,
                                      subject=subject)
        else:
            unknown_label = labels[labels_names.index(unknown_label_name)]
        unknown_labels[hemi] = unknown_label
        if not op.isfile(unknown_labels_fname_template.format(hemi=hemi)):
            unknown_label.save(unknown_labels_fname_template.format(hemi=hemi))
    return unknown_labels
Пример #2
0
def merge_labels(subject, fmri_names):
    utils.delete_folder_files(op.join(MMVT_DIR, subject, 'fmri', 'labels'))
    vertices_labels_lookup = utils.load(
        op.join(MMVT_DIR, subject,
                'aparc.DKTatlas40_vertices_labels_lookup.pkl'))
    output_fol = utils.make_dir(op.join(MMVT_DIR, subject, 'fmri', 'labels'))
    for fmri_name in fmri_names:
        labels = []
        for hemi in utils.HEMIS:
            surf_fname = op.join(
                MMVT_DIR, subject, 'fmri', 'fmri_{}_{}.npy'.format(
                    fmri_name.replace('_insulaopercula', ''), hemi))
            surf_data = np.load(surf_fname)
            vertices_indices = np.where(surf_data >= 0.95)[0]
            if len(vertices_indices) == 0:
                continue
            insulaopercula_vertices = []
            vertices, _ = utils.read_pial(subject, MMVT_DIR, hemi)
            for vert_ind in tqdm(vertices_indices):
                vert_label = vertices_labels_lookup[hemi][vert_ind]
                if vert_label.startswith(
                        'insula'
                ):  # or vert_label.startswith('parsopercularis')
                    insulaopercula_vertices.append(vert_ind)
            label = mne.Label(insulaopercula_vertices,
                              vertices[insulaopercula_vertices],
                              hemi=hemi,
                              name=fmri_name,
                              subject=subject)
            labels.append(label)
            label.save(op.join(output_fol, '{}.label'.format(fmri_name)))
        anat.labels_to_annot(subject, atlas=fmri_name, labels=labels)
        anat.calc_labeles_contours(subject, fmri_name)
Пример #3
0
 def check_loopup_is_ok(lookup):
     unique_values_num = sum(
         [len(set(lookup[hemi].values())) for hemi in utils.HEMIS])
     # check it's not only the unknowns
     lookup_ok = unique_values_num > 2
     err = ''
     if not lookup_ok:
         err = 'unique_values_num = {}\n'.format(unique_values_num)
     for hemi in utils.HEMIS:
         verts, _ = utils.read_pial(subject, MMVT_DIR, hemi)
         lookup_ok = lookup_ok and len(lookup[hemi].keys()) == len(verts)
         if not lookup_ok:
             err += 'len(lookup[{}].keys()) != len(verts) ({}!={})\n'.format(
                 hemi, len(lookup[hemi].keys()), len(verts))
     return lookup_ok, err
Пример #4
0
def load_surf(subject, mmvt_dir, subjects_dir):
    verts = {}
    for hemi in HEMIS:
        if op.isfile(
                op.join(mmvt_dir, subject, 'surf',
                        '{}.pial.npz'.format(hemi))):
            hemi_verts, _ = utils.read_pial(subject, mmvt_dir, hemi)
        elif op.isfile(
                op.join(subjects_dir, subject, 'surf',
                        '{}.pial.ply'.format(hemi))):
            hemis_verts, _ = utils.read_ply_file(
                op.join(subjects_dir, subject, 'surf',
                        '{}.pial.ply'.format(hemi)))
        else:
            print("Can't find {} pial ply/npz files!".format(hemi))
            return False
        verts[hemi] = hemi_verts
    return verts
Пример #5
0
def create_vertices_labels_lookup(subject,
                                  atlas,
                                  save_labels_ids=False,
                                  overwrite=False,
                                  read_labels_from_fol=''):
    def check_loopup_is_ok(lookup):
        unique_values_num = sum(
            [len(set(lookup[hemi].values())) for hemi in utils.HEMIS])
        # check it's not only the unknowns
        lookup_ok = unique_values_num > 2
        err = ''
        if not lookup_ok:
            err = 'unique_values_num = {}\n'.format(unique_values_num)
        for hemi in utils.HEMIS:
            verts, _ = utils.read_pial(subject, MMVT_DIR, hemi)
            lookup_ok = lookup_ok and len(lookup[hemi].keys()) == len(verts)
            if not lookup_ok:
                err += 'len(lookup[{}].keys()) != len(verts) ({}!={})\n'.format(
                    hemi, len(lookup[hemi].keys()), len(verts))
        return lookup_ok, err

    output_fname = op.join(
        MMVT_DIR, subject, '{}_vertices_labels_{}lookup.pkl'.format(
            atlas, 'ids_' if save_labels_ids else ''))
    if op.isfile(output_fname) and not overwrite:
        lookup = utils.load(output_fname)
        loopup_is_ok, _ = check_loopup_is_ok(lookup)
        if loopup_is_ok:
            return lookup
    lookup = {}

    for hemi in utils.HEMIS:
        lookup[hemi] = {}
        if read_labels_from_fol != '':
            labels = read_labels(subject,
                                 SUBJECTS_DIR,
                                 atlas,
                                 hemi=hemi,
                                 try_first_from_annotation=False,
                                 labels_fol=read_labels_from_fol)
        else:
            labels = read_labels(subject, SUBJECTS_DIR, atlas, hemi=hemi)
        if len(labels) == 0:
            raise Exception("Can't read labels from {} {}".format(
                subject, atlas))
        labels_names = [l.name for l in labels]
        if len([l for l in labels_names if 'unknown' in l.lower()]) == 0:
            # add the unknown label
            # todo: this code is needed to be debugged!
            annot_fname = get_annot_fnames(subject,
                                           SUBJECTS_DIR,
                                           atlas,
                                           hemi=hemi)[0]
            if op.isfile(annot_fname):
                backup_fname = utils.add_str_to_file_name(
                    annot_fname, '_backup')
                shutil.copy(annot_fname, backup_fname)
            try:
                mne.write_labels_to_annot(subject=subject,
                                          hemi=hemi,
                                          labels=labels,
                                          parc=atlas,
                                          overwrite=True,
                                          subjects_dir=SUBJECTS_DIR)
            except:
                print(
                    'create_vertices_labels_lookup: Error writing labels to annot file!'
                )
                print('Creating unknown label manually')
                create_unknown_labels(subject, atlas)
            labels = mne.read_labels_from_annot(subject,
                                                atlas,
                                                subjects_dir=SUBJECTS_DIR,
                                                surf_name='pial',
                                                hemi=hemi)
            labels_names = [l.name for l in labels]
        if len([l for l in labels_names if 'unknown' in l.lower()]) == 0:
            raise Exception('No unknown label in {}'.format(annot_fname))
        verts, _ = utils.read_pial(subject, MMVT_DIR, hemi)
        verts_indices = set(range(len(verts)))
        for label in labels:
            for vertice in label.vertices:
                if vertice in verts_indices:
                    lookup[hemi][vertice] = labels_names.index(
                        label.name) if save_labels_ids else label.name
                else:
                    print(
                        'vertice {} of label {} not in verts! ({}, {})'.format(
                            vertice, label.name, subject, hemi))
    loopup_is_ok, err = check_loopup_is_ok(lookup)
    if loopup_is_ok:
        utils.save(lookup, output_fname)
        return lookup
    else:
        print('unknown labels: ', [l for l in labels_names if 'unknown' in l])
        raise Exception('Error in vertices_labels_lookup!\n{}'.format(err))
Пример #6
0
def find_clusters_overlapped_labeles(subject,
                                     clusters,
                                     data,
                                     atlas,
                                     hemi,
                                     verts,
                                     min_cluster_max=0,
                                     min_cluster_size=0,
                                     clusters_label='',
                                     n_jobs=6):
    cluster_labels = []
    if not op.isfile(
            op.join(SUBJECTS_DIR, subject, 'surf', '{}.pial'.format(hemi))):
        from src.utils import freesurfer_utils as fu
        verts, faces = utils.read_pial(subject, MMVT_DIR, hemi)
        fu.write_surf(
            op.join(SUBJECTS_DIR, subject, 'surf', '{}.pial'.format(hemi)),
            verts, faces)
    labels = read_labels(subject,
                         SUBJECTS_DIR,
                         atlas,
                         hemi=hemi,
                         n_jobs=n_jobs)
    if len(labels) == 0:
        print('No labels!')
        return None
    for cluster in clusters:
        x = data[cluster]
        cluster_max = np.min(x) if abs(np.min(x)) > abs(
            np.max(x)) else np.max(x)
        if abs(cluster_max) < min_cluster_max or len(
                cluster) < min_cluster_size:
            continue
        max_vert_ind = np.argmin(x) if abs(np.min(x)) > abs(
            np.max(x)) else np.argmax(x)
        max_vert = cluster[max_vert_ind]
        inter_labels, inter_labels_tups = [], []
        for label in labels:
            overlapped_vertices = np.intersect1d(cluster, label.vertices)
            if len(overlapped_vertices) > 0:
                if 'unknown' not in label.name:
                    inter_labels_tups.append(
                        (len(overlapped_vertices), label.name))
                    # inter_labels.append(dict(name=label.name, num=len(overlapped_vertices)))
        inter_labels_tups = sorted(inter_labels_tups)[::-1]
        for inter_labels_tup in inter_labels_tups:
            inter_labels.append(
                dict(name=inter_labels_tup[1], num=inter_labels_tup[0]))
        if len(inter_labels) > 0 and clusters_label in inter_labels[0]['name']:
            # max_inter = max([(il['num'], il['name']) for il in inter_labels])
            cluster_labels.append(
                dict(vertices=cluster,
                     intersects=inter_labels,
                     name=inter_labels[0]['name'],
                     coordinates=verts[cluster],
                     max=cluster_max,
                     hemi=hemi,
                     size=len(cluster),
                     max_vert=max_vert))
        else:
            print('No intersected labels!')
    return cluster_labels
Пример #7
0
def create_vertices_labels_lookup(subject,
                                  atlas,
                                  save_labels_ids=False,
                                  overwrite=False,
                                  read_labels_from_fol=''):
    output_fname = op.join(
        MMVT_DIR, subject, '{}_vertices_labels_{}lookup.pkl'.format(
            atlas, 'ids_' if save_labels_ids else ''))
    if op.isfile(output_fname) and not overwrite:
        lookup = utils.load(output_fname)
        unique_values_num = sum(
            [len(set(lookup[hemi].values())) for hemi in utils.HEMIS])
        # check it's not only the unknowns
        lookup_ok = unique_values_num > 2
        if lookup_ok:
            for hemi in utils.HEMIS:
                verts, _ = utils.read_pial(subject, MMVT_DIR, hemi)
                lookup_ok = lookup_ok and len(
                    lookup[hemi].keys()) == len(verts)
        if lookup_ok:
            return lookup
    lookup = {}

    for hemi in utils.HEMIS:
        lookup[hemi] = {}
        create_unknown_label = False
        if read_labels_from_fol != '':
            labels = read_labels(subject,
                                 SUBJECTS_DIR,
                                 atlas,
                                 hemi=hemi,
                                 try_first_from_annotation=False,
                                 labels_fol=read_labels_from_fol)
        else:
            labels = read_labels(subject, SUBJECTS_DIR, atlas, hemi=hemi)
        labels_names = [l.name for l in labels]
        # if 'unknown-{}'.format(hemi) not in [l.name for l in labels]:
        create_unknown_label = True
        verts, _ = utils.read_pial(subject, MMVT_DIR, hemi)
        unknown_verts = set(range(verts.shape[0]))
        for label in labels:
            for vertice in label.vertices:
                lookup[hemi][vertice] = labels_names.index(
                    label.name) if save_labels_ids else label.name
            if create_unknown_label and label.name != 'unknown-{}'.format(
                    hemi):
                unknown_verts -= set(label.vertices)
        if create_unknown_label:
            for vertice in unknown_verts:
                lookup[hemi][vertice] = len(
                    labels_names) if save_labels_ids else 'unknown-{}'.format(
                        hemi)
            if 'unknown-{}'.format(hemi) in labels_names:
                unknown_label = labels[labels_names.index(
                    'unknown-{}'.format(hemi))]
                recreate_annot = set(unknown_label.vertices) != unknown_verts
            if recreate_annot:
                while 'unknown-{}'.format(hemi) in labels_names:
                    del labels[labels_names.index('unknown-{}'.format(hemi))]
                    labels_names = [l.name for l in labels]
                    # labels[labels_names.index('unknown-{}'.format(hemi))].vertices = sorted(list(unknown_verts))
                # else:s
                #     unknown_label = mne.Label(
                #         sorted(list(unknown_verts)), hemi=hemi, name='unknown-{}'.format(hemi), subject=subject)
                #     labels.append(unknown_label)
                annot_fname = op.join(SUBJECTS_DIR, subject, 'label',
                                      '{}.{}.annot'.format(hemi, atlas))
                shutil.copy(
                    annot_fname,
                    op.join(SUBJECTS_DIR, subject, 'label',
                            '{}.{}_backup.annot'.format(hemi, atlas)))
                mne.write_labels_to_annot(labels,
                                          subject=subject,
                                          parc=atlas,
                                          overwrite=True,
                                          subjects_dir=SUBJECTS_DIR,
                                          hemi=hemi)
                # labels = mne.read_labels_from_annot(subject, annot_fname=annot_fname)
    utils.save(lookup, output_fname)
    return lookup