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 createOfflineParJobsMergeScript
 
def createTrackSplitPlotScript
 
def loadTemplates
 
def main
 — Main —############################ More...
 

Function Documentation

def validateAlignments.createExtendedValidationScript (   offlineValidationList,
  outFilePath,
  resultPlotFile 
)

Definition at line 237 of file validateAlignments.py.

References helperFunctions.replaceByMap().

Referenced by createMergeScript().

238 def createExtendedValidationScript(offlineValidationList, outFilePath, resultPlotFile):
239  repMap = offlineValidationList[0].getRepMap() # bit ugly since some special features are filled
240  repMap[ "CMSSW_BASE" ] = os.environ['CMSSW_BASE']
241  repMap[ "resultPlotFile" ] = resultPlotFile
242  repMap[ "extendedInstantiation" ] = "" #give it a "" at first in order to get the initialisation back
243 
244  for validation in offlineValidationList:
245  repMap[ "extendedInstantiation" ] = validation.appendToExtendedValidation( repMap[ "extendedInstantiation" ] )
246 
247  theFile = open( outFilePath, "w" )
248  # theFile.write( replaceByMap( configTemplates.extendedValidationTemplate ,repMap ) )
249  theFile.write( replaceByMap( configTemplates.extendedValidationTemplate ,repMap ) )
250  theFile.close()
def replaceByMap
— Helpers —############################
def validateAlignments.createMergeScript (   path,
  validations 
)

Definition at line 264 of file validateAlignments.py.

References python.multivaluedict.append(), createExtendedValidationScript(), createOfflineParJobsMergeScript(), createTrackSplitPlotScript(), if(), join(), and helperFunctions.replaceByMap().

Referenced by main().

