CMS 3D CMS Logo

Classes | Functions

validateAlignments Namespace Reference

Classes

class  Alignment
class  BetterConfigParser
 --- Classes ---############################ More...
class  GenericValidation
class  GeometryComparision
class  MonteCarloValidation
class  OfflineValidation
class  OfflineValidationDQM
class  TrackSplittingValidation

Functions

def castorDirExists
def createExtendedValidationScript
def createMergeScript
def getCommandOutput2
def loadTemplates
def main
 --- Main ---############################
def readAlignments
def readCompare
def readGeneral
def replaceByMap
 --- Helpers ---############################ replaces .oO[id]Oo.
def runJob

Function Documentation

def validateAlignments::castorDirExists (   path)

Definition at line 43 of file validateAlignments.py.

00044                          :
00045     if path[-1] == "/":
00046         path = path[:-1]
00047     containingPath = os.path.join( *path.split("/")[:-1] )
00048     dirInQuestion = path.split("/")[-1]
00049     try:
00050         rawLines =getCommandOutput2("rfdir /"+containingPath).splitlines()
00051     except RuntimeError:
00052         return False
00053     for line in rawLines:
00054         if line.split()[0][0] == "d":
00055             if line.split()[8] == dirInQuestion:
00056                 return True
00057     return False

def validateAlignments::createExtendedValidationScript (   offlineValidationList,
  outFilePath 
)

Definition at line 582 of file validateAlignments.py.

00583                                                                       :
00584     repMap = offlineValidationList[0].getRepMap() # bit ugly since some special features are filled
00585     repMap[ "extendedInstantiation" ] = "" #give it a "" at first in order to get the initialisation back
00586 
00587     for validation in offlineValidationList:
00588         repMap[ "extendedInstantiation" ] = validation.appendToExtendedValidation( repMap[ "extendedInstantiation" ] )
00589     
00590     theFile = open( outFilePath, "w" )
00591     theFile.write( replaceByMap( configTemplates.extendedVaidationTemplate ,repMap ) )
00592     theFile.close()
    
def validateAlignments::createMergeScript (   path,
  validations 
)

Definition at line 593 of file validateAlignments.py.

00594                                           :
00595     if( len(validations) == 0 ):
00596         raise StandardError, "cowardly refusing to merge nothing!"
00597 
00598     repMap = validations[0].getRepMap() #FIXME - not nice this way
00599     repMap.update({
00600             "DownloadData":"",
00601             "CompareAllignments":"",
00602             "RunExtendedOfflineValidation":""
00603             })
00604 
00605     comparisonLists = {} # directory of lists containing the validations that are comparable
00606     for validation in validations:
00607         for referenceName in validation.filesToCompare:    
00608             validationName = "%s.%s"%(validation.__class__.__name__, referenceName)
00609             validationName = validationName.split(".%s"%GenericValidation.defaultReferenceName )[0]
00610             if validationName in comparisonLists:
00611                 comparisonLists[ validationName ].append( validation )
00612             else:
00613                 comparisonLists[ validationName ] = [ validation ]
00614 
00615     if "OfflineValidation" in comparisonLists:
00616         repMap["extendeValScriptPath"] = os.path.join(path, "TkAlExtendedOfflineValidation.C")
00617         createExtendedValidationScript( comparisonLists["OfflineValidation"], repMap["extendeValScriptPath"] )
00618         repMap["RunExtendedOfflineValidation"] = replaceByMap(configTemplates.extendedVaidationExecution, repMap)
00619 
00620     repMap["CompareAllignments"] = "#run comparisons"
00621     for validationId in comparisonLists:
00622         compareStrings = [ val.getCompareStrings(validationId) for val in comparisonLists[validationId] ]
00623             
00624         repMap.update({"validationId": validationId,
00625                        "compareStrings": " , ".join(compareStrings) })
00626         
00627         repMap["CompareAllignments"] += replaceByMap( configTemplates.compareAlignmentsExecution, repMap )
00628       
00629     filePath = os.path.join(path, "TkAlMerge.sh")
00630     theFile = open( filePath, "w" )
00631     theFile.write( replaceByMap( configTemplates.mergeTemplate, repMap ) )
00632     theFile.close()
00633     os.chmod(filePath,0755)
00634     
00635     return filePath
    
