test
CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
Classes | Functions
validateAlignments Namespace Reference

Classes

class  ValidationJob
 — Classes —############################ More...
 

Functions

def createExtendedValidationScript
 
def createMergeScript
 
def createMergeZmumuPlotsScript
 
def createOfflineParJobsMergeScript
 
def createPrimaryVertexPlotScript
 
def createTrackSplitPlotScript
 
def loadTemplates
 
def main
 — Main —############################ More...
 

Function Documentation

def validateAlignments.createExtendedValidationScript (   offlineValidationList,
  outFilePath,
  resultPlotFile 
)

Definition at line 251 of file validateAlignments.py.

References plottingOptions.PlottingOptions(), and helperFunctions.replaceByMap().

Referenced by createMergeScript().

252 def createExtendedValidationScript(offlineValidationList, outFilePath, resultPlotFile):
253  config = offlineValidationList[0].config
254  repMap = PlottingOptions(config, "offline")
255  repMap[ "resultPlotFile" ] = resultPlotFile
256  repMap[ "extendedInstantiation" ] = "" #give it a "" at first in order to get the initialisation back
257 
258  for validation in offlineValidationList:
259  repMap[ "extendedInstantiation" ] = validation.appendToExtendedValidation( repMap[ "extendedInstantiation" ] )
260 
261  theFile = open( outFilePath, "w" )
262  theFile.write( replaceByMap( configTemplates.extendedValidationTemplate ,repMap ) )
263  theFile.close()
def replaceByMap
— Helpers —############################
def validateAlignments.createMergeScript (   path,
  validations 
)

Definition at line 300 of file validateAlignments.py.

References bitset_utilities.append(), createExtendedValidationScript(), createMergeZmumuPlotsScript(), createOfflineParJobsMergeScript(), createPrimaryVertexPlotScript(), createTrackSplitPlotScript(), reco.if(), join(), plottingOptions.PlottingOptions(), and helperFunctions.replaceByMap().

Referenced by main().