265 def createMergeScript( path, validations ):
266  if(len(validations) == 0):
267  raise AllInOneError("Cowardly refusing to merge nothing!")
268 
269  repMap = validations[0].getRepMap() #FIXME - not nice this way
270  repMap.update({
271  "DownloadData":"",
272  "CompareAlignments":"",
273  "RunExtendedOfflineValidation":"",
274  "RunTrackSplitPlot":"",
275  "CMSSW_BASE": os.environ["CMSSW_BASE"],
276  "SCRAM_ARCH": os.environ["SCRAM_ARCH"],
277  "CMSSW_RELEASE_BASE": os.environ["CMSSW_RELEASE_BASE"],
278  })
279 
280  comparisonLists = {} # directory of lists containing the validations that are comparable
281  for validation in validations:
282  for referenceName in validation.filesToCompare:
283  validationName = "%s.%s"%(validation.__class__.__name__, referenceName)
284  validationName = validationName.split(".%s"%GenericValidation.defaultReferenceName )[0]
285  validationName = validationName.split("Preexisting")[-1]
286  if validationName in comparisonLists:
287  comparisonLists[ validationName ].append( validation )
288  else:
289  comparisonLists[ validationName ] = [ validation ]
290 
291  # introduced to merge individual validation outputs separately
292  # -> avoids problems with merge script
293  repMap["haddLoop"] = "mergeRetCode=0\n"
294  repMap["rmUnmerged"] = ("if [[ mergeRetCode -eq 0 ]]; then\n"
295  " echo -e \\n\"Merging succeeded, removing original files.\"\n")
296  repMap["copyMergeScripts"] = ""
297  repMap["mergeParallelFilePrefixes"] = ""
298 
299  anythingToMerge = []
300  for validationType in comparisonLists:
301  for validation in comparisonLists[validationType]:
302  if isinstance(validation, PreexistingValidation) or validation.NJobs == 1:
303  continue
304  if validationType not in anythingToMerge:
305  anythingToMerge += [validationType]
306  repMap["haddLoop"] += '\n\n\n\necho -e "\n\nMerging results from %s jobs"\n\n' % validationType
307  repMap["haddLoop"] = validation.appendToMerge(repMap["haddLoop"])
308  repMap["haddLoop"] += "tmpMergeRetCode=${?}\n"
309  repMap["haddLoop"] += ("if [[ tmpMergeRetCode -eq 0 ]]; then "
310  "cmsStage -f "
311  +validation.getRepMap()["finalOutputFile"]
312  +" "
313  +validation.getRepMap()["finalResultFile"]
314  +"; fi\n")
315  repMap["haddLoop"] += ("if [[ ${tmpMergeRetCode} -gt ${mergeRetCode} ]]; then "
316  "mergeRetCode=${tmpMergeRetCode}; fi\n")
317  for f in validation.getRepMap()["outputFiles"]:
318  longName = os.path.join("/store/caf/user/$USER/",
319  validation.getRepMap()["eosdir"], f)
320  repMap["rmUnmerged"] += " cmsRm "+longName+"\n"
321  repMap["rmUnmerged"] += ("else\n"
322  " echo -e \\n\"WARNING: Merging failed, unmerged"
323  " files won't be deleted.\\n"
324  "(Ignore this warning if merging was done earlier)\"\n"
325  "fi\n")
326 
327  if "OfflineValidation" in anythingToMerge:
328  repMap["mergeOfflineParJobsScriptPath"] = os.path.join(path, "TkAlOfflineJobsMerge.C")
329  createOfflineParJobsMergeScript( comparisonLists["OfflineValidation"],
330  repMap["mergeOfflineParJobsScriptPath"] )
331  repMap["copyMergeScripts"] += ("cp .oO[CMSSW_BASE]Oo./src/Alignment/OfflineValidation/scripts/merge_TrackerOfflineValidation.C .\n"
332  "rfcp %s .\n" % repMap["mergeOfflineParJobsScriptPath"])
333 
334  if anythingToMerge:
335  # DownloadData is the section which merges output files from parallel jobs
336  # it uses the file TkAlOfflineJobsMerge.C
337  repMap["DownloadData"] += replaceByMap( configTemplates.mergeParallelResults, repMap )
338  else:
339  repMap["DownloadData"] = ""
340 
341 
342  if "OfflineValidation" in comparisonLists:
343  repMap["extendedValScriptPath"] = os.path.join(path, "TkAlExtendedOfflineValidation.C")
344  createExtendedValidationScript(comparisonLists["OfflineValidation"],
345  repMap["extendedValScriptPath"],
346  "OfflineValidation")
347  repMap["RunExtendedOfflineValidation"] = \
348  replaceByMap(configTemplates.extendedValidationExecution, repMap)
349 
350  if "TrackSplittingValidation" in comparisonLists:
351  repMap["trackSplitPlotScriptPath"] = \
352  os.path.join(path, "TkAlTrackSplitPlot.C")
353  createTrackSplitPlotScript(comparisonLists["TrackSplittingValidation"],
354  repMap["trackSplitPlotScriptPath"] )
355  repMap["RunTrackSplitPlot"] = \
356  replaceByMap(configTemplates.trackSplitPlotExecution, repMap)
357 
358  repMap["CompareAlignments"] = "#run comparisons"
359  for validationId in comparisonLists:
360  compareStrings = [ val.getCompareStrings(validationId) for val in comparisonLists[validationId] ]
361  compareStringsPlain = [ val.getCompareStrings(validationId, plain=True) for val in comparisonLists[validationId] ]
362 
363  repMap.update({"validationId": validationId,
364  "compareStrings": " , ".join(compareStrings),
365  "compareStringsPlain": " ".join(compareStringsPlain) })
366 
367  repMap["CompareAlignments"] += \
368  replaceByMap(configTemplates.compareAlignmentsExecution, repMap)
369 
370  filePath = os.path.join(path, "TkAlMerge.sh")
371  theFile = open( filePath, "w" )
372  theFile.write( replaceByMap( configTemplates.mergeTemplate, repMap ) )
373  theFile.close()
374  os.chmod(filePath,0755)
375 
376  return filePath
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def replaceByMap
— Helpers —############################
if(conf.exists("allCellsPositionCalc"))
def validateAlignments.createOfflineParJobsMergeScript (   offlineValidationList,
  outFilePath 
)

Definition at line 230 of file validateAlignments.py.

References helperFunctions.replaceByMap().

Referenced by createMergeScript().

231 def createOfflineParJobsMergeScript(offlineValidationList, outFilePath):
232  repMap = offlineValidationList[0].getRepMap() # bit ugly since some special features are filled
233 
234  theFile = open( outFilePath, "w" )
235  theFile.write( replaceByMap( configTemplates.mergeOfflineParJobsTemplate ,repMap ) )
236  theFile.close()
def replaceByMap
— Helpers —############################
def validateAlignments.createTrackSplitPlotScript (   trackSplittingValidationList,
  outFilePath 
)

Definition at line 251 of file validateAlignments.py.

References helperFunctions.replaceByMap().

Referenced by createMergeScript().

