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
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, OfflineValidationParallel
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 import Alignment.OfflineValidation.TkAlAllInOneTool.globalDictionaries \
34  as globalDictionaries
35 
36 
37 ####################--- Classes ---############################
39  def __init__( self, validation, config, options ):
40  if validation[1] == "":
41  # intermediate syntax
42  valString = validation[0].split( "->" )[0]
43  alignments = validation[0].split( "->" )[1]
44  # force user to use the normal syntax
45  if "->" in validation[0]:
46  msg = ("Instead of using the intermediate syntax\n'"
47  +valString.strip()+"-> "+alignments.strip()
48  +":'\nyou have to use the now fully supported syntax \n'"
49  +valString.strip()+": "
50  +alignments.strip()+"'.")
51  raise AllInOneError(msg)
52  else:
53  valString = validation[0]
54  alignments = validation[1]
55  valString = valString.split()
56  self.__valType = valString[0]
57  self.__valName = valString[1]
58  self.__commandLineOptions = options
59  self.__config = config
60  # workaround for intermediate parallel version
61  if self.__valType == "offlineParallel":
62  section = "offline" + ":" + self.__valName
63  else:
64  section = self.__valType + ":" + self.__valName
65  if not self.__config.has_section( section ):
66  raise AllInOneError, ("Validation '%s' of type '%s' is requested in"
67  " '[validation]' section, but is not defined."
68  "\nYou have to add a '[%s]' section."
69  %( self.__valName, self.__valType, section ))
70  self.validation = self.__getValidation( self.__valType, self.__valName,
71  alignments, self.__config,
72  options )
73 
74  def __getValidation( self, valType, name, alignments, config, options ):
75  if valType == "compare":
76  alignmentsList = alignments.split( "," )
77  firstAlignList = alignmentsList[0].split()
78  firstAlignName = firstAlignList[0].strip()
79  if firstAlignName == "IDEAL":
80  raise AllInOneError, ("'IDEAL' has to be the second (reference)"
81  " alignment in 'compare <val_name>: "
82  "<alignment> <reference>'.")
83  if len( firstAlignList ) > 1:
84  firstRun = firstAlignList[1]
85  else:
86  firstRun = "1"
87  firstAlign = Alignment( firstAlignName, self.__config, firstRun )
88  secondAlignList = alignmentsList[1].split()
89  secondAlignName = secondAlignList[0].strip()
90  if len( secondAlignList ) > 1:
91  secondRun = secondAlignList[1]
92  else:
93  secondRun = "1"
94  if secondAlignName == "IDEAL":
95  secondAlign = secondAlignName
96  else:
97  secondAlign = Alignment( secondAlignName, self.__config,
98  secondRun )
99  # check if alignment was already compared previously
100  try:
101  randomWorkdirPart = \
102  globalDictionaries.alignRandDict[firstAlignName]
103  except KeyError:
104  randomWorkdirPart = None
105 
106  validation = GeometryComparison( name, firstAlign, secondAlign,
107  self.__config,
108  self.__commandLineOptions.getImages,
109  randomWorkdirPart )
110  globalDictionaries.alignRandDict[firstAlignName] = \
111  validation.randomWorkdirPart
112  if not secondAlignName == "IDEAL":
113  globalDictionaries.alignRandDict[secondAlignName] = \
114  validation.randomWorkdirPart
115  elif valType == "offline":
116  validation = OfflineValidation( name,
117  Alignment( alignments.strip(), self.__config ), self.__config )
118  elif valType == "offlineDQM":
119  validation = OfflineValidationDQM( name,
120  Alignment( alignments.strip(), self.__config ), self.__config )
121  elif valType == "offlineParallel":
122  validation = OfflineValidationParallel( name,
123  Alignment( alignments.strip(), self.__config ), self.__config )
124  elif valType == "mcValidate":
125  validation = MonteCarloValidation( name,
126  Alignment( alignments.strip(), self.__config ), self.__config )
127  elif valType == "split":
128  validation = TrackSplittingValidation( name,
129  Alignment( alignments.strip(), self.__config ), self.__config )
130  elif valType == "zmumu":
131  validation = ZMuMuValidation( name,
132  Alignment( alignments.strip(), self.__config ), self.__config )
133  else:
134  raise AllInOneError, "Unknown validation mode '%s'"%valType
135  return validation
136 
137  def __createJob( self, jobMode, outpath ):
138  """This private method creates the needed files for the validation job.
139  """
140  self.validation.createConfiguration( outpath )
141  self.__scripts = self.validation.createScript( outpath )
142  if jobMode.split( ',' )[0] == "crab":
143  self.validation.createCrabCfg( outpath )
144  return None
145 
146  def createJob(self):
147  """This is the method called to create the job files."""
148  self.__createJob( self.validation.jobmode,
149  os.path.abspath( self.__commandLineOptions.Name) )
150 
151  def runJob( self ):
152  general = self.__config.getGeneral()
153  log = ""
154  for script in self.__scripts:
155  name = os.path.splitext( os.path.basename( script) )[0]
156  if self.__commandLineOptions.dryRun:
157  print "%s would run: %s"%( name, os.path.basename( script) )
158  continue
159  log = "> Validating "+name
160  print "> Validating "+name
161  if self.validation.jobmode == "interactive":
162  log += getCommandOutput2( script )
163  elif self.validation.jobmode.split(",")[0] == "lxBatch":
164  repMap = {
165  "commands": self.validation.jobmode.split(",")[1],
166  "logDir": general["logdir"],
167  "jobName": name,
168  "script": script,
169  "bsub": "/afs/cern.ch/cms/caf/scripts/cmsbsub"
170  }
171  log+=getCommandOutput2("%(bsub)s %(commands)s -J %(jobName)s "
172  "-o %(logDir)s/%(jobName)s.stdout -e "
173  "%(logDir)s/%(jobName)s.stderr "
174  "%(script)s"%repMap)
175  elif self.validation.jobmode.split( "," )[0] == "crab":
176  os.chdir( general["logdir"] )
177  crabName = "crab." + os.path.basename( script )[:-3]
178  theCrab = crabWrapper.CrabWrapper()
179  options = { "-create": "",
180  "-cfg": crabName + ".cfg",
181  "-submit": "" }
182  try:
183  theCrab.run( options )
184  except AllInOneError, e:
185  print "crab:", str(e).split("\n")[0]
186  exit(1)
187  else:
188  raise AllInOneError, ("Unknown 'jobmode'!\n"
189  "Please change this parameter either in "
190  "the [general] or in the ["
191  + self.__valType + ":" + self.__valName
192  + "] section to one of the following "
193  "values:\n"
194  "\tinteractive\n\tlxBatch, -q <queue>\n"
195  "\tcrab, -q <queue>")
196  return log
197 
198  def getValidation( self ):
199  return self.validation
200 
201 
202 ####################--- Functions ---############################
203 def createOfflineJobsMergeScript(offlineValidationList, outFilePath):
204  repMap = offlineValidationList[0].getRepMap() # bit ugly since some special features are filled
205  repMap[ "mergeOfflinParJobsInstantiation" ] = "" #give it a "" at first in order to get the initialisation back
206 
207  theFile = open( outFilePath, "w" )
208  theFile.write( replaceByMap( configTemplates.mergeOfflineParJobsTemplate ,repMap ) )
209  theFile.close()
210 
211 def createExtendedValidationScript(offlineValidationList, outFilePath):
212  repMap = offlineValidationList[0].getRepMap() # bit ugly since some special features are filled
213  repMap[ "extendedInstantiation" ] = "" #give it a "" at first in order to get the initialisation back
214 
215  for validation in offlineValidationList:
216  repMap[ "extendedInstantiation" ] = validation.appendToExtendedValidation( repMap[ "extendedInstantiation" ] )
217 
218  theFile = open( outFilePath, "w" )
219  # theFile.write( replaceByMap( configTemplates.extendedValidationTemplate ,repMap ) )
220  theFile.write( replaceByMap( configTemplates.extendedValidationTemplate ,repMap ) )
221  theFile.close()
222 
223 def createMergeScript( path, validations ):
224  if(len(validations) == 0):
225  msg = "Cowardly refusing to merge nothing!"
226  raise AllInOneError(msg)
227 
228  repMap = validations[0].getRepMap() #FIXME - not nice this way
229  repMap.update({
230  "DownloadData":"",
231  "CompareAlignments":"",
232  "RunExtendedOfflineValidation":""
233  })
234 
235  comparisonLists = {} # directory of lists containing the validations that are comparable
236  for validation in validations:
237  for referenceName in validation.filesToCompare:
238  validationName = "%s.%s"%(validation.__class__.__name__, referenceName)
239  validationName = validationName.split(".%s"%GenericValidation.defaultReferenceName )[0]
240  if validationName in comparisonLists:
241  comparisonLists[ validationName ].append( validation )
242  else:
243  comparisonLists[ validationName ] = [ validation ]
244 
245  if "OfflineValidation" in comparisonLists:
246  repMap["extendeValScriptPath"] = \
247  os.path.join(path, "TkAlExtendedOfflineValidation.C")
248  createExtendedValidationScript(comparisonLists["OfflineValidation"],
249  repMap["extendeValScriptPath"] )
250  repMap["RunExtendedOfflineValidation"] = \
251  replaceByMap(configTemplates.extendedValidationExecution, repMap)
252 
253  repMap["CompareAlignments"] = "#run comparisons"
254  for validationId in comparisonLists:
255  compareStrings = [ val.getCompareStrings(validationId) for val in comparisonLists[validationId] ]
256 
257  repMap.update({"validationId": validationId,
258  "compareStrings": " , ".join(compareStrings) })
259 
260  repMap["CompareAlignments"] += \
261  replaceByMap(configTemplates.compareAlignmentsExecution, repMap)
262 
263  filePath = os.path.join(path, "TkAlMerge.sh")
264  theFile = open( filePath, "w" )
265  theFile.write( replaceByMap( configTemplates.mergeTemplate, repMap ) )
266  theFile.close()
267  os.chmod(filePath,0755)
268 
269  return filePath
270 
271 def createParallelMergeScript( path, validations ):
272  if( len(validations) == 0 ):
273  raise AllInOneError, "cowardly refusing to merge nothing!"
274 
275  repMap = validations[0].getRepMap() #FIXME - not nice this way
276  repMap.update({
277  "DownloadData":"",
278  "CompareAlignments":"",
279  "RunExtendedOfflineValidation":""
280  })
281 
282  comparisonLists = {} # directory of lists containing the validations that are comparable
283  for validation in validations:
284  for referenceName in validation.filesToCompare:
285  validationName = "%s.%s"%(validation.__class__.__name__, referenceName)
286  validationName = validationName.split(".%s"%GenericValidation.defaultReferenceName )[0]
287  if validationName in comparisonLists:
288  comparisonLists[ validationName ].append( validation )
289  else:
290  comparisonLists[ validationName ] = [ validation ]
291 
292  if "OfflineValidationParallel" in comparisonLists:
293  repMap["extendeValScriptPath"] = os.path.join(path, "TkAlExtendedOfflineValidation.C")
294  createExtendedValidationScript( comparisonLists["OfflineValidationParallel"], repMap["extendeValScriptPath"] )
295  repMap["mergeOfflineParJobsScriptPath"] = os.path.join(path, "TkAlOfflineJobsMerge.C")
296  createOfflineJobsMergeScript( comparisonLists["OfflineValidationParallel"],
297  repMap["mergeOfflineParJobsScriptPath"] )
298 
299  # introduced to merge individual validation outputs separately
300  # -> avoids problems with merge script
301  repMap["haddLoop"] = ""
302  for validation in comparisonLists["OfflineValidationParallel"]:
303  repMap["haddLoop"] = validation.appendToMergeParJobs(repMap["haddLoop"])
304  repMap["haddLoop"] += ("cmsStage -f "
305  +validation.getRepMap()["outputFile"]
306  +" "
307  +validation.getRepMap()["resultFile"]
308  +"\n")
309 
310  repMap["RunExtendedOfflineValidation"] = \
311  replaceByMap(configTemplates.extendedValidationExecution, repMap)
312 
313  # DownloadData is the section which merges output files from parallel jobs
314  # it uses the file TkAlOfflineJobsMerge.C
315  repMap["DownloadData"] += replaceByMap("rfcp .oO[mergeOfflineParJobsScriptPath]Oo. .", repMap)
316  repMap["DownloadData"] += replaceByMap( configTemplates.mergeOfflineParallelResults, repMap )
317 
318  repMap["CompareAlignments"] = "#run comparisons"
319  for validationId in comparisonLists:
320  compareStrings = [ val.getCompareStrings(validationId) for val in comparisonLists[validationId] ]
321 
322  repMap.update({"validationId": validationId,
323  "compareStrings": " , ".join(compareStrings) })
324 
325  repMap["CompareAlignments"] += \
326  replaceByMap(configTemplates.compareAlignmentsExecution, repMap)
327 
328  filePath = os.path.join(path, "TkAlMerge.sh")
329  theFile = open( filePath, "w" )
330  theFile.write( replaceByMap( configTemplates.mergeTemplate, repMap ) )
331  theFile.close()
332  os.chmod(filePath,0755)
333 
334  return filePath
335 
336 def loadTemplates( config ):
337  if config.has_section("alternateTemplates"):
338  for templateName in config.options("alternateTemplates"):
339  newTemplateName = config.get("alternateTemplates", templateName )
340  #print "replacing default %s template by %s"%( templateName, newTemplateName)
341  configTemplates.alternateTemplate(templateName, newTemplateName)
342 
343 
344 ####################--- Main ---############################
345 def main(argv = None):
346  if argv == None:
347  argv = sys.argv[1:]
348  optParser = optparse.OptionParser()
349  optParser.description = """ all-in-one alignment Validation
350  This will run various validation procedures either on batch queues or interactviely.
351 
352  If no name is given (-N parameter) a name containing time and date is created automatically
353 
354  To merge the outcome of all validation procedures run TkAlMerge.sh in your validation's directory.
355  """
356  optParser.add_option("-n", "--dryRun", dest="dryRun", action="store_true", default=False,
357  help="create all scripts and cfg File but do not start jobs (default=False)")
358  optParser.add_option( "--getImages", dest="getImages", action="store_true", default=False,
359  help="get all Images created during the process (default= False)")
360  defaultConfig = "TkAlConfig.ini"
361  optParser.add_option("-c", "--config", dest="config", default = defaultConfig,
362  help="configuration to use (default TkAlConfig.ini) this can be a comma-seperated list of all .ini file you want to merge", metavar="CONFIG")
363  optParser.add_option("-N", "--Name", dest="Name",
364  help="Name of this validation (default: alignmentValidation_DATE_TIME)", metavar="NAME")
365  optParser.add_option("-r", "--restrictTo", dest="restrictTo",
366  help="restrict validations to given modes (comma seperated) (default: no restriction)", metavar="RESTRICTTO")
367  optParser.add_option("-s", "--status", dest="crabStatus", action="store_true", default = False,
368  help="get the status of the crab jobs", metavar="STATUS")
369  optParser.add_option("-d", "--debug", dest="debugMode", action="store_true",
370  default = False,
371  help="Run the tool to get full traceback of errors.",
372  metavar="DEBUG")
373 
374  (options, args) = optParser.parse_args(argv)
375 
376  if not options.restrictTo == None:
377  options.restrictTo = options.restrictTo.split(",")
378 
379  options.config = [ os.path.abspath( iniFile ) for iniFile in \
380  options.config.split( "," ) ]
381  config = BetterConfigParser()
382  outputIniFileSet = set( config.read( options.config ) )
383  failedIniFiles = [ iniFile for iniFile in options.config if iniFile not in outputIniFileSet ]
384 
385  # Check for missing ini file
386  if options.config == [ os.path.abspath( defaultConfig ) ]:
387  if ( not options.crabStatus ) and \
388  ( not os.path.exists( defaultConfig ) ):
389  raise AllInOneError, ( "Default 'ini' file '%s' not found!\n"
390  "You can specify another name with the "
391  "command line option '-c'/'--config'."
392  %( defaultConfig ))
393  else:
394  for iniFile in failedIniFiles:
395  if not os.path.exists( iniFile ):
396  raise AllInOneError, ( "'%s' does not exist. Please check for "
397  "typos in the filename passed to the "
398  "'-c'/'--config' option!"
399  %( iniFile ) )
400  else:
401  raise AllInOneError, ( "'%s' does exist, but parsing of the "
402  "content failed!" )
403 
404  # get the job name
405  if options.Name == None:
406  if not options.crabStatus:
407  options.Name = "alignmentValidation_%s"%(datetime.datetime.now().strftime("%y%m%d_%H%M%S"))
408  else:
409  existingValDirs = fnmatch.filter( os.walk( '.' ).next()[1],
410  "alignmentValidation_*" )
411  if len( existingValDirs ) > 0:
412  options.Name = existingValDirs[-1]
413  else:
414  print "Cannot guess last working directory!"
415  print ( "Please use the parameter '-N' or '--Name' to specify "
416  "the task for which you want a status report." )
417  return 1
418 
419  # set output path
420  outPath = os.path.abspath( options.Name )
421 
422  # Check status of submitted jobs and return
423  if options.crabStatus:
424  os.chdir( outPath )
425  crabLogDirs = fnmatch.filter( os.walk('.').next()[1], "crab.*" )
426  if len( crabLogDirs ) == 0:
427  print "Found no crab tasks for job name '%s'"%( options.Name )
428  return 1
429  theCrab = crabWrapper.CrabWrapper()
430  for crabLogDir in crabLogDirs:
431  print
432  print "*" + "=" * 78 + "*"
433  print ( "| Status report and output retrieval for:"
434  + " " * (77 - len( "Status report and output retrieval for:" ) )
435  + "|" )
436  taskName = crabLogDir.replace( "crab.", "" )
437  print "| " + taskName + " " * (77 - len( taskName ) ) + "|"
438  print "*" + "=" * 78 + "*"
439  print
440  crabOptions = { "-getoutput":"",
441  "-c": crabLogDir }
442  try:
443  theCrab.run( crabOptions )
444  except AllInOneError, e:
445  print "crab: No output retrieved for this task."
446  crabOptions = { "-status": "",
447  "-c": crabLogDir }
448  theCrab.run( crabOptions )
449  return
450 
451  general = config.getGeneral()
452  config.set("internals","workdir",os.path.join(general["workdir"],options.Name) )
453  config.set("general","datadir",os.path.join(general["datadir"],options.Name) )
454  config.set("general","logdir",os.path.join(general["logdir"],options.Name) )
455  config.set("general","eosdir",os.path.join("AlignmentValidation", general["eosdir"], options.Name) )
456 
457  # clean up of log directory to avoid cluttering with files with different
458  # random numbers for geometry comparison
459  if os.path.isdir( outPath ):
460  shutil.rmtree( outPath )
461 
462  if not os.path.exists( outPath ):
463  os.makedirs( outPath )
464  elif not os.path.isdir( outPath ):
465  raise AllInOneError,"the file %s is in the way rename the Job or move it away"%outPath
466 
467  # replace default templates by the ones specified in the "alternateTemplates" section
468  loadTemplates( config )
469 
470  #save backup configuration file
471  backupConfigFile = open( os.path.join( outPath, "usedConfiguration.ini" ) , "w" )
472  config.write( backupConfigFile )
473 
474  validations = []
475  for validation in config.items("validation"):
476  alignmentList = validation[1].split(config.getSep())
477  validationsToAdd = [(validation[0],alignment) \
478  for alignment in alignmentList]
479  validations.extend(validationsToAdd)
480  jobs = [ ValidationJob( validation, config, options) \
481  for validation in validations ]
482  map( lambda job: job.createJob(), jobs )
483  validations = [ job.getValidation() for job in jobs ]
484 
485  if "OfflineValidationParallel" not in [val.__class__.__name__ for val in validations]:
486  createMergeScript(outPath, validations)
487  else:
488  createParallelMergeScript( outPath, validations )
489 
490  print
491  map( lambda job: job.runJob(), jobs )
492 
493 
494 if __name__ == "__main__":
495  # main(["-n","-N","test","-c","defaultCRAFTValidation.ini,latestObjects.ini","--getImages"])
496  if "-d" in sys.argv[1:] or "--debug" in sys.argv[1:]:
497  main()
498  else:
499  try:
500  main()
501  except AllInOneError, e:
502  print "\nAll-In-One Tool:", str(e)
503  exit(1)
— Classes —############################
def main
— Main —############################
dictionary map
Definition: Association.py:205
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