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

◆ createMergeScript()

def validateAlignments.createMergeScript (   path,
  validations,
  options 
)

Definition at line 485 of file validateAlignments.py.

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

Referenced by main().

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

◆ flatten()

def validateAlignments.flatten (   l)

Definition at line 606 of file validateAlignments.py.

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

606 def flatten(l):
607  flattenList = []
608 
609  for item in l:
610  if type(item) == list:
611  flattenList.extend(flatten(item))
612 
613  else:
614  flattenList.append(item)
615 
616  return flattenList
617 
618 

◆ loadTemplates()

def validateAlignments.loadTemplates (   config)

Definition at line 597 of file validateAlignments.py.

References configTemplates.alternateTemplate().

Referenced by main().

597 def loadTemplates( config ):
598  if config.has_section("alternateTemplates"):
599  for templateName in config.options("alternateTemplates"):
600  if templateName == "AutoAlternates":
601  continue
602  newTemplateName = config.get("alternateTemplates", templateName )
603  #print "replacing default %s template by %s"%( templateName, newTemplateName)
604  configTemplates.alternateTemplate(templateName, newTemplateName)
605 
def alternateTemplate(templateName, alternateTemplateName)
Alternate Templates ###

◆ main()

def validateAlignments.main (   argv = None)

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

Definition at line 620 of file validateAlignments.py.

References createMergeScript(), edm.decode(), beamvalidation.exit(), flatten(), helperFunctions.getCommandOutput2(), createfilelist.int, loadTemplates(), GetRecoTauVFromDQM_MC_cff.next, print(), submitPVValidationJobs.split(), str, and digitizers_cfi.strip.

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