252 def createTrackSplitPlotScript(trackSplittingValidationList, outFilePath):
253  repMap = trackSplittingValidationList[0].getRepMap() # bit ugly since some special features are filled
254  repMap[ "CMSSW_BASE" ] = os.environ['CMSSW_BASE']
255  repMap[ "trackSplitPlotInstantiation" ] = "" #give it a "" at first in order to get the initialisation back
256 
257  for validation in trackSplittingValidationList:
258  repMap[ "trackSplitPlotInstantiation" ] = validation.appendToExtendedValidation( repMap[ "trackSplitPlotInstantiation" ] )
259 
260  theFile = open( outFilePath, "w" )
261  # theFile.write( replaceByMap( configTemplates.trackSplitPlotTemplate ,repMap ) )
262  theFile.write( replaceByMap( configTemplates.trackSplitPlotTemplate ,repMap ) )
263  theFile.close()
def replaceByMap
— Helpers —############################
def validateAlignments.loadTemplates (   config)

Definition at line 377 of file validateAlignments.py.

References configTemplates.alternateTemplate().

Referenced by main().

378 def loadTemplates( config ):
379  if config.has_section("alternateTemplates"):
380  for templateName in config.options("alternateTemplates"):
381  if templateName == "AutoAlternates":
382  continue
383  newTemplateName = config.get("alternateTemplates", templateName )
384  #print "replacing default %s template by %s"%( templateName, newTemplateName)
385  configTemplates.alternateTemplate(templateName, newTemplateName)
386 
def alternateTemplate
### Alternate Templates ###
def validateAlignments.main (   argv = None)

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

Definition at line 388 of file validateAlignments.py.

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

