Esempio n. 1
0
def remove_large_negative_values_from_ct(ct_fname, new_ct_fname='', threshold=-200, overwrite=False):
    '''
    Opens the CT, checks for values less than threshold. Sets all values less than
    threshold to threshold instead. This is helpful for registration as extremely 
    large negative values present in the CT but not in the MR skew the mutual
    information algorithm.

    Parameters
    ----------
    ct_fname : Str
        The filename containing the CT scan
    new_ct_fname: Str
        The output fname
    '''
    if not op.isfile(ct_fname):
        print('The CT could not be found in {}!'.format(ct_fname))
        return ''
    if new_ct_fname == '':
        new_ct_fname = op.join(utils.get_parent_fol(ct_fname), 'ct_no_large_negative_values.mgz')
    if op.isfile(new_ct_fname):
        if overwrite:
            os.remove(new_ct_fname)
        else:
            return new_ct_fname
    h = nib.load(ct_fname)
    ct_data = h.get_data()
    ct_data[ct_data < threshold] = threshold
    ct_new = nib.Nifti1Image(ct_data, header=h.get_header(), affine=h.get_affine())
    try:
        nib.save(ct_new, new_ct_fname)
    except:
        utils.print_last_error_line()
        os.remove(new_ct_fname)
        return ct_fname
    return new_ct_fname
Esempio n. 2
0
def calc_dipoles_rois(subject, atlas='laus125', overwrite=False, n_jobs=4):
    links_dir = utils.get_links_dir()
    subjects_dir = utils.get_link_dir(links_dir, 'subjects')
    mmvt_dir = utils.get_link_dir(links_dir, 'mmvt')
    diploes_rois_output_fname = op.join(mmvt_dir, subject, 'meg', 'dipoles_rois.pkl')
    if op.isfile(diploes_rois_output_fname) and not overwrite:
        diploes_rois = utils.load(diploes_rois_output_fname)
        for dip in diploes_rois.keys():
            diploes_rois[dip]['cortical_probs'] *= 1/sum(diploes_rois[dip]['cortical_probs'])
            diploes_rois[dip]['subcortical_probs'] = []
            diploes_rois[dip]['subcortical_rois'] = []
        # coritcal_labels = set(utils.flat_list_of_lists([diploes_rois[k]['cortical_rois'] for k in diploes_rois.keys()]))
        utils.save(diploes_rois, diploes_rois_output_fname)
        return True

    diploes_input_fname = op.join(mmvt_dir, subject, 'meg', 'dipoles.pkl')
    if not op.isfile(diploes_input_fname):
        print('No dipoles file!')
        return False

    labels = lu.read_labels(subject, subjects_dir, atlas, n_jobs=n_jobs)
    labels = list([{'name': label.name, 'hemi': label.hemi, 'vertices': label.vertices}
                   for label in labels])
    if len(labels) == 0:
        print('Can\'t find the labels for atlas {}!'.format(atlas))
        return False

    # find the find_rois package
    mmvt_code_fol = utils.get_mmvt_code_root()
    ela_code_fol = op.join(utils.get_parent_fol(mmvt_code_fol), 'electrodes_rois')
    if not op.isdir(ela_code_fol) or not op.isfile(op.join(ela_code_fol, 'find_rois', 'main.py')):
        print("Can't find ELA folder!")
        print('git pull https://github.com/pelednoam/electrodes_rois.git')
        return False

    # load the find_rois package
    try:
        import sys
        if ela_code_fol not in sys.path:
            sys.path.append(ela_code_fol)
        from find_rois import main as ela
    except:
        print('Can\'t load find_rois package!')
        utils.print_last_error_line()
        return False

    dipoles_dict = utils.load(diploes_input_fname)
    diploles_names, dipoles_pos = [], []
    for cluster_name, dipoles in dipoles_dict.items():
        for begin_t, _, x, y, z, _, _, _, _, _ in dipoles:
            dipole_name = '{}_{}'.format(cluster_name, begin_t) if len(dipoles) > 1 else cluster_name
            diploles_names.append(dipole_name.replace(' ', ''))
            dipoles_pos.append([k * 1e3 for k in [x, y, z]])
    dipoles_rois = ela.identify_roi_from_atlas(
        atlas, labels, diploles_names, dipoles_pos, approx=3, elc_length=0, hit_only_cortex=True,
        subjects_dir=subjects_dir, subject=subject, n_jobs=n_jobs)
    # Convert the list to a dict
    dipoles_rois_dict = {dipoles_rois['name']: dipoles_rois for dipoles_rois in dipoles_rois}
    utils.save(dipoles_rois_dict, diploes_rois_output_fname)
