예제 #1
0
 def _generateQCForRois(self, space, roi_list):
     for roi in roi_list:
         roi_name = self._extractFileName(roi,
                                          remove_extension=True,
                                          extension_count=2)
         image_files_base = os.path.join(self.getBaseDirectory(),
                                         'QC_LesionLoad', space, roi_name)
         generateQCPage('LL_%s' % (roi_name), image_files_base)
예제 #2
0
    def runBrainExtraction(self, anatomical_id, lesion_mask_id):
        # Skip this step if user has already performed brain extraction
        if self.controller.b_brain_extraction.get() == True or self.skip:
            self.incrementStage()
            return False

        image_files_base = os.path.join(self.getBaseDirectory(),
                                        'QC_BrainExtractions')

        self.logger.info('Brain extraction has been initiated')
        for subject in self.subjects:
            try:
                anatomical_file_path, lesion_files = self._setSubjectSpecificPaths_1(
                    subject, anatomical_id, lesion_mask_id)
                ((t1_mgz, seg_file), bet_brain_file,
                 wm_mask_file) = self._setSubjectSpecificPaths_2(subject)

                self.com.runBet(
                    anatomical_file_path,
                    os.path.join(self.getIntermediatePath(subject),
                                 subject + '_Brain'))

                image_path = os.path.join(image_files_base,
                                          subject + '_BET.png')
                self.com.runFslEyes(anatomical_file_path, bet_brain_file,
                                    image_path)
            except:
                self.logger.debug(traceback.format_exc())
                pass
        html_file_path = generateQCPage('BET', image_files_base)
        self.printQCPageUrl('Brain extraction', html_file_path)
        self.logger.info('Brain extraction completed for all subjects')
    def runLesionLoadCalculation(self, anatomical_id, lesion_mask_id):
        if self.stage in (6, 7):
            if self.controller.b_own_rois.get() == True:
                space = 'custom'
                template_brain = self.controller.sv_user_brain_template.get()
                if self.stage == 6:
                    self.runReg(template_brain, space, anatomical_id,
                                lesion_mask_id)
                if self.stage == 7:
                    roi_list = self.controller.user_roi_paths
                    self._runLesionLoadCalculationHelper(
                        space, roi_list, anatomical_id, lesion_mask_id)
                    self.incrementStage()
            else:
                self.incrementStage(2)

        if self.stage in (8, 9):
            if self.controller.b_default_rois.get() == True:
                space = 'MNI152'
                template_brain = os.path.join(
                    self.controller.getProjectDirectory(), 'ROIs',
                    'MNI152_T1_2mm_brain.nii.gz')
                if self.stage == 8:
                    self.runReg(template_brain, space, anatomical_id,
                                lesion_mask_id)
                if self.stage == 9:
                    roi_list = self.controller.default_roi_paths
                    self._runLesionLoadCalculationHelper(
                        space, roi_list, anatomical_id, lesion_mask_id)
                    self.incrementStage()
            else:
                self.incrementStage(2)

        if self.stage in (10, 11):
            if self.controller.b_freesurfer_rois.get() == True:
                space = 'FS'
                template_brain = ''
                if self.stage == 10:
                    self.runReg(template_brain, space, anatomical_id,
                                lesion_mask_id)
                if self.stage == 11:
                    self.runLesionLoadCalculationFS(space, anatomical_id,
                                                    lesion_mask_id)
                    self.incrementStage()
            else:
                self.incrementStage(2)

        if self.stage == 12:
            image_files_base = os.path.join(self.getBaseDirectory(),
                                            'QC_Registrations', space)
            html_file_path = generateQCPage('Registration', image_files_base)
            self.logger.info(
                'Lesion Load Calculation completed for all subjects')
            self.printQCPageUrl('LL Calculation', html_file_path, pause=False)
            self.incrementStage()
 def _generateQCForRois(self, space, roi_list):
     for roi in roi_list:
         roi_name = self._extractFileName(roi,
                                          remove_extension=True,
                                          extension_count=2)
         image_files_base = os.path.join(self.getBaseDirectory(),
                                         'QC_LesionLoad', space, roi_name)
         html_file_path = generateQCPage('LL_%s' % (roi_name),
                                         image_files_base)
         self.printQCPageUrl('%s-Lesion Load' % roi_name,
                             html_file_path,
                             pause=False)