389 def main(argv = None):
390  if argv == None:
391  argv = sys.argv[1:]
392  optParser = optparse.OptionParser()
393  optParser.description = """All-in-one Alignment Validation.
394 This will run various validation procedures either on batch queues or interactively.
395 If no name is given (-N parameter) a name containing time and date is created automatically.
396 To merge the outcome of all validation procedures run TkAlMerge.sh in your validation's directory.
397 """
398  optParser.add_option("-n", "--dryRun", dest="dryRun", action="store_true", default=False,
399  help="create all scripts and cfg File but do not start jobs (default=False)")
400  optParser.add_option( "--getImages", dest="getImages", action="store_true", default=True,
401  help="get all Images created during the process (default= True)")
402  defaultConfig = "TkAlConfig.ini"
403  optParser.add_option("-c", "--config", dest="config", default = defaultConfig,
404  help="configuration to use (default TkAlConfig.ini) this can be a comma-seperated list of all .ini file you want to merge", metavar="CONFIG")
405  optParser.add_option("-N", "--Name", dest="Name",
406  help="Name of this validation (default: alignmentValidation_DATE_TIME)", metavar="NAME")
407  optParser.add_option("-r", "--restrictTo", dest="restrictTo",
408  help="restrict validations to given modes (comma seperated) (default: no restriction)", metavar="RESTRICTTO")
409  optParser.add_option("-s", "--status", dest="crabStatus", action="store_true", default = False,
410  help="get the status of the crab jobs", metavar="STATUS")
411  optParser.add_option("-d", "--debug", dest="debugMode", action="store_true",
412  default = False,
413  help="run the tool to get full traceback of errors",
414  metavar="DEBUG")
415  optParser.add_option("-m", "--autoMerge", dest="autoMerge", action="store_true", default = False,
416  help="submit TkAlMerge.sh to run automatically when all jobs have finished (default=False)."
417  " Works only for batch jobs")
418 
419  (options, args) = optParser.parse_args(argv)
420 
421  if not options.restrictTo == None:
422  options.restrictTo = options.restrictTo.split(",")
423 
424  options.config = [ os.path.abspath( iniFile ) for iniFile in \
425  options.config.split( "," ) ]
426  config = BetterConfigParser()
427  outputIniFileSet = set( config.read( options.config ) )
428  failedIniFiles = [ iniFile for iniFile in options.config if iniFile not in outputIniFileSet ]
429 
430  # Check for missing ini file
431  if options.config == [ os.path.abspath( defaultConfig ) ]:
432  if ( not options.crabStatus ) and \
433  ( not os.path.exists( defaultConfig ) ):
434  raise AllInOneError, ( "Default 'ini' file '%s' not found!\n"
435  "You can specify another name with the "
436  "command line option '-c'/'--config'."
437  %( defaultConfig ))
438  else:
439  for iniFile in failedIniFiles:
440  if not os.path.exists( iniFile ):
441  raise AllInOneError, ( "'%s' does not exist. Please check for "
442  "typos in the filename passed to the "
443  "'-c'/'--config' option!"
444  %( iniFile ) )
445  else:
446  raise AllInOneError, ( "'%s' does exist, but parsing of the "
447  "content failed!" ) % iniFile
448 
449  # get the job name
450  if options.Name == None:
451  if not options.crabStatus:
452  options.Name = "alignmentValidation_%s"%(datetime.datetime.now().strftime("%y%m%d_%H%M%S"))
453  else:
454  existingValDirs = fnmatch.filter( os.walk( '.' ).next()[1],
455  "alignmentValidation_*" )
456  if len( existingValDirs ) > 0:
457  options.Name = existingValDirs[-1]
458  else:
459  print "Cannot guess last working directory!"
460  print ( "Please use the parameter '-N' or '--Name' to specify "
461  "the task for which you want a status report." )
462  return 1
463 
464  # set output path
465  outPath = os.path.abspath( options.Name )
466 
467  # Check status of submitted jobs and return
468  if options.crabStatus:
469  os.chdir( outPath )
470  crabLogDirs = fnmatch.filter( os.walk('.').next()[1], "crab.*" )
471  if len( crabLogDirs ) == 0:
472  print "Found no crab tasks for job name '%s'"%( options.Name )
473  return 1
474  theCrab = crabWrapper.CrabWrapper()
475  for crabLogDir in crabLogDirs:
476  print
477  print "*" + "=" * 78 + "*"
478  print ( "| Status report and output retrieval for:"
479  + " " * (77 - len( "Status report and output retrieval for:" ) )
480  + "|" )
481  taskName = crabLogDir.replace( "crab.", "" )
482  print "| " + taskName + " " * (77 - len( taskName ) ) + "|"
483  print "*" + "=" * 78 + "*"
484  print
485  crabOptions = { "-getoutput":"",
486  "-c": crabLogDir }
487  try:
488  theCrab.run( crabOptions )
489  except AllInOneError, e:
490  print "crab: No output retrieved for this task."
491  crabOptions = { "-status": "",
492  "-c": crabLogDir }
493  theCrab.run( crabOptions )
494  return
495 
496  general = config.getGeneral()
497  config.set("internals","workdir",os.path.join(general["workdir"],options.Name) )
498  config.set("general","datadir",os.path.join(general["datadir"],options.Name) )
499  config.set("general","logdir",os.path.join(general["logdir"],options.Name) )
500  config.set("general","eosdir",os.path.join("AlignmentValidation", general["eosdir"], options.Name) )
501 
502  if not os.path.exists( outPath ):
503  os.makedirs( outPath )
504  elif not os.path.isdir( outPath ):
505  raise AllInOneError,"the file %s is in the way rename the Job or move it away"%outPath
506 
507  # replace default templates by the ones specified in the "alternateTemplates" section
508  loadTemplates( config )
509 
510  #save backup configuration file
511  backupConfigFile = open( os.path.join( outPath, "usedConfiguration.ini" ) , "w" )
512  config.write( backupConfigFile )
513 
514  validations = []
515  for validation in config.items("validation"):
516  alignmentList = [validation[1]]
517  validationsToAdd = [(validation[0],alignment) \
518  for alignment in alignmentList]
519  validations.extend(validationsToAdd)
520  jobs = [ ValidationJob( validation, config, options) \
521  for validation in validations ]
522  map( lambda job: job.createJob(), jobs )
523  validations = [ job.getValidation() for job in jobs ]
524 
525  createMergeScript(outPath, validations)
526 
527  print
528  map( lambda job: job.runJob(), jobs )
529 
530  if options.autoMerge:
531  # if everything is done as batch job, also submit TkAlMerge.sh to be run
532  # after the jobs have finished
533  if ValidationJob.jobCount == ValidationJob.batchCount and config.getGeneral()["jobmode"].split(",")[0] == "lxBatch":
534  print "> Automatically merging jobs when they have ended"
535  repMap = {
536  "commands": config.getGeneral()["jobmode"].split(",")[1],
537  "jobName": "TkAlMerge",
538  "logDir": config.getGeneral()["logdir"],
539  "script": "TkAlMerge.sh",
540  "bsub": "/afs/cern.ch/cms/caf/scripts/cmsbsub",
541  "conditions": '"' + " && ".join(["ended(" + jobId + ")" for jobId in ValidationJob.batchJobIds]) + '"'
542  }
543  getCommandOutput2("%(bsub)s %(commands)s "
544  "-o %(logDir)s/%(jobName)s.stdout "
545  "-e %(logDir)s/%(jobName)s.stderr "
546  "-w %(conditions)s "
547  "%(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