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
22 import GenericValidation, ParallelValidation, ValidationWithComparison, ValidationWithPlots
23 from Alignment.OfflineValidation.TkAlAllInOneTool.geometryComparison \
24 import GeometryComparison
26 import OfflineValidation, OfflineValidationDQM
27 from Alignment.OfflineValidation.TkAlAllInOneTool.monteCarloValidation \
28 import MonteCarloValidation
30 import TrackSplittingValidation
32 import ZMuMuValidation
34 import PrimaryVertexValidation
35 from Alignment.OfflineValidation.TkAlAllInOneTool.preexistingValidation \
37 from Alignment.OfflineValidation.TkAlAllInOneTool.plottingOptions \
38 import PlottingOptions
39 import Alignment.OfflineValidation.TkAlAllInOneTool.globalDictionaries \
51 if isinstance(dependency,list):
52 self.dependencies.extend(dependency)
54 self.dependencies.append(dependency)
57 "commands": config.getGeneral()[
"jobmode"].
split(
",")[1],
59 "logDir": config.getGeneral()[
"logdir"],
61 "bsub":
"/afs/cern.ch/cms/caf/scripts/cmsbsub",
62 "conditions":
'"' +
" && ".
join([
"ended(" + jobId +
")" for jobId
in self.
dependencies]) +
'"' 66 "-o %(logDir)s/%(jobName)s.stdout " 67 "-e %(logDir)s/%(jobName)s.stderr " 80 def __init__( self, validation, config, options ):
82 if validation[1] ==
"":
84 valString = validation[0].
split(
"->" )[0]
85 alignments = validation[0].
split(
"->" )[1]
87 if "->" in validation[0]:
88 msg = (
"Instead of using the intermediate syntax\n'" 89 +valString.strip()+
"-> "+alignments.strip()
90 +
":'\nyou have to use the now fully supported syntax \n'" 91 +valString.strip()+
": " 92 +alignments.strip()+
"'.")
93 raise AllInOneError(msg)
95 valString = validation[0]
96 alignments = validation[1]
97 valString = valString.split()
109 print (
"offlineParallel and offline are now the same. To run an offline parallel validation,\n" 110 "just set parallelJobs to something > 1. There is no reason to call it offlineParallel anymore.")
113 if not self.__config.has_section( section ):
114 raise AllInOneError(
"Validation '%s' of type '%s' is requested in" 115 " '[validation]' section, but is not defined." 116 "\nYou have to add a '[%s]' section." 123 if valType ==
"compare":
124 alignmentsList = alignments.split(
"," )
125 firstAlignList = alignmentsList[0].
split()
126 firstAlignName = firstAlignList[0].
strip()
127 if firstAlignName ==
"IDEAL":
128 raise AllInOneError(
"'IDEAL' has to be the second (reference)" 129 " alignment in 'compare <val_name>: " 130 "<alignment> <reference>'.")
131 if len( firstAlignList ) > 1:
132 firstRun = firstAlignList[1]
136 firstAlignName = firstAlign.name
137 secondAlignList = alignmentsList[1].
split()
138 secondAlignName = secondAlignList[0].
strip()
139 if len( secondAlignList ) > 1:
140 secondRun = secondAlignList[1]
143 if secondAlignName ==
"IDEAL":
144 secondAlign = secondAlignName
148 secondAlignName = secondAlign.name
150 validation = GeometryComparison( name, firstAlign, secondAlign,
152 self.__commandLineOptions.getImages)
153 elif valType ==
"offline":
154 validation = OfflineValidation( name,
156 elif valType ==
"preexistingoffline":
157 validation = PreexistingOfflineValidation(name, self.
__config)
158 elif valType ==
"offlineDQM":
159 validation = OfflineValidationDQM( name,
161 elif valType ==
"mcValidate":
162 validation = MonteCarloValidation( name,
164 elif valType ==
"preexistingmcValidate":
165 validation = PreexistingMonteCarloValidation(name, self.
__config)
166 elif valType ==
"split":
167 validation = TrackSplittingValidation( name,
169 elif valType ==
"preexistingsplit":
170 validation = PreexistingTrackSplittingValidation(name, self.
__config)
171 elif valType ==
"zmumu":
172 validation = ZMuMuValidation( name,
174 elif valType ==
"primaryvertex":
178 raise AllInOneError(
"Unknown validation mode '%s'"%valType)
183 """This private method creates the needed files for the validation job. 185 self.validation.createConfiguration( outpath )
188 self.
__scripts = sum([
addIndex(script, self.validation.NJobs)
for script
in self.validation.createScript( outpath )], [])
189 if jobMode.split(
',' )[0] ==
"crab":
190 self.validation.createCrabCfg( outpath )
194 """This is the method called to create the job files.""" 196 os.path.abspath( self.__commandLineOptions.Name) )
200 if self.validation.jobid:
201 self.batchJobIds.append(self.validation.jobid)
202 log =
"> " + self.validation.name +
" is already validated." 206 if self.validation.jobid:
207 print "jobid {} will be ignored, since the validation {} is not preexisting".
format(self.validation.jobid, self.validation.name)
209 general = self.__config.getGeneral()
212 name = os.path.splitext( os.path.basename( script) )[0]
213 ValidationJob.jobCount += 1
214 if self.__commandLineOptions.dryRun:
215 print "%s would run: %s"%( name, os.path.basename( script) )
217 log =
"> Validating "+name
218 print "> Validating "+name
219 if self.validation.jobmode ==
"interactive":
221 ValidationJob.interactCount += 1
222 elif self.validation.jobmode.split(
",")[0] ==
"lxBatch":
224 "commands": self.validation.jobmode.split(
",")[1],
225 "logDir": general[
"logdir"],
228 "bsub":
"/afs/cern.ch/cms/caf/scripts/cmsbsub" 230 for ext
in (
"stdout",
"stderr",
"stdout.gz",
"stderr.gz"):
231 oldlog =
"%(logDir)s/%(jobName)s."%repMap + ext
232 if os.path.exists(oldlog):
236 "-o %(logDir)s/%(jobName)s.stdout " 237 "-e %(logDir)s/%(jobName)s.stderr " 241 jobid=bsubOut.split(
"<")[1].
split(
">")[0]
242 self.JobId.append(jobid)
243 ValidationJob.batchJobIds.append(jobid)
245 ValidationJob.batchCount += 1
246 elif self.validation.jobmode.split(
"," )[0] ==
"crab":
247 os.chdir( general[
"logdir"] )
248 crabName =
"crab." + os.path.basename( script )[:-3]
250 options = {
"-create":
"",
251 "-cfg": crabName +
".cfg",
254 theCrab.run( options )
255 except AllInOneError
as e:
256 print "crab:",
str(e).
split(
"\n")[0]
258 ValidationJob.crabCount += 1
261 raise AllInOneError(
"Unknown 'jobmode'!\n" 262 "Please change this parameter either in " 263 "the [general] or in the [" 265 +
"] section to one of the following " 267 "\tinteractive\n\tlxBatch, -q <queue>\n" 268 "\tcrab, -q <queue>")
277 return self.validation.needsproxy
and not self.
__preexisting and not self.__commandLineOptions.dryRun
282 if(len(validations) == 0):
283 raise AllInOneError(
"Cowardly refusing to merge nothing!")
285 config = validations[0].config
286 repMap = config.getGeneral()
289 "CompareAlignments":
"",
290 "RunValidationPlots":
"",
291 "CMSSW_BASE": os.environ[
"CMSSW_BASE"],
292 "SCRAM_ARCH": os.environ[
"SCRAM_ARCH"],
293 "CMSSW_RELEASE_BASE": os.environ[
"CMSSW_RELEASE_BASE"],
297 for validation
in validations:
298 for referenceName
in validation.filesToCompare:
299 validationtype = type(validation)
300 if issubclass(validationtype, PreexistingValidation):
302 for parentclass
in validationtype.mro():
303 if not issubclass(parentclass, PreexistingValidation):
304 validationtype = parentclass
306 key = (validationtype, referenceName)
307 if key
in comparisonLists:
308 comparisonLists[key].
append(validation)
310 comparisonLists[key] = [validation]
314 repMap[
"doMerge"] =
"mergeRetCode=0\n" 315 repMap[
"rmUnmerged"] = (
"if [[ mergeRetCode -eq 0 ]]; then\n" 316 " echo -e \\n\"Merging succeeded, removing original files.\"\n")
317 repMap[
"beforeMerge"] =
"" 318 repMap[
"mergeParallelFilePrefixes"] =
"" 319 repMap[
"createResultsDirectory"]=
"" 326 if options.mergeOfflineParallel:
327 parallelMergeObjects={}
328 for (validationType, referencename), validations
in comparisonLists.iteritems():
329 for validation
in validations:
331 if (isinstance(validation, PreexistingValidation)
332 or validation.NJobs == 1
333 or not isinstance(validation, ParallelValidation)):
335 if options.mergeOfflineParallel
and validationType.valType==
'offline' and validation.jobmode.split(
",")[0]==
"lxBatch":
336 repMapTemp=repMap.copy()
337 if validationType
not in anythingToMerge:
338 anythingToMerge += [validationType]
340 fileName=
"TkAlMergeInit" 341 filePath = os.path.join(path, fileName+
".sh")
342 theFile = open( filePath,
"w" )
343 repMapTemp[
"createResultsDirectory"]=
"#!/bin/bash" 344 repMapTemp[
"createResultsDirectory"]+=
replaceByMap(configTemplates.createResultsDirectoryTemplate, repMapTemp)
345 theFile.write(
replaceByMap( configTemplates.createResultsDirectoryTemplate, repMapTemp ) )
347 os.chmod(filePath,0o755)
351 repMapTemp[
"createResultsDirectory"]=
"" 355 repMapTemp[
"beforeMerge"] += validationType.doInitMerge()
356 repMapTemp[
"doMerge"] +=
'\n\n\n\necho -e "\n\nMerging results from %s jobs with alignment %s"\n\n' % (validationType.valType,validation.alignmentToValidate.name)
357 repMapTemp[
"doMerge"] += validation.doMerge()
358 for f
in validation.getRepMap()[
"outputFiles"]:
359 longName = os.path.join(
"/eos/cms/store/caf/user/$USER/",
360 validation.getRepMap()[
"eosdir"], f)
361 repMapTemp[
"rmUnmerged"] +=
" rm "+longName+
"\n" 363 repMapTemp[
"rmUnmerged"] += (
"else\n" 364 " echo -e \\n\"WARNING: Merging failed, unmerged" 365 " files won't be deleted.\\n" 366 "(Ignore this warning if merging was done earlier)\"\n" 370 repMapTemp[
"DownloadData"] =
replaceByMap( configTemplates.mergeParallelResults, repMapTemp )
372 repMapTemp[
"RunValidationPlots"] = validationType.doRunPlots(validations)
375 fileName=
"TkAlMerge"+validation.alignmentToValidate.name
376 filePath = os.path.join(path, fileName+
".sh")
377 theFile = open( filePath,
"w" )
378 theFile.write(
replaceByMap( configTemplates.mergeParallelOfflineTemplate, repMapTemp ) )
380 os.chmod(filePath,0o755)
382 if "parallel" in parallelMergeObjects:
390 if validationType
not in anythingToMerge:
391 anythingToMerge += [validationType]
392 repMap[
"doMerge"] +=
'\n\n\n\necho -e "\n\nMerging results from %s jobs"\n\n' % validationType.valType
393 repMap[
"beforeMerge"] += validationType.doInitMerge()
394 repMap[
"doMerge"] += validation.doMerge()
395 for f
in validation.getRepMap()[
"outputFiles"]:
396 longName = os.path.join(
"/eos/cms/store/caf/user/$USER/",
397 validation.getRepMap()[
"eosdir"], f)
398 repMap[
"rmUnmerged"] +=
" rm "+longName+
"\n" 402 repMap[
"rmUnmerged"] += (
"else\n" 403 " echo -e \\n\"WARNING: Merging failed, unmerged" 404 " files won't be deleted.\\n" 405 "(Ignore this warning if merging was done earlier)\"\n" 411 repMap[
"DownloadData"] +=
replaceByMap( configTemplates.mergeParallelResults, repMap )
413 repMap[
"DownloadData"] =
"" 415 repMap[
"RunValidationPlots"] =
"" 416 for (validationType, referencename), validations
in comparisonLists.iteritems():
417 if issubclass(validationType, ValidationWithPlots):
418 repMap[
"RunValidationPlots"] += validationType.doRunPlots(validations)
420 repMap[
"CompareAlignments"] =
"#run comparisons" 421 for (validationType, referencename), validations
in comparisonLists.iteritems():
422 if issubclass(validationType, ValidationWithComparison):
423 repMap[
"CompareAlignments"] += validationType.doComparison(validations)
426 if options.mergeOfflineParallel
and parallelMergeObjects!={}:
427 parallelMergeObjects[
"continue"]=
ParallelMergeJob(
"TkAlMergeFinal",os.path.join(path,
"TkAlMergeFinal.sh"),[])
428 filePath = os.path.join(path,
"TkAlMergeFinal.sh")
431 repMap[
"createResultsDirectory"]=
replaceByMap(configTemplates.createResultsDirectoryTemplate, repMap)
432 filePath = os.path.join(path,
"TkAlMerge.sh")
436 theFile = open( filePath,
"w" )
437 theFile.write(
replaceByMap( configTemplates.mergeTemplate, repMap ) )
439 os.chmod(filePath,0o755)
441 if options.mergeOfflineParallel:
442 return {
'TkAlMerge.sh':filePath,
'parallelMergeObjects':parallelMergeObjects}
447 if config.has_section(
"alternateTemplates"):
448 for templateName
in config.options(
"alternateTemplates"):
449 if templateName ==
"AutoAlternates":
451 newTemplateName = config.get(
"alternateTemplates", templateName )
460 optParser = optparse.OptionParser()
461 optParser.description =
"""All-in-one Alignment Validation. 462 This will run various validation procedures either on batch queues or interactively. 463 If no name is given (-N parameter) a name containing time and date is created automatically. 464 To merge the outcome of all validation procedures run TkAlMerge.sh in your validation's directory. 466 optParser.add_option(
"-n",
"--dryRun", dest=
"dryRun", action=
"store_true", default=
False,
467 help=
"create all scripts and cfg File but do not start jobs (default=False)")
468 optParser.add_option(
"--getImages", dest=
"getImages", action=
"store_true", default=
True,
469 help=
"get all Images created during the process (default= True)")
470 defaultConfig =
"TkAlConfig.ini" 471 optParser.add_option(
"-c",
"--config", dest=
"config", default = defaultConfig,
472 help=
"configuration to use (default TkAlConfig.ini) this can be a comma-seperated list of all .ini file you want to merge", metavar=
"CONFIG")
473 optParser.add_option(
"-N",
"--Name", dest=
"Name",
474 help=
"Name of this validation (default: alignmentValidation_DATE_TIME)", metavar=
"NAME")
475 optParser.add_option(
"-r",
"--restrictTo", dest=
"restrictTo",
476 help=
"restrict validations to given modes (comma seperated) (default: no restriction)", metavar=
"RESTRICTTO")
477 optParser.add_option(
"-s",
"--status", dest=
"crabStatus", action=
"store_true", default =
False,
478 help=
"get the status of the crab jobs", metavar=
"STATUS")
479 optParser.add_option(
"-d",
"--debug", dest=
"debugMode", action=
"store_true",
481 help=
"run the tool to get full traceback of errors",
483 optParser.add_option(
"-m",
"--autoMerge", dest=
"autoMerge", action=
"store_true", default =
False,
484 help=
"submit TkAlMerge.sh to run automatically when all jobs have finished (default=False)." 485 " Works only for batch jobs")
486 optParser.add_option(
"--mergeOfflineParallel", dest=
"mergeOfflineParallel", action=
"store_true", default =
False,
487 help=
"Enable parallel merging of offline data. Best used with -m option. Only works with lxBatch-jobmode", metavar=
"MERGE_PARALLEL")
490 (options, args) = optParser.parse_args(argv)
492 if not options.restrictTo ==
None:
493 options.restrictTo = options.restrictTo.split(
",")
495 options.config = [ os.path.abspath( iniFile )
for iniFile
in \
496 options.config.split(
"," ) ]
497 config = BetterConfigParser()
498 outputIniFileSet = set( config.read( options.config ) )
499 failedIniFiles = [ iniFile
for iniFile
in options.config
if iniFile
not in outputIniFileSet ]
502 if options.config == [ os.path.abspath( defaultConfig ) ]:
503 if (
not options.crabStatus )
and \
504 (
not os.path.exists( defaultConfig ) ):
505 raise AllInOneError(
"Default 'ini' file '%s' not found!\n" 506 "You can specify another name with the " 507 "command line option '-c'/'--config'." 510 for iniFile
in failedIniFiles:
511 if not os.path.exists( iniFile ):
512 raise AllInOneError(
"'%s' does not exist. Please check for " 513 "typos in the filename passed to the " 514 "'-c'/'--config' option!" 517 raise AllInOneError((
"'%s' does exist, but parsing of the " 518 "content failed!" ) % iniFile)
521 if options.Name ==
None:
522 if not options.crabStatus:
523 options.Name =
"alignmentValidation_%s"%(datetime.datetime.now().strftime(
"%y%m%d_%H%M%S"))
525 existingValDirs = fnmatch.filter( os.walk(
'.' ).
next()[1],
526 "alignmentValidation_*" )
527 if len( existingValDirs ) > 0:
528 options.Name = existingValDirs[-1]
530 print "Cannot guess last working directory!" 531 print (
"Please use the parameter '-N' or '--Name' to specify " 532 "the task for which you want a status report." )
536 outPath = os.path.abspath( options.Name )
539 if options.crabStatus:
541 crabLogDirs = fnmatch.filter( os.walk(
'.').
next()[1],
"crab.*" )
542 if len( crabLogDirs ) == 0:
543 print "Found no crab tasks for job name '%s'"%( options.Name )
546 for crabLogDir
in crabLogDirs:
548 print "*" +
"=" * 78 +
"*" 549 print (
"| Status report and output retrieval for:" 550 +
" " * (77 - len(
"Status report and output retrieval for:" ) )
552 taskName = crabLogDir.replace(
"crab.",
"" )
553 print "| " + taskName +
" " * (77 - len( taskName ) ) +
"|" 554 print "*" +
"=" * 78 +
"*" 556 crabOptions = {
"-getoutput":
"",
559 theCrab.run( crabOptions )
560 except AllInOneError
as e:
561 print "crab: No output retrieved for this task." 562 crabOptions = {
"-status":
"",
564 theCrab.run( crabOptions )
567 general = config.getGeneral()
568 config.set(
"internals",
"workdir",os.path.join(general[
"workdir"],options.Name) )
569 config.set(
"internals",
"scriptsdir",outPath)
570 config.set(
"general",
"datadir",os.path.join(general[
"datadir"],options.Name) )
571 config.set(
"general",
"logdir",os.path.join(general[
"logdir"],options.Name) )
572 config.set(
"general",
"eosdir",os.path.join(
"AlignmentValidation", general[
"eosdir"], options.Name) )
574 if not os.path.exists( outPath ):
575 os.makedirs( outPath )
576 elif not os.path.isdir( outPath ):
577 raise AllInOneError(
"the file %s is in the way rename the Job or move it away"%outPath)
583 backupConfigFile = open( os.path.join( outPath,
"usedConfiguration.ini" ) ,
"w" )
584 config.write( backupConfigFile )
593 shutil.copyfile(
getCommandOutput2(
"voms-proxy-info --path").
strip(), os.path.join(outPath,
".user_proxy"))
596 for validation
in config.items(
"validation"):
597 alignmentList = [validation[1]]
598 validationsToAdd = [(validation[0],alignment) \
599 for alignment
in alignmentList]
600 validations.extend(validationsToAdd)
602 for validation
in validations ]
604 if job.needsproxy
and not proxyexists:
605 raise AllInOneError(
"At least one job needs a grid proxy, please init one.")
606 map(
lambda job: job.createJob(), jobs )
607 validations = [ job.getValidation()
for job
in jobs ]
609 if options.mergeOfflineParallel:
610 parallelMergeObjects=
createMergeScript(outPath, validations, options)[
'parallelMergeObjects']
616 map(
lambda job: job.runJob(), jobs )
618 if options.autoMerge
and ValidationJob.jobCount == ValidationJob.batchCount
and config.getGeneral()[
"jobmode"].
split(
",")[0] ==
"lxBatch":
619 print "> Automatically merging jobs when they have ended" 624 if options.mergeOfflineParallel
and parallelMergeObjects!={}:
625 initID=parallelMergeObjects[
"init"].runJob(config).
split(
"<")[1].
split(
">")[0]
627 for parallelMergeScript
in parallelMergeObjects[
"parallel"]:
628 parallelMergeScript.addDependency(initID)
630 if isinstance(job.validation, OfflineValidation)
and "TkAlMerge"+job.validation.alignmentToValidate.name==parallelMergeScript.name:
631 parallelMergeScript.addDependency(job.JobId)
632 parallelIDs.append(parallelMergeScript.runJob(config).
split(
"<")[1].
split(
">")[0])
633 parallelMergeObjects[
"continue"].addDependency(parallelIDs)
634 parallelMergeObjects[
"continue"].addDependency(ValidationJob.batchJobIds)
635 parallelMergeObjects[
"continue"].runJob(config)
642 "commands": config.getGeneral()[
"jobmode"].
split(
",")[1],
643 "jobName":
"TkAlMerge",
644 "logDir": config.getGeneral()[
"logdir"],
645 "script":
"TkAlMerge.sh",
646 "bsub":
"/afs/cern.ch/cms/caf/scripts/cmsbsub",
647 "conditions":
'"' +
" && ".
join([
"ended(" + jobId +
")" for jobId
in ValidationJob.batchJobIds]) +
'"' 649 for ext
in (
"stdout",
"stderr",
"stdout.gz",
"stderr.gz"):
650 oldlog =
"%(logDir)s/%(jobName)s."%repMap + ext
651 if os.path.exists(oldlog):
656 "-o %(logDir)s/%(jobName)s.stdout " 657 "-e %(logDir)s/%(jobName)s.stderr " 659 "%(logDir)s/%(script)s"%repMap)
661 if __name__ ==
"__main__":
663 if "-d" in sys.argv[1:]
or "--debug" in sys.argv[1:]:
668 except AllInOneError
as e:
669 print "\nAll-In-One Tool:",
str(e)
def main(argv=None)
— Main —############################
def loadTemplates(config)
def __init__(self, _name, _path, _dependency)
def createMergeScript(path, validations, options)
def getCommandOutput2(command)
— Classes —############################
def addIndex(filename, njobs, index=None)
def __getValidation(self, valType, name, alignments, config, options)
def replaceByMap(target, the_map)
— Helpers —############################
def __createJob(self, jobMode, outpath)
static std::string join(char **cmd)
def alternateTemplate(templateName, alternateTemplateName)
Alternate Templates ###
def __init__(self, validation, config, options)
def addDependency(self, dependency)