CMS 3D CMS Logo

genericValidation.py
Go to the documentation of this file.
1 from abc import ABCMeta, abstractmethod, abstractproperty
2 import os
3 import re
4 import json
5 import globalDictionaries
6 import configTemplates
7 from dataset import Dataset
8 from helperFunctions import replaceByMap, addIndex, getCommandOutput2, boolfromstring, pythonboolstring
9 from TkAlExceptions import AllInOneError
10 
11 class ValidationMetaClass(ABCMeta):
12  sets = ["mandatories", "optionals", "needpackages"]
13  dicts = ["defaults"]
14  def __new__(cls, clsname, bases, dct):
15  for setname in cls.sets:
16  if setname not in dct: dct[setname] = set()
17  dct[setname] = set.union(dct[setname], *(getattr(base, setname) for base in bases if hasattr(base, setname)))
18 
19  for dictname in cls.dicts:
20  if dictname not in dct: dct[dictname] = {}
21  for base in bases:
22  if not hasattr(base, dictname): continue
23  newdict = getattr(base, dictname)
24  for key in set(newdict) & set(dct[dictname]):
25  if newdict[key] != dct[dictname][key]:
26  raise ValueError("Inconsistent values of defaults[{}]: {}, {}".format(key, newdict[key], dct[dictname][key]))
27  dct[dictname].update(newdict)
28 
29  for setname in cls.sets: #e.g. removemandatories, used in preexistingvalidation
30  #use with caution
31  if "remove"+setname not in dct: dct["remove"+setname] = set()
32  dct["remove"+setname] = set.union(dct["remove"+setname], *(getattr(base, "remove"+setname) for base in bases if hasattr(base, "remove"+setname)))
33 
34  dct[setname] -= dct["remove"+setname]
35 
36  return super(ValidationMetaClass, cls).__new__(cls, clsname, bases, dct)
37 
39  __metaclass__ = ValidationMetaClass
40  defaultReferenceName = "DEFAULT"
41  mandatories = set()
42  defaults = {
43  "cmssw": os.environ['CMSSW_BASE'],
44  "parallelJobs": "1",
45  "jobid": "",
46  "needsproxy": "false",
47  }
48  needpackages = {"Alignment/OfflineValidation"}
49  optionals = {"jobmode"}
50 
51  def __init__(self, valName, alignment, config):
52  import random
53  self.name = valName
54  self.alignmentToValidate = alignment
55  self.general = config.getGeneral()
56  self.randomWorkdirPart = "%0i"%random.randint(1,10e9)
57  self.configFiles = []
58  self.config = config
59  self.jobid = ""
60 
61  theUpdate = config.getResultingSection(self.valType+":"+self.name,
62  defaultDict = self.defaults,
63  demandPars = self.mandatories)
64  self.general.update(theUpdate)
65  self.jobmode = self.general["jobmode"]
66  self.NJobs = int(self.general["parallelJobs"])
67  self.needsproxy = boolfromstring(self.general["needsproxy"], "needsproxy")
68 
69  # limit maximum number of parallel jobs to 40
70  # (each output file is approximately 20MB)
71  maximumNumberJobs = 40
72  if self.NJobs > maximumNumberJobs:
73  msg = ("Maximum allowed number of parallel jobs "
74  +str(maximumNumberJobs)+" exceeded!!!")
75  raise AllInOneError(msg)
76  if self.NJobs > 1 and not isinstance(self, ParallelValidation):
77  raise AllInOneError("Parallel jobs not implemented for {}!\n"
78  "Please set parallelJobs = 1.".format(type(self).__name__))
79 
80  self.jobid = self.general["jobid"]
81  if self.jobid:
82  try: #make sure it's actually a valid jobid
83  output = getCommandOutput2("bjobs %(jobid)s 2>&1"%self.general)
84  if "is not found" in output: raise RuntimeError
85  except RuntimeError:
86  raise AllInOneError("%s is not a valid jobid.\nMaybe it finished already?"%self.jobid)
87 
88  self.cmssw = self.general["cmssw"]
89  badcharacters = r"\'"
90  for character in badcharacters:
91  if character in self.cmssw:
92  raise AllInOneError("The bad characters " + badcharacters + " are not allowed in the cmssw\n"
93  "path name. If you really have it in such a ridiculously named location,\n"
94  "try making a symbolic link somewhere with a decent name.")
95  try:
96  os.listdir(self.cmssw)
97  except OSError:
98  raise AllInOneError("Your cmssw release " + self.cmssw + ' does not exist')
99 
100  if self.cmssw == os.environ["CMSSW_BASE"]:
101  self.scramarch = os.environ["SCRAM_ARCH"]
102  self.cmsswreleasebase = os.environ["CMSSW_RELEASE_BASE"]
103  else:
104  command = ("cd '" + self.cmssw + "' && eval `scramv1 ru -sh 2> /dev/null`"
105  ' && echo "$CMSSW_BASE\n$SCRAM_ARCH\n$CMSSW_RELEASE_BASE"')
106  commandoutput = getCommandOutput2(command).split('\n')
107  self.cmssw = commandoutput[0]
108  self.scramarch = commandoutput[1]
109  self.cmsswreleasebase = commandoutput[2]
110 
111  self.packages = {}
112  for package in self.needpackages:
113  for placetolook in self.cmssw, self.cmsswreleasebase:
114  pkgpath = os.path.join(placetolook, "src", package)
115  if os.path.exists(pkgpath):
116  self.packages[package] = pkgpath
117  break
118  else:
119  raise AllInOneError("Package {} does not exist in {} or {}!".format(package, self.cmssw, self.cmsswreleasebase))
120 
121  self.AutoAlternates = True
122  if config.has_option("alternateTemplates","AutoAlternates"):
123  try:
124  self.AutoAlternates = json.loads(config.get("alternateTemplates","AutoAlternates").lower())
125  except ValueError:
126  raise AllInOneError("AutoAlternates needs to be true or false, not %s" % config.get("alternateTemplates","AutoAlternates"))
127 
128  knownOpts = set(self.defaults.keys())|self.mandatories|self.optionals
129  ignoreOpts = []
130  config.checkInput(self.valType+":"+self.name,
131  knownSimpleOptions = knownOpts,
132  ignoreOptions = ignoreOpts)
133 
134  def getRepMap(self, alignment = None):
135  from plottingOptions import PlottingOptions
136  if alignment == None:
137  alignment = self.alignmentToValidate
138  try:
139  result = PlottingOptions(self.config, self.valType)
140  except KeyError:
141  result = {}
142  result.update(alignment.getRepMap())
143  result.update(self.general)
144  result.update({
145  "workdir": os.path.join(self.general["workdir"],
146  self.randomWorkdirPart),
147  "datadir": self.general["datadir"],
148  "logdir": self.general["logdir"],
149  "CommandLineTemplate": ("#run configfile and post-proccess it\n"
150  "cmsRun %(cfgFile)s\n"
151  "%(postProcess)s "),
152  "CMSSW_BASE": self.cmssw,
153  "SCRAM_ARCH": self.scramarch,
154  "CMSSW_RELEASE_BASE": self.cmsswreleasebase,
155  "alignmentName": alignment.name,
156  "condLoad": alignment.getConditions(),
157  "LoadGlobalTagTemplate": configTemplates.loadGlobalTagTemplate,
158  })
159  result.update(self.packages)
160  return result
161 
162  @abstractproperty
163  def filesToCompare(self):
164  pass
165 
166  def getCompareStrings( self, requestId = None, plain = False ):
167  result = {}
168  repMap = self.getRepMap().copy()
169  for validationId in self.filesToCompare:
170  repMap["file"] = self.filesToCompare[ validationId ]
171  if repMap["file"].startswith( "/castor/" ):
172  repMap["file"] = "rfio:%(file)s"%repMap
173  elif repMap["file"].startswith( "/store/" ):
174  repMap["file"] = "root://eoscms.cern.ch//eos/cms%(file)s"%repMap
175  if plain:
176  result[validationId]=repMap["file"]
177  else:
178  result[validationId]= "%(file)s=%(title)s|%(color)s|%(style)s"%repMap
179  if requestId == None:
180  return result
181  else:
182  if not "." in requestId:
183  requestId += ".%s"%self.defaultReferenceName
184  if not requestId.split(".")[-1] in result:
185  msg = ("could not find %s in reference Objects!"
186  %requestId.split(".")[-1])
187  raise AllInOneError(msg)
188  return result[ requestId.split(".")[-1] ]
189 
190  def createFiles(self, fileContents, path, repMap = None, repMaps = None):
191  """repMap: single map for all files
192  repMaps: a dict, with the filenames as the keys"""
193  if repMap is not None and repMaps is not None:
194  raise AllInOneError("createFiles can only take repMap or repMaps (or neither), not both")
195  result = []
196  for fileName in fileContents:
197  filePath = os.path.join(path, fileName)
198  result.append(filePath)
199 
200  for (i, filePathi) in enumerate(addIndex(filePath, self.NJobs)):
201  theFile = open( filePathi, "w" )
202  fileContentsi = fileContents[ fileName ]
203  if repMaps is not None:
204  repMap = repMaps[fileName]
205  if repMap is not None:
206  repMap.update({"nIndex": str(i)})
207  fileContentsi = replaceByMap(fileContentsi, repMap)
208  theFile.write( fileContentsi )
209  theFile.close()
210 
211  return result
212 
213  def createConfiguration(self, fileContents, path, schedule = None, repMap = None, repMaps = None):
214  self.configFiles = self.createFiles(fileContents,
215  path, repMap = repMap, repMaps = repMaps)
216  if not schedule == None:
217  schedule = [os.path.join( path, cfgName) for cfgName in schedule]
218  for cfgName in schedule:
219  if not cfgName in self.configFiles:
220  msg = ("scheduled %s missing in generated configfiles: %s"
221  %(cfgName, self.configFiles))
222  raise AllInOneError(msg)
223  for cfgName in self.configFiles:
224  if not cfgName in schedule:
225  msg = ("generated configuration %s not scheduled: %s"
226  %(cfgName, schedule))
227  raise AllInOneError(msg)
228  self.configFiles = schedule
229  return self.configFiles
230 
231  def createScript(self, fileContents, path, downloadFiles=[], repMap = None, repMaps = None):
232  self.scriptFiles = self.createFiles(fileContents,
233  path, repMap = repMap, repMaps = repMaps)
234  for script in self.scriptFiles:
235  for scriptwithindex in addIndex(script, self.NJobs):
236  os.chmod(scriptwithindex,0o755)
237  return self.scriptFiles
238 
239  def createCrabCfg(self, fileContents, path ):
240  if self.NJobs > 1:
241  msg = ("jobmode 'crab' not supported for parallel validation."
242  " Please set parallelJobs = 1.")
243  raise AllInOneError(msg)
244  self.crabConfigFiles = self.createFiles(fileContents, path)
245  return self.crabConfigFiles
246 
247 
249  """
250  Subclass of `GenericValidation` which is the base for validations using
251  datasets.
252  """
253  needParentFiles = False
254  mandatories = {"dataset", "maxevents"}
255  defaults = {
256  "runRange": "",
257  "firstRun": "",
258  "lastRun": "",
259  "begin": "",
260  "end": "",
261  "JSON": "",
262  "dasinstance": "prod/global",
263  "ttrhbuilder":"WithAngleAndTemplate",
264  "usepixelqualityflag": "True",
265  }
266  optionals = {"magneticfield"}
267 
268  def __init__(self, valName, alignment, config):
269  """
270  This method adds additional items to the `self.general` dictionary
271  which are only needed for validations using datasets.
272 
273  Arguments:
274  - `valName`: String which identifies individual validation instances
275  - `alignment`: `Alignment` instance to validate
276  - `config`: `BetterConfigParser` instance which includes the
277  configuration of the validations
278  """
279 
280  super(GenericValidationData, self).__init__(valName, alignment, config)
281 
282  # if maxevents is not specified, cannot calculate number of events for
283  # each parallel job, and therefore running only a single job
284  if int( self.general["maxevents"] ) == -1 and self.NJobs > 1:
285  msg = ("Maximum number of events (maxevents) not specified: "
286  "cannot use parallel jobs.")
287  raise AllInOneError(msg)
288 
289  tryPredefinedFirst = (not self.jobmode.split( ',' )[0] == "crab" and self.general["JSON"] == ""
290  and self.general["firstRun"] == "" and self.general["lastRun"] == ""
291  and self.general["begin"] == "" and self.general["end"] == "")
292 
293  if self.general["dataset"] not in globalDictionaries.usedDatasets:
294  globalDictionaries.usedDatasets[self.general["dataset"]] = {}
295 
296  if self.cmssw not in globalDictionaries.usedDatasets[self.general["dataset"]]:
297  if globalDictionaries.usedDatasets[self.general["dataset"]] != {}:
298  print ("Warning: you use the same dataset '%s' in multiple cmssw releases.\n"
299  "This is allowed, but make sure it's not a mistake") % self.general["dataset"]
300  globalDictionaries.usedDatasets[self.general["dataset"]][self.cmssw] = {False: None, True: None}
301 
302  Bfield = self.general.get("magneticfield", None)
303  if globalDictionaries.usedDatasets[self.general["dataset"]][self.cmssw][tryPredefinedFirst] is None:
304  dataset = Dataset(
305  self.general["dataset"], tryPredefinedFirst = tryPredefinedFirst,
306  cmssw = self.cmssw, cmsswrelease = self.cmsswreleasebase, magneticfield = Bfield,
307  dasinstance = self.general["dasinstance"])
308  globalDictionaries.usedDatasets[self.general["dataset"]][self.cmssw][tryPredefinedFirst] = dataset
309  if tryPredefinedFirst and not dataset.predefined(): #No point finding the data twice in that case
310  globalDictionaries.usedDatasets[self.general["dataset"]][self.cmssw][False] = dataset
311 
312  self.dataset = globalDictionaries.usedDatasets[self.general["dataset"]][self.cmssw][tryPredefinedFirst]
313  self.general["magneticField"] = self.dataset.magneticField()
314  self.general["defaultMagneticField"] = "MagneticField"
315  if self.general["magneticField"] == "unknown":
316  print "Could not get the magnetic field for this dataset."
317  print "Using the default: ", self.general["defaultMagneticField"]
318  self.general["magneticField"] = '.oO[defaultMagneticField]Oo.'
319 
320  if not self.jobmode.split( ',' )[0] == "crab":
321  try:
322  self.general["datasetDefinition"] = self.dataset.datasetSnippet(
323  jsonPath = self.general["JSON"],
324  firstRun = self.general["firstRun"],
325  lastRun = self.general["lastRun"],
326  begin = self.general["begin"],
327  end = self.general["end"],
328  parent = self.needParentFiles )
329  except AllInOneError as e:
330  msg = "In section [%s:%s]: "%(self.valType, self.name)
331  msg += str(e)
332  raise AllInOneError(msg)
333  else:
334  if self.dataset.predefined():
335  msg = ("For jobmode 'crab' you cannot use predefined datasets "
336  "(in your case: '%s')."%( self.dataset.name() ))
337  raise AllInOneError( msg )
338  try:
339  theUpdate = config.getResultingSection(self.valType+":"+self.name,
340  demandPars = ["parallelJobs"])
341  except AllInOneError as e:
342  msg = str(e)[:-1]+" when using 'jobmode: crab'."
343  raise AllInOneError(msg)
344  self.general.update(theUpdate)
345  if self.general["begin"] or self.general["end"]:
346  ( self.general["begin"],
347  self.general["end"],
348  self.general["firstRun"],
349  self.general["lastRun"] ) = self.dataset.convertTimeToRun(
350  firstRun = self.general["firstRun"],
351  lastRun = self.general["lastRun"],
352  begin = self.general["begin"],
353  end = self.general["end"],
354  shortTuple = False)
355  if self.general["begin"] == None:
356  self.general["begin"] = ""
357  if self.general["end"] == None:
358  self.general["end"] = ""
359  self.general["firstRun"] = str( self.general["firstRun"] )
360  self.general["lastRun"] = str( self.general["lastRun"] )
361  if ( not self.general["firstRun"] ) and \
362  ( self.general["end"] or self.general["lastRun"] ):
363  self.general["firstRun"] = str(
364  self.dataset.runList()[0]["run_number"])
365  if ( not self.general["lastRun"] ) and \
366  ( self.general["begin"] or self.general["firstRun"] ):
367  self.general["lastRun"] = str(
368  self.dataset.runList()[-1]["run_number"])
369  if self.general["firstRun"] and self.general["lastRun"]:
370  if int(self.general["firstRun"]) > int(self.general["lastRun"]):
371  msg = ( "The lower time/runrange limit ('begin'/'firstRun') "
372  "chosen is greater than the upper time/runrange limit "
373  "('end'/'lastRun').")
374  raise AllInOneError( msg )
375  self.general["runRange"] = (self.general["firstRun"]
376  + '-' + self.general["lastRun"])
377  try:
378  self.general["datasetDefinition"] = self.dataset.datasetSnippet(
379  jsonPath = self.general["JSON"],
380  firstRun = self.general["firstRun"],
381  lastRun = self.general["lastRun"],
382  begin = self.general["begin"],
383  end = self.general["end"],
384  crab = True )
385  except AllInOneError as e:
386  msg = "In section [%s:%s]: "%(self.valType, self.name)
387  msg += str( e )
388  raise AllInOneError( msg )
389 
390  self.general["usepixelqualityflag"] = pythonboolstring(self.general["usepixelqualityflag"], "usepixelqualityflag")
391 
392  def getRepMap(self, alignment = None):
393  result = super(GenericValidationData, self).getRepMap(alignment)
394  outputfile = os.path.expandvars(replaceByMap(
395  "%s_%s_.oO[name]Oo..root" % (self.outputBaseName, self.name)
396  , result))
397  resultfile = os.path.expandvars(replaceByMap(("/store/caf/user/$USER/.oO[eosdir]Oo./" +
398  "%s_%s_.oO[name]Oo..root" % (self.resultBaseName, self.name))
399  , result))
400  result.update({
401  "resultFile": ".oO[resultFiles[.oO[nIndex]Oo.]]Oo.",
402  "resultFiles": addIndex(resultfile, self.NJobs),
403  "finalResultFile": resultfile,
404  "outputFile": ".oO[outputFiles[.oO[nIndex]Oo.]]Oo.",
405  "outputFiles": addIndex(outputfile, self.NJobs),
406  "finalOutputFile": outputfile,
407  "ProcessName": self.ProcessName,
408  "Bookkeeping": self.Bookkeeping,
409  "LoadBasicModules": self.LoadBasicModules,
410  "TrackSelectionRefitting": self.TrackSelectionRefitting,
411  "ValidationConfig": self.ValidationTemplate,
412  "FileOutputTemplate": self.FileOutputTemplate,
413  "DefinePath": self.DefinePath,
414  })
415  return result
416 
417  @property
418  def cfgName(self):
419  return "%s.%s.%s_cfg.py"%( self.configBaseName, self.name,
420  self.alignmentToValidate.name )
421  @abstractproperty
422  def ProcessName(self):
423  pass
424 
425  @property
426  def cfgTemplate(self):
427  return configTemplates.cfgTemplate
428 
429  @abstractproperty
431  pass
432 
433  @property
434  def filesToCompare(self):
435  return {self.defaultReferenceName: self.getRepMap()["finalResultFile"]}
436 
437  def createConfiguration(self, path ):
438  repMap = self.getRepMap()
439  cfgs = {self.cfgName: self.cfgTemplate}
440  super(GenericValidationData, self).createConfiguration(cfgs, path, repMap=repMap)
441 
442  def createScript(self, path, template = configTemplates.scriptTemplate, downloadFiles=[], repMap = None, repMaps = None):
443  scriptName = "%s.%s.%s.sh"%(self.scriptBaseName, self.name,
444  self.alignmentToValidate.name )
445  if repMap is None and repMaps is None:
446  repMap = self.getRepMap()
447  repMap["CommandLine"]=""
448  for cfg in self.configFiles:
449  repMap["CommandLine"]+= repMap["CommandLineTemplate"]%{"cfgFile":addIndex(cfg, self.NJobs, ".oO[nIndex]Oo."),
450  "postProcess":""
451  }
452  scripts = {scriptName: template}
453  return super(GenericValidationData, self).createScript(scripts, path, downloadFiles = downloadFiles,
454  repMap = repMap, repMaps = repMaps)
455 
456  def createCrabCfg(self, path, crabCfgBaseName):
457  """
458  Method which creates a `crab.cfg` for a validation on datasets.
459 
460  Arguments:
461  - `path`: Path at which the file will be stored.
462  - `crabCfgBaseName`: String which depends on the actual type of
463  validation calling this method.
464  """
465  crabCfgName = "crab.%s.%s.%s.cfg"%( crabCfgBaseName, self.name,
466  self.alignmentToValidate.name )
467  repMap = self.getRepMap()
468  repMap["script"] = "dummy_script.sh"
469  # repMap["crabOutputDir"] = os.path.basename( path )
470  repMap["crabWorkingDir"] = crabCfgName.split( '.cfg' )[0]
471  self.crabWorkingDir = repMap["crabWorkingDir"]
472  repMap["numberOfJobs"] = self.general["parallelJobs"]
473  repMap["cfgFile"] = self.configFiles[0]
474  repMap["queue"] = self.jobmode.split( ',' )[1].split( '-q' )[1]
475  if self.dataset.dataType() == "mc":
476  repMap["McOrData"] = "events = .oO[nEvents]Oo."
477  elif self.dataset.dataType() == "data":
478  repMap["McOrData"] = "lumis = -1"
479  if self.jobmode.split( ',' )[0] == "crab":
480  print ("For jobmode 'crab' the parameter 'maxevents' will be "
481  "ignored and all events will be processed.")
482  else:
483  raise AllInOneError("Unknown data type! Can't run in crab mode")
484  crabCfg = {crabCfgName: replaceByMap( configTemplates.crabCfgTemplate,
485  repMap ) }
486  return super(GenericValidationData, self).createCrabCfg( crabCfg, path )
487 
488  @property
489  def Bookkeeping(self):
490  return configTemplates.Bookkeeping
491  @property
492  def LoadBasicModules(self):
493  return configTemplates.LoadBasicModules
494  @abstractproperty
496  pass
497  @property
499  return configTemplates.FileOutputTemplate
500  @abstractproperty
501  def DefinePath(self):
502  pass
503 
504 class GenericValidationData_CTSR(GenericValidationData):
505  #common track selection and refitting
506  defaults = {
507  "momentumconstraint": "None",
508  "openmasswindow": "False",
509  "cosmicsdecomode": "True",
510  "removetrackhitfiltercommands": "",
511  "appendtrackhitfiltercommands": "",
512  }
513  def getRepMap(self, alignment=None):
514  result = super(GenericValidationData_CTSR, self).getRepMap(alignment)
515 
516  from trackSplittingValidation import TrackSplittingValidation
517  result.update({
518  "ValidationSequence": self.ValidationSequence,
519  "istracksplitting": str(isinstance(self, TrackSplittingValidation)),
520  "cosmics0T": str(self.cosmics0T),
521  "use_d0cut": str(self.use_d0cut),
522  })
523 
524  commands = []
525  for removeorappend in "remove", "append":
526  optionname = removeorappend + "trackhitfiltercommands"
527  if result[optionname]:
528  for command in result[optionname].split(","):
529  command = command.strip()
530  commands.append('process.TrackerTrackHitFilter.commands.{}("{}")'.format(removeorappend, command))
531  result["trackhitfiltercommands"] = "\n".join(commands)
532 
533  return result
534  @property
535  def use_d0cut(self):
536  return "Cosmics" not in self.general["trackcollection"] #use it for collisions only
537  @property
539  return configTemplates.CommonTrackSelectionRefitting
540  @property
541  def DefinePath(self):
542  return configTemplates.DefinePath_CommonSelectionRefitting
543  @abstractproperty
545  pass
546  @property
547  def cosmics0T(self):
548  if "Cosmics" not in self.general["trackcollection"]: return False
549  Bfield = self.dataset.magneticFieldForRun()
550  if Bfield < 0.5: return True
551  if isinstance(Bfield, str):
552  if "unknown " in Bfield:
553  msg = Bfield.replace("unknown ","",1)
554  elif Bfield == "unknown":
555  msg = "Can't get the B field for %s." % self.dataset.name()
556  else:
557  msg = "B field = {}???".format(Bfield)
558  raise AllInOneError(msg + "\n"
559  "To use this dataset, specify magneticfield = [value] in your .ini config file.")
560  return False
561 
563  @classmethod
564  def initMerge(cls):
565  return ""
566  @abstractmethod
567  def appendToMerge(self):
568  pass
569 
570  @classmethod
571  def doInitMerge(cls):
572  from plottingOptions import PlottingOptions
573  result = cls.initMerge()
574  result = replaceByMap(result, PlottingOptions(None, cls))
575  if result and result[-1] != "\n": result += "\n"
576  return result
577  def doMerge(self):
578  result = self.appendToMerge()
579  if result[-1] != "\n": result += "\n"
580  result += ("if [[ tmpMergeRetCode -eq 0 ]]; then\n"
581  " xrdcp -f .oO[finalOutputFile]Oo. root://eoscms//eos/cms.oO[finalResultFile]Oo.\n"
582  "fi\n"
583  "if [[ ${tmpMergeRetCode} -gt ${mergeRetCode} ]]; then\n"
584  " mergeRetCode=${tmpMergeRetCode}\n"
585  "fi\n")
586  result = replaceByMap(result, self.getRepMap())
587  return result
588 
590  @classmethod
591  def runPlots(cls, validations):
592  return ("rfcp .oO[plottingscriptpath]Oo. .\n"
593  "root -x -b -q .oO[plottingscriptname]Oo.++")
594  @abstractmethod
595  def appendToPlots(self):
596  pass
597  @abstractmethod
599  """override with a classmethod"""
600  @abstractmethod
602  """override with a classmethod"""
603  @abstractmethod
604  def plotsdirname(cls):
605  """override with a classmethod"""
606 
607  @classmethod
608  def doRunPlots(cls, validations):
609  from plottingOptions import PlottingOptions
610  cls.createPlottingScript(validations)
611  result = cls.runPlots(validations)
612  result = replaceByMap(result, PlottingOptions(None, cls))
613  if result and result[-1] != "\n": result += "\n"
614  return result
615  @classmethod
616  def createPlottingScript(cls, validations):
617  from plottingOptions import PlottingOptions
618  repmap = PlottingOptions(None, cls).copy()
619  filename = replaceByMap(".oO[plottingscriptpath]Oo.", repmap)
620  repmap["PlottingInstantiation"] = "\n".join(
621  replaceByMap(v.appendToPlots(), v.getRepMap()).rstrip("\n")
622  for v in validations
623  )
624  plottingscript = replaceByMap(cls.plottingscripttemplate(), repmap)
625  with open(filename, 'w') as f:
626  f.write(plottingscript)
627 
630  def __init__(self, name, values, format=None, latexname=None, latexformat=None):
631  """
632  name: name of the summary item, goes on top of the column
633  values: value for each alignment (in order of rows)
634  format: python format string (default: {:.3g}, meaning up to 3 significant digits)
635  latexname: name in latex form, e.g. if name=sigma you might want latexname=\sigma (default: name)
636  latexformat: format for latex (default: format)
637  """
638  if format is None: format = "{:.3g}"
639  if latexname is None: latexname = name
640  if latexformat is None: latexformat = format
641 
642  self.__name = name
643  self.__values = values
644  self.__format = format
645  self.__latexname = latexname
646  self.__latexformat = latexformat
647 
648  def name(self, latex=False):
649  if latex:
650  return self.__latexname
651  else:
652  return self.__name
653 
654  def format(self, value, latex=False):
655  if latex:
656  fmt = self.__latexformat
657  else:
658  fmt = self.__format
659  if re.match(".*[{][^}]*[fg][}].*", fmt):
660  value = float(value)
661  return fmt.format(value)
662 
663  def values(self, latex=False):
664  result = [self.format(v, latex=latex) for v in self.__values]
665  return result
666 
667  def value(self, i, latex):
668  return self.values(latex)[i]
669 
670  @abstractmethod
671  def getsummaryitems(cls, folder):
672  """override with a classmethod that returns a list of SummaryItems
673  based on the plots saved in folder"""
674 
675  __summaryitems = None
676  __lastfolder = None
677 
678  @classmethod
679  def summaryitemsstring(cls, folder=None, latex=False, transpose=True):
680  if folder is None: folder = cls.plotsdirname()
681  if folder.startswith( "/castor/" ):
682  folder = "rfio:%(file)s"%repMap
683  elif folder.startswith( "/store/" ):
684  folder = "root://eoscms.cern.ch//eos/cms%(file)s"%repMap
685 
686  if cls.__summaryitems is None or cls.__lastfolder != folder:
687  cls.__lastfolder = folder
688  cls.__summaryitems = cls.getsummaryitems(folder)
689 
690  summaryitems = cls.__summaryitems
691 
692  if not summaryitems:
693  raise AllInOneError("No summary items!")
694  size = {len(_.values(latex)) for _ in summaryitems}
695  if len(size) != 1:
696  raise AllInOneError("Some summary items have different numbers of values\n{}".format(size))
697  size = size.pop()
698 
699  if transpose:
700  columnwidths = ([max(len(_.name(latex)) for _ in summaryitems)]
701  + [max(len(_.value(i, latex)) for _ in summaryitems) for i in range(size)])
702  else:
703  columnwidths = [max(len(entry) for entry in [_.name(latex)] + _.values(latex)) for _ in summaryitems]
704 
705  if latex:
706  join = " & "
707  else:
708  join = " "
709  row = join.join("{{:{}}}".format(width) for width in columnwidths)
710 
711  if transpose:
712  rows = [row.format(*[_.name(latex)]+_.values(latex)) for _ in summaryitems]
713  else:
714  rows = []
715  rows.append(row.format(*(_.name for _ in summaryitems)))
716  for i in range(size):
717  rows.append(row.format(*(_.value(i, latex) for _ in summaryitems)))
718 
719  if latex:
720  join = " \\\\\n"
721  else:
722  join = "\n"
723  result = join.join(rows)
724  if latex:
725  result = (r"\begin{{tabular}}{{{}}}".format("|" + "|".join("c"*(len(columnwidths))) + "|") + "\n"
726  + result + "\n"
727  + r"\end{tabular}")
728  return result
729 
730  @classmethod
731  def printsummaryitems(cls, *args, **kwargs):
732  print cls.summaryitemsstring(*args, **kwargs)
733  @classmethod
734  def writesummaryitems(cls, filename, *args, **kwargs):
735  with open(filename, "w") as f:
736  f.write(cls.summaryitemsstring(*args, **kwargs)+"\n")
737 
739  @classmethod
740  def getsummaryitems(cls, folder):
741  result = []
742  with open(os.path.join(folder, "{}Summary.txt".format(cls.__name__))) as f:
743  for line in f:
744  split = line.rstrip("\n").split("\t")
745  kwargs = {}
746  for thing in split[:]:
747  if thing.startswith("format="):
748  kwargs["format"] = thing.replace("format=", "", 1)
749  split.remove(thing)
750  if thing.startswith("latexname="):
751  kwargs["latexname"] = thing.replace("latexname=", "", 1)
752  split.remove(thing)
753  if thing.startswith("latexformat="):
754  kwargs["latexformat"] = thing.replace("latexformat=", "", 1)
755  split.remove(thing)
756 
757  name = split[0]
758  values = split[1:]
759  result.append(cls.SummaryItem(name, values, **kwargs))
760  return result
761 
763  @classmethod
764  def doComparison(cls, validations):
765  from plottingOptions import PlottingOptions
766  repmap = PlottingOptions(None, cls).copy()
767  repmap["compareStrings"] = " , ".join(v.getCompareStrings("OfflineValidation") for v in validations)
768  repmap["compareStringsPlain"] = " , ".join(v.getCompareStrings("OfflineValidation", True) for v in validations)
769  comparison = replaceByMap(cls.comparisontemplate(), repmap)
770  return comparison
771 
772  @classmethod
774  return configTemplates.compareAlignmentsExecution
775  @classmethod
777  return ".oO[Alignment/OfflineValidation]Oo./scripts/.oO[compareAlignmentsName]Oo."
778  @abstractmethod
780  """classmethod"""
781 
782 class ValidationForPresentation(ValidationWithPlots):
783  @abstractmethod
785  """classmethod"""
def __init__(self, valName, alignment, config)
def pythonboolstring(string, name)
def createConfiguration(self, fileContents, path, schedule=None, repMap=None, repMaps=None)
def getCommandOutput2(command)
def createScript(self, fileContents, path, downloadFiles=[], repMap=None, repMaps=None)
def writesummaryitems(cls, filename, args, kwargs)
def __init__(self, valName, alignment, config)
def addIndex(filename, njobs, index=None)
def createCrabCfg(self, path, crabCfgBaseName)
def __new__(cls, clsname, bases, dct)
def summaryitemsstring(cls, folder=None, latex=False, transpose=True)
def PlottingOptions(config, valType)
def replaceByMap(target, the_map)
— Helpers —############################
def createFiles(self, fileContents, path, repMap=None, repMaps=None)
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def __init__(self, name, values, format=None, latexname=None, latexformat=None)
def boolfromstring(string, name)
def createScript(self, path, template=configTemplates.scriptTemplate, downloadFiles=[], repMap=None, repMaps=None)
def createCrabCfg(self, fileContents, path)
#define update(a, b)
def getRepMap(self, alignment=None)
def getCompareStrings(self, requestId=None, plain=False)
double split
Definition: MVATrainer.cc:139