CMS 3D CMS Logo

Classes | Functions
validateAlignments Namespace Reference

Classes

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

Functions

def createMergeScript (path, validations, options)
 
def loadTemplates (config)
 
def main (argv=None)
 — Main —############################ More...
 

Function Documentation

def validateAlignments.createMergeScript (   path,
  validations,
  options 
)

Definition at line 281 of file validateAlignments.py.

References mps_setup.append, reco.if(), and helperFunctions.replaceByMap().

Referenced by main().

281 def createMergeScript( path, validations, options ):
282  if(len(validations) == 0):
283  raise AllInOneError("Cowardly refusing to merge nothing!")
284 
285  config = validations[0].config
286  repMap = config.getGeneral()
287  repMap.update({
288  "DownloadData":"",
289  "CompareAlignments":"",
290  "RunValidationPlots":"",
291  "CMSSW_BASE": os.environ["CMSSW_BASE"],
292  "SCRAM_ARCH": os.environ["SCRAM_ARCH"],
293  "CMSSW_RELEASE_BASE": os.environ["CMSSW_RELEASE_BASE"],
294  })
295 
296  comparisonLists = {} # directory of lists containing the validations that are comparable
297  for validation in validations:
298  for referenceName in validation.filesToCompare:
299  validationtype = type(validation)
300  if isinstance(validationtype, PreexistingValidation):
301  #find the actual validationtype
302  for parentclass in validationtype.mro():
303  if not issubclass(parentclass, PreexistingValidation):
304  validationtype = parentclass
305  break
306  key = (validationtype, referenceName)
307  if key in comparisonLists:
308  comparisonLists[key].append(validation)
309  else:
310  comparisonLists[key] = [validation]
311 
312  # introduced to merge individual validation outputs separately
313  # -> avoids problems with merge script
314  repMap["doMerge"] = "mergeRetCode=0\n"
315  repMap["rmUnmerged"] = ("if [[ mergeRetCode -eq 0 ]]; then\n"
316  " echo -e \\n\"Merging succeeded, removing original files.\"\n")
317  repMap["beforeMerge"] = ""
318  repMap["mergeParallelFilePrefixes"] = ""
319  repMap["createResultsDirectory"]=""
320 
321 
322  anythingToMerge = []
323 
324 
325  #prepare dictionary containing handle objects for parallel merge batch jobs
326  if options.mergeOfflineParallel:
327  parallelMergeObjects={}
328  for (validationType, referencename), validations in comparisonLists.iteritems():
329  for validation in validations:
330  #parallel merging
331  if (isinstance(validation, PreexistingValidation)
332  or validation.NJobs == 1
333  or not isinstance(validation, ParallelValidation)):
334  continue
335  if options.mergeOfflineParallel and validationType.valType=='offline' and validation.jobmode.split(",")[0]=="lxBatch":
336  repMapTemp=repMap.copy()
337  if validationType not in anythingToMerge:
338  anythingToMerge += [validationType]
339  #create init script
340  fileName="TkAlMergeInit"
341  filePath = os.path.join(path, fileName+".sh")
342  theFile = open( filePath, "w" )
343  repMapTemp["createResultsDirectory"]="#!/bin/bash"
344  repMapTemp["createResultsDirectory"]+=replaceByMap(configTemplates.createResultsDirectoryTemplate, repMapTemp)
345  theFile.write( replaceByMap( configTemplates.createResultsDirectoryTemplate, repMapTemp ) )
346  theFile.close()
347  os.chmod(filePath,0o755)
348  #create handle
349  parallelMergeObjects["init"]=ParallelMergeJob(fileName, filePath,[])
350  #clear 'create result directory' code
351  repMapTemp["createResultsDirectory"]=""
352 
353  #edit repMapTmp as necessary:
354  #fill contents of mergeParallelResults
355  repMapTemp["beforeMerge"] += validationType.doInitMerge()
356  repMapTemp["doMerge"] += '\n\n\n\necho -e "\n\nMerging results from %s jobs with alignment %s"\n\n' % (validationType.valType,validation.alignmentToValidate.name)
357  repMapTemp["doMerge"] += validation.doMerge()
358  for f in validation.getRepMap()["outputFiles"]:
359  longName = os.path.join("/eos/cms/store/caf/user/$USER/",
360  validation.getRepMap()["eosdir"], f)
361  repMapTemp["rmUnmerged"] += " rm "+longName+"\n"
362 
363  repMapTemp["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  #fill mergeParallelResults area of mergeTemplate
370  repMapTemp["DownloadData"] = replaceByMap( configTemplates.mergeParallelResults, repMapTemp )
371  #fill runValidationPlots area of mergeTemplate
372  repMapTemp["RunValidationPlots"] = validationType.doRunPlots(validations)
373 
374  #create script file
375  fileName="TkAlMerge"+validation.alignmentToValidate.name
376  filePath = os.path.join(path, fileName+".sh")
377  theFile = open( filePath, "w" )
378  theFile.write( replaceByMap( configTemplates.mergeParallelOfflineTemplate, repMapTemp ) )
379  theFile.close()
380  os.chmod(filePath,0o755)
381  #create handle object
382  if "parallel" in parallelMergeObjects:
383  parallelMergeObjects["parallel"].append(ParallelMergeJob(fileName, filePath,[]))
384  else:
385  parallelMergeObjects["parallel"]=[ParallelMergeJob(fileName, filePath,[])]
386  continue
387 
388 
389  else:
390  if validationType not in anythingToMerge:
391  anythingToMerge += [validationType]
392  repMap["doMerge"] += '\n\n\n\necho -e "\n\nMerging results from %s jobs"\n\n' % validationType.valType
393  repMap["beforeMerge"] += validationType.doInitMerge()
394  repMap["doMerge"] += validation.doMerge()
395  for f in validation.getRepMap()["outputFiles"]:
396  longName = os.path.join("/eos/cms/store/caf/user/$USER/",
397  validation.getRepMap()["eosdir"], f)
398  repMap["rmUnmerged"] += " rm "+longName+"\n"
399 
400 
401 
402  repMap["rmUnmerged"] += ("else\n"
403  " echo -e \\n\"WARNING: Merging failed, unmerged"
404  " files won't be deleted.\\n"
405  "(Ignore this warning if merging was done earlier)\"\n"
406  "fi\n")
407 
408 
409 
410  if anythingToMerge:
411  repMap["DownloadData"] += replaceByMap( configTemplates.mergeParallelResults, repMap )
412  else:
413  repMap["DownloadData"] = ""
414 
415  repMap["RunValidationPlots"] = ""
416  for (validationType, referencename), validations in comparisonLists.iteritems():
417  if issubclass(validationType, ValidationWithPlots):
418  repMap["RunValidationPlots"] += validationType.doRunPlots(validations)
419 
420  repMap["CompareAlignments"] = "#run comparisons"
421  for (validationType, referencename), validations in comparisonLists.iteritems():
422  if issubclass(validationType, ValidationWithComparison):
423  repMap["CompareAlignments"] += validationType.doComparison(validations)
424 
425  #if user wants to merge parallely and if there are valid parallel scripts, create handle for plotting job and set merge script name accordingly
426  if options.mergeOfflineParallel and parallelMergeObjects!={}:
427  parallelMergeObjects["continue"]=ParallelMergeJob("TkAlMergeFinal",os.path.join(path, "TkAlMergeFinal.sh"),[])
428  filePath = os.path.join(path, "TkAlMergeFinal.sh")
429  #if not merging parallel, add code to create results directory and set merge script name accordingly
430  else:
431  repMap["createResultsDirectory"]=replaceByMap(configTemplates.createResultsDirectoryTemplate, repMap)
432  filePath = os.path.join(path, "TkAlMerge.sh")
433 
434 
435  #filePath = os.path.join(path, "TkAlMerge.sh")
436  theFile = open( filePath, "w" )
437  theFile.write( replaceByMap( configTemplates.mergeTemplate, repMap ) )
438  theFile.close()
439  os.chmod(filePath,0o755)
440 
441  if options.mergeOfflineParallel:
442  return {'TkAlMerge.sh':filePath, 'parallelMergeObjects':parallelMergeObjects}
443  else:
444  return filePath
445 
def createMergeScript(path, validations, options)
— Classes —############################
def replaceByMap(target, the_map)
— Helpers —############################
if(dp >Float(M_PI)) dp-
def validateAlignments.loadTemplates (   config)

Definition at line 446 of file validateAlignments.py.

References configTemplates.alternateTemplate().

Referenced by main().

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

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

Definition at line 457 of file validateAlignments.py.

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

457 def main(argv = None):
458  if argv == None:
459  argv = sys.argv[1:]
460  optParser = optparse.OptionParser()
461  optParser.description = """All-in-one Alignment Validation.
462 This will run various validation procedures either on batch queues or interactively.
463 If no name is given (-N parameter) a name containing time and date is created automatically.
464 To merge the outcome of all validation procedures run TkAlMerge.sh in your validation's directory.
465 """
466  optParser.add_option("-n", "--dryRun", dest="dryRun", action="store_true", default=False,
467  help="create all scripts and cfg File but do not start jobs (default=False)")
468  optParser.add_option( "--getImages", dest="getImages", action="store_true", default=True,
469  help="get all Images created during the process (default= True)")
470  defaultConfig = "TkAlConfig.ini"
471  optParser.add_option("-c", "--config", dest="config", default = defaultConfig,
472  help="configuration to use (default TkAlConfig.ini) this can be a comma-seperated list of all .ini file you want to merge", metavar="CONFIG")
473  optParser.add_option("-N", "--Name", dest="Name",
474  help="Name of this validation (default: alignmentValidation_DATE_TIME)", metavar="NAME")
475  optParser.add_option("-r", "--restrictTo", dest="restrictTo",
476  help="restrict validations to given modes (comma seperated) (default: no restriction)", metavar="RESTRICTTO")
477  optParser.add_option("-s", "--status", dest="crabStatus", action="store_true", default = False,
478  help="get the status of the crab jobs", metavar="STATUS")
479  optParser.add_option("-d", "--debug", dest="debugMode", action="store_true",
480  default = False,
481  help="run the tool to get full traceback of errors",
482  metavar="DEBUG")
483  optParser.add_option("-m", "--autoMerge", dest="autoMerge", action="store_true", default = False,
484  help="submit TkAlMerge.sh to run automatically when all jobs have finished (default=False)."
485  " Works only for batch jobs")
486  optParser.add_option("--mergeOfflineParallel", dest="mergeOfflineParallel", action="store_true", default = False,
487  help="Enable parallel merging of offline data. Best used with -m option. Only works with lxBatch-jobmode", metavar="MERGE_PARALLEL")
488 
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("internals","scriptsdir",outPath)
570  config.set("general","datadir",os.path.join(general["datadir"],options.Name) )
571  config.set("general","logdir",os.path.join(general["logdir"],options.Name) )
572  config.set("general","eosdir",os.path.join("AlignmentValidation", general["eosdir"], options.Name) )
573 
574  if not os.path.exists( outPath ):
575  os.makedirs( outPath )
576  elif not os.path.isdir( outPath ):
577  raise AllInOneError("the file %s is in the way rename the Job or move it away"%outPath)
578 
579  # replace default templates by the ones specified in the "alternateTemplates" section
580  loadTemplates( config )
581 
582  #save backup configuration file
583  backupConfigFile = open( os.path.join( outPath, "usedConfiguration.ini" ) , "w" )
584  config.write( backupConfigFile )
585 
586  #copy proxy, if there is one
587  try:
588  proxyexists = int(getCommandOutput2("voms-proxy-info --timeleft")) > 10
589  except RuntimeError:
590  proxyexists = False
591 
592  if proxyexists:
593  shutil.copyfile(getCommandOutput2("voms-proxy-info --path").strip(), os.path.join(outPath, ".user_proxy"))
594 
595  validations = []
596  for validation in config.items("validation"):
597  alignmentList = [validation[1]]
598  validationsToAdd = [(validation[0],alignment) \
599  for alignment in alignmentList]
600  validations.extend(validationsToAdd)
601  jobs = [ ValidationJob( validation, config, options) \
602  for validation in validations ]
603  for job in jobs:
604  if job.needsproxy and not proxyexists:
605  raise AllInOneError("At least one job needs a grid proxy, please init one.")
606  map( lambda job: job.createJob(), jobs )
607  validations = [ job.getValidation() for job in jobs ]
608 
609  if options.mergeOfflineParallel:
610  parallelMergeObjects=createMergeScript(outPath, validations, options)['parallelMergeObjects']
611  else:
612  createMergeScript(outPath, validations, options)
613 
614 
615  print
616  map( lambda job: job.runJob(), jobs )
617 
618  if options.autoMerge and ValidationJob.jobCount == ValidationJob.batchCount and config.getGeneral()["jobmode"].split(",")[0] == "lxBatch":
619  print "> Automatically merging jobs when they have ended"
620  # if everything is done as batch job, also submit TkAlMerge.sh to be run
621  # after the jobs have finished
622 
623  #if parallel merge scripts: manage dependencies
624  if options.mergeOfflineParallel and parallelMergeObjects!={}:
625  initID=parallelMergeObjects["init"].runJob(config).split("<")[1].split(">")[0]
626  parallelIDs=[]
627  for parallelMergeScript in parallelMergeObjects["parallel"]:
628  parallelMergeScript.addDependency(initID)
629  for job in jobs:
630  if isinstance(job.validation, OfflineValidation) and "TkAlMerge"+job.validation.alignmentToValidate.name==parallelMergeScript.name:
631  parallelMergeScript.addDependency(job.JobId)
632  parallelIDs.append(parallelMergeScript.runJob(config).split("<")[1].split(">")[0])
633  parallelMergeObjects["continue"].addDependency(parallelIDs)
634  parallelMergeObjects["continue"].addDependency(ValidationJob.batchJobIds)
635  parallelMergeObjects["continue"].runJob(config)
636 
637 
638 
639 
640  else:
641  repMap = {
642  "commands": config.getGeneral()["jobmode"].split(",")[1],
643  "jobName": "TkAlMerge",
644  "logDir": config.getGeneral()["logdir"],
645  "script": "TkAlMerge.sh",
646  "bsub": "/afs/cern.ch/cms/caf/scripts/cmsbsub",
647  "conditions": '"' + " && ".join(["ended(" + jobId + ")" for jobId in ValidationJob.batchJobIds]) + '"'
648  }
649  for ext in ("stdout", "stderr", "stdout.gz", "stderr.gz"):
650  oldlog = "%(logDir)s/%(jobName)s."%repMap + ext
651  if os.path.exists(oldlog):
652  os.remove(oldlog)
653 
654  #issue job
655  getCommandOutput2("%(bsub)s %(commands)s "
656  "-o %(logDir)s/%(jobName)s.stdout "
657  "-e %(logDir)s/%(jobName)s.stderr "
658  "-w %(conditions)s "
659  "%(logDir)s/%(script)s"%repMap)
660 
def main(argv=None)
— Main —############################
def createMergeScript(path, validations, options)
def getCommandOutput2(command)
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
double split
Definition: MVATrainer.cc:139