target = []
    for j in range(0, len(M.StructureSetROISequence)):
        target.append(M.StructureSetROISequence[j].ROIName)
    print target

    for k in range(0, len(target)):
        try:
            print i, k
            Image, Mask = PyrexReader.Img_Bimask(
                Img_path[i], RT_path[i],
                target[k])  #create image array and binary mask
            featureVector = PyrexWithParams.CalculationRun(
                Image, Mask, paramsFile)  #compute radiomics
            featureVector.update({
                'patient': PatientID[i],
                'contour': target[k]
            })  #add patient ID and contour
            if export_format == 'csv' and i == 0 and k == 0:
                with open(os.path.join(exportDir, export_name),
                          'wb') as mydata:
                    w = csv.DictWriter(mydata, featureVector.keys())
                    w.writeheader()
                    w.writerow(featureVector)
            else:
                PyrexOutput.RadiomicsStore(
                    featureVector, exportDir, PatientID[i], target[k],
                    export_format, export_name
                )  #store radiomics locally with a specific format
        except:
            #       logging.debug('Error: Could not find %s' % target[k])
            print 'Error: Could not find', target[k]
Esempio n. 2
0
def executeORAWbatch_roi(myWorkingDirectory, roi, myStructUID, exportDir,
                         export_format, export_name):
    outPath = r''
    #read Params file of Pyradiomics
    progress_filename = os.path.join(outPath, 'pyrexbatch_log.txt')
    # Configure logging
    rLogger = logging.getLogger('radiomics')

    # Set logging level
    # rLogger.setLevel(logging.INFO)  # Not needed, default log level of logger is INFO
    handler = logging.FileHandler(
        filename=progress_filename,
        mode='w')  # Create handler for writing to log file
    handler.setFormatter(
        logging.Formatter('%(levelname)s:%(name)s: %(message)s'))
    rLogger.addHandler(handler)
    logger = rLogger.getChild(
        'batch')  # Initialize logging for batch log messages

    # Set verbosity level for output to stderr (default level = WARNING)
    #radiomics.setVerbosity(logging.INFO)

    logger.info('pyradiomics version: %s', radiomics.__version__)
    logger.info('Reading Params file for pyradiomics')
    # Reading Params file for pyradiomics
    try:
        paramsFile = os.path.join(os.getcwd(), 'ParamsSettings',
                                  'Pyradiomics_Params.yaml')
    except Exception:
        logger.error('Could not find params file of Pyradiomics!',
                     exc_info=True)
        exit(-1)
#  logger.info('Reading Params file of Pyrex')

    patient = os.listdir(myWorkingDirectory)
    #  logger.info('Parsing DICOM files and RTSTRUCT in working directory')
    #xnat_collection(myWorkingDirectory,collectionURL,myProjectID)
    Img_path, RT_path = ParseStructure(
        myWorkingDirectory)  #detect the path of Image and RTstruct
    logger.info('DICOM and RTSTRUCT Parsing Done')

    flists = pandas.DataFrame(data={
        'patient': patient
    }).T  # create a pandas data frame for data
    logger.info('Starting Pyrex')

    # define export output format
    if export_format == 'csv':
        RESULT = pandas.DataFrame()
    else:
        RESULT = Graph()

    for entry in flists:
        results = pandas.DataFrame()
        #      logger.info('processing patient: %s', patient[entry])
        mask_vol = PyrexReader.Read_RTSTRUCT(RT_path[entry])
        logger.info('Loading RTSTRUCT: %s', RT_path[entry])
        M = mask_vol[0]
        target = []
        for j in range(0, len(M.StructureSetROISequence)):
            target.append(M.StructureSetROISequence[j].ROIName)
        logger.info('ROI: %s', target)

        if roi in target:
            try:
                featureVector = flists[entry]
                #featureVector['patient'] = featureVector['patient'] + 'Pyrex_' + target[k]
                Image, Mask = PyrexReader.Img_Bimask(Img_path[entry],
                                                     RT_path[entry], roi)
                logger.info('Processing Radiomics on %s of Patient (%s)', roi,
                            patient[entry])
                if export_format == 'csv':  # sava results in csv
                    try:
                        result = pandas.Series(
                            PyrexWithParams.CalculationRun(
                                Image, Mask, paramsFile))
                        contour = pandas.Series({'contour': roi})
                        structUID = pandas.Series({'structUID': myStructUID})
                        featureVector = featureVector.append(contour)
                        featureVector = featureVector.append(structUID)
                        featureVector = featureVector.append(result)
                        featureVector.name = 1
                        results = results.join(featureVector, how='outer')
                        Image = []
                        Mask = []
                        result = []
                        RESULT = pandas.concat([RESULT, results], axis=1)
                    except Exception:
                        logger.error(
                            'FEATURE EXTRACTION FAILED for CSV output:',
                            exc_info=True)
                else:  # save results in triple stroe
                    try:
                        featureVector = PyrexWithParams.CalculationRun(
                            Image, Mask, paramsFile)  #compute radiomics
                        featureVector.update({
                            'patient': patient[entry],
                            'contour': target[k],
                            'RTid': myStructUID
                        })  #add patient ID and contour
                        graph_roi = PyrexOutput.RadiomicsRDF(
                            featureVector, exportDir, patient[entry],
                            myStructUID, target[k], export_format, export_name
                        )  #store radiomics locally with a specific format
                        RESULT = RESULT + graph_roi
                        logger.info('Extraction complete, writing rdf')
                    except Exception:
                        logger.error(
                            'FEATURE EXTRACTION FAILED for RDF output:',
                            exc_info=True)
            except Exception:
                logger.info('FEATURE EXTRACTION FAILED:')
            logger.info('-------------------------------------------')
            print(patient[entry], roi)
        else:
            print('%s is not exist in RTSTRUCTURE', roi)