def validateAlignments::getCommandOutput2 (   command)

Definition at line 34 of file validateAlignments.py.

00035                               :
00036     child = os.popen(command)
00037     data = child.read()
00038     err = child.close()
00039     if err:
00040         raise RuntimeError, '%s failed w/ exit code %d' % (command, err)
00041     return data
00042 
#check if a directory exsits on castor
def validateAlignments::loadTemplates (   config)

Definition at line 636 of file validateAlignments.py.

00637                            :
00638     if config.has_section("alternateTemplates"):
00639         for templateName in config.options("alternateTemplates"):
00640             newTemplateName = config.get("alternateTemplates", templateName )
00641             #print "replacing default %s template by %s"%( templateName, newTemplateName)
00642             configTemplates.alternateTemplate(templateName, newTemplateName)
    
def validateAlignments::main (   argv = None)

--- Main ---############################

Definition at line 644 of file validateAlignments.py.

Referenced by FWTableView::addTo(), FWTableView::setFrom(), and FWTriggerTableView::setFrom().

00645                      :
00646     if argv == None:
00647        argv = sys.argv[1:]
00648     optParser = optparse.OptionParser()
00649     optParser.description = """ all-in-one alignment Validation 
00650     This will run various validation procedures either on batch queues or interactviely. 
00651     
00652     If no name is given (-N parameter) a name containing time and date is created automatically
00653     
00654     To merge the outcome of all validation procedures run TkAlMerge.sh in your validation's directory.
00655     """
00656     optParser.add_option("-n", "--dryRun", dest="dryRun", action="store_true", default=False,
00657                          help="create all scripts and cfg File but do not start jobs (default=False)")
00658     optParser.add_option( "--getImages", dest="getImages", action="store_true", default=False,
00659                           help="get all Images created during the process (default= False)")
00660     optParser.add_option("-c", "--config", dest="config",
00661                          help="configuration to use (default compareConfig.ini) this can be a comma-seperated list of all .ini file you want to merge", metavar="CONFIG")
00662     optParser.add_option("-N", "--Name", dest="Name",
00663                          help="Name of this validation (default: alignmentValidation_DATE_TIME)", metavar="NAME")
00664     optParser.add_option("-r", "--restrictTo", dest="restrictTo",
00665                          help="restrict validations to given modes (comma seperated) (default: no restriction)", metavar="RESTRICTTO")
00666 
00667     (options, args) = optParser.parse_args(argv)
00668 
00669     if not options.restrictTo == None:
00670         options.restrictTo = options.restrictTo.split(",")
00671     if options.config == None:
00672         options.config = "compareConfig.ini"
00673     else:
00674         options.config = options.config.split(",")
00675         result = []
00676         for iniFile in options.config:
00677             result.append( os.path.abspath(iniFile) )
00678         options.config = result
00679     config = BetterConfigParser()
00680     config.read( options.config )
00681 
00682     if options.Name == None:
00683         options.Name = "alignmentValidation_%s"%(datetime.datetime.now().strftime("%y%m%d_%H%M%S"))
00684 
00685     outPath = os.path.abspath( options.Name )
00686     general = readGeneral( config )
00687     config.set("general","workdir",os.path.join(general["workdir"],options.Name) )
00688     config.set("general","datadir",os.path.join(general["datadir"],options.Name) )
00689     config.set("general","logdir",os.path.join(general["logdir"],options.Name) )
00690     if not os.path.exists( outPath ):
00691         os.makedirs( outPath )
00692     elif not os.path.isdir( outPath ):
00693         raise StandardError,"the file %s is in the way rename the Job or move it away"%outPath
00694 
00695     #replace default templates by the once specified in the "alternateTemplates" section
00696     loadTemplates( config )
00697 
00698     log = ""
00699     alignments = readAlignments( config )
00700     validations = []
00701     for alignment in alignments:
00702         alignment.restrictTo( options.restrictTo )
00703         validations.extend( alignment.createValidations( config, options, alignments ) )
00704 
00705     scripts = []
00706     for validation in validations:
00707         validation.createConfiguration( outPath )
00708         scripts.extend( validation.createScript( outPath ) )
00709     
00710     createMergeScript( outPath, validations )
00711 
00712     #save backup configuration file
00713     backupConfigFile = open( os.path.join( outPath, "usedConfiguration.ini" ) , "w"  )
00714     config.write( backupConfigFile )
00715 
00716     for script in scripts:
00717         name = os.path.splitext( os.path.basename( script ) )[0]
00718         if options.dryRun:
00719             print "%s would run: %s"%( name, script)
00720         else:
00721             runJob( name, script, config)

