CMS 3D CMS Logo

Classes | Functions
validateAlignments Namespace Reference

Classes

class  ValidationBase
 — Classes —############################ More...
 
class  ValidationJob
 
class  ValidationJobMultiIOV
 

Functions

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

Function Documentation

def validateAlignments.createMergeScript (   path,
  validations,
  options 
)

Definition at line 479 of file validateAlignments.py.

References mps_setup.append, genParticles_cff.map, helperFunctions.replaceByMap(), and update.

Referenced by main().

479 def createMergeScript( path, validations, options ):
480  if(len(validations) == 0):
481  raise AllInOneError("Cowardly refusing to merge nothing!")
482 
483  repMap = {}
484 
485  comparisonLists = {} # directory of lists containing the validations that are comparable
486  for validation in validations:
487  if validation.config.has_section("IOV"):
488  iov = validation.config.get("IOV", "iov")
489  validation.defaultReferenceName = iov
490  for referenceName in validation.filesToCompare:
491  validationtype = type(validation)
492  validationName = validation.name
493  if validation.config.has_section("IOV") and (referenceName == "Tracker_defaultRange" or referenceName == "Tracker_autoRange"):
494  referenceName = iov
495  if issubclass(validationtype, PreexistingValidation):
496  validationName = validation.originalValName
497  #find the actual validationtype
498  for parentclass in validationtype.mro():
499  if not issubclass(parentclass, PreexistingValidation):
500  validationtype = parentclass
501  break
502  key = (validationtype, validationName, referenceName)
503 
504 
505  if key in comparisonLists:
506  comparisonLists[key].append(validation)
507  else:
508  comparisonLists[key] = [validation]
509  repMap[key] = validation.config.getGeneral()
510  repMap[key].update({
511  "DownloadData":"",
512  "CompareAlignments":"",
513  "RunValidationPlots":"",
514  "CMSSW_BASE": os.environ["CMSSW_BASE"],
515  "SCRAM_ARCH": os.environ["SCRAM_ARCH"],
516  "CMSSW_RELEASE_BASE": os.environ["CMSSW_RELEASE_BASE"],
517  })
518 
519  # introduced to merge individual validation outputs separately
520  # -> avoids problems with merge script
521  repMap[key]["doMerge"] = "mergeRetCode=0\n"
522  repMap[key]["rmUnmerged"] = ("if [[ mergeRetCode -eq 0 ]]; then\n"
523  " echo -e \\n\"Merging succeeded, removing original files.\"\n")
524  repMap[key]["beforeMerge"] = ""
525  repMap[key]["mergeParallelFilePrefixes"] = ""
526  repMap[key]["createResultsDirectory"]=""
527 
528  #print("comparisonLists")
529  #pprint.pprint(comparisonLists)
530  anythingToMerge = []
531 
532  for (validationtype, validationName, referenceName), validations in comparisonLists.iteritems():
533  #pprint.pprint("validations")
534  #pprint.pprint(validations)
535  globalDictionaries.plottingOptions = {}
536  map( lambda validation: validation.getRepMap(), validations )
537  #plotInfo = "plots:offline"
538  #allPlotInfo = dict(validations[0].config.items(plotInfo))
539  #repMap[(validationtype, validationName, referenceName)].update(allPlotInfo)
540 
541  for validation in validations:
542  validation.getRepMap()
543  #pprint.pprint("validation in validations")
544  #pprint.pprint(validation)
545  #parallel merging
546  if not (isinstance(validation, PreexistingValidation) or validation.NJobs == 1 or not isinstance(validation, ParallelValidation)):
547  if (validationtype, validationName, referenceName) not in anythingToMerge:
548  anythingToMerge.append((validationtype, validationName, referenceName))
549  repMap[(validationtype, validationName, referenceName)]["doMerge"] += '\n\n\n\necho -e "\n\nMerging results from %s jobs"\n\n' % validationtype.valType
550  repMap[(validationtype, validationName, referenceName)]["beforeMerge"] += validationtype.doInitMerge()
551  repMap[(validationtype, validationName, referenceName)]["doMerge"] += validation.doMerge()
552  for f in validation.getRepMap()["outputFiles"]:
553  longName = os.path.join("/eos/cms/store/group/alca_trackeralign/AlignmentValidation/",
554  validation.getRepMap()["eosdir"], f)
555  repMap[(validationtype, validationName, referenceName)]["rmUnmerged"] += " rm "+longName+"\n"
556 
557  repMap[(validationtype, validationName, referenceName)]["rmUnmerged"] += ("else\n"
558  " echo -e \\n\"WARNING: Merging failed, unmerged"
559  " files won't be deleted.\\n"
560  "(Ignore this warning if merging was done earlier)\"\n"
561  "fi\n")
562 
563 
564  if anythingToMerge:
565  repMap[(validationtype, validationName, referenceName)]["DownloadData"] += replaceByMap( configTemplates.mergeParallelResults, repMap[(validationtype, validationName, referenceName)] )
566  else:
567  repMap[(validationtype, validationName, referenceName)]["DownloadData"] = ""
568 
569  repMap[(validationtype, validationName, referenceName)]["RunValidationPlots"] = ""
570  repMap[(validationtype, validationName, referenceName)]["plottingscriptpath"] = ""
571  if issubclass(validationtype, ValidationWithPlots):
572  repMap[(validationtype, validationName, referenceName)]["RunValidationPlots"] = validationtype.doRunPlots(validations)
573 
574  repMap[(validationtype, validationName, referenceName)]["CompareAlignments"] = "#run comparisons"
575  if issubclass(validationtype, ValidationWithComparison):
576  repMap[(validationtype, validationName, referenceName)]["CompareAlignments"] += validationtype.doComparison(validations)
577 
578  #if not merging parallel, add code to create results directory and set merge script name accordingly
579  if validations[0].config.has_section("IOV"):
580  repMap[(validationtype, validationName, referenceName)]["createResultsDirectory"]=replaceByMap(configTemplates.createResultsDirectoryTemplate, repMap[(validationtype, validationName, referenceName)])
581  filePath = os.path.join(repMap[(validationtype, validationName, referenceName)]["scriptsdir"], "TkAlMerge.sh")
582  else:
583  repMap[(validationtype, validationName, referenceName)]["createResultsDirectory"]=replaceByMap(configTemplates.createResultsDirectoryTemplate, repMap[(validationtype, validationName, referenceName)])
584  filePath = os.path.join(path, "TkAlMerge.sh")
585 
586  theFile = open( filePath, "w" )
587  theFile.write( replaceByMap( configTemplates.mergeTemplate, repMap[(validationtype, validationName, referenceName)]) )
588  theFile.close()
589  os.chmod(filePath,0o755)
590 
def createMergeScript(path, validations, options)
def replaceByMap(target, the_map)
— Helpers —############################
#define update(a, b)
def validateAlignments.flatten (   l)