301 def createMergeScript( path, validations ):
302  if(len(validations) == 0):
303  raise AllInOneError("Cowardly refusing to merge nothing!")
304 
305  config = validations[0].config
306  repMap = config.getGeneral()
307  repMap.update({
308  "DownloadData":"",
309  "CompareAlignments":"",
310  "RunExtendedOfflineValidation":"",
311  "RunTrackSplitPlot":"",
312  "MergeZmumuPlots":"",
313  "RunPrimaryVertexPlot":"",
314  "CMSSW_BASE": os.environ["CMSSW_BASE"],
315  "SCRAM_ARCH": os.environ["SCRAM_ARCH"],
316  "CMSSW_RELEASE_BASE": os.environ["CMSSW_RELEASE_BASE"],
317  })
318 
319  comparisonLists = {} # directory of lists containing the validations that are comparable
320  for validation in validations:
321  for referenceName in validation.filesToCompare:
322  validationName = "%s.%s"%(validation.__class__.__name__, referenceName)
323  validationName = validationName.split(".%s"%GenericValidation.defaultReferenceName )[0]
324  validationName = validationName.split("Preexisting")[-1]
325  if validationName in comparisonLists:
326  comparisonLists[ validationName ].append( validation )
327  else:
328  comparisonLists[ validationName ] = [ validation ]
329 
330  # introduced to merge individual validation outputs separately
331  # -> avoids problems with merge script
332  repMap["haddLoop"] = "mergeRetCode=0\n"
333  repMap["rmUnmerged"] = ("if [[ mergeRetCode -eq 0 ]]; then\n"
334  " echo -e \\n\"Merging succeeded, removing original files.\"\n")
335  repMap["copyMergeScripts"] = ""
336  repMap["mergeParallelFilePrefixes"] = ""
337 
338  anythingToMerge = []
339 
340  for validationType in comparisonLists:
341  for validation in comparisonLists[validationType]:
342  if isinstance(validation, PreexistingValidation) or validation.NJobs == 1:
343  continue
344  if validationType not in anythingToMerge:
345  anythingToMerge += [validationType]
346  repMap["haddLoop"] += '\n\n\n\necho -e "\n\nMerging results from %s jobs"\n\n' % validationType
347  repMap["haddLoop"] = validation.appendToMerge(repMap["haddLoop"])
348  repMap["haddLoop"] += "tmpMergeRetCode=${?}\n"
349  repMap["haddLoop"] += ("if [[ tmpMergeRetCode -eq 0 ]]; then "
350  "xrdcp -f "
351  +validation.getRepMap()["finalOutputFile"]
352  +" root://eoscms//eos/cms"
353  +validation.getRepMap()["finalResultFile"]
354  +"; fi\n")
355  repMap["haddLoop"] += ("if [[ ${tmpMergeRetCode} -gt ${mergeRetCode} ]]; then "
356  "mergeRetCode=${tmpMergeRetCode}; fi\n")
357  for f in validation.getRepMap()["outputFiles"]:
358  longName = os.path.join("/store/caf/user/$USER/",
359  validation.getRepMap()["eosdir"], f)
360  repMap["rmUnmerged"] += " $eos rm "+longName+"\n"
361  repMap["rmUnmerged"] += ("else\n"
362  " echo -e \\n\"WARNING: Merging failed, unmerged"
363  " files won't be deleted.\\n"
364  "(Ignore this warning if merging was done earlier)\"\n"
365  "fi\n")
366 
367  if "OfflineValidation" in anythingToMerge:
368  repMap["mergeOfflineParJobsScriptPath"] = os.path.join(path, "TkAlOfflineJobsMerge.C")
369 
370  createOfflineParJobsMergeScript( comparisonLists["OfflineValidation"],
371  repMap["mergeOfflineParJobsScriptPath"] )
372  repMap["copyMergeScripts"] += ("cp .oO[Alignment/OfflineValidation]Oo./scripts/merge_TrackerOfflineValidation.C .\n"
373  "rfcp %s .\n" % repMap["mergeOfflineParJobsScriptPath"])
374  repMap_offline = repMap.copy()
375  repMap_offline.update(PlottingOptions(config, "offline"))
376  repMap["copyMergeScripts"] = \
377  replaceByMap(repMap["copyMergeScripts"], repMap_offline)
378 
379  if anythingToMerge:
380  # DownloadData is the section which merges output files from parallel jobs
381  # it uses the file TkAlOfflineJobsMerge.C
382  repMap["DownloadData"] += replaceByMap( configTemplates.mergeParallelResults, repMap )
383  else:
384  repMap["DownloadData"] = ""
385 
386  if "OfflineValidation" in comparisonLists:
387  repMap["extendedValScriptPath"] = os.path.join(path, "TkAlExtendedOfflineValidation.C")
388  createExtendedValidationScript(comparisonLists["OfflineValidation"],
389  repMap["extendedValScriptPath"],
390  "OfflineValidation")
391  repMap_offline = repMap.copy()
392  repMap_offline.update(PlottingOptions(config, "offline"))
393  repMap["RunExtendedOfflineValidation"] = \
394  replaceByMap(configTemplates.extendedValidationExecution, repMap_offline)
395 
396  if "TrackSplittingValidation" in comparisonLists:
397  repMap["trackSplitPlotScriptPath"] = \
398  os.path.join(path, "TkAlTrackSplitPlot.C")
399  createTrackSplitPlotScript(comparisonLists["TrackSplittingValidation"],
400  repMap["trackSplitPlotScriptPath"] )
401  repMap_split = repMap.copy()
402  repMap_split.update(PlottingOptions(config, "split"))
403  repMap["RunTrackSplitPlot"] = \
404  replaceByMap(configTemplates.trackSplitPlotExecution, repMap_split)
405 
406  if "ZMuMuValidation" in comparisonLists:
407  repMap["mergeZmumuPlotsScriptPath"] = \
408  os.path.join(path, "TkAlMergeZmumuPlots.C")
409  createMergeZmumuPlotsScript(comparisonLists["ZMuMuValidation"],
410  repMap["mergeZmumuPlotsScriptPath"] )
411  repMap_zMuMu = repMap.copy()
412  repMap_zMuMu.update(PlottingOptions(config, "zmumu"))
413  repMap["MergeZmumuPlots"] = \
414  replaceByMap(configTemplates.mergeZmumuPlotsExecution, repMap_zMuMu)
415 
416  if "PrimaryVertexValidation" in comparisonLists:
417  repMap["PrimaryVertexPlotScriptPath"] = \
418  os.path.join(path, "TkAlPrimaryVertexValidationPlot.C")
419 
420  createPrimaryVertexPlotScript(comparisonLists["PrimaryVertexValidation"],
421  repMap["PrimaryVertexPlotScriptPath"] )
422  repMap_PVVal = repMap.copy()
423  repMap_PVVal.update(PlottingOptions(config,"primaryvertex"))
424  repMap["RunPrimaryVertexPlot"] = \
425  replaceByMap(configTemplates.PrimaryVertexPlotExecution, repMap_PVVal)
426 
427  repMap["CompareAlignments"] = "#run comparisons"
428  if "OfflineValidation" in comparisonLists:
429  compareStrings = [ val.getCompareStrings("OfflineValidation") for val in comparisonLists["OfflineValidation"] ]
430  compareStringsPlain = [ val.getCompareStrings("OfflineValidation", plain=True) for val in comparisonLists["OfflineValidation"] ]
431 
432  repMap_offline = repMap.copy()
433  repMap_offline.update(PlottingOptions(config, "offline"))
434  repMap_offline.update({"validationId": "OfflineValidation",
435  "compareStrings": " , ".join(compareStrings),
436  "compareStringsPlain": " ".join(compareStringsPlain) })
437 
438  repMap["CompareAlignments"] += \
439  replaceByMap(configTemplates.compareAlignmentsExecution, repMap_offline)
440 
441  filePath = os.path.join(path, "TkAlMerge.sh")
442  theFile = open( filePath, "w" )
443  theFile.write( replaceByMap( configTemplates.mergeTemplate, repMap ) )
444  theFile.close()
445  os.chmod(filePath,0o755)
446 
447  return filePath
boost::dynamic_bitset append(const boost::dynamic_bitset<> &bs1, const boost::dynamic_bitset<> &bs2)
this method takes two bitsets bs1 and bs2 and returns result of bs2 appended to the end of bs1 ...
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def replaceByMap
— Helpers —############################
if(dp >Float(M_PI)) dp-
def validateAlignments.createMergeZmumuPlotsScript (   zMuMuValidationList,
  outFilePath 
)

