10 import Alignment.OfflineValidation.TkAlAllInOneTool.configTemplates \
12 import Alignment.OfflineValidation.TkAlAllInOneTool.crabWrapper
as crabWrapper
13 from Alignment.OfflineValidation.TkAlAllInOneTool.TkAlExceptions \
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
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 \
35 import Alignment.OfflineValidation.TkAlAllInOneTool.globalDictionaries \
49 def __init__( self, validation, config, options ):
50 if validation[1] ==
"":
52 valString = validation[0].
split(
"->" )[0]
53 alignments = validation[0].
split(
"->" )[1]
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)
63 valString = validation[0]
64 alignments = validation[1]
65 valString = valString.split()
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.")
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."
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]
104 firstAlignName = firstAlign.name
105 secondAlignList = alignmentsList[1].
split()
106 secondAlignName = secondAlignList[0].strip()
107 if len( secondAlignList ) > 1:
108 secondRun = secondAlignList[1]
111 if secondAlignName ==
"IDEAL":
112 secondAlign = secondAlignName
116 secondAlignName = secondAlign.name
118 validation = GeometryComparison( name, firstAlign, secondAlign,
120 self.__commandLineOptions.getImages)
121 elif valType ==
"offline":
122 validation = OfflineValidation( name,
124 elif valType ==
"preexistingoffline":
125 validation = PreexistingOfflineValidation(name, self.
__config)
126 elif valType ==
"offlineDQM":
127 validation = OfflineValidationDQM( name,
129 elif valType ==
"mcValidate":
130 validation = MonteCarloValidation( name,
132 elif valType ==
"preexistingmcValidate":
133 validation = PreexistingMonteCarloValidation(name, self.
__config)
134 elif valType ==
"split":
135 validation = TrackSplittingValidation( name,
137 elif valType ==
"preexistingsplit":
138 validation = PreexistingTrackSplittingValidation(name, self.
__config)
139 elif valType ==
"zmumu":
140 validation = ZMuMuValidation( name,
143 raise AllInOneError,
"Unknown validation mode '%s'"%valType
147 """This private method creates the needed files for the validation job.
149 self.validation.createConfiguration( outpath )
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 )
158 """This is the method called to create the job files."""
160 os.path.abspath( self.__commandLineOptions.Name) )
164 log =
"> " + self.validation.name +
" is already validated."
168 general = self.__config.getGeneral()
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) )
176 log =
"> Validating "+name
177 print "> Validating "+name
178 if self.validation.jobmode ==
"interactive":
180 ValidationJob.interactCount += 1
181 elif self.validation.jobmode.split(
",")[0] ==
"lxBatch":
183 "commands": self.validation.jobmode.split(
",")[1],
184 "logDir": general[
"logdir"],
187 "bsub":
"/afs/cern.ch/cms/caf/scripts/cmsbsub"
191 "-o %(logDir)s/%(jobName)s.stdout "
192 "-e %(logDir)s/%(jobName)s.stderr "
196 ValidationJob.batchJobIds.append(bsubOut.split(
"<")[1].
split(
">")[0])
198 ValidationJob.batchCount += 1
199 elif self.validation.jobmode.split(
"," )[0] ==
"crab":
200 os.chdir( general[
"logdir"] )
201 crabName =
"crab." + os.path.basename( script )[:-3]
203 options = {
"-create":
"",
204 "-cfg": crabName +
".cfg",
207 theCrab.run( options )
208 except AllInOneError, e:
209 print "crab:", str(e).
split(
"\n")[0]
211 ValidationJob.crabCount += 1
214 raise AllInOneError, (
"Unknown 'jobmode'!\n"
215 "Please change this parameter either in "
216 "the [general] or in the ["
218 +
"] section to one of the following "
220 "\tinteractive\n\tlxBatch, -q <queue>\n"
221 "\tcrab, -q <queue>")
231 repMap = offlineValidationList[0].getRepMap()
233 theFile = open( outFilePath,
"w" )
234 theFile.write(
replaceByMap( configTemplates.mergeOfflineParJobsTemplate ,repMap ) )
238 repMap = offlineValidationList[0].getRepMap()
239 repMap[
"CMSSW_BASE" ] = os.environ[
'CMSSW_BASE']
240 repMap[
"resultPlotFile" ] = resultPlotFile
241 repMap[
"extendedInstantiation" ] =
""
243 for validation
in offlineValidationList:
244 repMap[
"extendedInstantiation" ] = validation.appendToExtendedValidation( repMap[
"extendedInstantiation" ] )
246 theFile = open( outFilePath,
"w" )
248 theFile.write(
replaceByMap( configTemplates.extendedValidationTemplate ,repMap ) )
252 repMap = trackSplittingValidationList[0].getRepMap()
253 repMap[
"CMSSW_BASE" ] = os.environ[
'CMSSW_BASE']
254 repMap[
"trackSplitPlotInstantiation" ] =
""
256 for validation
in trackSplittingValidationList:
257 repMap[
"trackSplitPlotInstantiation" ] = validation.appendToExtendedValidation( repMap[
"trackSplitPlotInstantiation" ] )
259 theFile = open( outFilePath,
"w" )
261 theFile.write(
replaceByMap( configTemplates.trackSplitPlotTemplate ,repMap ) )
265 if(len(validations) == 0):
266 raise AllInOneError(
"Cowardly refusing to merge nothing!")
268 repMap = validations[0].getRepMap()
271 "CompareAlignments":
"",
272 "RunExtendedOfflineValidation":
"",
273 "RunTrackSplitPlot":
"",
274 "CMSSW_BASE": os.environ[
"CMSSW_BASE"],
275 "SCRAM_ARCH": os.environ[
"SCRAM_ARCH"],
276 "CMSSW_RELEASE_BASE": os.environ[
"CMSSW_RELEASE_BASE"],
280 for validation
in validations:
281 for referenceName
in validation.filesToCompare:
282 validationName =
"%s.%s"%(validation.__class__.__name__, referenceName)
283 validationName = validationName.split(
".%s"%GenericValidation.defaultReferenceName )[0]
284 validationName = validationName.split(
"Preexisting")[-1]
285 if validationName
in comparisonLists:
286 comparisonLists[ validationName ].
append( validation )
288 comparisonLists[ validationName ] = [ validation ]
292 repMap[
"haddLoop"] =
"mergeRetCode=0\n"
293 repMap[
"rmUnmerged"] = (
"if [[ mergeRetCode -eq 0 ]]; then\n"
294 " echo -e \\n\"Merging succeeded, removing original files.\"\n")
295 repMap[
"copyMergeScripts"] =
""
296 repMap[
"mergeParallelFilePrefixes"] =
""
299 for validationType
in comparisonLists:
300 for validation
in comparisonLists[validationType]:
301 if isinstance(validation, PreexistingValidation)
or validation.NJobs == 1:
303 if validationType
not in anythingToMerge:
304 anythingToMerge += [validationType]
305 repMap[
"haddLoop"] +=
'\n\n\n\necho -e "\n\nMerging results from %s jobs"\n\n' % validationType
306 repMap[
"haddLoop"] = validation.appendToMerge(repMap[
"haddLoop"])
307 repMap[
"haddLoop"] +=
"tmpMergeRetCode=${?}\n"
308 repMap[
"haddLoop"] += (
"if [[ tmpMergeRetCode -eq 0 ]]; then "
310 +validation.getRepMap()[
"finalOutputFile"]
312 +validation.getRepMap()[
"finalResultFile"]
314 repMap[
"haddLoop"] += (
"if [[ ${tmpMergeRetCode} -gt ${mergeRetCode} ]]; then "
315 "mergeRetCode=${tmpMergeRetCode}; fi\n")
316 for f
in validation.getRepMap()[
"outputFiles"]:
317 longName = os.path.join(
"/store/caf/user/$USER/",
318 validation.getRepMap()[
"eosdir"], f)
319 repMap[
"rmUnmerged"] +=
" cmsRm "+longName+
"\n"
320 repMap[
"rmUnmerged"] += (
"else\n"
321 " echo -e \\n\"WARNING: Merging failed, unmerged"
322 " files won't be deleted.\\n"
323 "(Ignore this warning if merging was done earlier)\"\n"
326 if "OfflineValidation" in anythingToMerge:
327 repMap[
"mergeOfflineParJobsScriptPath"] = os.path.join(path,
"TkAlOfflineJobsMerge.C")
329 repMap[
"mergeOfflineParJobsScriptPath"] )
330 repMap[
"copyMergeScripts"] += (
"cp .oO[CMSSW_BASE]Oo./src/Alignment/OfflineValidation/scripts/merge_TrackerOfflineValidation.C .\n"
331 "rfcp %s .\n" % repMap[
"mergeOfflineParJobsScriptPath"])
336 repMap[
"DownloadData"] +=
replaceByMap( configTemplates.mergeParallelResults, repMap )
338 repMap[
"DownloadData"] =
""
341 if "OfflineValidation" in comparisonLists:
342 repMap[
"extendedValScriptPath"] = os.path.join(path,
"TkAlExtendedOfflineValidation.C")
344 repMap[
"extendedValScriptPath"],
346 repMap[
"RunExtendedOfflineValidation"] = \
347 replaceByMap(configTemplates.extendedValidationExecution, repMap)
349 if "TrackSplittingValidation" in comparisonLists:
350 repMap[
"trackSplitPlotScriptPath"] = \
351 os.path.join(path,
"TkAlTrackSplitPlot.C")
353 repMap[
"trackSplitPlotScriptPath"] )
354 repMap[
"RunTrackSplitPlot"] = \
355 replaceByMap(configTemplates.trackSplitPlotExecution, repMap)
357 repMap[
"CompareAlignments"] =
"#run comparisons"
358 for validationId
in comparisonLists:
359 compareStrings = [ val.getCompareStrings(validationId)
for val
in comparisonLists[validationId] ]
360 compareStringsPlain = [ val.getCompareStrings(validationId, plain=
True)
for val
in comparisonLists[validationId] ]
362 repMap.update({
"validationId": validationId,
363 "compareStrings":
" , ".
join(compareStrings),
364 "compareStringsPlain":
" ".
join(compareStringsPlain) })
366 repMap[
"CompareAlignments"] += \
367 replaceByMap(configTemplates.compareAlignmentsExecution, repMap)
369 filePath = os.path.join(path,
"TkAlMerge.sh")
370 theFile = open( filePath,
"w" )
371 theFile.write(
replaceByMap( configTemplates.mergeTemplate, repMap ) )
373 os.chmod(filePath,0755)
378 if config.has_section(
"alternateTemplates"):
379 for templateName
in config.options(
"alternateTemplates"):
380 if templateName ==
"AutoAlternates":
382 newTemplateName = config.get(
"alternateTemplates", templateName )
391 optParser = optparse.OptionParser()
392 optParser.description =
"""All-in-one Alignment Validation.
393 This will run various validation procedures either on batch queues or interactively.
394 If no name is given (-N parameter) a name containing time and date is created automatically.
395 To merge the outcome of all validation procedures run TkAlMerge.sh in your validation's directory.
397 optParser.add_option(
"-n",
"--dryRun", dest=
"dryRun", action=
"store_true", default=
False,
398 help=
"create all scripts and cfg File but do not start jobs (default=False)")
399 optParser.add_option(
"--getImages", dest=
"getImages", action=
"store_true", default=
True,
400 help=
"get all Images created during the process (default= True)")
401 defaultConfig =
"TkAlConfig.ini"
402 optParser.add_option(
"-c",
"--config", dest=
"config", default = defaultConfig,
403 help=
"configuration to use (default TkAlConfig.ini) this can be a comma-seperated list of all .ini file you want to merge", metavar=
"CONFIG")
404 optParser.add_option(
"-N",
"--Name", dest=
"Name",
405 help=
"Name of this validation (default: alignmentValidation_DATE_TIME)", metavar=
"NAME")
406 optParser.add_option(
"-r",
"--restrictTo", dest=
"restrictTo",
407 help=
"restrict validations to given modes (comma seperated) (default: no restriction)", metavar=
"RESTRICTTO")
408 optParser.add_option(
"-s",
"--status", dest=
"crabStatus", action=
"store_true", default =
False,
409 help=
"get the status of the crab jobs", metavar=
"STATUS")
410 optParser.add_option(
"-d",
"--debug", dest=
"debugMode", action=
"store_true",
412 help=
"run the tool to get full traceback of errors",
414 optParser.add_option(
"-m",
"--autoMerge", dest=
"autoMerge", action=
"store_true", default =
False,
415 help=
"submit TkAlMerge.sh to run automatically when all jobs have finished (default=False)."
416 " Works only for batch jobs")
418 (options, args) = optParser.parse_args(argv)
420 if not options.restrictTo ==
None:
421 options.restrictTo = options.restrictTo.split(
",")
423 options.config = [ os.path.abspath( iniFile )
for iniFile
in \
424 options.config.split(
"," ) ]
425 config = BetterConfigParser()
426 outputIniFileSet = set( config.read( options.config ) )
427 failedIniFiles = [ iniFile
for iniFile
in options.config
if iniFile
not in outputIniFileSet ]
430 if options.config == [ os.path.abspath( defaultConfig ) ]:
431 if (
not options.crabStatus )
and \
432 (
not os.path.exists( defaultConfig ) ):
433 raise AllInOneError, (
"Default 'ini' file '%s' not found!\n"
434 "You can specify another name with the "
435 "command line option '-c'/'--config'."
438 for iniFile
in failedIniFiles:
439 if not os.path.exists( iniFile ):
440 raise AllInOneError, (
"'%s' does not exist. Please check for "
441 "typos in the filename passed to the "
442 "'-c'/'--config' option!"
445 raise AllInOneError, (
"'%s' does exist, but parsing of the "
446 "content failed!" ) % iniFile
449 if options.Name ==
None:
450 if not options.crabStatus:
451 options.Name =
"alignmentValidation_%s"%(datetime.datetime.now().strftime(
"%y%m%d_%H%M%S"))
453 existingValDirs = fnmatch.filter( os.walk(
'.' ).
next()[1],
454 "alignmentValidation_*" )
455 if len( existingValDirs ) > 0:
456 options.Name = existingValDirs[-1]
458 print "Cannot guess last working directory!"
459 print (
"Please use the parameter '-N' or '--Name' to specify "
460 "the task for which you want a status report." )
464 outPath = os.path.abspath( options.Name )
467 if options.crabStatus:
469 crabLogDirs = fnmatch.filter( os.walk(
'.').
next()[1],
"crab.*" )
470 if len( crabLogDirs ) == 0:
471 print "Found no crab tasks for job name '%s'"%( options.Name )
474 for crabLogDir
in crabLogDirs:
476 print "*" +
"=" * 78 +
"*"
477 print (
"| Status report and output retrieval for:"
478 +
" " * (77 - len(
"Status report and output retrieval for:" ) )
480 taskName = crabLogDir.replace(
"crab.",
"" )
481 print "| " + taskName +
" " * (77 - len( taskName ) ) +
"|"
482 print "*" +
"=" * 78 +
"*"
484 crabOptions = {
"-getoutput":
"",
487 theCrab.run( crabOptions )
488 except AllInOneError, e:
489 print "crab: No output retrieved for this task."
490 crabOptions = {
"-status":
"",
492 theCrab.run( crabOptions )
495 general = config.getGeneral()
496 config.set(
"internals",
"workdir",os.path.join(general[
"workdir"],options.Name) )
497 config.set(
"general",
"datadir",os.path.join(general[
"datadir"],options.Name) )
498 config.set(
"general",
"logdir",os.path.join(general[
"logdir"],options.Name) )
499 config.set(
"general",
"eosdir",os.path.join(
"AlignmentValidation", general[
"eosdir"], options.Name) )
501 if not os.path.exists( outPath ):
502 os.makedirs( outPath )
503 elif not os.path.isdir( outPath ):
504 raise AllInOneError,
"the file %s is in the way rename the Job or move it away"%outPath
510 backupConfigFile = open( os.path.join( outPath,
"usedConfiguration.ini" ) ,
"w" )
511 config.write( backupConfigFile )
514 for validation
in config.items(
"validation"):
515 alignmentList = [validation[1]]
516 validationsToAdd = [(validation[0],alignment) \
517 for alignment
in alignmentList]
518 validations.extend(validationsToAdd)
520 for validation
in validations ]
521 map(
lambda job: job.createJob(), jobs )
522 validations = [ job.getValidation()
for job
in jobs ]
527 map(
lambda job: job.runJob(), jobs )
529 if options.autoMerge:
532 if ValidationJob.jobCount == ValidationJob.batchCount
and config.getGeneral()[
"jobmode"].
split(
",")[0] ==
"lxBatch":
533 print "> Automatically merging jobs when they have ended"
535 "commands": config.getGeneral()[
"jobmode"].
split(
",")[1],
536 "jobName":
"TkAlMerge",
537 "logDir": config.getGeneral()[
"logdir"],
538 "script":
"TkAlMerge.sh",
539 "bsub":
"/afs/cern.ch/cms/caf/scripts/cmsbsub",
540 "conditions":
'"' +
" && ".
join([
"ended(" + jobId +
")" for jobId
in ValidationJob.batchJobIds]) +
'"'
543 "-o %(logDir)s/%(jobName)s.stdout "
544 "-e %(logDir)s/%(jobName)s.stderr "
546 "%(logDir)s/%(script)s"%repMap)
548 if __name__ ==
"__main__":
550 if "-d" in sys.argv[1:]
or "--debug" in sys.argv[1:]:
555 except AllInOneError, e:
556 print "\nAll-In-One Tool:", str(e)
def createTrackSplitPlotScript
— Classes —############################
def createOfflineParJobsMergeScript
def main
— Main —############################
def createExtendedValidationScript
def alternateTemplate
### Alternate Templates ###
static std::string join(char **cmd)
def replaceByMap
— Helpers —############################
if(conf.exists("allCellsPositionCalc"))