예제 #5
0
	def createQCPage(self):
		self.logger.info('Visual QC module has been initiated.')
		images_dir = os.path.join(self.getBaseDirectory(), 'QC_Lesions')
		os.makedirs(images_dir)

		for subject in self.subjects:
			anatomical_file_path, lesion_files = self.getT1NLesionFromInput(subject)
			for counter, lesion_file in enumerate(lesion_files):
				cog = self.com.runFslStats(lesion_file, '-C')
				x,y,z=cog.split(' ')
				x=int(x)
				y=int(y)
				z=int(z)

				output_image_path = os.path.join(self.getBaseDirectory(), 'QC_Lesions', '%s_Lesion%d.png'%(subject, counter+1))
				self.com.runFslEyes2(anatomical_file_path[0], lesion_file, '', x, y, z, output_image_path)

		html_file_path = generateQCPage('Lesions', images_dir)
		self.printQCPageUrl('createQCPage', html_file_path, pause=False)
		self.logger.info('QC Page generation completed')
예제 #6
0
    def runLesionCorrection(self, anatomical_id, lesion_mask_id):
        self.logger.info('Lesion correction has been initiated.')
        max_lesions = 0
        subject_info_all = []
        for subject in self.subjects:
            subject_info = [subject]

            anatomical_file_path, lesion_files = self._setSubjectSpecificPaths_1(
                subject, anatomical_id, lesion_mask_id)
            ((t1_mgz, seg_file), bet_brain_file,
             wm_mask_file) = self._setSubjectSpecificPaths_2(subject)

            if not self.com.runFslMathToCheckInSameSpace(
                    wm_mask_file, lesion_files[0],
                    os.path.join(self.getIntermediatePath(subject),
                                 subject + '_corrWM')):
                self.logger.info(
                    'Check Image Orientations for T1 and Lesion Mask. Skipping Subject: %s'
                    % subject)
                subject_info.append('Skipped')
                continue

            # assign the new wm seg file (with lesion removed) to corrWM
            corrected_wm_file = os.path.join(self.getIntermediatePath(subject),
                                             subject + '_corrWM.nii.gz')
            output_file = os.path.join(self.getIntermediatePath(subject),
                                       subject + '_NormRangeWM')
            # set values for healthy WM removal
            # multiply WM mask by intensity normalized T1
            self.com.runFslWithArgs(anatomical_file_path, corrected_wm_file,
                                    output_file, '-mul')
            wm_mean = self.com.runFslStats(output_file, '-M')

            lesion_files_count = len(lesion_files)

            if max_lesions < lesion_files_count:
                max_lesions = lesion_files_count
                self.logger.debug('Updated num of max lesions : ' +
                                  str(max_lesions))

            total_native_brain_volume = self.com.runBrainVolume(bet_brain_file)

            subject_info.append(total_native_brain_volume)
            subject_info.append(wm_mean)

            for counter, lesion_file in enumerate(lesion_files):
                # calculate original and white matter adjusted lesion volumes
                original_lesion_vol = self.com.runBrainVolume(lesion_file)
                skip_subject, corrected_lesion_volume, wm_adjusted_lesion = self._lesionCorrection(
                    subject, counter + 1, wm_mean, anatomical_file_path,
                    lesion_file)
                if skip_subject:
                    self.logger.log(
                        'Check Image Orientations for T1 and Lesion Mask. Skipping Subject: '
                        + subject)
                    subject_info.append('Skipped')
                    continue

                volume_removed = original_lesion_vol - corrected_lesion_volume
                percent_removed = volume_removed * 1.0 / total_native_brain_volume

                #determine side of lesion
                #this gets the center of gravity of the lesion using the mni coord and then extracts the first char of the X coordinate
                lesion_side = self.com.runFslStats(lesion_file, '-c')

                subject_info.append(lesion_side)
                subject_info.append(original_lesion_vol)
                subject_info.append(corrected_lesion_volume)
                subject_info.append(volume_removed)
                subject_info.append(percent_removed)

                cog = self.com.runFslStats(lesion_file, '-C')
                x, y, z = cog.split(' ')
                x = int(x)
                y = int(y)
                z = int(z)

                output_image_path = os.path.join(
                    self.getBaseDirectory(), 'QC_LesionCorrection',
                    '%s_WMAdjLesion%d.png' % (subject, counter + 1))
                self.com.runFslEyes2(anatomical_file_path, lesion_file,
                                     wm_adjusted_lesion, x, y, z,
                                     output_image_path)
        subject_info_all.append(subject_info)

        header = [
            'Subject', 'Total_Native_Brain_Volume',
            'Mean_White_Matter_Intensity'
        ]
        for lesion_counter in range(max_lesions):

            lesion_num = str(lesion_counter + 1)
            header.append('Lesion%s_Hemisphere' % lesion_num)
            header.append('Lesion%s_Original_Lesion_Volume' % lesion_num)
            header.append('Lesion%s_Corrected_Lesion_Volume' % lesion_num)
            header.append('Lesion%s_Volume_Removed' % lesion_num)
            header.append('Lesion%s_Percent_Removed' % lesion_num)

        # Write data to the csv file
        subject_info_with_header = [header] + subject_info_all
        self.com.runAppendToCSV(
            subject_info_with_header,
            os.path.join(self.getBaseDirectory(),
                         'lesion_correction_database.csv'))

        image_files_base = os.path.join(self.getBaseDirectory(),
                                        'QC_LesionCorrection')
        html_file_path = generateQCPage('Lesions', image_files_base)
        self.printQCPageUrl('Lesion Correction', html_file_path)

        self.logger.info('Lesion correction completed for all subjects')
        lesion_mask_id = 'WMAdjusted'
        return lesion_mask_id
    def runReg(self, template_brain, space, anatomical_id, lesion_mask_id):
        self.logger.info(
            'Registration to either default or user-input ROI space has been initiated.'
        )

        if space == 'MNI152' or space == 'custom':
            #same template brain for all subject; passed in as template_brain
            for subject in self.subjects:
                anatomical_file_path, lesion_files = self._setSubjectSpecificPaths_1(
                    subject, anatomical_id, lesion_mask_id)
                ((t1_mgz, seg_file), bet_brain_file,
                 wm_mask_file) = self._setSubjectSpecificPaths_2(subject)

                reg_brain_file = os.path.join(
                    self.getIntermediatePath(subject),
                    '%s_Reg_brain_%s' % (subject, space))
                reg_file = os.path.join(self.getIntermediatePath(subject),
                                        '%s_Reg_%s.mat' % (subject, space))

                self.com.runFlirt(bet_brain_file, template_brain,
                                  reg_brain_file, reg_file)
                out_image_path = os.path.join(self.getBaseDirectory(),
                                              'QC_Registrations', space,
                                              '%s_Reg.png' % subject)
                cmd = 'fsleyes render -hl --hideCursor -of %s %s %s -cm yellow -a 90' % (
                    out_image_path, template_brain, reg_brain_file + '.nii.gz')
                self.com.runRawCommand(cmd)

        if space == 'FS':
            # new template brain for each subject
            for subject in self.subjects:
                anatomical_file_path, lesion_files = self._setSubjectSpecificPaths_1(
                    subject, anatomical_id, lesion_mask_id)
                ((t1_mgz, seg_file), bet_brain_file,
                 wm_mask_file) = self._setSubjectSpecificPaths_2(subject)

                template_brain = os.path.join(
                    self.getIntermediatePath(subject),
                    '%s_FST1.nii.gz' % subject)
                self.com.runMriConvert(t1_mgz, template_brain)

                # perform registration to FS Space for each subject to get transformation matrix
                reg_file = os.path.join(self.getIntermediatePath(subject),
                                        '%s_T12FS.xfm' % subject)
                reg_brain_file = os.path.join(
                    self.getIntermediatePath(subject), '%s_T12FS' % subject)

                self.com.runFlirt(anatomical_file_path, template_brain,
                                  reg_brain_file, reg_file)

                output_image_path = os.path.join(self.getBaseDirectory(),
                                                 'QC_Registrations', 'FS',
                                                 '%s_Reg.png' % subject)

                cmd = 'fsleyes render -hl --hideCursor -of %s %s %s -cm yellow -a 90' % (
                    output_image_path, template_brain,
                    reg_brain_file + '.nii.gz')
                self.com.runRawCommand(cmd)

                # invert transformation matrix
                xfm_inverse_file = os.path.join(
                    self.getIntermediatePath(subject),
                    '%s_T12FS_inv.xfm' % subject)
                cmd = 'convert_xfm -omat %s %s;' % (xfm_inverse_file, reg_file)
                self.com.runRawCommand(cmd)

        image_files_base = os.path.join(self.getBaseDirectory(),
                                        'QC_Registrations', space)
        html_file_path = generateQCPage('Registration', image_files_base)
        self.printQCPageUrl('Registrations', html_file_path)
        self.logger.info(
            'Registration to either default or user-input ROI space has been completed for all subjects.'
        )
