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
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, 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 \
39 def __init__( self, validation, config, options ):
40 if validation[1] ==
"":
42 valString = validation[0].
split(
"->" )[0]
43 alignments = validation[0].
split(
"->" )[1]
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)
53 valString = validation[0]
54 alignments = validation[1]
55 valString = valString.split()
62 section =
"offline" +
":" + 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."
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]
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]
94 if secondAlignName ==
"IDEAL":
95 secondAlign = secondAlignName
97 secondAlign = Alignment( secondAlignName, self.
__config,
101 randomWorkdirPart = \
102 globalDictionaries.alignRandDict[firstAlignName]
104 randomWorkdirPart =
None
106 validation = GeometryComparison( name, firstAlign, secondAlign,
108 self.__commandLineOptions.getImages,
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,
118 elif valType ==
"offlineDQM":
119 validation = OfflineValidationDQM( name,
121 elif valType ==
"offlineParallel":
122 validation = OfflineValidationParallel( name,
124 elif valType ==
"mcValidate":
125 validation = MonteCarloValidation( name,
127 elif valType ==
"split":
128 validation = TrackSplittingValidation( name,
130 elif valType ==
"zmumu":
131 validation = ZMuMuValidation( name,
134 raise AllInOneError,
"Unknown validation mode '%s'"%valType
138 """This private method creates the needed files for the validation job.
140 self.validation.createConfiguration( outpath )
141 self.
__scripts = self.validation.createScript( outpath )
142 if jobMode.split(
',' )[0] ==
"crab":
143 self.validation.createCrabCfg( outpath )
147 """This is the method called to create the job files."""
149 os.path.abspath( self.__commandLineOptions.Name) )
152 general = self.__config.getGeneral()
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) )
159 log =
"> Validating "+name
160 print "> Validating "+name
161 if self.validation.jobmode ==
"interactive":
163 elif self.validation.jobmode.split(
",")[0] ==
"lxBatch":
165 "commands": self.validation.jobmode.split(
",")[1],
166 "logDir": general[
"logdir"],
169 "bsub":
"/afs/cern.ch/cms/caf/scripts/cmsbsub"
172 "-o %(logDir)s/%(jobName)s.stdout -e "
173 "%(logDir)s/%(jobName)s.stderr "
175 elif self.validation.jobmode.split(
"," )[0] ==
"crab":
176 os.chdir( general[
"logdir"] )
177 crabName =
"crab." + os.path.basename( script )[:-3]
179 options = {
"-create":
"",
180 "-cfg": crabName +
".cfg",
183 theCrab.run( options )
184 except AllInOneError, e:
185 print "crab:", str(e).
split(
"\n")[0]
188 raise AllInOneError, (
"Unknown 'jobmode'!\n"
189 "Please change this parameter either in "
190 "the [general] or in the ["
192 +
"] section to one of the following "
194 "\tinteractive\n\tlxBatch, -q <queue>\n"
195 "\tcrab, -q <queue>")
204 repMap = offlineValidationList[0].getRepMap()
205 repMap[
"mergeOfflinParJobsInstantiation" ] =
""
207 theFile = open( outFilePath,
"w" )
208 theFile.write(
replaceByMap( configTemplates.mergeOfflineParJobsTemplate ,repMap ) )
212 repMap = offlineValidationList[0].getRepMap()
213 repMap[
"extendedInstantiation" ] =
""
215 for validation
in offlineValidationList:
216 repMap[
"extendedInstantiation" ] = validation.appendToExtendedValidation( repMap[
"extendedInstantiation" ] )
218 theFile = open( outFilePath,
"w" )
220 theFile.write(
replaceByMap( configTemplates.extendedValidationTemplate ,repMap ) )
224 if(len(validations) == 0):
225 msg =
"Cowardly refusing to merge nothing!"
226 raise AllInOneError(msg)
228 repMap = validations[0].getRepMap()
231 "CompareAlignments":
"",
232 "RunExtendedOfflineValidation":
""
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 )
243 comparisonLists[ validationName ] = [ validation ]
245 if "OfflineValidation" in comparisonLists:
246 repMap[
"extendeValScriptPath"] = \
247 os.path.join(path,
"TkAlExtendedOfflineValidation.C")
249 repMap[
"extendeValScriptPath"] )
250 repMap[
"RunExtendedOfflineValidation"] = \
251 replaceByMap(configTemplates.extendedValidationExecution, repMap)
253 repMap[
"CompareAlignments"] =
"#run comparisons"
254 for validationId
in comparisonLists:
255 compareStrings = [ val.getCompareStrings(validationId)
for val
in comparisonLists[validationId] ]
257 repMap.update({
"validationId": validationId,
258 "compareStrings":
" , ".
join(compareStrings) })
260 repMap[
"CompareAlignments"] += \
261 replaceByMap(configTemplates.compareAlignmentsExecution, repMap)
263 filePath = os.path.join(path,
"TkAlMerge.sh")
264 theFile = open( filePath,
"w" )
265 theFile.write(
replaceByMap( configTemplates.mergeTemplate, repMap ) )
267 os.chmod(filePath,0755)
272 if( len(validations) == 0 ):
273 raise AllInOneError,
"cowardly refusing to merge nothing!"
275 repMap = validations[0].getRepMap()
278 "CompareAlignments":
"",
279 "RunExtendedOfflineValidation":
""
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 )
290 comparisonLists[ validationName ] = [ validation ]
292 if "OfflineValidationParallel" in comparisonLists:
293 repMap[
"extendeValScriptPath"] = os.path.join(path,
"TkAlExtendedOfflineValidation.C")
295 repMap[
"mergeOfflineParJobsScriptPath"] = os.path.join(path,
"TkAlOfflineJobsMerge.C")
297 repMap[
"mergeOfflineParJobsScriptPath"] )
301 repMap[
"haddLoop"] =
"mergeRetCode=0\n"
302 repMap[
"rmUnmerged"] =
"if [[ mergeRetCode -eq 0 ]]; then\n"
303 for validation
in comparisonLists[
"OfflineValidationParallel"]:
304 repMap[
"haddLoop"] = validation.appendToMergeParJobs(repMap[
"haddLoop"])
305 repMap[
"haddLoop"] +=
"tmpMergeRetCode=${?}\n"
306 repMap[
"haddLoop"] += (
"if [[ mergeRetCode -eq 0 ]]; "
307 "then mergeRetCode=${tmpMergeRetCode}; "
309 repMap[
"haddLoop"] += (
"cmsStage -f "
310 +validation.getRepMap()[
"outputFile"]
312 +validation.getRepMap()[
"resultFile"]
314 for f
in validation.outputFiles:
315 longName = os.path.join(
"/store/caf/user/$USER/",
316 validation.getRepMap()[
"eosdir"], f)
317 repMap[
"rmUnmerged"] +=
" cmsRm "+longName+
"\n"
318 repMap[
"rmUnmerged"] += (
"else\n"
319 " echo \"WARNING: Merging failed, unmerged"
320 " files won't be deleted.\"\n"
323 repMap[
"RunExtendedOfflineValidation"] = \
324 replaceByMap(configTemplates.extendedValidationExecution, repMap)
328 repMap[
"DownloadData"] +=
replaceByMap(
"rfcp .oO[mergeOfflineParJobsScriptPath]Oo. .", repMap)
329 repMap[
"DownloadData"] +=
replaceByMap( configTemplates.mergeOfflineParallelResults, repMap )
331 repMap[
"CompareAlignments"] =
"#run comparisons"
332 for validationId
in comparisonLists:
333 compareStrings = [ val.getCompareStrings(validationId)
for val
in comparisonLists[validationId] ]
335 repMap.update({
"validationId": validationId,
336 "compareStrings":
" , ".
join(compareStrings) })
338 repMap[
"CompareAlignments"] += \
339 replaceByMap(configTemplates.compareAlignmentsExecution, repMap)
341 filePath = os.path.join(path,
"TkAlMerge.sh")
342 theFile = open( filePath,
"w" )
343 theFile.write(
replaceByMap( configTemplates.mergeTemplate, repMap ) )
345 os.chmod(filePath,0755)
350 if config.has_section(
"alternateTemplates"):
351 for templateName
in config.options(
"alternateTemplates"):
352 newTemplateName = config.get(
"alternateTemplates", templateName )
361 optParser = optparse.OptionParser()
362 optParser.description =
""" all-in-one alignment Validation
363 This will run various validation procedures either on batch queues or interactviely.
365 If no name is given (-N parameter) a name containing time and date is created automatically
367 To merge the outcome of all validation procedures run TkAlMerge.sh in your validation's directory.
369 optParser.add_option(
"-n",
"--dryRun", dest=
"dryRun", action=
"store_true", default=
False,
370 help=
"create all scripts and cfg File but do not start jobs (default=False)")
371 optParser.add_option(
"--getImages", dest=
"getImages", action=
"store_true", default=
False,
372 help=
"get all Images created during the process (default= False)")
373 defaultConfig =
"TkAlConfig.ini"
374 optParser.add_option(
"-c",
"--config", dest=
"config", default = defaultConfig,
375 help=
"configuration to use (default TkAlConfig.ini) this can be a comma-seperated list of all .ini file you want to merge", metavar=
"CONFIG")
376 optParser.add_option(
"-N",
"--Name", dest=
"Name",
377 help=
"Name of this validation (default: alignmentValidation_DATE_TIME)", metavar=
"NAME")
378 optParser.add_option(
"-r",
"--restrictTo", dest=
"restrictTo",
379 help=
"restrict validations to given modes (comma seperated) (default: no restriction)", metavar=
"RESTRICTTO")
380 optParser.add_option(
"-s",
"--status", dest=
"crabStatus", action=
"store_true", default =
False,
381 help=
"get the status of the crab jobs", metavar=
"STATUS")
382 optParser.add_option(
"-d",
"--debug", dest=
"debugMode", action=
"store_true",
384 help=
"Run the tool to get full traceback of errors.",
387 (options, args) = optParser.parse_args(argv)
389 if not options.restrictTo ==
None:
390 options.restrictTo = options.restrictTo.split(
",")
392 options.config = [ os.path.abspath( iniFile )
for iniFile
in \
393 options.config.split(
"," ) ]
394 config = BetterConfigParser()
395 outputIniFileSet = set( config.read( options.config ) )
396 failedIniFiles = [ iniFile
for iniFile
in options.config
if iniFile
not in outputIniFileSet ]
399 if options.config == [ os.path.abspath( defaultConfig ) ]:
400 if (
not options.crabStatus )
and \
401 (
not os.path.exists( defaultConfig ) ):
402 raise AllInOneError, (
"Default 'ini' file '%s' not found!\n"
403 "You can specify another name with the "
404 "command line option '-c'/'--config'."
407 for iniFile
in failedIniFiles:
408 if not os.path.exists( iniFile ):
409 raise AllInOneError, (
"'%s' does not exist. Please check for "
410 "typos in the filename passed to the "
411 "'-c'/'--config' option!"
414 raise AllInOneError, (
"'%s' does exist, but parsing of the "
418 if options.Name ==
None:
419 if not options.crabStatus:
420 options.Name =
"alignmentValidation_%s"%(datetime.datetime.now().strftime(
"%y%m%d_%H%M%S"))
422 existingValDirs = fnmatch.filter( os.walk(
'.' ).
next()[1],
423 "alignmentValidation_*" )
424 if len( existingValDirs ) > 0:
425 options.Name = existingValDirs[-1]
427 print "Cannot guess last working directory!"
428 print (
"Please use the parameter '-N' or '--Name' to specify "
429 "the task for which you want a status report." )
433 outPath = os.path.abspath( options.Name )
436 if options.crabStatus:
438 crabLogDirs = fnmatch.filter( os.walk(
'.').
next()[1],
"crab.*" )
439 if len( crabLogDirs ) == 0:
440 print "Found no crab tasks for job name '%s'"%( options.Name )
443 for crabLogDir
in crabLogDirs:
445 print "*" +
"=" * 78 +
"*"
446 print (
"| Status report and output retrieval for:"
447 +
" " * (77 - len(
"Status report and output retrieval for:" ) )
449 taskName = crabLogDir.replace(
"crab.",
"" )
450 print "| " + taskName +
" " * (77 - len( taskName ) ) +
"|"
451 print "*" +
"=" * 78 +
"*"
453 crabOptions = {
"-getoutput":
"",
456 theCrab.run( crabOptions )
457 except AllInOneError, e:
458 print "crab: No output retrieved for this task."
459 crabOptions = {
"-status":
"",
461 theCrab.run( crabOptions )
464 general = config.getGeneral()
465 config.set(
"internals",
"workdir",os.path.join(general[
"workdir"],options.Name) )
466 config.set(
"general",
"datadir",os.path.join(general[
"datadir"],options.Name) )
467 config.set(
"general",
"logdir",os.path.join(general[
"logdir"],options.Name) )
468 config.set(
"general",
"eosdir",os.path.join(
"AlignmentValidation", general[
"eosdir"], options.Name) )
472 if os.path.isdir( outPath ):
473 shutil.rmtree( outPath )
475 if not os.path.exists( outPath ):
476 os.makedirs( outPath )
477 elif not os.path.isdir( outPath ):
478 raise AllInOneError,
"the file %s is in the way rename the Job or move it away"%outPath
484 backupConfigFile = open( os.path.join( outPath,
"usedConfiguration.ini" ) ,
"w" )
485 config.write( backupConfigFile )
488 for validation
in config.items(
"validation"):
489 alignmentList = validation[1].
split(config.getSep())
490 validationsToAdd = [(validation[0],alignment) \
491 for alignment
in alignmentList]
492 validations.extend(validationsToAdd)
494 for validation
in validations ]
495 map(
lambda job: job.createJob(), jobs )
496 validations = [ job.getValidation()
for job
in jobs ]
498 if "OfflineValidationParallel" not in [val.__class__.__name__
for val
in validations]:
504 map(
lambda job: job.runJob(), jobs )
507 if __name__ ==
"__main__":
509 if "-d" in sys.argv[1:]
or "--debug" in sys.argv[1:]:
514 except AllInOneError, e:
515 print "\nAll-In-One Tool:", str(e)
def createOfflineJobsMergeScript
def createParallelMergeScript
— Classes —############################
def main
— Main —############################
def createExtendedValidationScript
def alternateTemplate
### Alternate Templates ###
static std::string join(char **cmd)
def replaceByMap
— Helpers —############################