3 from __future__
import print_function
12 import Alignment.OfflineValidation.TkAlAllInOneTool.configTemplates \
14 import Alignment.OfflineValidation.TkAlAllInOneTool.crabWrapper
as crabWrapper
15 from Alignment.OfflineValidation.TkAlAllInOneTool.TkAlExceptions \
17 from Alignment.OfflineValidation.TkAlAllInOneTool.helperFunctions \
18 import replaceByMap, getCommandOutput2, addIndex
19 from Alignment.OfflineValidation.TkAlAllInOneTool.betterConfigParser \
20 import BetterConfigParser
21 from Alignment.OfflineValidation.TkAlAllInOneTool.alignment
import Alignment
24 import GenericValidation, ParallelValidation, ValidationWithComparison, ValidationWithPlots
25 from Alignment.OfflineValidation.TkAlAllInOneTool.geometryComparison \
26 import GeometryComparison
28 import OfflineValidation, OfflineValidationDQM
29 from Alignment.OfflineValidation.TkAlAllInOneTool.monteCarloValidation \
30 import MonteCarloValidation
32 import TrackSplittingValidation
34 import ZMuMuValidation
36 import PrimaryVertexValidation
37 from Alignment.OfflineValidation.TkAlAllInOneTool.preexistingValidation \
39 from Alignment.OfflineValidation.TkAlAllInOneTool.plottingOptions \
40 import PlottingOptions
41 import Alignment.OfflineValidation.TkAlAllInOneTool.globalDictionaries \
53 if isinstance(dependency,list):
54 self.dependencies.extend(dependency)
56 self.dependencies.append(dependency)
59 "commands": config.getGeneral()[
"jobmode"].
split(
",")[1],
61 "logDir": config.getGeneral()[
"logdir"],
63 "bsub":
"/afs/cern.ch/cms/caf/scripts/cmsbsub",
64 "conditions":
'"' +
" && ".
join([
"ended(" + jobId +
")" for jobId
in self.
dependencies]) +
'"' 68 "-o %(logDir)s/%(jobName)s.stdout " 69 "-e %(logDir)s/%(jobName)s.stderr " 82 def __init__( self, validation, config, options ):
84 if validation[1] ==
"":
86 valString = validation[0].
split(
"->" )[0]
87 alignments = validation[0].
split(
"->" )[1]
89 if "->" in validation[0]:
90 msg = (
"Instead of using the intermediate syntax\n'" 91 +valString.strip()+
"-> "+alignments.strip()
92 +
":'\nyou have to use the now fully supported syntax \n'" 93 +valString.strip()+
": " 94 +alignments.strip()+
"'.")
95 raise AllInOneError(msg)
97 valString = validation[0]
98 alignments = validation[1]
99 valString = valString.split()
111 print (
"offlineParallel and offline are now the same. To run an offline parallel validation,\n" 112 "just set parallelJobs to something > 1. There is no reason to call it offlineParallel anymore.")
115 if not self.__config.has_section( section ):
116 raise AllInOneError(
"Validation '%s' of type '%s' is requested in" 117 " '[validation]' section, but is not defined." 118 "\nYou have to add a '[%s]' section." 125 if valType ==
"compare":
126 alignmentsList = alignments.split(
"," )
127 firstAlignList = alignmentsList[0].
split()
128 firstAlignName = firstAlignList[0].
strip()
129 if firstAlignName ==
"IDEAL":
130 raise AllInOneError(
"'IDEAL' has to be the second (reference)" 131 " alignment in 'compare <val_name>: " 132 "<alignment> <reference>'.")
133 if len( firstAlignList ) > 1:
134 firstRun = firstAlignList[1]
136 raise AllInOneError(
"Have to provide a run number for geometry comparison")
138 firstAlignName = firstAlign.name
139 secondAlignList = alignmentsList[1].
split()
140 secondAlignName = secondAlignList[0].
strip()
141 if secondAlignName ==
"IDEAL":
142 secondAlign = secondAlignName
144 if len( secondAlignList ) > 1:
145 secondRun = secondAlignList[1]
147 raise AllInOneError(
"Have to provide a run number for geometry comparison")
150 secondAlignName = secondAlign.name
152 validation = GeometryComparison( name, firstAlign, secondAlign,
154 self.__commandLineOptions.getImages)
155 elif valType ==
"offline":
156 validation = OfflineValidation( name,
158 elif valType ==
"preexistingoffline":
159 validation = PreexistingOfflineValidation(name, self.
__config)
160 elif valType ==
"offlineDQM":
161 validation = OfflineValidationDQM( name,
163 elif valType ==
"mcValidate":
164 validation = MonteCarloValidation( name,
166 elif valType ==
"preexistingmcValidate":
167 validation = PreexistingMonteCarloValidation(name, self.
__config)
168 elif valType ==
"split":
169 validation = TrackSplittingValidation( name,
171 elif valType ==
"preexistingsplit":
172 validation = PreexistingTrackSplittingValidation(name, self.
__config)
173 elif valType ==
"zmumu":
174 validation = ZMuMuValidation( name,
176 elif valType ==
"primaryvertex":
179 elif valType ==
"preexistingprimaryvertex":
180 validation = PreexistingPrimaryVertexValidation(name, self.
__config)
182 raise AllInOneError(
"Unknown validation mode '%s'"%valType)
187 """This private method creates the needed files for the validation job. 189 self.validation.createConfiguration( outpath )
192 self.
__scripts = sum([
addIndex(script, self.validation.NJobs)
for script
in self.validation.createScript( outpath )], [])
193 if jobMode.split(
',' )[0] ==
"crab":
194 self.validation.createCrabCfg( outpath )
198 """This is the method called to create the job files.""" 200 os.path.abspath( self.__commandLineOptions.Name) )
204 if self.validation.jobid:
205 self.batchJobIds.append(self.validation.jobid)
206 log =
"> " + self.validation.name +
" is already validated." 210 if self.validation.jobid:
211 print(
"jobid {} will be ignored, since the validation {} is not preexisting".
format(self.validation.jobid, self.validation.name))
213 general = self.__config.getGeneral()
216 name = os.path.splitext( os.path.basename( script) )[0]
217 ValidationJob.jobCount += 1
218 if self.__commandLineOptions.dryRun:
219 print(
"%s would run: %s"%( name, os.path.basename( script) ))
221 log =
"> Validating "+name
222 print(
"> Validating "+name)
223 if self.validation.jobmode ==
"interactive":
225 ValidationJob.interactCount += 1
226 elif self.validation.jobmode.split(
",")[0] ==
"lxBatch":
228 "commands": self.validation.jobmode.split(
",")[1],
229 "logDir": general[
"logdir"],
232 "bsub":
"/afs/cern.ch/cms/caf/scripts/cmsbsub" 234 for ext
in (
"stdout",
"stderr",
"stdout.gz",
"stderr.gz"):
235 oldlog =
"%(logDir)s/%(jobName)s."%repMap + ext
236 if os.path.exists(oldlog):
240 "-o %(logDir)s/%(jobName)s.stdout " 241 "-e %(logDir)s/%(jobName)s.stderr " 245 jobid=bsubOut.split(
"<")[1].
split(
">")[0]
246 self.JobId.append(jobid)
247 ValidationJob.batchJobIds.append(jobid)
249 ValidationJob.batchCount += 1
250 elif self.validation.jobmode.split(
"," )[0] ==
"crab":
251 os.chdir( general[
"logdir"] )
252 crabName =
"crab." + os.path.basename( script )[:-3]
254 options = {
"-create":
"",
255 "-cfg": crabName +
".cfg",
258 theCrab.run( options )
259 except AllInOneError
as e:
262 ValidationJob.crabCount += 1
265 raise AllInOneError(
"Unknown 'jobmode'!\n" 266 "Please change this parameter either in " 267 "the [general] or in the [" 269 +
"] section to one of the following " 271 "\tinteractive\n\tlxBatch, -q <queue>\n" 272 "\tcrab, -q <queue>")
281 return self.validation.needsproxy
and not self.
__preexisting and not self.__commandLineOptions.dryRun
286 if(len(validations) == 0):
287 raise AllInOneError(
"Cowardly refusing to merge nothing!")
289 config = validations[0].config
290 repMap = config.getGeneral()
293 "CompareAlignments":
"",
294 "RunValidationPlots":
"",
295 "CMSSW_BASE": os.environ[
"CMSSW_BASE"],
296 "SCRAM_ARCH": os.environ[
"SCRAM_ARCH"],
297 "CMSSW_RELEASE_BASE": os.environ[
"CMSSW_RELEASE_BASE"],
301 for validation
in validations:
302 for referenceName
in validation.filesToCompare:
303 validationtype = type(validation)
304 if issubclass(validationtype, PreexistingValidation):
306 for parentclass
in validationtype.mro():
307 if not issubclass(parentclass, PreexistingValidation):
308 validationtype = parentclass
310 key = (validationtype, referenceName)
311 if key
in comparisonLists:
312 comparisonLists[key].
append(validation)
314 comparisonLists[key] = [validation]
318 repMap[
"doMerge"] =
"mergeRetCode=0\n" 319 repMap[
"rmUnmerged"] = (
"if [[ mergeRetCode -eq 0 ]]; then\n" 320 " echo -e \\n\"Merging succeeded, removing original files.\"\n")
321 repMap[
"beforeMerge"] =
"" 322 repMap[
"mergeParallelFilePrefixes"] =
"" 323 repMap[
"createResultsDirectory"]=
"" 330 if options.mergeOfflineParallel:
331 parallelMergeObjects={}
332 for (validationType, referencename), validations
in six.iteritems(comparisonLists):
333 for validation
in validations:
335 if (isinstance(validation, PreexistingValidation)
336 or validation.NJobs == 1
337 or not isinstance(validation, ParallelValidation)):
339 if options.mergeOfflineParallel
and validationType.valType==
'offline' and validation.jobmode.split(
",")[0]==
"lxBatch":
340 repMapTemp=repMap.copy()
341 if validationType
not in anythingToMerge:
342 anythingToMerge += [validationType]
344 fileName=
"TkAlMergeInit" 345 filePath = os.path.join(path, fileName+
".sh")
346 theFile = open( filePath,
"w" )
347 repMapTemp[
"createResultsDirectory"]=
"#!/bin/bash" 348 repMapTemp[
"createResultsDirectory"]+=
replaceByMap(configTemplates.createResultsDirectoryTemplate, repMapTemp)
349 theFile.write(
replaceByMap( configTemplates.createResultsDirectoryTemplate, repMapTemp ) )
351 os.chmod(filePath,0o755)
355 repMapTemp[
"createResultsDirectory"]=
"" 359 repMapTemp[
"beforeMerge"] += validationType.doInitMerge()
360 repMapTemp[
"doMerge"] +=
'\n\n\n\necho -e "\n\nMerging results from %s jobs with alignment %s"\n\n' % (validationType.valType,validation.alignmentToValidate.name)
361 repMapTemp[
"doMerge"] += validation.doMerge()
362 for f
in validation.getRepMap()[
"outputFiles"]:
363 longName = os.path.join(
"/eos/cms/store/group/alca_trackeralign/AlignmentValidation/",
364 validation.getRepMap()[
"eosdir"], f)
365 repMapTemp[
"rmUnmerged"] +=
" rm "+longName+
"\n" 367 repMapTemp[
"rmUnmerged"] += (
"else\n" 368 " echo -e \\n\"WARNING: Merging failed, unmerged" 369 " files won't be deleted.\\n" 370 "(Ignore this warning if merging was done earlier)\"\n" 374 repMapTemp[
"DownloadData"] =
replaceByMap( configTemplates.mergeParallelResults, repMapTemp )
376 repMapTemp[
"RunValidationPlots"] = validationType.doRunPlots(validations)
379 fileName=
"TkAlMergeOfflineValidation"+validation.name+validation.alignmentToValidate.name
380 filePath = os.path.join(path, fileName+
".sh")
381 theFile = open( filePath,
"w" )
382 theFile.write(
replaceByMap( configTemplates.mergeParallelOfflineTemplate, repMapTemp ) )
384 os.chmod(filePath,0o755)
386 if "parallel" in parallelMergeObjects:
394 if validationType
not in anythingToMerge:
395 anythingToMerge += [validationType]
396 repMap[
"doMerge"] +=
'\n\n\n\necho -e "\n\nMerging results from %s jobs"\n\n' % validationType.valType
397 repMap[
"beforeMerge"] += validationType.doInitMerge()
398 repMap[
"doMerge"] += validation.doMerge()
399 for f
in validation.getRepMap()[
"outputFiles"]:
400 longName = os.path.join(
"/eos/cms/store/group/alca_trackeralign/AlignmentValidation/",
401 validation.getRepMap()[
"eosdir"], f)
402 repMap[
"rmUnmerged"] +=
" rm "+longName+
"\n" 406 repMap[
"rmUnmerged"] += (
"else\n" 407 " echo -e \\n\"WARNING: Merging failed, unmerged" 408 " files won't be deleted.\\n" 409 "(Ignore this warning if merging was done earlier)\"\n" 415 repMap[
"DownloadData"] +=
replaceByMap( configTemplates.mergeParallelResults, repMap )
417 repMap[
"DownloadData"] =
"" 419 repMap[
"RunValidationPlots"] =
"" 420 for (validationType, referencename), validations
in six.iteritems(comparisonLists):
421 if issubclass(validationType, ValidationWithPlots):
422 repMap[
"RunValidationPlots"] += validationType.doRunPlots(validations)
424 repMap[
"CompareAlignments"] =
"#run comparisons" 425 for (validationType, referencename), validations
in six.iteritems(comparisonLists):
426 if issubclass(validationType, ValidationWithComparison):
427 repMap[
"CompareAlignments"] += validationType.doComparison(validations)
430 if options.mergeOfflineParallel
and parallelMergeObjects!={}:
431 parallelMergeObjects[
"continue"]=
ParallelMergeJob(
"TkAlMergeFinal",os.path.join(path,
"TkAlMergeFinal.sh"),[])
432 filePath = os.path.join(path,
"TkAlMergeFinal.sh")
435 repMap[
"createResultsDirectory"]=
replaceByMap(configTemplates.createResultsDirectoryTemplate, repMap)
436 filePath = os.path.join(path,
"TkAlMerge.sh")
440 theFile = open( filePath,
"w" )
441 theFile.write(
replaceByMap( configTemplates.mergeTemplate, repMap ) )
443 os.chmod(filePath,0o755)
445 if options.mergeOfflineParallel:
446 return {
'TkAlMerge.sh':filePath,
'parallelMergeObjects':parallelMergeObjects}
451 if config.has_section(
"alternateTemplates"):
452 for templateName
in config.options(
"alternateTemplates"):
453 if templateName ==
"AutoAlternates":
455 newTemplateName = config.get(
"alternateTemplates", templateName )
464 optParser = optparse.OptionParser()
465 optParser.description =
"""All-in-one Alignment Validation. 466 This will run various validation procedures either on batch queues or interactively. 467 If no name is given (-N parameter) a name containing time and date is created automatically. 468 To merge the outcome of all validation procedures run TkAlMerge.sh in your validation's directory. 470 optParser.add_option(
"-n",
"--dryRun", dest=
"dryRun", action=
"store_true", default=
False,
471 help=
"create all scripts and cfg File but do not start jobs (default=False)")
472 optParser.add_option(
"--getImages", dest=
"getImages", action=
"store_true", default=
True,
473 help=
"get all Images created during the process (default= True)")
474 defaultConfig =
"TkAlConfig.ini" 475 optParser.add_option(
"-c",
"--config", dest=
"config", default = defaultConfig,
476 help=
"configuration to use (default TkAlConfig.ini) this can be a comma-seperated list of all .ini file you want to merge", metavar=
"CONFIG")
477 optParser.add_option(
"-N",
"--Name", dest=
"Name",
478 help=
"Name of this validation (default: alignmentValidation_DATE_TIME)", metavar=
"NAME")
479 optParser.add_option(
"-r",
"--restrictTo", dest=
"restrictTo",
480 help=
"restrict validations to given modes (comma seperated) (default: no restriction)", metavar=
"RESTRICTTO")
481 optParser.add_option(
"-s",
"--status", dest=
"crabStatus", action=
"store_true", default =
False,
482 help=
"get the status of the crab jobs", metavar=
"STATUS")
483 optParser.add_option(
"-d",
"--debug", dest=
"debugMode", action=
"store_true",
485 help=
"run the tool to get full traceback of errors",
487 optParser.add_option(
"-m",
"--autoMerge", dest=
"autoMerge", action=
"store_true", default =
False,
488 help=
"submit TkAlMerge.sh to run automatically when all jobs have finished (default=False)." 489 " Works only for batch jobs")
490 optParser.add_option(
"--mergeOfflineParallel", dest=
"mergeOfflineParallel", action=
"store_true", default =
False,
491 help=
"Enable parallel merging of offline data. Best used with -m option. Only works with lxBatch-jobmode", metavar=
"MERGE_PARALLEL")
494 (options, args) = optParser.parse_args(argv)
496 if not options.restrictTo ==
None:
497 options.restrictTo = options.restrictTo.split(
",")
499 options.config = [ os.path.abspath( iniFile )
for iniFile
in \
500 options.config.split(
"," ) ]
501 config = BetterConfigParser()
502 outputIniFileSet = set( config.read( options.config ) )
503 failedIniFiles = [ iniFile
for iniFile
in options.config
if iniFile
not in outputIniFileSet ]
506 if options.config == [ os.path.abspath( defaultConfig ) ]:
507 if (
not options.crabStatus )
and \
508 (
not os.path.exists( defaultConfig ) ):
509 raise AllInOneError(
"Default 'ini' file '%s' not found!\n" 510 "You can specify another name with the " 511 "command line option '-c'/'--config'." 514 for iniFile
in failedIniFiles:
515 if not os.path.exists( iniFile ):
516 raise AllInOneError(
"'%s' does not exist. Please check for " 517 "typos in the filename passed to the " 518 "'-c'/'--config' option!" 521 raise AllInOneError((
"'%s' does exist, but parsing of the " 522 "content failed!" ) % iniFile)
525 if options.Name ==
None:
526 if not options.crabStatus:
527 options.Name =
"alignmentValidation_%s"%(datetime.datetime.now().strftime(
"%y%m%d_%H%M%S"))
529 existingValDirs = fnmatch.filter( os.walk(
'.' ).
next()[1],
530 "alignmentValidation_*" )
531 if len( existingValDirs ) > 0:
532 options.Name = existingValDirs[-1]
534 print(
"Cannot guess last working directory!")
535 print (
"Please use the parameter '-N' or '--Name' to specify " 536 "the task for which you want a status report." )
540 outPath = os.path.abspath( options.Name )
543 if options.crabStatus:
545 crabLogDirs = fnmatch.filter( os.walk(
'.').
next()[1],
"crab.*" )
546 if len( crabLogDirs ) == 0:
547 print(
"Found no crab tasks for job name '%s'"%( options.Name ))
550 for crabLogDir
in crabLogDirs:
552 print(
"*" +
"=" * 78 +
"*")
553 print (
"| Status report and output retrieval for:" 554 +
" " * (77 - len(
"Status report and output retrieval for:" ) )
556 taskName = crabLogDir.replace(
"crab.",
"" )
557 print(
"| " + taskName +
" " * (77 - len( taskName ) ) +
"|")
558 print(
"*" +
"=" * 78 +
"*")
560 crabOptions = {
"-getoutput":
"",
563 theCrab.run( crabOptions )
564 except AllInOneError
as e:
565 print(
"crab: No output retrieved for this task.")
566 crabOptions = {
"-status":
"",
568 theCrab.run( crabOptions )
571 general = config.getGeneral()
572 config.set(
"internals",
"workdir",os.path.join(general[
"workdir"],options.Name) )
573 config.set(
"internals",
"scriptsdir",outPath)
574 config.set(
"general",
"datadir",os.path.join(general[
"datadir"],options.Name) )
575 config.set(
"general",
"logdir",os.path.join(general[
"logdir"],options.Name) )
576 config.set(
"general",
"eosdir",os.path.join(
"AlignmentValidation", general[
"eosdir"], options.Name) )
578 if not os.path.exists( outPath ):
579 os.makedirs( outPath )
580 elif not os.path.isdir( outPath ):
581 raise AllInOneError(
"the file %s is in the way rename the Job or move it away"%outPath)
587 backupConfigFile = open( os.path.join( outPath,
"usedConfiguration.ini" ) ,
"w" )
588 config.write( backupConfigFile )
597 shutil.copyfile(
getCommandOutput2(
"voms-proxy-info --path").
strip(), os.path.join(outPath,
".user_proxy"))
600 for validation
in config.items(
"validation"):
601 alignmentList = [validation[1]]
602 validationsToAdd = [(validation[0],alignment) \
603 for alignment
in alignmentList]
604 validations.extend(validationsToAdd)
606 for validation
in validations ]
608 if job.needsproxy
and not proxyexists:
609 raise AllInOneError(
"At least one job needs a grid proxy, please init one.")
610 map(
lambda job: job.createJob(), jobs )
611 validations = [ job.getValidation()
for job
in jobs ]
613 if options.mergeOfflineParallel:
614 parallelMergeObjects=
createMergeScript(outPath, validations, options)[
'parallelMergeObjects']
620 map(
lambda job: job.runJob(), jobs )
622 if options.autoMerge
and ValidationJob.jobCount == ValidationJob.batchCount
and config.getGeneral()[
"jobmode"].
split(
",")[0] ==
"lxBatch":
623 print(
"> Automatically merging jobs when they have ended")
628 if options.mergeOfflineParallel
and parallelMergeObjects!={}:
629 initID=parallelMergeObjects[
"init"].runJob(config).
split(
"<")[1].
split(
">")[0]
631 for parallelMergeScript
in parallelMergeObjects[
"parallel"]:
632 parallelMergeScript.addDependency(initID)
634 if isinstance(job.validation, OfflineValidation)
and "TkAlMerge"+job.validation.alignmentToValidate.name==parallelMergeScript.name:
635 parallelMergeScript.addDependency(job.JobId)
636 parallelIDs.append(parallelMergeScript.runJob(config).
split(
"<")[1].
split(
">")[0])
637 parallelMergeObjects[
"continue"].addDependency(parallelIDs)
638 parallelMergeObjects[
"continue"].addDependency(ValidationJob.batchJobIds)
639 parallelMergeObjects[
"continue"].runJob(config)
646 "commands": config.getGeneral()[
"jobmode"].
split(
",")[1],
647 "jobName":
"TkAlMerge",
648 "logDir": config.getGeneral()[
"logdir"],
649 "script":
"TkAlMerge.sh",
650 "bsub":
"/afs/cern.ch/cms/caf/scripts/cmsbsub",
651 "conditions":
'"' +
" && ".
join([
"ended(" + jobId +
")" for jobId
in ValidationJob.batchJobIds]) +
'"' 653 for ext
in (
"stdout",
"stderr",
"stdout.gz",
"stderr.gz"):
654 oldlog =
"%(logDir)s/%(jobName)s."%repMap + ext
655 if os.path.exists(oldlog):
660 "-o %(logDir)s/%(jobName)s.stdout " 661 "-e %(logDir)s/%(jobName)s.stderr " 663 "%(logDir)s/%(script)s"%repMap)
665 if __name__ ==
"__main__":
667 if "-d" in sys.argv[1:]
or "--debug" in sys.argv[1:]:
672 except AllInOneError
as e:
def main(argv=None)
— Main —############################
def loadTemplates(config)
def __init__(self, _name, _path, _dependency)
def createMergeScript(path, validations, options)
S & print(S &os, JobReport::InputFile const &f)
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)