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 227 of file validateAlignments.py.

References helperFunctions.replaceByMap().

Referenced by createMergeScript().

228 def createExtendedValidationScript(offlineValidationList, outFilePath, resultPlotFile):
229  repMap = offlineValidationList[0].getRepMap() # bit ugly since some special features are filled
230  repMap[ "CMSSW_BASE" ] = os.environ['CMSSW_BASE']
231  repMap[ "resultPlotFile" ] = resultPlotFile
232  repMap[ "extendedInstantiation" ] = "" #give it a "" at first in order to get the initialisation back
233 
234  for validation in offlineValidationList:
235  repMap[ "extendedInstantiation" ] = validation.appendToExtendedValidation( repMap[ "extendedInstantiation" ] )
236 
237  theFile = open( outFilePath, "w" )
238  # theFile.write( replaceByMap( configTemplates.extendedValidationTemplate ,repMap ) )
239  theFile.write( replaceByMap( configTemplates.extendedValidationTemplate ,repMap ) )
240  theFile.close()
def replaceByMap
— Helpers —############################
def validateAlignments.createMergeScript (   path,
  validations 
)

Definition at line 254 of file validateAlignments.py.

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

Referenced by main().

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

References helperFunctions.replaceByMap().

Referenced by createMergeScript().

221 def createOfflineParJobsMergeScript(offlineValidationList, outFilePath):
222  repMap = offlineValidationList[0].getRepMap() # bit ugly since some special features are filled
223 
224  theFile = open( outFilePath, "w" )
225  theFile.write( replaceByMap( configTemplates.mergeOfflineParJobsTemplate ,repMap ) )
226  theFile.close()
def replaceByMap
— Helpers —############################
def validateAlignments.createTrackSplitPlotScript (   trackSplittingValidationList,
  outFilePath 
)

Definition at line 241 of file validateAlignments.py.

References helperFunctions.replaceByMap().

Referenced by createMergeScript().

242 def createTrackSplitPlotScript(trackSplittingValidationList, outFilePath):
243  repMap = trackSplittingValidationList[0].getRepMap() # bit ugly since some special features are filled
244  repMap[ "CMSSW_BASE" ] = os.environ['CMSSW_BASE']
245  repMap[ "trackSplitPlotInstantiation" ] = "" #give it a "" at first in order to get the initialisation back
246 
247  for validation in trackSplittingValidationList:
248  repMap[ "trackSplitPlotInstantiation" ] = validation.appendToExtendedValidation( repMap[ "trackSplitPlotInstantiation" ] )
249 
250  theFile = open( outFilePath, "w" )
251  # theFile.write( replaceByMap( configTemplates.trackSplitPlotTemplate ,repMap ) )
252  theFile.write( replaceByMap( configTemplates.trackSplitPlotTemplate ,repMap ) )
253  theFile.close()
def replaceByMap
— Helpers —############################
def validateAlignments.loadTemplates (   config)

Definition at line 363 of file validateAlignments.py.

References configTemplates.alternateTemplate().

Referenced by main().

364 def loadTemplates( config ):
365  if config.has_section("alternateTemplates"):
366  for templateName in config.options("alternateTemplates"):
367  if templateName == "AutoAlternates":
368  continue
369  newTemplateName = config.get("alternateTemplates", templateName )
370  #print "replacing default %s template by %s"%( templateName, newTemplateName)
371  configTemplates.alternateTemplate(templateName, newTemplateName)
372 
def alternateTemplate
### Alternate Templates ###
def validateAlignments.main (   argv = None)

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

Definition at line 374 of file validateAlignments.py.

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

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