Esempio n. 3
0
def _morph_electrodes_parallel(p):
    subjects, atlas, subject_to, subjects_electrodes, annotation_template, overwrite = p
    bad_subjects = []
    for subject in subjects:
        get_subject_files_from_mad([subject], atlas)
        atlas = utils.fix_atlas_name(subject, atlas, SUBJECTS_DIR)
        if not utils.both_hemi_files_exist(
                op.join(SUBJECTS_DIR, subject, 'label', '{}.{}.annot'.format(
                    '{hemi}', atlas))):
            err = ''
            try:
                anat.create_annotation(subject,
                                       atlas,
                                       annotation_template,
                                       n_jobs=1,
                                       overwrite_vertices_labels_lookup=True)
            except:
                print(traceback.format_exc())
                err = utils.print_last_error_line()
            if not utils.both_hemi_files_exist(
                    op.join(SUBJECTS_DIR, subject, 'label',
                            '{}.{}.annot'.format('{hemi}', atlas))):
                bad_subjects.append(
                    (subject, 'No atlas' if err == '' else err))
                continue
        try:
            electrodes = list(
                set(utils.flat_list_of_lists(subjects_electrodes[subject])))
            if not overwrite:
                electrodes = [
                    elc_name for elc_name in electrodes if not op.isfile(
                        op.join(MMVT_DIR, subject, 'electrodes',
                                '{}_ela_morphed.npz'.format(elc_name)))
                ]
            ela_morph_electrodes.calc_elas(subject,
                                           subject_to,
                                           electrodes,
                                           bipolar=False,
                                           atlas=atlas,
                                           overwrite=overwrite,
                                           n_jobs=1)
        except:
            print(traceback.format_exc())
            err = utils.print_last_error_line()
            bad_subjects.append((subject, err))
    return bad_subjects
Esempio n. 4
0
def read_surface(surf_name):
    print('Reading {}'.format(surf_name))
    try:
        verts, faces = nib.freesurfer.read_geometry(surf_name)
    except:
        from src.utils import utils
        import shutil
        utils.print_last_error_line()
        print('Trying to recreate the surface')
        surf_wavefront_name = '{}.asc'.format(surf_name)
        print('mris_convert {} {}'.format(surf_name, surf_wavefront_name))
        utils.run_script('mris_convert {} {}'.format(surf_name,
                                                     surf_wavefront_name))
        ply_fname = '{}.ply'.format(surf_name)
        verts, faces = utils.srf2ply(surf_wavefront_name, ply_fname)
        shutil.copyfile(surf_name, '{}.org'.format(surf_name))
        nib.freesurfer.write_geometry(surf_name, verts, faces)
    return verts, faces
def read_xls(xls_fname,
             subject_to='colin27',
             atlas='aparc.DKTatlas',
             overwrite=False,
             check_morph_file=False):
    bipolar = True
    template_header = nib.load(
        op.join(SUBJECTS_DIR, subject_to, 'mri', 'T1.mgz')).header
    subjects_electrodes = defaultdict(list)
    electrodes_colors = defaultdict(list)
    for line in utils.xlsx_reader(xls_fname, skip_rows=1):
        subject, _, elec_name, _, anat_group = line
        subject = subject.replace('\'', '')
        if subject == '':
            break
        if check_morph_file:
            electrodes_fname = op.join(
                MMVT_DIR, subject, 'electrodes',
                'electrodes_morph_to_{}.txt'.format(subject_to))
            if not op.isfile(electrodes_fname):
                continue
        elec_group, num1, num2 = utils.elec_group_number(elec_name, bipolar)
        if '{}{}-{}'.format(elec_group, num2, num1) != elec_name:
            num1, num2 = str(num1).zfill(2), str(num2).zfill(2)
        if '{}{}-{}'.format(elec_group, num2, num1) != elec_name:
            raise Exception('Wrong group or numbers!')
        for num in [num1, num2]:
            subjects_electrodes[subject].append('{}{}'.format(elec_group, num))
        electrodes_colors[subject].append((elec_name, int(anat_group)))
    subjects = list(subjects_electrodes.keys())
    bad_subjects = []
    for subject in subjects:
        atlas = utils.fix_atlas_name(subject, atlas, SUBJECTS_DIR)
        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))):
                print('No atlas for {}!'.format(atlas))
                bad_subjects.append((subject, 'No atlas'))
                continue
        try:
            ela_morph_electrodes.calc_elas(subject,
                                           subject_to,
                                           subjects_electrodes[subject],
                                           bipolar=False,
                                           atlas=atlas,
                                           overwrite=overwrite)
        except:
            err = utils.print_last_error_line()
            bad_subjects.append((subject, err))
            continue

    print(bad_subjects)
