Exemplo n.º 1
0
    def CoregisterCT2MRI(self,
                         subjects,
                         input_folder,
                         fixed_image='reg_run[0-9]_bc_t1'):
        """Co-registration of postoperative CT to preoperative MRI for further analyses in same space; before registration
        presence of registered MRI data is ensured to avoid redundancy"""

        print('\nStarting co-registration for {} subject(s)'.format(
            len(subjects)))
        allfiles = FileOperations.get_filelist_as_tuple(inputdir=input_folder,
                                                        subjects=subjects)
        self.check_for_normalisation(subjects)

        regex_complete = ['CT_', '{}_'.format(fixed_image.upper())]
        included_sequences = [
            x for x in list(
                filter(re.compile(r"^(?!~).*").match, regex_complete))
        ]

        file_ID_CT, file_ID_MRI = ([] for _ in range(2))
        [
            file_ID_CT.append(x) for x in allfiles
            if 'run' not in x[0] and re.search(
                r'\w+{}.'.format(included_sequences[0]), x[0], re.IGNORECASE)
            and x[0].endswith('.nii')
        ]

        [
            file_ID_MRI.append(x) for x in
            allfiles  # for simplicity written in a second line as regexp is slightly different
            if re.search(r'\w+(?!_).({}).'.format(included_sequences[1]), x[0],
                         re.IGNORECASE) and x[0].endswith('.nii')
        ]

        if not file_ID_MRI:
            Output.msg_box(text="Bias-corrected MRI not found!",
                           title="Preprocessed MRI unavailable")
            return
        fileIDs = list(FileOperations.inner_join(file_ID_CT, file_ID_MRI))

        self.wrapper_multiprocessing(fileIDs, subjects, 'CT')
Exemplo n.º 2
0
def PaCER_script(subjects, inputfolder=''):
    """wrapper script for all steps included in the PaCER algorithm"""

    print("\nLead detection of {} subject(s)".format(len(subjects)))
    inputfolder = cfg['folders']['nifti'] if not inputfolder else inputfolder  # select default input folder
    LW = LeadWorks()  # load the class including necessary functions

    # Look for data files containing CT imaging including the brainMask and load this into workspace
    available_files = FileOperations.get_filelist_as_tuple(inputdir=inputfolder, subjects=subjects)
    regex2lookfor = 'reg_' + 'run[0-9]', 'brainmask_'
    file_id_CTimaging = [file_tuple for file_tuple in available_files
                         if re.search(r'\w.({}).'.format(regex2lookfor[0]), file_tuple[0], re.IGNORECASE)
                         and file_tuple[0].endswith('.nii') and 'CT' in file_tuple[0]]

    file_id_brainMask = [file_tuple for file_tuple in available_files
                         if re.search(r'\w.({}).'.format(regex2lookfor[1]), file_tuple[0], re.IGNORECASE)
                         and file_tuple[0].endswith('.nii')]

    if any(t > 2 for t in [len(k) for k in file_id_CTimaging]):
        print("More than one files for imaging or brainmask available. Please double-check!")
        return

    if not file_id_brainMask:
        warnings.warn(message="\tNo brain mask was found, trying to obtain a mask using ANTSpyNET routines")
        regex2lookforT1 = cfg['preprocess']['normalisation']['prefix'] + 'run'
        file_id_T1 = [file_tuple for file_tuple in available_files
                      if re.search(r'\w.({}).'.format(regex2lookforT1), file_tuple[0], re.IGNORECASE)
                      and 't1' in file_tuple[0] and file_tuple[0].endswith('.nii')]
        if not file_id_T1:
            Output.msg_box(text='No T1-sequence imaging available. BrainMask extraction impossible.',
                           title='T1 sequences missing")')
            return
        else:
            T1imaging = ants.image_read(file_id_T1[0][0])
            file_id_brainMask = Imaging.create_brainmask(input_folder=inputfolder, subj=''.join(subjects),
                                                         registered_images=T1imaging)
            file_id_brainMask = [file_id_brainMask] if type(file_id_brainMask) == tuple else file_id_brainMask

    fileID = list(FileOperations.inner_join(file_id_brainMask, file_id_CTimaging))  # joins all to single list
    metal_threshold = int(cfg['lead_detection']['PaCER']['metal_threshold'])
    elecModels, intensityProfiles, skelSkalms = LW.electrodeEstimation(fileID[0], threshold=metal_threshold)
    elecModels, skelSkalms, intensityProfiles, _ = \
        LeadProperties.estimate_hemisphere(elecModels, intensityProfiles, skelSkalms)  # returns hemisphere from coords.

    filename_save = os.path.join(os.path.join(inputfolder, subjects[0]), 'elecModels_' + subjects[0] + '.pkl')
    with open(filename_save, "wb") as f:
        pickle.dump(elecModels, f)
        pickle.dump(intensityProfiles, f)
        pickle.dump(skelSkalms, f)

    sides = ['left', 'right']
    rotation_default, rotation_mod = [{k: [] for k in sides} for _ in range(2)]
    for s in sides:
        rotation_default[s] = function_wrapper(subj=subjects[0], side=s)
        rotation_mod[s] = Configuration.rotation_dict_mod()  # creates an empty array to save modified data later

    filename_save = os.path.join(os.path.join(inputfolder, subjects[0]), 'rotation_' + subjects[0] + '.pkl')
    with open(filename_save, "wb") as f:
        pickle.dump(rotation_default, f)
        pickle.dump(rotation_mod, f)

    print("Finished with lead detection!")
    # TODO: it does not return to the empty command line.
    return