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