#!/usr/bin/python import sys import ConfigParser import time import datetime import string import csv import os import os.path if len(sys.argv)!=2: print "Wrong Number of Arguments" print "Usage: startEval realdata_configfile" sys.exit(1) # some global constants displacementFieldFilenameExtension = ".mha" analyzeHeaderFilenameExtension = ".hdr" analyzeImageFilenameExtension = ".img" stdOutLogfileExtension = ".log" configParser = ConfigParser.ConfigParser() configParser.read( sys.argv[1] ) print "Dataset Processing Configuration File: " + sys.argv[1] print "Start Processing .." writeDisplacements = configParser.get("Parameters","WriteDisplacements") generateDiagrams = configParser.get("Parameters","generateDiagrams") zipOutputFiles = configParser.get("Parameters","ZipOutputFiles") resampleDefaultValue = configParser.get("Images","resampleDefaultValue") evaluationTag = configParser.get("Identification","evaluationTag") evaluationOnly = configParser.get("Identification", "evaluationOnly") existingEvaluationDate = configParser.get("Identification", "existingEvaluationDate") #print evaluationOnly #print existingEvaluationDate fixedImageInputPath = configParser.get("Images","fixedImageInputPath") movingImageInputPath = configParser.get("Images","movingImageInputPath") if not os.path.isdir(fixedImageInputPath): print "Error: fixed image input directory'" + fixedImageInputPath + "'doesn't exist!" sys.exit(1) if not os.path.isdir(movingImageInputPath): print "Error: moving image input directory'" + movingImageInputPath + "'doesn't exist!" sys.exit(1) fixedImageFilename = configParser.get("Images","fixedImage") movingImageFilename = configParser.get("Images","movingImage") fixedImageAbsoluteFilename = fixedImageInputPath + fixedImageFilename movingImageAbsoluteFilename = movingImageInputPath + movingImageFilename # test if the fixed and moving image files exist if not os.path.isfile(fixedImageAbsoluteFilename): print "Error: fixed image '" + fixedImageAbsoluteFilename + "'doesn't exist!" sys.exit(1) print "Fixed Image: " + fixedImageAbsoluteFilename if not os.path.isfile(movingImageAbsoluteFilename): print "Error: moving image '" + mvngFilename + "'doesn't exist!" sys.exit(1) print "Moving Image: " + movingImageAbsoluteFilename resultsBasePath = configParser.get( "Filenames", "outputResultsBasePath" ) if evaluationOnly != "true": # append a subdirectory that identifies the date of the evaluation run: resultsBasePath = resultsBasePath + datetime.date.today().isoformat() + "/" + evaluationTag + "/" else: # append a subdirectory that identifies the date of the already existingevaluation run: resultsBasePath = resultsBasePath + existingEvaluationDate + "/" + evaluationTag + "/" # test if the resultsBasePath exists if not os.path.isdir(resultsBasePath): print resultsBasePath + " doesn't exist! -> Let's try to create it!" try: os.makedirs(resultsBasePath) except IOError: print "it was impossible to create directory: " + resultsBasePath sys.exit(1) resultsOutputImagePath = resultsBasePath + "output_images/" if not os.path.isdir(resultsOutputImagePath): print resultsOutputImagePath + " doesn't exist! -> Let's try to create it!" try: os.mkdir(resultsOutputImagePath) except IOError: print "it was impossible to create directory: " + resultsOutputImagePath sys.exit(1) print "output images will be written to: " + resultsOutputImagePath resultTimeConfigFilename = resultsBasePath + configParser.get( "Filenames" , "ComputationTime" ) resultIntensityFilename = resultsBasePath + configParser.get( "Filenames" , "IntensityResults" ) configFilename = resultsBasePath + configParser.get( "Filenames", "ConfigFileName" ) configFilenameExtension = configParser.get( "Filenames", "ConfigFileNameExtension" ) commandLineInterface = configParser.get( "Execution", "CommandLineInterface" ) commandLineInterfacePath = configParser.get( "Execution", "CommandLineInterfacePath" ) evaluationToolCommand = configParser.get( "Execution", "EvaluationTool" ) evaluationToolCommandPath = configParser.get( "Execution", "EvaluationToolPath" ) commandLineInterfaceCMD = commandLineInterfacePath + commandLineInterface evaluationToolCMD = evaluationToolCommandPath + evaluationToolCommand # test if the command line registration and the evaluation tools exist and are executable if not os.path.isfile(commandLineInterfaceCMD): print "command line interface tool: '" + commandLineInterfaceCMD + "' doesn't exist!" sys.exit(1) if not os.path.isfile(evaluationToolCMD): print "evaluation tool: '" + evaluationToolCMD + "' doesn't exist!" sys.exit(1) if not os.access(commandLineInterfaceCMD, os.X_OK): print "command line interface tool: '" + commandLineInterfaceCMD + "' is not executable!" sys.exit(1) if not os.access(evaluationToolCMD, os.X_OK): print "evaluation tool: '" + evaluationToolCMD + "' is not executable!" sys.exit(1) counter = 0; configFilenameList = [] for ProcessingList in configParser.options( "ProcessingList" ): currentline = configParser.get( "ProcessingList" , ProcessingList ).split(",") currentlineLength = len( currentline ) upperCaseMode = string.upper( currentline[0] ) mode = currentline[0] # index = string.rfind(syntheticImageAbsoluteFilename, '/') + 1 # fixedImageIdentifier = fixedImageAbsoluteFilename[index:] # fixedImageIdentifier = fixedImageIdentifier[:-4] # outputImageFilename = movingImageFilename[:-4] + "_" + string.lower( ProcessingList ) + "_warp_to_" + fixedImageIdentifier + analyzeHeaderFilenameExtension outputImageFilename = movingImageFilename[:-4] + "_" + string.lower( ProcessingList ) + analyzeHeaderFilenameExtension outputDefFilename = movingImageFilename[:-4] + "_" + string.lower( ProcessingList ) + displacementFieldFilenameExtension fname = configFilename + str(counter) + "_" + ProcessingList + configFilenameExtension configFilenameList = [fname] + configFilenameList counter = counter + 1 currentfile = open( fname, 'w') currentfile.write("#This is a Config File\n") currentfile.write("#Name of Execution: " + ProcessingList + "\n") currentfile.write("EXECUTION_NAME " + ProcessingList + "\n") currentfile.write("FIXED_INPUT_FILENAME " + fixedImageAbsoluteFilename + "\n") currentfile.write("MOVING_INPUT_FILENAME " + movingImageAbsoluteFilename + "\n") currentfile.write("WRITE_DISPLACEMENT_FIELD " + writeDisplacements + "\n") currentfile.write("OUTPUT_IMAGE_FILENAME " + resultsOutputImagePath + outputImageFilename + "\n") currentfile.write("OUTPUT_DISPLACEMENT_FILENAME " + resultsOutputImagePath + outputDefFilename + "\n") currentfile.write("RESAMPLE_DEFAULT_VALUE " + resampleDefaultValue + "\n" ) currentfile.write("REGISTRATION_MODE " + mode + "\n" ) # parse the standard parameters file parametersFile = open ( 'parameters.txt' ) readingParametersFinished = "false" while readingParametersFinished == "false": parametersLine = parametersFile.readline() if not parametersLine: break if not parametersLine == "\n": if not parametersLine.startswith('#'): # skip irrelevant information if parametersLine.startswith('['): # get headers of parameters if parametersLine.find( "[" + upperCaseMode + "]" ) != -1: # find correct header # consume parameter values until the next group or EOF is reached count = 1 while 1: parametersLine = parametersFile.readline() if parametersLine.startswith('[') or parametersLine == '': readingParametersFinished = "true" break if not parametersLine == "\n": splittedParameters = parametersLine.split(':') if len(splittedParameters) != 2: print "Syntax error in parameter file" sys.exit(1) standardValue = splittedParameters[1] parameterName = splittedParameters[0] if currentlineLength > count: currentfile.write( parameterName + " " + currentline[count] + "\n" ) else: currentfile.write( parameterName + " " + standardValue ) print "Take a standard Parameter Value for " + parameterName count = count + 1 parametersFile.close() currentfile.close() print "Generation of", counter, "Configfiles finished" if evaluationOnly != "true": timeResultList = [ ['ExecutionName','ExecutionTime'] , ['Original','0'] ] print print "--------------------------------------------------" print "Starting Computation" print "--------------------------------------------------" print filesToZip = [] # perform registration algorithm here for currentConfigFilename in configFilenameList: t0 = time.time() # get current execution name currentConfigFile = open ( currentConfigFilename ) lines = currentConfigFile.readlines() currentExecutionName = lines[2].split()[1] currentConfigFile.close() resultStdOutputFilename = string.replace(currentConfigFilename, configFilenameExtension, stdOutLogfileExtension) print print "--------------------------------------------------" print " Execute Command Line Registration Tool" print "--------------------------------------------------" print print " " + commandLineInterfaceCMD + " " + currentConfigFilename (pin, pout, perr) = os.popen3( commandLineInterfaceCMD + " " + currentConfigFilename ) info1 = pout.read() info2 = perr.read() print computationTime = time.time() - t0 # write the results to disk print currentExecutionName + " :" , computationTime ,"seconds Runtime" timeResultList = timeResultList + [[currentExecutionName, str( computationTime )]] currentOutputFile = open ( resultStdOutputFilename,'w' ) currentOutputFile.writelines( info1 ) currentOutputFile.writelines( info2 ) currentOutputFile.close() # write time results to disk writeFile = open( resultTimeConfigFilename ,'w'); writer = csv.writer( writeFile, dialect='excel', delimiter=';' ) writer.writerows(timeResultList) writeFile.close() # create the files that build up the results intensityCreationFile = open( resultIntensityFilename, "w" ) intensityCreationFile.write( "Filename1 ;Filename2 ;RMS_int ;STD_int ;min int;max int;normalized mutual information ;median deviation int ;edge overlap\n" ) intensityCreationFile.close() # peform evaluation for every config file for currentConfigFilename2 in configFilenameList: currentFile = open( currentConfigFilename2 ) lines = currentFile.readlines() # get the output filenames from the config file idx1 = lines[6].rfind(' ') + 1 outputImageFilename = lines[6][idx1:-1] filesToZip = filesToZip + [string.replace(outputImageFilename,analyzeHeaderFilenameExtension,analyzeImageFilenameExtension)] if writeDisplacements == "true": filesToZip = filesToZip + [outputDefFilename] evaluationToolCMDn = evaluationToolCMD + " " + fixedImageAbsoluteFilename + " " + movingImageAbsoluteFilename + " " + outputImageFilename + " " + resampleDefaultValue + " " + resultIntensityFilename print print "--------------------------------------------------" print " Execute Evaluation Tool" print "--------------------------------------------------" print print " " + evaluationToolCMDn (pin, pout, perr) = os.popen3( evaluationToolCMDn ) print pout.read() print perr.read() print # if chosen, zip the created intermediate images if zipOutputFiles == "true": for fileToZip in filesToZip: if os.path.isfile(fileToZip): zipCommand = "gzip" + " -f " + fileToZip + " && " + "rm -f " + fileToZip print zipCommand (pin,pout,perr) = os.popen3( zipCommand ) print pout.read() print perr.read()