예제 #8
0
    def runReg(self, template_brain, space, anatomical_id, lesion_mask_id):
        self.logger.info('Performing registration...')

        if space == 'MNI152' or space == 'custom':
            #same template brain for all subject; passed in as template_brain
            for subject in self.subjects:
                anatomical_file_path, lesion_files = self._setSubjectSpecificPaths_1(
                    subject, anatomical_id, lesion_mask_id)
                ((t1_mgz, seg_file), bet_brain_file,
                 wm_mask_file) = self._setSubjectSpecificPaths_2(subject)

                reg_brain_file = os.path.join(
                    self.getIntermediatePath(subject),
                    '%s_Reg_brain_%s' % (subject, space))
                reg_file = os.path.join(self.getIntermediatePath(subject),
                                        '%s_Reg_%s.mat' % (subject, space))

                self.com.runFlirt(bet_brain_file, template_brain,
                                  reg_brain_file, reg_file)
                out_image_path = os.path.join(self.getBaseDirectory(),
                                              'QC_Registrations', space,
                                              '%s_Reg.png' % subject)
                self.com.runFslEyes(out_image_path,
                                    reg_brain_file + '.nii.gz',
                                    options='')

        if space == 'FS':
            # new template brain for each subject
            for subject in self.subjects:
                anatomical_file_path, lesion_files = self._setSubjectSpecificPaths_1(
                    subject, anatomical_id, lesion_mask_id)
                ((t1_mgz, seg_file), bet_brain_file,
                 wm_mask_file) = self._setSubjectSpecificPaths_2(subject)

                template_brain = os.path.join(
                    self.getIntermediatePath(subject),
                    '%s_FST1.nii.gz' % subject)
                self.com.runMriConvert(t1_mgz, template_brain)

                # perform registration to FS Space for each subject to get transformation matrix
                reg_file = os.path.join(self.getIntermediatePath(subject),
                                        '%s_T12FS.xfm' % subject)
                reg_brain_file = os.path.join(
                    self.getIntermediatePath(subject), '%s_T12FS' % subject)
                #cmd = 'flirt -in %s -ref %s -omat %s -out %s;'%(anatomical_file_path, template_brain, reg_file, reg_brain_file)
                #self.com.runRawCommand(cmd)
                self.com.runFlirt(anatomical_file_path, template_brain,
                                  reg_brain_file, reg_file)

                output_image_path = os.path.join(self.getBaseDirectory(),
                                                 'QC_Registrations', 'FS',
                                                 '%s_Reg.png' % subject)
                self.com.runFslEyes(out_image_path,
                                    reg_brain_file + '.nii.gz',
                                    options='')
                #self.com.runFslEyes(reg_brain_file, output_image_path=output_image_path, options='')

                # invert transformation matrix
                xfm_inverse_file = os.path.join(
                    self.getIntermediatePath(subject),
                    '%s_T12FS_inv.xfm' % subject)
                cmd = 'convert_xfm -omat %s %s;' % (xfm_inverse_file, reg_file)
                self.com.runRawCommand(cmd)

        image_files_base = os.path.join(self.getBaseDirectory(),
                                        'QC_Registrations', space)
        generateQCPage('Registration', image_files_base)