Definition at line 600 of file validateAlignments.py.

Referenced by python.rootplot.root2matplotlib.Hist2D.box(), python.rootplot.core.divide_axes(), and main().

600 def flatten(l):
601  flattenList = []
602 
603  for item in l:
604  if type(item) == list:
605  flattenList.extend(flatten(item))
606 
607  else:
608  flattenList.append(item)
609 
610  return flattenList
611 
612 
def validateAlignments.loadTemplates (   config)

Definition at line 591 of file validateAlignments.py.

References configTemplates.alternateTemplate().

Referenced by main().

591 def loadTemplates( config ):
592  if config.has_section("alternateTemplates"):
593  for templateName in config.options("alternateTemplates"):
594  if templateName == "AutoAlternates":
595  continue
596  newTemplateName = config.get("alternateTemplates", templateName )
597  #print "replacing default %s template by %s"%( templateName, newTemplateName)
598  configTemplates.alternateTemplate(templateName, newTemplateName)
599 
def alternateTemplate(templateName, alternateTemplateName)
Alternate Templates ###
def validateAlignments.main (   argv = None)

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

Definition at line 614 of file validateAlignments.py.

References createMergeScript(), cmsRelvalreport.exit, flatten(), helperFunctions.getCommandOutput2(), createfilelist.int, loadTemplates(), genParticles_cff.map, GetRecoTauVFromDQM_MC_cff.next, edm.print(), str, and digitizers_cfi.strip.