def validateAlignments::readAlignments (   config)

Definition at line 524 of file validateAlignments.py.

00525                             :
00526     result = []
00527     for section in config.sections():
00528         if "alignment:" in section:
00529             result.append( Alignment( section.split("alignment:")[1], config ) )
00530     return result

def validateAlignments::readCompare (   config)

Definition at line 531 of file validateAlignments.py.

00532                          :
00533     result = {}
00534     for section in config.sections():
00535         if "compare:" in section:
00536             levels =  config.get(section, "levels")
00537             dbOutput = config.get(section, "dbOutput")
00538             result[section.split(":")[1]] =(levels,dbOutput)
00539     return result

def validateAlignments::readGeneral (   config)

Definition at line 540 of file validateAlignments.py.

00541                          :
00542     result = {
00543         "jobmode":"interactive",
00544         "superPointingDataset":"",# see remark about rethroughung missing entries in general. this is needed to be backward compatible
00545         "workdir":os.getcwd(),
00546         "datadir":os.getcwd(),
00547         "logdir":os.getcwd(),
00548         "offlineModuleLevelHistsTransient":"False",
00549         "OfflineTreeBaseDir":"TrackHitFilter",
00550         "DMRMethod":"medianX",
00551         "DMRMinimum":"30"
00552         }
00553     try:
00554        for option in config.options("general"):
00555           result[option] = config.get("general",option)
00556            
00557        if "localGeneral" in config.sections():
00558           for option in result:
00559              if option in [item[0] for item in config.items("localGeneral")]:
00560                 result[ option ] = config.get("localGeneral", option)
00561     except ConfigParser.NoSectionError, section:
00562        raise StandardError, "missing section '%s' in configuration files. This section is mandatory."%section
00563     return result

def validateAlignments::replaceByMap (   target,
  map 
)

--- Helpers ---############################ replaces .oO[id]Oo.

by map[id] in target

Definition at line 14 of file validateAlignments.py.

00015                              :
00016     result = target
00017     for id in map:
00018         #print "  "+id+": "+map[id]
00019         lifeSaver = 10e3
00020         iteration = 0
00021         while ".oO[" in result and "]Oo." in result:
00022             for id in map:
00023                 result = result.replace(".oO["+id+"]Oo.",map[id])
00024                 iteration += 1
00025             if iteration > lifeSaver:
00026                 problematicLines = ""
00027                 print map.keys()
00028                 for line in result.splitlines():
00029                     if  ".oO[" in result and "]Oo." in line:
00030                         problematicLines += "%s\n"%line
00031                 raise StandardError, "Oh Dear, there seems to be an endless loop in replaceByMap!!\n%s\nrepMap"%problematicLines
00032     return result
00033 
#excute [command] and return output
def validateAlignments::runJob (   jobName,
  script,
  config 
)

Definition at line 564 of file validateAlignments.py.

00565                                    :
00566     general = readGeneral( config )
00567     log = ">             Validating "+jobName
00568     print ">             Validating "+jobName
00569     if general["jobmode"] == "interactive":
00570         log += getCommandOutput2( script )
00571     if general["jobmode"].split(",")[0] == "lxBatch":
00572         repMap = { 
00573             "commands": general["jobmode"].split(",")[1],
00574             "logDir": general["logdir"],
00575             "jobName": jobName,
00576             "script": script,
00577             "bsub": "/afs/cern.ch/cms/caf/scripts/cmsbsub"
00578             }
00579         
00580         log+=getCommandOutput2("%(bsub)s %(commands)s -J %(jobName)s -o %(logDir)s/%(jobName)s.stdout -e %(logDir)s/%(jobName)s.stderr %(script)s"%repMap)
00581     return log