Definition at line 288 of file validateAlignments.py.

References plottingOptions.PlottingOptions(), and helperFunctions.replaceByMap().

Referenced by createMergeScript().

289 def createMergeZmumuPlotsScript(zMuMuValidationList, outFilePath):
290  config = zMuMuValidationList[0].config
291  repMap = PlottingOptions(config, "zmumu")
292  repMap[ "mergeZmumuPlotsInstantiation" ] = "" #give it a "" at first in order to get the initialisation back
293 
294  for validation in zMuMuValidationList:
295  repMap[ "mergeZmumuPlotsInstantiation" ] = validation.appendToExtendedValidation( repMap[ "mergeZmumuPlotsInstantiation" ] )
296 
297  theFile = open( outFilePath, "w" )
298  theFile.write( replaceByMap( configTemplates.mergeZmumuPlotsTemplate ,repMap ) )
299  theFile.close()
def replaceByMap
— Helpers —############################
def validateAlignments.createOfflineParJobsMergeScript (   offlineValidationList,
  outFilePath 
)

Definition at line 244 of file validateAlignments.py.

References helperFunctions.replaceByMap().

Referenced by createMergeScript().

245 def createOfflineParJobsMergeScript(offlineValidationList, outFilePath):
246  repMap = offlineValidationList[0].getRepMap() # bit ugly since some special features are filled
247 
248  theFile = open( outFilePath, "w" )
249  theFile.write( replaceByMap( configTemplates.mergeOfflineParJobsTemplate ,repMap ) )
250  theFile.close()
def replaceByMap
— Helpers —############################
def validateAlignments.createPrimaryVertexPlotScript (   PrimaryVertexValidationList,
  outFilePath 
)

