CMS 3D CMS Logo

Classes | Functions
validateAlignments Namespace Reference

Classes

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

Functions

def createExtendedValidationScript (offlineValidationList, outFilePath, resultPlotFile)
 
def createMergeScript (path, validations)
 
def createMergeZmumuPlotsScript (zMuMuValidationList, outFilePath)
 
def createOfflineParJobsMergeScript (offlineValidationList, outFilePath)
 
def createPrimaryVertexPlotScript (PrimaryVertexValidationList, outFilePath)
 
def createTrackSplitPlotScript (trackSplittingValidationList, outFilePath)
 
def loadTemplates (config)
 
def main (argv=None)
 — Main —############################ More...
 

Function Documentation

def validateAlignments.createExtendedValidationScript (   offlineValidationList,
  outFilePath,
  resultPlotFile 
)

Definition at line 254 of file validateAlignments.py.

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

Referenced by createMergeScript().

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

Definition at line 303 of file validateAlignments.py.

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

Referenced by main().

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

Definition at line 291 of file validateAlignments.py.

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

Referenced by createMergeScript().

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

Definition at line 247 of file validateAlignments.py.

References helperFunctions.replaceByMap().

Referenced by createMergeScript().

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

Definition at line 279 of file validateAlignments.py.

References helperFunctions.replaceByMap().

Referenced by createMergeScript().

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

Definition at line 267 of file validateAlignments.py.

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

Referenced by createMergeScript().

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

Definition at line 451 of file validateAlignments.py.

References configTemplates.alternateTemplate().

Referenced by main().

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

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

Definition at line 462 of file validateAlignments.py.

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

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