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