CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
validateAlignments.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 #test execute: export CMSSW_BASE=/tmp/CMSSW && ./validateAlignments.py -c defaultCRAFTValidation.ini,test.ini -n -N test
3 import os
4 import sys
5 import optparse
6 import datetime
7 import shutil
8 import fnmatch
9 
10 import Alignment.OfflineValidation.TkAlAllInOneTool.configTemplates \
11  as configTemplates
12 import Alignment.OfflineValidation.TkAlAllInOneTool.crabWrapper as crabWrapper
13 from Alignment.OfflineValidation.TkAlAllInOneTool.TkAlExceptions \
14  import AllInOneError
15 from Alignment.OfflineValidation.TkAlAllInOneTool.helperFunctions \
16  import replaceByMap, getCommandOutput2, addIndex
17 from Alignment.OfflineValidation.TkAlAllInOneTool.betterConfigParser \
18  import BetterConfigParser
19 from Alignment.OfflineValidation.TkAlAllInOneTool.alignment import Alignment
20 
21 from Alignment.OfflineValidation.TkAlAllInOneTool.genericValidation \
22  import GenericValidation
23 from Alignment.OfflineValidation.TkAlAllInOneTool.geometryComparison \
24  import GeometryComparison
25 from Alignment.OfflineValidation.TkAlAllInOneTool.offlineValidation \
26  import OfflineValidation, OfflineValidationDQM
27 from Alignment.OfflineValidation.TkAlAllInOneTool.monteCarloValidation \
28  import MonteCarloValidation
29 from Alignment.OfflineValidation.TkAlAllInOneTool.trackSplittingValidation \
30  import TrackSplittingValidation
31 from Alignment.OfflineValidation.TkAlAllInOneTool.zMuMuValidation \
32  import ZMuMuValidation
33 from Alignment.OfflineValidation.TkAlAllInOneTool.preexistingValidation \
34  import *
35 import Alignment.OfflineValidation.TkAlAllInOneTool.globalDictionaries \
36  as globalDictionaries
37 
38 
39 ####################--- Classes ---############################
41 
42  # these count the jobs of different varieties that are being run
43  crabCount = 0
44  interactCount = 0
45  batchCount = 0
46  batchJobIds = []
47  jobCount = 0
48 
49  def __init__( self, validation, config, options ):
50  if validation[1] == "":
51  # intermediate syntax
52  valString = validation[0].split( "->" )[0]
53  alignments = validation[0].split( "->" )[1]
54  # force user to use the normal syntax
55  if "->" in validation[0]:
56  msg = ("Instead of using the intermediate syntax\n'"
57  +valString.strip()+"-> "+alignments.strip()
58  +":'\nyou have to use the now fully supported syntax \n'"
59  +valString.strip()+": "
60  +alignments.strip()+"'.")
61  raise AllInOneError(msg)
62  else:
63  valString = validation[0]
64  alignments = validation[1]
65  valString = valString.split()
66  self.__valType = valString[0]
67  self.__valName = valString[1]
68  self.__commandLineOptions = options
69  self.__config = config
70  self.__preexisting = ("preexisting" in self.__valType)
71  if self.__valType[0] == "*":
72  self.__valType = self.__valType[1:]
73  self.__preexisting = True
74 
75  # workaround for intermediate parallel version
76  if self.__valType == "offlineParallel":
77  print ("offlineParallel and offline are now the same. To run an offline parallel validation,\n"
78  "just set parallelJobs to something > 1. There is no reason to call it offlineParallel anymore.")
79  self.__valType = "offline"
80  section = self.__valType + ":" + self.__valName
81  if not self.__config.has_section( section ):
82  raise AllInOneError, ("Validation '%s' of type '%s' is requested in"
83  " '[validation]' section, but is not defined."
84  "\nYou have to add a '[%s]' section."
85  %( self.__valName, self.__valType, section ))
86  self.validation = self.__getValidation( self.__valType, self.__valName,
87  alignments, self.__config,
88  options )
89 
90  def __getValidation( self, valType, name, alignments, config, options ):
91  if valType == "compare":
92  alignmentsList = alignments.split( "," )
93  firstAlignList = alignmentsList[0].split()
94  firstAlignName = firstAlignList[0].strip()
95  if firstAlignName == "IDEAL":
96  raise AllInOneError, ("'IDEAL' has to be the second (reference)"
97  " alignment in 'compare <val_name>: "
98  "<alignment> <reference>'.")
99  if len( firstAlignList ) > 1:
100  firstRun = firstAlignList[1]
101  else:
102  firstRun = "1"
103  firstAlign = Alignment( firstAlignName, self.__config, firstRun )
104  firstAlignName = firstAlign.name
105  secondAlignList = alignmentsList[1].split()
106  secondAlignName = secondAlignList[0].strip()
107  if len( secondAlignList ) > 1:
108  secondRun = secondAlignList[1]
109  else:
110  secondRun = "1"
111  if secondAlignName == "IDEAL":
112  secondAlign = secondAlignName
113  else:
114  secondAlign = Alignment( secondAlignName, self.__config,
115  secondRun )
116  secondAlignName = secondAlign.name
117 
118  validation = GeometryComparison( name, firstAlign, secondAlign,
119  self.__config,
120  self.__commandLineOptions.getImages)
121  elif valType == "offline":
122  validation = OfflineValidation( name,
123  Alignment( alignments.strip(), self.__config ), self.__config )
124  elif valType == "preexistingoffline":
125  validation = PreexistingOfflineValidation(name, self.__config)
126  elif valType == "offlineDQM":
127  validation = OfflineValidationDQM( name,
128  Alignment( alignments.strip(), self.__config ), self.__config )
129  elif valType == "mcValidate":
130  validation = MonteCarloValidation( name,
131  Alignment( alignments.strip(), self.__config ), self.__config )
132  elif valType == "preexistingmcValidate":
133  validation = PreexistingMonteCarloValidation(name, self.__config)
134  elif valType == "split":
135  validation = TrackSplittingValidation( name,
136  Alignment( alignments.strip(), self.__config ), self.__config )
137  elif valType == "preexistingsplit":
138  validation = PreexistingTrackSplittingValidation(name, self.__config)
139  elif valType == "zmumu":
140  validation = ZMuMuValidation( name,
141  Alignment( alignments.strip(), self.__config ), self.__config )
142  else:
143  raise AllInOneError, "Unknown validation mode '%s'"%valType
144  return validation
145 
146  def __createJob( self, jobMode, outpath ):
147  """This private method creates the needed files for the validation job.
148  """
149  self.validation.createConfiguration( outpath )
150  if self.__preexisting:
151  return
152  self.__scripts = sum([addIndex(script, self.validation.NJobs) for script in self.validation.createScript( outpath )], [])
153  if jobMode.split( ',' )[0] == "crab":
154  self.validation.createCrabCfg( outpath )
155  return None
156 
157  def createJob(self):
158  """This is the method called to create the job files."""
159  self.__createJob( self.validation.jobmode,
160  os.path.abspath( self.__commandLineOptions.Name) )
161 
162  def runJob( self ):
163  if self.__preexisting:
164  log = "> " + self.validation.name + " is already validated."
165  print log
166  return log
167 
168  general = self.__config.getGeneral()
169  log = ""
170  for script in self.__scripts:
171  name = os.path.splitext( os.path.basename( script) )[0]
172  ValidationJob.jobCount += 1
173  if self.__commandLineOptions.dryRun:
174  print "%s would run: %s"%( name, os.path.basename( script) )
175  continue
176  log = "> Validating "+name
177  print "> Validating "+name
178  if self.validation.jobmode == "interactive":
179  log += getCommandOutput2( script )
180  ValidationJob.interactCount += 1
181  elif self.validation.jobmode.split(",")[0] == "lxBatch":
182  repMap = {
183  "commands": self.validation.jobmode.split(",")[1],
184  "logDir": general["logdir"],
185  "jobName": name,
186  "script": script,
187  "bsub": "/afs/cern.ch/cms/caf/scripts/cmsbsub"
188  }
189  for ext in ("stdout", "stderr", "stdout.gz", "stderr.gz"):
190  oldlog = "%(logDir)s/%(jobName)s."%repMap + ext
191  if os.path.exists(oldlog):
192  os.remove(oldlog)
193  bsubOut=getCommandOutput2("%(bsub)s %(commands)s "
194  "-J %(jobName)s "
195  "-o %(logDir)s/%(jobName)s.stdout "
196  "-e %(logDir)s/%(jobName)s.stderr "
197  "%(script)s"%repMap)
198  #Attention: here it is assumed that bsub returns a string
199  #containing a job id like <123456789>
200  ValidationJob.batchJobIds.append(bsubOut.split("<")[1].split(">")[0])
201  log+=bsubOut
202  ValidationJob.batchCount += 1
203  elif self.validation.jobmode.split( "," )[0] == "crab":
204  os.chdir( general["logdir"] )
205  crabName = "crab." + os.path.basename( script )[:-3]
206  theCrab = crabWrapper.CrabWrapper()
207  options = { "-create": "",
208  "-cfg": crabName + ".cfg",
209  "-submit": "" }
210  try:
211  theCrab.run( options )
212  except AllInOneError, e:
213  print "crab:", str(e).split("\n")[0]
214  exit(1)
215  ValidationJob.crabCount += 1
216 
217  else:
218  raise AllInOneError, ("Unknown 'jobmode'!\n"
219  "Please change this parameter either in "
220  "the [general] or in the ["
221  + self.__valType + ":" + self.__valName
222  + "] section to one of the following "
223  "values:\n"
224  "\tinteractive\n\tlxBatch, -q <queue>\n"
225  "\tcrab, -q <queue>")
226 
227  return log
228 
229  def getValidation( self ):
230  return self.validation
231 
232 
233 ####################--- Functions ---############################
234 def createOfflineParJobsMergeScript(offlineValidationList, outFilePath):
235  repMap = offlineValidationList[0].getRepMap() # bit ugly since some special features are filled
236 
237  theFile = open( outFilePath, "w" )
238  theFile.write( replaceByMap( configTemplates.mergeOfflineParJobsTemplate ,repMap ) )
239  theFile.close()
240 
241 def createExtendedValidationScript(offlineValidationList, outFilePath, resultPlotFile):
242  repMap = offlineValidationList[0].getRepMap() # bit ugly since some special features are filled
243  repMap[ "CMSSW_BASE" ] = os.environ['CMSSW_BASE']
244  repMap[ "resultPlotFile" ] = resultPlotFile
245  repMap[ "extendedInstantiation" ] = "" #give it a "" at first in order to get the initialisation back
246 
247  for validation in offlineValidationList:
248  repMap[ "extendedInstantiation" ] = validation.appendToExtendedValidation( repMap[ "extendedInstantiation" ] )
249 
250  theFile = open( outFilePath, "w" )
251  # theFile.write( replaceByMap( configTemplates.extendedValidationTemplate ,repMap ) )
252  theFile.write( replaceByMap( configTemplates.extendedValidationTemplate ,repMap ) )
253  theFile.close()
254 
255 def createTrackSplitPlotScript(trackSplittingValidationList, outFilePath):
256  repMap = trackSplittingValidationList[0].getRepMap() # bit ugly since some special features are filled
257  repMap[ "CMSSW_BASE" ] = os.environ['CMSSW_BASE']
258  repMap[ "trackSplitPlotInstantiation" ] = "" #give it a "" at first in order to get the initialisation back
259 
260  for validation in trackSplittingValidationList:
261  repMap[ "trackSplitPlotInstantiation" ] = validation.appendToExtendedValidation( repMap[ "trackSplitPlotInstantiation" ] )
262 
263  theFile = open( outFilePath, "w" )
264  # theFile.write( replaceByMap( configTemplates.trackSplitPlotTemplate ,repMap ) )
265  theFile.write( replaceByMap( configTemplates.trackSplitPlotTemplate ,repMap ) )
266  theFile.close()
267 
268 def createMergeScript( path, validations ):
269  if(len(validations) == 0):
270  raise AllInOneError("Cowardly refusing to merge nothing!")
271 
272  repMap = validations[0].getRepMap() #FIXME - not nice this way
273  repMap.update({
274  "DownloadData":"",
275  "CompareAlignments":"",
276  "RunExtendedOfflineValidation":"",
277  "RunTrackSplitPlot":"",
278  "CMSSW_BASE": os.environ["CMSSW_BASE"],
279  "SCRAM_ARCH": os.environ["SCRAM_ARCH"],
280  "CMSSW_RELEASE_BASE": os.environ["CMSSW_RELEASE_BASE"],
281  })
282 
283  comparisonLists = {} # directory of lists containing the validations that are comparable
284  for validation in validations:
285  for referenceName in validation.filesToCompare:
286  validationName = "%s.%s"%(validation.__class__.__name__, referenceName)
287  validationName = validationName.split(".%s"%GenericValidation.defaultReferenceName )[0]
288  validationName = validationName.split("Preexisting")[-1]
289  if validationName in comparisonLists:
290  comparisonLists[ validationName ].append( validation )
291  else:
292  comparisonLists[ validationName ] = [ validation ]
293 
294  # introduced to merge individual validation outputs separately
295  # -> avoids problems with merge script
296  repMap["haddLoop"] = "mergeRetCode=0\n"
297  repMap["rmUnmerged"] = ("if [[ mergeRetCode -eq 0 ]]; then\n"
298  " echo -e \\n\"Merging succeeded, removing original files.\"\n")
299  repMap["copyMergeScripts"] = ""
300  repMap["mergeParallelFilePrefixes"] = ""
301 
302  anythingToMerge = []
303  for validationType in comparisonLists:
304  for validation in comparisonLists[validationType]:
305  if isinstance(validation, PreexistingValidation) or validation.NJobs == 1:
306  continue
307  if validationType not in anythingToMerge:
308  anythingToMerge += [validationType]
309  repMap["haddLoop"] += '\n\n\n\necho -e "\n\nMerging results from %s jobs"\n\n' % validationType
310  repMap["haddLoop"] = validation.appendToMerge(repMap["haddLoop"])
311  repMap["haddLoop"] += "tmpMergeRetCode=${?}\n"
312  repMap["haddLoop"] += ("if [[ tmpMergeRetCode -eq 0 ]]; then "
313  "xrdcp -f "
314  +validation.getRepMap()["finalOutputFile"]
315  +" root://eoscms//eos/cms"
316  +validation.getRepMap()["finalResultFile"]
317  +"; fi\n")
318  repMap["haddLoop"] += ("if [[ ${tmpMergeRetCode} -gt ${mergeRetCode} ]]; then "
319  "mergeRetCode=${tmpMergeRetCode}; fi\n")
320  for f in validation.getRepMap()["outputFiles"]:
321  longName = os.path.join("/store/caf/user/$USER/",
322  validation.getRepMap()["eosdir"], f)
323  repMap["rmUnmerged"] += " $eos rm "+longName+"\n"
324  repMap["rmUnmerged"] += ("else\n"
325  " echo -e \\n\"WARNING: Merging failed, unmerged"
326  " files won't be deleted.\\n"
327  "(Ignore this warning if merging was done earlier)\"\n"
328  "fi\n")
329 
330  if "OfflineValidation" in anythingToMerge:
331  repMap["mergeOfflineParJobsScriptPath"] = os.path.join(path, "TkAlOfflineJobsMerge.C")
332  createOfflineParJobsMergeScript( comparisonLists["OfflineValidation"],
333  repMap["mergeOfflineParJobsScriptPath"] )
334  repMap["copyMergeScripts"] += ("cp .oO[CMSSW_BASE]Oo./src/Alignment/OfflineValidation/scripts/merge_TrackerOfflineValidation.C .\n"
335  "rfcp %s .\n" % repMap["mergeOfflineParJobsScriptPath"])
336 
337  if anythingToMerge:
338  # DownloadData is the section which merges output files from parallel jobs
339  # it uses the file TkAlOfflineJobsMerge.C
340  repMap["DownloadData"] += replaceByMap( configTemplates.mergeParallelResults, repMap )
341  else:
342  repMap["DownloadData"] = ""
343 
344 
345  if "OfflineValidation" in comparisonLists:
346  repMap["extendedValScriptPath"] = os.path.join(path, "TkAlExtendedOfflineValidation.C")
347  createExtendedValidationScript(comparisonLists["OfflineValidation"],
348  repMap["extendedValScriptPath"],
349  "OfflineValidation")
350  repMap["RunExtendedOfflineValidation"] = \
351  replaceByMap(configTemplates.extendedValidationExecution, repMap)
352 
353  if "TrackSplittingValidation" in comparisonLists:
354  repMap["trackSplitPlotScriptPath"] = \
355  os.path.join(path, "TkAlTrackSplitPlot.C")
356  createTrackSplitPlotScript(comparisonLists["TrackSplittingValidation"],
357  repMap["trackSplitPlotScriptPath"] )
358  repMap["RunTrackSplitPlot"] = \
359  replaceByMap(configTemplates.trackSplitPlotExecution, repMap)
360 
361  repMap["CompareAlignments"] = "#run comparisons"
362  for validationId in comparisonLists:
363  compareStrings = [ val.getCompareStrings(validationId) for val in comparisonLists[validationId] ]
364  compareStringsPlain = [ val.getCompareStrings(validationId, plain=True) for val in comparisonLists[validationId] ]
365 
366  repMap.update({"validationId": validationId,
367  "compareStrings": " , ".join(compareStrings),
368  "compareStringsPlain": " ".join(compareStringsPlain) })
369 
370  repMap["CompareAlignments"] += \
371  replaceByMap(configTemplates.compareAlignmentsExecution, repMap)
372 
373  filePath = os.path.join(path, "TkAlMerge.sh")
374  theFile = open( filePath, "w" )
375  theFile.write( replaceByMap( configTemplates.mergeTemplate, repMap ) )
376  theFile.close()
377  os.chmod(filePath,0755)
378 
379  return filePath
380 
381 def loadTemplates( config ):
382  if config.has_section("alternateTemplates"):
383  for templateName in config.options("alternateTemplates"):
384  if templateName == "AutoAlternates":
385  continue
386  newTemplateName = config.get("alternateTemplates", templateName )
387  #print "replacing default %s template by %s"%( templateName, newTemplateName)
388  configTemplates.alternateTemplate(templateName, newTemplateName)
389 
390 
391 ####################--- Main ---############################
392 def main(argv = None):
393  if argv == None:
394  argv = sys.argv[1:]
395  optParser = optparse.OptionParser()
396  optParser.description = """All-in-one Alignment Validation.
397 This will run various validation procedures either on batch queues or interactively.
398 If no name is given (-N parameter) a name containing time and date is created automatically.
399 To merge the outcome of all validation procedures run TkAlMerge.sh in your validation's directory.
400 """
401  optParser.add_option("-n", "--dryRun", dest="dryRun", action="store_true", default=False,
402  help="create all scripts and cfg File but do not start jobs (default=False)")
403  optParser.add_option( "--getImages", dest="getImages", action="store_true", default=True,
404  help="get all Images created during the process (default= True)")
405  defaultConfig = "TkAlConfig.ini"
406  optParser.add_option("-c", "--config", dest="config", default = defaultConfig,
407  help="configuration to use (default TkAlConfig.ini) this can be a comma-seperated list of all .ini file you want to merge", metavar="CONFIG")
408  optParser.add_option("-N", "--Name", dest="Name",
409  help="Name of this validation (default: alignmentValidation_DATE_TIME)", metavar="NAME")
410  optParser.add_option("-r", "--restrictTo", dest="restrictTo",
411  help="restrict validations to given modes (comma seperated) (default: no restriction)", metavar="RESTRICTTO")
412  optParser.add_option("-s", "--status", dest="crabStatus", action="store_true", default = False,
413  help="get the status of the crab jobs", metavar="STATUS")
414  optParser.add_option("-d", "--debug", dest="debugMode", action="store_true",
415  default = False,
416  help="run the tool to get full traceback of errors",
417  metavar="DEBUG")
418  optParser.add_option("-m", "--autoMerge", dest="autoMerge", action="store_true", default = False,
419  help="submit TkAlMerge.sh to run automatically when all jobs have finished (default=False)."
420  " Works only for batch jobs")
421 
422  (options, args) = optParser.parse_args(argv)
423 
424  if not options.restrictTo == None:
425  options.restrictTo = options.restrictTo.split(",")
426 
427  options.config = [ os.path.abspath( iniFile ) for iniFile in \
428  options.config.split( "," ) ]
429  config = BetterConfigParser()
430  outputIniFileSet = set( config.read( options.config ) )
431  failedIniFiles = [ iniFile for iniFile in options.config if iniFile not in outputIniFileSet ]
432 
433  # Check for missing ini file
434  if options.config == [ os.path.abspath( defaultConfig ) ]:
435  if ( not options.crabStatus ) and \
436  ( not os.path.exists( defaultConfig ) ):
437  raise AllInOneError, ( "Default 'ini' file '%s' not found!\n"
438  "You can specify another name with the "
439  "command line option '-c'/'--config'."
440  %( defaultConfig ))
441  else:
442  for iniFile in failedIniFiles:
443  if not os.path.exists( iniFile ):
444  raise AllInOneError, ( "'%s' does not exist. Please check for "
445  "typos in the filename passed to the "
446  "'-c'/'--config' option!"
447  %( iniFile ) )
448  else:
449  raise AllInOneError, ( "'%s' does exist, but parsing of the "
450  "content failed!" ) % iniFile
451 
452  # get the job name
453  if options.Name == None:
454  if not options.crabStatus:
455  options.Name = "alignmentValidation_%s"%(datetime.datetime.now().strftime("%y%m%d_%H%M%S"))
456  else:
457  existingValDirs = fnmatch.filter( os.walk( '.' ).next()[1],
458  "alignmentValidation_*" )
459  if len( existingValDirs ) > 0:
460  options.Name = existingValDirs[-1]
461  else:
462  print "Cannot guess last working directory!"
463  print ( "Please use the parameter '-N' or '--Name' to specify "
464  "the task for which you want a status report." )
465  return 1
466 
467  # set output path
468  outPath = os.path.abspath( options.Name )
469 
470  # Check status of submitted jobs and return
471  if options.crabStatus:
472  os.chdir( outPath )
473  crabLogDirs = fnmatch.filter( os.walk('.').next()[1], "crab.*" )
474  if len( crabLogDirs ) == 0:
475  print "Found no crab tasks for job name '%s'"%( options.Name )
476  return 1
477  theCrab = crabWrapper.CrabWrapper()
478  for crabLogDir in crabLogDirs:
479  print
480  print "*" + "=" * 78 + "*"
481  print ( "| Status report and output retrieval for:"
482  + " " * (77 - len( "Status report and output retrieval for:" ) )
483  + "|" )
484  taskName = crabLogDir.replace( "crab.", "" )
485  print "| " + taskName + " " * (77 - len( taskName ) ) + "|"
486  print "*" + "=" * 78 + "*"
487  print
488  crabOptions = { "-getoutput":"",
489  "-c": crabLogDir }
490  try:
491  theCrab.run( crabOptions )
492  except AllInOneError, e:
493  print "crab: No output retrieved for this task."
494  crabOptions = { "-status": "",
495  "-c": crabLogDir }
496  theCrab.run( crabOptions )
497  return
498 
499  general = config.getGeneral()
500  config.set("internals","workdir",os.path.join(general["workdir"],options.Name) )
501  config.set("general","datadir",os.path.join(general["datadir"],options.Name) )
502  config.set("general","logdir",os.path.join(general["logdir"],options.Name) )
503  config.set("general","eosdir",os.path.join("AlignmentValidation", general["eosdir"], options.Name) )
504 
505  if not os.path.exists( outPath ):
506  os.makedirs( outPath )
507  elif not os.path.isdir( outPath ):
508  raise AllInOneError,"the file %s is in the way rename the Job or move it away"%outPath
509 
510  # replace default templates by the ones specified in the "alternateTemplates" section
511  loadTemplates( config )
512 
513  #save backup configuration file
514  backupConfigFile = open( os.path.join( outPath, "usedConfiguration.ini" ) , "w" )
515  config.write( backupConfigFile )
516 
517  validations = []
518  for validation in config.items("validation"):
519  alignmentList = [validation[1]]
520  validationsToAdd = [(validation[0],alignment) \
521  for alignment in alignmentList]
522  validations.extend(validationsToAdd)
523  jobs = [ ValidationJob( validation, config, options) \
524  for validation in validations ]
525  map( lambda job: job.createJob(), jobs )
526  validations = [ job.getValidation() for job in jobs ]
527 
528  createMergeScript(outPath, validations)
529 
530  print
531  map( lambda job: job.runJob(), jobs )
532 
533  if options.autoMerge:
534  # if everything is done as batch job, also submit TkAlMerge.sh to be run
535  # after the jobs have finished
536  if ValidationJob.jobCount == ValidationJob.batchCount and config.getGeneral()["jobmode"].split(",")[0] == "lxBatch":
537  print "> Automatically merging jobs when they have ended"
538  repMap = {
539  "commands": config.getGeneral()["jobmode"].split(",")[1],
540  "jobName": "TkAlMerge",
541  "logDir": config.getGeneral()["logdir"],
542  "script": "TkAlMerge.sh",
543  "bsub": "/afs/cern.ch/cms/caf/scripts/cmsbsub",
544  "conditions": '"' + " && ".join(["ended(" + jobId + ")" for jobId in ValidationJob.batchJobIds]) + '"'
545  }
546  for ext in ("stdout", "stderr", "stdout.gz", "stderr.gz"):
547  oldlog = "%(logDir)s/%(jobName)s."%repMap + ext
548  if os.path.exists(oldlog):
549  os.remove(oldlog)
550 
551  getCommandOutput2("%(bsub)s %(commands)s "
552  "-o %(logDir)s/%(jobName)s.stdout "
553  "-e %(logDir)s/%(jobName)s.stderr "
554  "-w %(conditions)s "
555  "%(logDir)s/%(script)s"%repMap)
556 
557 if __name__ == "__main__":
558  # main(["-n","-N","test","-c","defaultCRAFTValidation.ini,latestObjects.ini","--getImages"])
559  if "-d" in sys.argv[1:] or "--debug" in sys.argv[1:]:
560  main()
561  else:
562  try:
563  main()
564  except AllInOneError, e:
565  print "\nAll-In-One Tool:", str(e)
566  exit(1)
— Classes —############################
def main
— Main —############################
def alternateTemplate
### Alternate Templates ###
if(c.getParameter< edm::InputTag >("puppiValueMap").label().size()!=0)
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def replaceByMap
— Helpers —############################
Definition: main.py:1
double split
Definition: MVATrainer.cc:139