614 def main(argv = None):
615  if argv == None:
616  argv = sys.argv[1:]
617  optParser = optparse.OptionParser()
618  optParser.description = """All-in-one Alignment Validation.
619 This will run various validation procedures either on batch queues or interactively.
620 If no name is given (-N parameter) a name containing time and date is created automatically.
621 To merge the outcome of all validation procedures run TkAlMerge.sh in your validation's directory.
622 """
623  optParser.add_option("-n", "--dryRun", dest="dryRun", action="store_true", default=False,
624  help="create all scripts and cfg File but do not start jobs (default=False)")
625  optParser.add_option( "--getImages", dest="getImages", action="store_true", default=True,
626  help="get all Images created during the process (default= True)")
627  defaultConfig = "TkAlConfig.ini"
628  optParser.add_option("-c", "--config", dest="config", default = defaultConfig,
629  help="configuration to use (default TkAlConfig.ini) this can be a comma-seperated list of all .ini file you want to merge", metavar="CONFIG")
630  optParser.add_option("-N", "--Name", dest="Name",
631  help="Name of this validation (default: alignmentValidation_DATE_TIME)", metavar="NAME")
632  optParser.add_option("-r", "--restrictTo", dest="restrictTo",
633  help="restrict validations to given modes (comma seperated) (default: no restriction)", metavar="RESTRICTTO")
634  optParser.add_option("-d", "--debug", dest="debugMode", action="store_true",
635  default = False,
636  help="run the tool to get full traceback of errors",
637  metavar="DEBUG")
638 
639 
640  (options, args) = optParser.parse_args(argv)
641 
642 
643  if not options.restrictTo == None:
644  options.restrictTo = options.restrictTo.split(",")
645 
646  options.config = [ os.path.abspath( iniFile ) for iniFile in \
647  options.config.split( "," )]
648 
649  config = BetterConfigParser()
650  outputIniFileSet = set( config.read( options.config ) )
651  failedIniFiles = [ iniFile for iniFile in options.config if iniFile not in outputIniFileSet ]
652 
653  # Check for missing ini file
654  if options.config == [ os.path.abspath( defaultConfig ) ]:
655  if ( not os.path.exists( defaultConfig ) ):
656  raise AllInOneError( "Default 'ini' file '%s' not found!\n"
657  "You can specify another name with the "
658  "command line option '-c'/'--config'."
659  %( defaultConfig ))
660  else:
661  for iniFile in failedIniFiles:
662  if not os.path.exists( iniFile ):
663  raise AllInOneError( "'%s' does not exist. Please check for "
664  "typos in the filename passed to the "
665  "'-c'/'--config' option!"
666  %( iniFile ))
667  else:
668  raise AllInOneError(( "'%s' does exist, but parsing of the "
669  "content failed!" ) % iniFile)
670 
671  # get the job name
672  if options.Name == None:
673  existingValDirs = fnmatch.filter( os.walk( '.' ).next()[1],
674  "alignmentValidation_*" )
675  if len( existingValDirs ) > 0:
676  options.Name = existingValDirs[-1]
677  else:
678  print("Cannot guess last working directory!")
679  print ( "Please use the parameter '-N' or '--Name' to specify "
680  "the task for which you want a status report." )
681  return 1
682 
683  # set output path
684  outPath = os.path.abspath( options.Name )
685 
686  general = config.getGeneral()
687  config.set("internals","workdir",os.path.join(general["workdir"],options.Name) )
688  config.set("internals","scriptsdir",outPath)
689  config.set("general","datadir",os.path.join(general["datadir"],options.Name) )
690  config.set("general","logdir",os.path.join(general["logdir"],options.Name) )
691  config.set("general","eosdir",os.path.join("AlignmentValidation", general["eosdir"], options.Name) )
692 
693  if not os.path.exists( outPath ):
694  os.makedirs( outPath )
695  elif not os.path.isdir( outPath ):
696  raise AllInOneError("the file %s is in the way rename the Job or move it away"%outPath)
697 
698  # replace default templates by the ones specified in the "alternateTemplates" section
699  loadTemplates( config )
700 
701  #save backup configuration file
702  backupConfigFile = open( os.path.join( outPath, "usedConfiguration.ini" ) , "w" )
703  config.write( backupConfigFile )
704 
705  #copy proxy, if there is one
706  try:
707  proxyexists = int(getCommandOutput2("voms-proxy-info --timeleft")) > 10
708  except RuntimeError:
709  proxyexists = False
710 
711  if proxyexists:
712  shutil.copyfile(getCommandOutput2("voms-proxy-info --path").strip(), os.path.join(outPath, ".user_proxy"))
713 
714  validations = []
715  jobs = []
716  for validation in config.items("validation"):
717  alignmentList = [validation[1]]
718  validationsToAdd = [(validation[0],alignment) \
719  for alignment in alignmentList]
720  validations.extend(validationsToAdd)
721 
722 
723  for validation in validations:
724  job = ValidationJobMultiIOV(validation, config, options, outPath, len(validations))
725  if (job.optionMultiIOV == True):
726  jobs.extend(job)
727  else:
728  jobs.extend( ValidationJob(validation, config, options, 1) )
729 
730  for job in jobs:
731  if job.needsproxy and not proxyexists:
732  raise AllInOneError("At least one job needs a grid proxy, please init one.")
733 
734  map( lambda job: job.createJob(), jobs )
735 
736  validations = [ job.getValidation() for job in jobs ]
737  validations = flatten(validations)
738 
739  createMergeScript(outPath, validations, options)
740 
741 
742  map( lambda job: job.runJob(), jobs )
743 
744  if options.dryRun:
745  pass
746  else:
747  ValidationJobMultiIOV.runCondorJobs(outPath)
748 
749 
def main(argv=None)
— Main —############################
def createMergeScript(path, validations, options)
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def getCommandOutput2(command)