Esempio n. 6
0
def convert_rest_dicoms_to_mgz(subject, rest_fol, overwrite=False):
    try:
        root = utils.make_dir(op.join(FMRI_DIR, subject))
        output_fname = op.join(root, '{}_rest.mgz'.format(subject))
        if op.isfile(output_fname):
            if not overwrite:
                return output_fname
            if overwrite:
                os.remove(output_fname)
        dicom_files = glob.glob(op.join(rest_fol, 'MR*'))
        dicom_files.sort(key=op.getmtime)
        fu.mri_convert(dicom_files[0], output_fname)
        if op.isfile(output_fname):
            return output_fname
        else:
            print('Can\'t find {}!'.format(output_fname))
            return ''
    except:
        utils.print_last_error_line()
        return ''
Esempio n. 7
0
def read_labels(subject,
                subjects_dir,
                atlas,
                try_first_from_annotation=True,
                only_names=False,
                output_fname='',
                exclude=None,
                rh_then_lh=False,
                lh_then_rh=False,
                sorted_according_to_annot_file=False,
                hemi='both',
                surf_name='pial',
                labels_fol='',
                read_only_from_annot=False,
                n_jobs=1):
    try:
        labels = []
        if try_first_from_annotation:
            try:
                labels = mne.read_labels_from_annot(subject,
                                                    atlas,
                                                    subjects_dir=subjects_dir,
                                                    surf_name=surf_name,
                                                    hemi=hemi)
            except:
                # print(traceback.format_exc())
                print(
                    "read_labels_from_annot failed! subject {} atlas {} surf name {} hemi {}."
                    .format(subject, atlas, surf_name, hemi))
                utils.print_last_error_line()
                print('Trying to read labels files')
                if not read_only_from_annot:
                    labels_fol = op.join(
                        subjects_dir, subject, 'label',
                        atlas) if labels_fol == '' else labels_fol
                    labels = read_labels_parallel(subject,
                                                  subjects_dir,
                                                  atlas,
                                                  hemi,
                                                  labels_fol=labels_fol,
                                                  n_jobs=n_jobs)
        else:
            if not read_only_from_annot:
                labels = read_labels_parallel(subject,
                                              subjects_dir,
                                              atlas,
                                              hemi=hemi,
                                              labels_fol=labels_fol,
                                              n_jobs=n_jobs)
        if len(labels) == 0:
            raise Exception("Can't read the {} labels!".format(atlas))
        if exclude is None:
            exclude = []
        labels = [
            l for l in labels if not np.any([e in l.name for e in exclude])
        ]
        if rh_then_lh or lh_then_rh:
            rh_labels = [l for l in labels if l.hemi == 'rh']
            lh_labels = [l for l in labels if l.hemi == 'lh']
            labels = rh_labels + lh_labels if rh_then_lh else lh_labels + rh_labels
        if sorted_according_to_annot_file:
            annot_labels = get_atlas_labels_names(subject,
                                                  atlas,
                                                  subjects_dir,
                                                  return_flat_labels_list=True,
                                                  include_corpuscallosum=True,
                                                  include_unknown=True)
            try:
                labels.sort(key=lambda x: annot_labels.index(x.name))
            except ValueError:
                print("Can't sort labels according to the annot file")
                print(traceback.format_exc())
        if output_fname != '':
            with open(output_fname, 'w') as output_file:
                for label in labels:
                    output_file.write('{}\n'.format(label.name))
        if only_names:
            labels = [l.name for l in labels]
        return labels
    except:
        print(traceback.format_exc())
        return []