Definition at line 276 of file validateAlignments.py.

References helperFunctions.replaceByMap().

Referenced by createMergeScript().

277 def createPrimaryVertexPlotScript(PrimaryVertexValidationList, outFilePath):
278  repMap = PrimaryVertexValidationList[0].getRepMap() # bit ugly since some special features are filled
279  repMap[ "CMSSW_BASE" ] = os.environ['CMSSW_BASE']
280  repMap[ "PrimaryVertexPlotInstantiation" ] = "" #give it a "" at first in order to get the initialisation back
281 
282  for validation in PrimaryVertexValidationList:
283  repMap[ "PrimaryVertexPlotInstantiation" ] = validation.appendToExtendedValidation( repMap[ "PrimaryVertexPlotInstantiation" ] )
284 
285  theFile = open( outFilePath, "w" )
286  theFile.write( replaceByMap( configTemplates.PrimaryVertexPlotTemplate ,repMap ) )
287  theFile.close()
def replaceByMap
— Helpers —############################
def validateAlignments.createTrackSplitPlotScript (   trackSplittingValidationList,
  outFilePath 
)

Definition at line 264 of file validateAlignments.py.

References plottingOptions.PlottingOptions(), and helperFunctions.replaceByMap().

Referenced by createMergeScript().

265 def createTrackSplitPlotScript(trackSplittingValidationList, outFilePath):
266  config = trackSplittingValidationList[0].config
267  repMap = PlottingOptions(config, "split")
268  repMap[ "trackSplitPlotInstantiation" ] = "" #give it a "" at first in order to get the initialisation back
269 
270  for validation in trackSplittingValidationList:
271  repMap[ "trackSplitPlotInstantiation" ] = validation.appendToExtendedValidation( repMap[ "trackSplitPlotInstantiation" ] )
272 
273  theFile = open( outFilePath, "w" )
274  theFile.write( replaceByMap( configTemplates.trackSplitPlotTemplate ,repMap ) )
275  theFile.close()
def replaceByMap
— Helpers —############################
def validateAlignments.loadTemplates (   config)

Definition at line 448 of file validateAlignments.py.

References configTemplates.alternateTemplate().

Referenced by main().

449 def loadTemplates( config ):
450  if config.has_section("alternateTemplates"):
451  for templateName in config.options("alternateTemplates"):
452  if templateName == "AutoAlternates":
453  continue
454  newTemplateName = config.get("alternateTemplates", templateName )
455  #print "replacing default %s template by %s"%( templateName, newTemplateName)
456  configTemplates.alternateTemplate(templateName, newTemplateName)
457 
def alternateTemplate
### Alternate Templates ###
def validateAlignments.main (   argv = None)

— Main —############################

Definition at line 459 of file validateAlignments.py.

References createMergeScript(), cmsRelvalreport.exit, helperFunctions.getCommandOutput2(), join(), loadTemplates(), GetRecoTauVFromDQM_MC_cff.next, and split.

460 def main(argv = None):
461  if argv == None:
462  argv = sys.argv[1:]
463  optParser = optparse.OptionParser()
464  optParser.description = """All-in-one Alignment Validation.
465 This will run various validation procedures either on batch queues or interactively.
466 If no name is given (-N parameter) a name containing time and date is created automatically.
467 To merge the outcome of all validation procedures run TkAlMerge.sh in your validation's directory.
468 """
469  optParser.add_option("-n", "--dryRun", dest="dryRun", action="store_true", default=False,
470  help="create all scripts and cfg File but do not start jobs (default=False)")
471  optParser.add_option( "--getImages", dest="getImages", action="store_true", default=True,
472  help="get all Images created during the process (default= True)")
473  defaultConfig = "TkAlConfig.ini"
474  optParser.add_option("-c", "--config", dest="config", default = defaultConfig,
475  help="configuration to use (default TkAlConfig.ini) this can be a comma-seperated list of all .ini file you want to merge", metavar="CONFIG")
476  optParser.add_option("-N", "--Name", dest="Name",
477  help="Name of this validation (default: alignmentValidation_DATE_TIME)", metavar="NAME")
478  optParser.add_option("-r", "--restrictTo", dest="restrictTo",
479  help="restrict validations to given modes (comma seperated) (default: no restriction)", metavar="RESTRICTTO")
480  optParser.add_option("-s", "--status", dest="crabStatus", action="store_true", default = False,
481  help="get the status of the crab jobs", metavar="STATUS")
482  optParser.add_option("-d", "--debug", dest="debugMode", action="store_true",
483  default = False,
484  help="run the tool to get full traceback of errors",
485  metavar="DEBUG")
486  optParser.add_option("-m", "--autoMerge", dest="autoMerge", action="store_true", default = False,
487  help="submit TkAlMerge.sh to run automatically when all jobs have finished (default=False)."
488  " Works only for batch jobs")
489 
490  (options, args) = optParser.parse_args(argv)
491 
492  if not options.restrictTo == None:
493  options.restrictTo = options.restrictTo.split(",")
494 
495  options.config = [ os.path.abspath( iniFile ) for iniFile in \
496  options.config.split( "," ) ]
497  config = BetterConfigParser()
498  outputIniFileSet = set( config.read( options.config ) )
499  failedIniFiles = [ iniFile for iniFile in options.config if iniFile not in outputIniFileSet ]
500 
501  # Check for missing ini file
502  if options.config == [ os.path.abspath( defaultConfig ) ]:
503  if ( not options.crabStatus ) and \
504  ( not os.path.exists( defaultConfig ) ):
505  raise AllInOneError( "Default 'ini' file '%s' not found!\n"
506  "You can specify another name with the "
507  "command line option '-c'/'--config'."
508  %( defaultConfig ))
509  else:
510  for iniFile in failedIniFiles:
511  if not os.path.exists( iniFile ):
512  raise AllInOneError( "'%s' does not exist. Please check for "
513  "typos in the filename passed to the "
514  "'-c'/'--config' option!"
515  %( iniFile ))
516  else:
517  raise AllInOneError(( "'%s' does exist, but parsing of the "
518  "content failed!" ) % iniFile)
519 
520  # get the job name
521  if options.Name == None:
522  if not options.crabStatus:
523  options.Name = "alignmentValidation_%s"%(datetime.datetime.now().strftime("%y%m%d_%H%M%S"))
524  else:
525  existingValDirs = fnmatch.filter( os.walk( '.' ).next()[1],
526  "alignmentValidation_*" )
527  if len( existingValDirs ) > 0:
528  options.Name = existingValDirs[-1]
529  else:
530  print "Cannot guess last working directory!"
531  print ( "Please use the parameter '-N' or '--Name' to specify "
532  "the task for which you want a status report." )
533  return 1
534 
535  # set output path
536  outPath = os.path.abspath( options.Name )
537 
538  # Check status of submitted jobs and return
539  if options.crabStatus:
540  os.chdir( outPath )
541  crabLogDirs = fnmatch.filter( os.walk('.').next()[1], "crab.*" )
542  if len( crabLogDirs ) == 0:
543  print "Found no crab tasks for job name '%s'"%( options.Name )
544  return 1
545  theCrab = crabWrapper.CrabWrapper()
546  for crabLogDir in crabLogDirs:
547  print
548  print "*" + "=" * 78 + "*"
549  print ( "| Status report and output retrieval for:"
550  + " " * (77 - len( "Status report and output retrieval for:" ) )
551  + "|" )
552  taskName = crabLogDir.replace( "crab.", "" )
553  print "| " + taskName + " " * (77 - len( taskName ) ) + "|"
554  print "*" + "=" * 78 + "*"
555  print
556  crabOptions = { "-getoutput":"",
557  "-c": crabLogDir }
558  try:
559  theCrab.run( crabOptions )
560  except AllInOneError as e:
561  print "crab: No output retrieved for this task."
562  crabOptions = { "-status": "",
563  "-c": crabLogDir }
564  theCrab.run( crabOptions )
565  return
566 
567  general = config.getGeneral()
568  config.set("internals","workdir",os.path.join(general["workdir"],options.Name) )
569  config.set("general","datadir",os.path.join(general["datadir"],options.Name) )
570  config.set("general","logdir",os.path.join(general["logdir"],options.Name) )
571  config.set("general","eosdir",os.path.join("AlignmentValidation", general["eosdir"], options.Name) )
572 
573  if not os.path.exists( outPath ):
574  os.makedirs( outPath )
575  elif not os.path.isdir( outPath ):
576  raise AllInOneError("the file %s is in the way rename the Job or move it away"%outPath)
577 
578  # replace default templates by the ones specified in the "alternateTemplates" section
579  loadTemplates( config )
580 
581  #save backup configuration file
582  backupConfigFile = open( os.path.join( outPath, "usedConfiguration.ini" ) , "w" )
583  config.write( backupConfigFile )
584 
585  validations = []
586  for validation in config.items("validation"):
587  alignmentList = [validation[1]]
588  validationsToAdd = [(validation[0],alignment) \
589  for alignment in alignmentList]
590  validations.extend(validationsToAdd)
591  jobs = [ ValidationJob( validation, config, options) \
592  for validation in validations ]
593  map( lambda job: job.createJob(), jobs )
594  validations = [ job.getValidation() for job in jobs ]
595 
596  createMergeScript(outPath, validations)
597 
598  print
599  map( lambda job: job.runJob(), jobs )
600 
601  if options.autoMerge:
602  # if everything is done as batch job, also submit TkAlMerge.sh to be run
603  # after the jobs have finished
604  if ValidationJob.jobCount == ValidationJob.batchCount and config.getGeneral()["jobmode"].split(",")[0] == "lxBatch":
605  print "> Automatically merging jobs when they have ended"
606  repMap = {
607  "commands": config.getGeneral()["jobmode"].split(",")[1],
608  "jobName": "TkAlMerge",
609  "logDir": config.getGeneral()["logdir"],
610  "script": "TkAlMerge.sh",
611  "bsub": "/afs/cern.ch/cms/caf/scripts/cmsbsub",
612  "conditions": '"' + " && ".join(["ended(" + jobId + ")" for jobId in ValidationJob.batchJobIds]) + '"'
613  }
614  for ext in ("stdout", "stderr", "stdout.gz", "stderr.gz"):
615  oldlog = "%(logDir)s/%(jobName)s."%repMap + ext
616  if os.path.exists(oldlog):
617  os.remove(oldlog)
618 
619  getCommandOutput2("%(bsub)s %(commands)s "
620  "-o %(logDir)s/%(jobName)s.stdout "
621  "-e %(logDir)s/%(jobName)s.stderr "
622  "-w %(conditions)s "
623  "%(logDir)s/%(script)s"%repMap)
— Classes —############################
def main
— Main —############################
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
double split
Definition: MVATrainer.cc:139