CMS 3D CMS Logo

Config.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 
3 
4 from __future__ import print_function
5 from __future__ import absolute_import
6 import os
7 from .Options import Options
8 options = Options()
9 
10 
11 
12 import sys
13 from .Mixins import PrintOptions,_ParameterTypeBase,_SimpleParameterTypeBase, _Parameterizable, _ConfigureComponent, _TypedParameterizable, _Labelable, _Unlabelable, _ValidatingListBase, _modifyParametersFromDict
14 from .Mixins import *
15 from .Types import *
16 from .Modules import *
17 from .Modules import _Module
18 from .SequenceTypes import *
19 from .SequenceTypes import _ModuleSequenceType, _Sequenceable #extend needs it
20 from .SequenceVisitors import PathValidator, EndPathValidator, FinalPathValidator, ScheduleTaskValidator, NodeVisitor, CompositeVisitor, ModuleNamesFromGlobalsVisitor
21 from .MessageLogger import MessageLogger
22 from . import DictTypes
23 
24 from .ExceptionHandling import *
25 
26 #when building RECO paths we have hit the default recursion limit
27 if sys.getrecursionlimit()<5000:
28  sys.setrecursionlimit(5000)
29 
30 class edm(object):
31  class errors(object):
32  #Allowed errors to be used within Python
33  Configuration = "{Configuration}"
34  UnavailableAccelerator = "{UnavailableAccelerator}"
35 
37  def __init__(self, error, message):
38  super().__init__(error+"\n"+message)
39 
40 
41 def checkImportPermission(minLevel = 2, allowedPatterns = []):
42  """
43  Raise an exception if called by special config files. This checks
44  the call or import stack for the importing file. An exception is raised if
45  the importing module is not in allowedPatterns and if it is called too deeply:
46  minLevel = 2: inclusion by top lvel cfg only
47  minLevel = 1: No inclusion allowed
48  allowedPatterns = ['Module1','Module2/SubModule1'] allows import
49  by any module in Module1 or Submodule1
50  """
51 
52  import inspect
53  import os
54 
55  ignorePatterns = ['FWCore/ParameterSet/Config.py', 'FWCore/ParameterSet/python/Config.py','<string>','<frozen ']
56  CMSSWPath = [os.environ['CMSSW_BASE'],os.environ['CMSSW_RELEASE_BASE']]
57 
58  # Filter the stack to things in CMSSWPath and not in ignorePatterns
59  trueStack = []
60  for item in inspect.stack():
61  inPath = False
62  ignore = False
63 
64  for pattern in CMSSWPath:
65  if item[1].find(pattern) != -1:
66  inPath = True
67  break
68  if item[1].find('/') == -1: # The base file, no path
69  inPath = True
70 
71  for pattern in ignorePatterns:
72  if item[1].find(pattern) != -1:
73  ignore = True
74  break
75 
76  if inPath and not ignore:
77  trueStack.append(item[1])
78 
79  importedFile = trueStack[0]
80  importedBy = ''
81  if len(trueStack) > 1:
82  importedBy = trueStack[1]
83 
84  for pattern in allowedPatterns:
85  if importedBy.find(pattern) > -1:
86  return True
87 
88  if len(trueStack) <= minLevel: # Imported directly
89  return True
90 
91  raise ImportError("Inclusion of %s is allowed only by cfg or specified cfi files."
92  % importedFile)
93 
94 def findProcess(module):
95  """Look inside the module and find the Processes it contains"""
96  class Temp(object):
97  pass
98  process = None
99  if isinstance(module,dict):
100  if 'process' in module:
101  p = module['process']
102  module = Temp()
103  module.process = p
104  if hasattr(module,'process'):
105  if isinstance(module.process,Process):
106  process = module.process
107  else:
108  raise RuntimeError("The attribute named 'process' does not inherit from the Process class")
109  else:
110  raise RuntimeError("no 'process' attribute found in the module, please add one")
111  return process
112 
114  """Root class for a CMS configuration process"""
115  _firstProcess = True
116  def __init__(self,name,*Mods):
117  """The argument 'name' will be the name applied to this Process
118  Can optionally pass as additional arguments cms.Modifier instances
119  that will be used to modify the Process as it is built
120  """
121  self.__dict__['_Process__name'] = name
122  if not name.isalnum():
123  raise RuntimeError("Error: The process name is an empty string or contains non-alphanumeric characters")
124  self.__dict__['_Process__filters'] = {}
125  self.__dict__['_Process__producers'] = {}
126  self.__dict__['_Process__switchproducers'] = {}
127  self.__dict__['_Process__source'] = None
128  self.__dict__['_Process__looper'] = None
129  self.__dict__['_Process__subProcesses'] = []
130  self.__dict__['_Process__schedule'] = None
131  self.__dict__['_Process__analyzers'] = {}
132  self.__dict__['_Process__outputmodules'] = {}
133  self.__dict__['_Process__paths'] = DictTypes.SortedKeysDict() # have to keep the order
134  self.__dict__['_Process__endpaths'] = DictTypes.SortedKeysDict() # of definition
135  self.__dict__['_Process__finalpaths'] = DictTypes.SortedKeysDict() # of definition
136  self.__dict__['_Process__sequences'] = {}
137  self.__dict__['_Process__tasks'] = {}
138  self.__dict__['_Process__conditionaltasks'] = {}
139  self.__dict__['_Process__services'] = {}
140  self.__dict__['_Process__essources'] = {}
141  self.__dict__['_Process__esproducers'] = {}
142  self.__dict__['_Process__esprefers'] = {}
143  self.__dict__['_Process__aliases'] = {}
144  self.__dict__['_Process__psets']={}
145  self.__dict__['_Process__vpsets']={}
146  self.__dict__['_cloneToObjectDict'] = {}
147  # policy switch to avoid object overwriting during extend/load
148  self.__dict__['_Process__InExtendCall'] = False
149  self.__dict__['_Process__partialschedules'] = {}
150  self.__isStrict = False
151  self.__dict__['_Process__modifiers'] = Mods
152  self.__dict__['_Process__accelerators'] = {}
153  self.__injectValidValue('options', Process.defaultOptions_())
154  self.__injectValidValue('maxEvents', Process.defaultMaxEvents_())
155  self.maxLuminosityBlocks = Process.defaultMaxLuminosityBlocks_()
156  # intentionally not cloned to ensure that everyone taking
157  # MessageLogger still via
158  # FWCore.Message(Logger|Service).MessageLogger_cfi
159  # use the very same MessageLogger object.
160  self.MessageLogger = MessageLogger
161  if Process._firstProcess:
162  Process._firstProcess = False
163  else:
164  if len(Mods) > 0:
165  for m in self.__modifiers:
166  if not m._isChosen():
167  raise RuntimeError("The Process {} tried to redefine which Modifiers to use after another Process was already started".format(name))
168  for m in self.__modifiers:
169  m._setChosen()
170 
171  def setStrict(self, value):
172  self.__isStrict = value
173  _Module.__isStrict__ = True
174 
175  # some user-friendly methods for command-line browsing
176  def producerNames(self):
177  """Returns a string containing all the EDProducer labels separated by a blank"""
178  return ' '.join(self.producers_().keys())
180  """Returns a string containing all the SwitchProducer labels separated by a blank"""
181  return ' '.join(self.switchProducers_().keys())
182  def analyzerNames(self):
183  """Returns a string containing all the EDAnalyzer labels separated by a blank"""
184  return ' '.join(self.analyzers_().keys())
185  def filterNames(self):
186  """Returns a string containing all the EDFilter labels separated by a blank"""
187  return ' '.join(self.filters_().keys())
188  def pathNames(self):
189  """Returns a string containing all the Path names separated by a blank"""
190  return ' '.join(self.paths_().keys())
191 
192  def __setstate__(self, pkldict):
193  """
194  Unpickling hook.
195 
196  Since cloneToObjectDict stores a hash of objects by their
197  id() it needs to be updated when unpickling to use the
198  new object id values instantiated during the unpickle.
199 
200  """
201  self.__dict__.update(pkldict)
202  tmpDict = {}
203  for value in self._cloneToObjectDict.values():
204  tmpDict[id(value)] = value
205  self.__dict__['_cloneToObjectDict'] = tmpDict
206 
207 
208 
209  def filters_(self):
210  """returns a dict of the filters that have been added to the Process"""
211  return DictTypes.FixedKeysDict(self.__filters)
212  filters = property(filters_, doc="dictionary containing the filters for the process")
213  def name_(self):
214  return self.__name
215  def setName_(self,name):
216  if not name.isalnum():
217  raise RuntimeError("Error: The process name is an empty string or contains non-alphanumeric characters")
218  self.__dict__['_Process__name'] = name
219  process = property(name_,setName_, doc="name of the process")
220  def producers_(self):
221  """returns a dict of the producers that have been added to the Process"""
222  return DictTypes.FixedKeysDict(self.__producers)
223  producers = property(producers_,doc="dictionary containing the producers for the process")
224  def switchProducers_(self):
225  """returns a dict of the SwitchProducers that have been added to the Process"""
226  return DictTypes.FixedKeysDict(self.__switchproducers)
227  switchProducers = property(switchProducers_,doc="dictionary containing the SwitchProducers for the process")
228  def source_(self):
229  """returns the source that has been added to the Process or None if none have been added"""
230  return self.__source
231  def setSource_(self,src):
232  self._placeSource('source',src)
233  source = property(source_,setSource_,doc='the main source or None if not set')
234  def looper_(self):
235  """returns the looper that has been added to the Process or None if none have been added"""
236  return self.__looper
237  def setLooper_(self,lpr):
238  self._placeLooper('looper',lpr)
239  looper = property(looper_,setLooper_,doc='the main looper or None if not set')
240  @staticmethod
242  return untracked.PSet(numberOfThreads = untracked.uint32(1),
243  numberOfStreams = untracked.uint32(0),
244  numberOfConcurrentRuns = untracked.uint32(1),
245  numberOfConcurrentLuminosityBlocks = untracked.uint32(0),
246  eventSetup = untracked.PSet(
247  numberOfConcurrentIOVs = untracked.uint32(0),
248  forceNumberOfConcurrentIOVs = untracked.PSet(
249  allowAnyLabel_ = required.untracked.uint32
250  )
251  ),
252  accelerators = untracked.vstring('*'),
253  wantSummary = untracked.bool(False),
254  fileMode = untracked.string('FULLMERGE'),
255  forceEventSetupCacheClearOnNewRun = untracked.bool(False),
256  throwIfIllegalParameter = untracked.bool(True),
257  printDependencies = untracked.bool(False),
258  deleteNonConsumedUnscheduledModules = untracked.bool(True),
259  sizeOfStackForThreadsInKB = optional.untracked.uint32,
260  Rethrow = untracked.vstring(),
261  TryToContinue = untracked.vstring(),
262  IgnoreCompletely = untracked.vstring(),
263  modulesToCallForTryToContinue = untracked.vstring(),
264  canDeleteEarly = untracked.vstring(),
265  holdsReferencesToDeleteEarly = untracked.VPSet(),
266  modulesToIgnoreForDeleteEarly = untracked.vstring(),
267  dumpOptions = untracked.bool(False),
268  allowUnscheduled = obsolete.untracked.bool,
269  emptyRunLumiMode = obsolete.untracked.string,
270  makeTriggerResults = obsolete.untracked.bool,
271  )
272  def __updateOptions(self,opt):
273  newOpts = self.defaultOptions_()
274  if isinstance(opt,dict):
275  for k,v in opt.items():
276  setattr(newOpts,k,v)
277  else:
278  for p in opt.parameters_():
279  setattr(newOpts, p, getattr(opt,p))
280  return newOpts
281  @staticmethod
283  return untracked.PSet(input=optional.untracked.int32,
284  output=optional.untracked.allowed(int32,PSet))
285  def __updateMaxEvents(self,ps):
286  newMax = self.defaultMaxEvents_()
287  if isinstance(ps,dict):
288  for k,v in ps.items():
289  setattr(newMax,k,v)
290  else:
291  for p in ps.parameters_():
292  setattr(newMax, p, getattr(ps,p))
293  return newMax
294  @staticmethod
296  return untracked.PSet(input=untracked.int32(-1))
297  def subProcesses_(self):
298  """returns a list of the subProcesses that have been added to the Process"""
299  return self.__subProcesses
300  subProcesses = property(subProcesses_,doc='the SubProcesses that have been added to the Process')
301  def analyzers_(self):
302  """returns a dict of the analyzers that have been added to the Process"""
303  return DictTypes.FixedKeysDict(self.__analyzers)
304  analyzers = property(analyzers_,doc="dictionary containing the analyzers for the process")
305  def outputModules_(self):
306  """returns a dict of the output modules that have been added to the Process"""
307  return DictTypes.FixedKeysDict(self.__outputmodules)
308  outputModules = property(outputModules_,doc="dictionary containing the output_modules for the process")
309  def paths_(self):
310  """returns a dict of the paths that have been added to the Process"""
311  return DictTypes.SortedAndFixedKeysDict(self.__paths)
312  paths = property(paths_,doc="dictionary containing the paths for the process")
313  def endpaths_(self):
314  """returns a dict of the endpaths that have been added to the Process"""
315  return DictTypes.SortedAndFixedKeysDict(self.__endpaths)
316  endpaths = property(endpaths_,doc="dictionary containing the endpaths for the process")
317  def finalpaths_(self):
318  """returns a dict of the finalpaths that have been added to the Process"""
319  return DictTypes.SortedAndFixedKeysDict(self.__finalpaths)
320  finalpaths = property(finalpaths_,doc="dictionary containing the finalpaths for the process")
321  def sequences_(self):
322  """returns a dict of the sequences that have been added to the Process"""
323  return DictTypes.FixedKeysDict(self.__sequences)
324  sequences = property(sequences_,doc="dictionary containing the sequences for the process")
325  def tasks_(self):
326  """returns a dict of the tasks that have been added to the Process"""
327  return DictTypes.FixedKeysDict(self.__tasks)
328  tasks = property(tasks_,doc="dictionary containing the tasks for the process")
329  def conditionaltasks_(self):
330  """returns a dict of the conditionaltasks that have been added to the Process"""
331  return DictTypes.FixedKeysDict(self.__conditionaltasks)
332  conditionaltasks = property(conditionaltasks_,doc="dictionary containing the conditionatasks for the process")
333  def schedule_(self):
334  """returns the schedule that has been added to the Process or None if none have been added"""
335  return self.__schedule
336  def setPartialSchedule_(self,sch,label):
337  if label == "schedule":
338  self.setSchedule_(sch)
339  else:
340  self._place(label, sch, self.__partialschedules)
341  def setSchedule_(self,sch):
342  # See if every path and endpath has been inserted into the process
343  index = 0
344  try:
345  for p in sch:
346  p.label_()
347  index +=1
348  except:
349  raise RuntimeError("The path at index "+str(index)+" in the Schedule was not attached to the process.")
350  self.__dict__['_Process__schedule'] = sch
351  schedule = property(schedule_,setSchedule_,doc='the schedule or None if not set')
352  def services_(self):
353  """returns a dict of the services that have been added to the Process"""
354  return DictTypes.FixedKeysDict(self.__services)
355  services = property(services_,doc="dictionary containing the services for the process")
357  """returns a dict of the ProcessAccelerators that have been added to the Process"""
358  return DictTypes.FixedKeysDict(self.__accelerators)
359  processAccelerators = property(processAccelerators_,doc="dictionary containing the ProcessAccelerators for the process")
360  def es_producers_(self):
361  """returns a dict of the esproducers that have been added to the Process"""
362  return DictTypes.FixedKeysDict(self.__esproducers)
363  es_producers = property(es_producers_,doc="dictionary containing the es_producers for the process")
364  def es_sources_(self):
365  """returns a the es_sources that have been added to the Process"""
366  return DictTypes.FixedKeysDict(self.__essources)
367  es_sources = property(es_sources_,doc="dictionary containing the es_sources for the process")
368  def es_prefers_(self):
369  """returns a dict of the es_prefers that have been added to the Process"""
370  return DictTypes.FixedKeysDict(self.__esprefers)
371  es_prefers = property(es_prefers_,doc="dictionary containing the es_prefers for the process")
372  def aliases_(self):
373  """returns a dict of the aliases that have been added to the Process"""
374  return DictTypes.FixedKeysDict(self.__aliases)
375  aliases = property(aliases_,doc="dictionary containing the aliases for the process")
376  def psets_(self):
377  """returns a dict of the PSets that have been added to the Process"""
378  return DictTypes.FixedKeysDict(self.__psets)
379  psets = property(psets_,doc="dictionary containing the PSets for the process")
380  def vpsets_(self):
381  """returns a dict of the VPSets that have been added to the Process"""
382  return DictTypes.FixedKeysDict(self.__vpsets)
383  vpsets = property(vpsets_,doc="dictionary containing the PSets for the process")
384 
385  def isUsingModifier(self,mod):
386  """returns True if the Modifier is in used by this Process"""
387  if mod._isChosen():
388  for m in self.__modifiers:
389  if m._isOrContains(mod):
390  return True
391  return False
392 
393  def __setObjectLabel(self, object, newLabel) :
394  if not object.hasLabel_() :
395  object.setLabel(newLabel)
396  return
397  if newLabel == object.label_() :
398  return
399  if newLabel is None :
400  object.setLabel(None)
401  return
402  if (hasattr(self, object.label_()) and id(getattr(self, object.label_())) == id(object)) :
403  msg100 = "Attempting to change the label of an attribute of the Process\n"
404  msg101 = "Old label = "+object.label_()+" New label = "+newLabel+"\n"
405  msg102 = "Type = "+str(type(object))+"\n"
406  msg103 = "Some possible solutions:\n"
407  msg104 = " 1. Clone modules instead of using simple assignment. Cloning is\n"
408  msg105 = " also preferred for other types when possible.\n"
409  msg106 = " 2. Declare new names starting with an underscore if they are\n"
410  msg107 = " for temporaries you do not want propagated into the Process. The\n"
411  msg108 = " underscore tells \"from x import *\" and process.load not to import\n"
412  msg109 = " the name.\n"
413  msg110 = " 3. Reorganize so the assigment is not necessary. Giving a second\n"
414  msg111 = " name to the same object usually causes confusion and problems.\n"
415  msg112 = " 4. Compose Sequences: newName = cms.Sequence(oldName)\n"
416  raise ValueError(msg100+msg101+msg102+msg103+msg104+msg105+msg106+msg107+msg108+msg109+msg110+msg111+msg112)
417  object.setLabel(None)
418  object.setLabel(newLabel)
419 
420  def __setattr__(self,name,value):
421  # check if the name is well-formed (only _ and alphanumerics are allowed)
422  if not name.replace('_','').isalnum():
423  raise ValueError('The label '+name+' contains forbiden characters')
424 
425  if name == 'options':
426  value = self.__updateOptions(value)
427  if name == 'maxEvents':
428  value = self.__updateMaxEvents(value)
429 
430  # private variable exempt from all this
431  if name.startswith('_Process__'):
432  self.__dict__[name]=value
433  return
434  if not isinstance(value,_ConfigureComponent):
435  raise TypeError("can only assign labels to an object that inherits from '_ConfigureComponent'\n"
436  +"an instance of "+str(type(value))+" will not work - requested label is "+name)
437  if not isinstance(value,_Labelable) and not isinstance(value,Source) and not isinstance(value,Looper) and not isinstance(value,Schedule):
438  if name == value.type_():
439  if hasattr(self,name) and (getattr(self,name)!=value):
440  self._replaceInTasks(name, value)
441  self._replaceInConditionalTasks(name, value)
442  # Only Services get handled here
443  self.add_(value)
444  return
445  else:
446  raise TypeError("an instance of "+str(type(value))+" can not be assigned the label '"+name+"'.\n"+
447  "Please either use the label '"+value.type_()+" or use the 'add_' method instead.")
448  #clone the item
449  if self.__isStrict:
450  newValue =value.copy()
451  try:
452  newValue._filename = value._filename
453  except:
454  pass
455  value.setIsFrozen()
456  else:
457  newValue =value
458  if not self._okToPlace(name, value, self.__dict__):
459  newFile='top level config'
460  if hasattr(value,'_filename'):
461  newFile = value._filename
462  oldFile='top level config'
463  oldValue = getattr(self,name)
464  if hasattr(oldValue,'_filename'):
465  oldFile = oldValue._filename
466  msg = "Trying to override definition of process."+name
467  msg += "\n new object defined in: "+newFile
468  msg += "\n existing object defined in: "+oldFile
469  raise ValueError(msg)
470  # remove the old object of the name (if there is one)
471  if hasattr(self,name) and not (getattr(self,name)==newValue):
472  # Complain if items in sequences or tasks from load() statements have
473  # degenerate names, but if the user overwrites a name in the
474  # main config, replace it everywhere
475  if newValue._isTaskComponent():
476  if not self.__InExtendCall:
477  self._replaceInTasks(name, newValue)
478  self._replaceInConditionalTasks(name, newValue)
479  self._replaceInSchedule(name, newValue)
480  else:
481  if not isinstance(newValue, Task):
482  #should check to see if used in task before complaining
483  newFile='top level config'
484  if hasattr(value,'_filename'):
485  newFile = value._filename
486  oldFile='top level config'
487  oldValue = getattr(self,name)
488  if hasattr(oldValue,'_filename'):
489  oldFile = oldValue._filename
490  msg1 = "Trying to override definition of "+name+" while it is used by the task "
491  msg2 = "\n new object defined in: "+newFile
492  msg2 += "\n existing object defined in: "+oldFile
493  s = self.__findFirstUsingModule(self.tasks,oldValue)
494  if s is not None:
495  raise ValueError(msg1+s.label_()+msg2)
496 
497  if isinstance(newValue, _Sequenceable) or newValue._isTaskComponent() or isinstance(newValue, ConditionalTask):
498  if not self.__InExtendCall:
499  if isinstance(newValue, ConditionalTask):
500  self._replaceInConditionalTasks(name, newValue)
501  self._replaceInSequences(name, newValue)
502  else:
503  #should check to see if used in sequence before complaining
504  newFile='top level config'
505  if hasattr(value,'_filename'):
506  newFile = value._filename
507  oldFile='top level config'
508  oldValue = getattr(self,name)
509  if hasattr(oldValue,'_filename'):
510  oldFile = oldValue._filename
511  msg1 = "Trying to override definition of "+name+" while it is used by the "
512  msg2 = "\n new object defined in: "+newFile
513  msg2 += "\n existing object defined in: "+oldFile
514  s = self.__findFirstUsingModule(self.sequences,oldValue)
515  if s is not None:
516  raise ValueError(msg1+"sequence "+s.label_()+msg2)
517  s = self.__findFirstUsingModule(self.paths,oldValue)
518  if s is not None:
519  raise ValueError(msg1+"path "+s.label_()+msg2)
520  s = self.__findFirstUsingModule(self.endpaths,oldValue)
521  if s is not None:
522  raise ValueError(msg1+"endpath "+s.label_()+msg2)
523  s = self.__findFirstUsingModule(self.finalpaths,oldValue)
524  if s is not None:
525  raise ValueError(msg1+"finalpath "+s.label_()+msg2)
526 
527  # In case of EDAlias, raise Exception always to avoid surprises
528  if isinstance(newValue, EDAlias):
529  oldValue = getattr(self, name)
530  #should check to see if used in task/sequence before complaining
531  newFile='top level config'
532  if hasattr(value,'_filename'):
533  newFile = value._filename
534  oldFile='top level config'
535  if hasattr(oldValue,'_filename'):
536  oldFile = oldValue._filename
537  msg1 = "Trying to override definition of "+name+" with an EDAlias while it is used by the "
538  msg2 = "\n new object defined in: "+newFile
539  msg2 += "\n existing object defined in: "+oldFile
540  s = self.__findFirstUsingModule(self.tasks,oldValue)
541  if s is not None:
542  raise ValueError(msg1+"task "+s.label_()+msg2)
543  s = self.__findFirstUsingModule(self.sequences,oldValue)
544  if s is not None:
545  raise ValueError(msg1+"sequence "+s.label_()+msg2)
546  s = self.__findFirstUsingModule(self.paths,oldValue)
547  if s is not None:
548  raise ValueError(msg1+"path "+s.label_()+msg2)
549  s = self.__findFirstUsingModule(self.endpaths,oldValue)
550  if s is not None:
551  raise ValueError(msg1+"endpath "+s.label_()+msg2)
552  s = self.__findFirstUsingModule(self.finalpaths,oldValue)
553  if s is not None:
554  raise ValueError(msg1+"finalpath "+s.label_()+msg2)
555 
556  if not self.__InExtendCall and (Schedule._itemIsValid(newValue) or isinstance(newValue, Task)):
557  self._replaceInScheduleDirectly(name, newValue)
558 
559  self._delattrFromSetattr(name)
560  self.__injectValidValue(name, value, newValue)
561  def __injectValidValue(self, name, value, newValue = None):
562  if newValue is None:
563  newValue = value
564  self.__dict__[name]=newValue
565  if isinstance(newValue,_Labelable):
566  self.__setObjectLabel(newValue, name)
567  self._cloneToObjectDict[id(value)] = newValue
568  self._cloneToObjectDict[id(newValue)] = newValue
569  #now put in proper bucket
570  newValue._place(name,self)
571  def __findFirstUsingModule(self, seqsOrTasks, mod):
572  """Given a container of sequences or tasks, find the first sequence or task
573  containing mod and return it. If none is found, return None"""
574  from FWCore.ParameterSet.SequenceTypes import ModuleNodeVisitor
575  l = list()
576  for seqOrTask in seqsOrTasks.values():
577  l[:] = []
578  v = ModuleNodeVisitor(l)
579  seqOrTask.visit(v)
580  if mod in l:
581  return seqOrTask
582  return None
583 
584  def _delHelper(self,name):
585  if not hasattr(self,name):
586  raise KeyError('process does not know about '+name)
587  elif name.startswith('_Process__'):
588  raise ValueError('this attribute cannot be deleted')
589 
590  # we have to remove it from all dictionaries/registries
591  dicts = [item for item in self.__dict__.values() if (isinstance(item, dict) or isinstance(item, DictTypes.SortedKeysDict))]
592  for reg in dicts:
593  if name in reg: del reg[name]
594  # if it was a labelable object, the label needs to be removed
595  obj = getattr(self,name)
596  if isinstance(obj,_Labelable):
597  obj.setLabel(None)
598  if isinstance(obj,Service):
599  obj._inProcess = False
600 
601  def __delattr__(self,name):
602  self._delHelper(name)
603  obj = getattr(self,name)
604  if not obj is None:
605  if not isinstance(obj, Sequence) and not isinstance(obj, Task) and not isinstance(obj,ConditionalTask):
606  # For modules, ES modules and services we can also remove
607  # the deleted object from Sequences, Paths, EndPaths, and
608  # Tasks. Note that for Sequences and Tasks that cannot be done
609  # reliably as the places where the Sequence or Task was used
610  # might have been expanded so we do not even try. We considered
611  # raising an exception if a Sequences or Task was explicitly
612  # deleted, but did not because when done carefully deletion
613  # is sometimes OK (for example in the prune function where it
614  # has been checked that the deleted Sequence is not used).
615  if obj._isTaskComponent():
616  self._replaceInTasks(name, None)
617  self._replaceInConditionalTasks(name, None)
618  self._replaceInSchedule(name, None)
619  if isinstance(obj, _Sequenceable) or obj._isTaskComponent():
620  self._replaceInSequences(name, None)
621  if Schedule._itemIsValid(obj) or isinstance(obj, Task):
622  self._replaceInScheduleDirectly(name, None)
623  # now remove it from the process itself
624  try:
625  del self.__dict__[name]
626  except:
627  pass
628 
629  def _delattrFromSetattr(self,name):
630  """Similar to __delattr__ but we need different behavior when called from __setattr__"""
631  self._delHelper(name)
632  # now remove it from the process itself
633  try:
634  del self.__dict__[name]
635  except:
636  pass
637 
638  def add_(self,value):
639  """Allows addition of components that do not have to have a label, e.g. Services"""
640  if not isinstance(value,_ConfigureComponent):
641  raise TypeError
642  if not isinstance(value,_Unlabelable):
643  raise TypeError
644  #clone the item
645  if self.__isStrict:
646  newValue =value.copy()
647  value.setIsFrozen()
648  else:
649  newValue =value
650  newValue._place('',self)
651 
652  def _okToPlace(self, name, mod, d):
653  if not self.__InExtendCall:
654  # if going
655  return True
656  elif not self.__isStrict:
657  return True
658  elif name in d:
659  # if there's an old copy, and the new one
660  # hasn't been modified, we're done. Still
661  # not quite safe if something has been defined twice.
662  # Need to add checks
663  if mod._isModified:
664  if d[name]._isModified:
665  return False
666  else:
667  return True
668  else:
669  return True
670  else:
671  return True
672 
673  def _place(self, name, mod, d):
674  if self._okToPlace(name, mod, d):
675  if self.__isStrict and isinstance(mod, _ModuleSequenceType):
676  d[name] = mod._postProcessFixup(self._cloneToObjectDict)
677  else:
678  d[name] = mod
679  if isinstance(mod,_Labelable):
680  self.__setObjectLabel(mod, name)
681  def _placeOutputModule(self,name,mod):
682  self._place(name, mod, self.__outputmodules)
683  def _placeProducer(self,name,mod):
684  self._place(name, mod, self.__producers)
685  def _placeSwitchProducer(self,name,mod):
686  self._place(name, mod, self.__switchproducers)
687  def _placeFilter(self,name,mod):
688  self._place(name, mod, self.__filters)
689  def _placeAnalyzer(self,name,mod):
690  self._place(name, mod, self.__analyzers)
691  def _placePath(self,name,mod):
692  self._validateSequence(mod, name)
693  try:
694  self._place(name, mod, self.__paths)
695  except ModuleCloneError as msg:
696  context = format_outerframe(4)
697  raise Exception("%sThe module %s in path %s is unknown to the process %s." %(context, msg, name, self._Process__name))
698  def _placeEndPath(self,name,mod):
699  self._validateSequence(mod, name)
700  try:
701  self._place(name, mod, self.__endpaths)
702  except ModuleCloneError as msg:
703  context = format_outerframe(4)
704  raise Exception("%sThe module %s in endpath %s is unknown to the process %s." %(context, msg, name, self._Process__name))
705  def _placeFinalPath(self,name,mod):
706  self._validateSequence(mod, name)
707  try:
708  self._place(name, mod, self.__finalpaths)
709  except ModuleCloneError as msg:
710  context = format_outerframe(4)
711  raise Exception("%sThe module %s in finalpath %s is unknown to the process %s." %(context, msg, name, self._Process__name))
712  def _placeSequence(self,name,mod):
713  self._validateSequence(mod, name)
714  self._place(name, mod, self.__sequences)
715  def _placeESProducer(self,name,mod):
716  self._place(name, mod, self.__esproducers)
717  def _placeESPrefer(self,name,mod):
718  self._place(name, mod, self.__esprefers)
719  def _placeESSource(self,name,mod):
720  self._place(name, mod, self.__essources)
721  def _placeTask(self,name,task):
722  self._validateTask(task, name)
723  self._place(name, task, self.__tasks)
724  def _placeConditionalTask(self,name,task):
725  self._validateConditionalTask(task, name)
726  self._place(name, task, self.__conditionaltasks)
727  def _placeAlias(self,name,mod):
728  self._place(name, mod, self.__aliases)
729  def _placePSet(self,name,mod):
730  self._place(name, mod, self.__psets)
731  def _placeVPSet(self,name,mod):
732  self._place(name, mod, self.__vpsets)
733  def _placeSource(self,name,mod):
734  """Allow the source to be referenced by 'source' or by type name"""
735  if name != 'source':
736  raise ValueError("The label '"+name+"' can not be used for a Source. Only 'source' is allowed.")
737  if self.__dict__['_Process__source'] is not None :
738  del self.__dict__[self.__dict__['_Process__source'].type_()]
739  self.__dict__['_Process__source'] = mod
740  self.__dict__[mod.type_()] = mod
741  def _placeLooper(self,name,mod):
742  if name != 'looper':
743  raise ValueError("The label '"+name+"' can not be used for a Looper. Only 'looper' is allowed.")
744  self.__dict__['_Process__looper'] = mod
745  self.__dict__[mod.type_()] = mod
746  def _placeSubProcess(self,name,mod):
747  self.__dict__['_Process__subProcess'] = mod
748  self.__dict__[mod.type_()] = mod
749  def addSubProcess(self,mod):
750  self.__subProcesses.append(mod)
751  def _placeService(self,typeName,mod):
752  self._place(typeName, mod, self.__services)
753  if typeName in self.__dict__:
754  self.__dict__[typeName]._inProcess = False
755  self.__dict__[typeName]=mod
756  def _placeAccelerator(self,typeName,mod):
757  self._place(typeName, mod, self.__accelerators)
758  self.__dict__[typeName]=mod
759  def load(self, moduleName):
760  moduleName = moduleName.replace("/",".")
761  module = __import__(moduleName)
762  self.extend(sys.modules[moduleName])
763  def extend(self,other,items=()):
764  """Look in other and find types that we can use"""
765  # enable explicit check to avoid overwriting of existing objects
766  self.__dict__['_Process__InExtendCall'] = True
767 
768  seqs = dict()
769  tasksToAttach = dict()
770  mods = []
771  for name in dir(other):
772  #'from XX import *' ignores these, and so should we.
773  if name.startswith('_'):
774  continue
775  item = getattr(other,name)
776  if name == "source" or name == "looper":
777  # In these cases 'item' could be None if the specific object was not defined
778  if item is not None:
779  self.__setattr__(name,item)
780  elif isinstance(item,_ModuleSequenceType):
781  seqs[name]=item
782  elif isinstance(item,Task) or isinstance(item, ConditionalTask):
783  tasksToAttach[name] = item
784  elif isinstance(item,_Labelable):
785  self.__setattr__(name,item)
786  if not item.hasLabel_() :
787  item.setLabel(name)
788  elif isinstance(item,Schedule):
789  self.__setattr__(name,item)
790  elif isinstance(item,_Unlabelable):
791  self.add_(item)
792  elif isinstance(item,ProcessModifier):
793  mods.append(item)
794  elif isinstance(item,ProcessFragment):
795  self.extend(item)
796 
797  #now create a sequence that uses the newly made items
798  for name,seq in seqs.items():
799  if id(seq) not in self._cloneToObjectDict:
800  self.__setattr__(name,seq)
801  else:
802  newSeq = self._cloneToObjectDict[id(seq)]
803  self.__dict__[name]=newSeq
804  self.__setObjectLabel(newSeq, name)
805  #now put in proper bucket
806  newSeq._place(name,self)
807 
808  for name, task in tasksToAttach.items():
809  self.__setattr__(name, task)
810 
811  #apply modifiers now that all names have been added
812  for item in mods:
813  item.apply(self)
814 
815  self.__dict__['_Process__InExtendCall'] = False
816 
817  def _dumpConfigNamedList(self,items,typeName,options):
818  returnValue = ''
819  for name,item in items:
820  returnValue +=options.indentation()+typeName+' '+name+' = '+item.dumpConfig(options)
821  return returnValue
822 
823  def _dumpConfigUnnamedList(self,items,typeName,options):
824  returnValue = ''
825  for name,item in items:
826  returnValue +=options.indentation()+typeName+' = '+item.dumpConfig(options)
827  return returnValue
828 
829  def _dumpConfigOptionallyNamedList(self,items,typeName,options):
830  returnValue = ''
831  for name,item in items:
832  if name == item.type_():
833  name = ''
834  returnValue +=options.indentation()+typeName+' '+name+' = '+item.dumpConfig(options)
835  return returnValue
836 
837  def dumpConfig(self, options=PrintOptions()):
838  """return a string containing the equivalent process defined using the old configuration language"""
839  config = "process "+self.__name+" = {\n"
840  options.indent()
841  if self.source_():
842  config += options.indentation()+"source = "+self.source_().dumpConfig(options)
843  if self.looper_():
844  config += options.indentation()+"looper = "+self.looper_().dumpConfig(options)
845 
846  config+=self._dumpConfigNamedList(self.subProcesses_(),
847  'subProcess',
848  options)
849  config+=self._dumpConfigNamedList(self.producers_().items(),
850  'module',
851  options)
852  config+=self._dumpConfigNamedList(self.switchProducers_().items(),
853  'module',
854  options)
855  config+=self._dumpConfigNamedList(self.filters_().items(),
856  'module',
857  options)
858  config+=self._dumpConfigNamedList(self.analyzers_().items(),
859  'module',
860  options)
861  config+=self._dumpConfigNamedList(self.outputModules_().items(),
862  'module',
863  options)
864  config+=self._dumpConfigNamedList(self.sequences_().items(),
865  'sequence',
866  options)
867  config+=self._dumpConfigNamedList(self.paths_().items(),
868  'path',
869  options)
870  config+=self._dumpConfigNamedList(self.endpaths_().items(),
871  'endpath',
872  options)
873  config+=self._dumpConfigNamedList(self.finalpaths_().items(),
874  'finalpath',
875  options)
876  config+=self._dumpConfigUnnamedList(self.services_().items(),
877  'service',
878  options)
879  config+=self._dumpConfigNamedList(self.aliases_().items(),
880  'alias',
881  options)
882  config+=self._dumpConfigOptionallyNamedList(
883  self.es_producers_().items(),
884  'es_module',
885  options)
886  config+=self._dumpConfigOptionallyNamedList(
887  self.es_sources_().items(),
888  'es_source',
889  options)
890  config += self._dumpConfigESPrefers(options)
891  for name,item in self.psets.items():
892  config +=options.indentation()+item.configTypeName()+' '+name+' = '+item.configValue(options)
893  for name,item in self.vpsets.items():
894  config +=options.indentation()+'VPSet '+name+' = '+item.configValue(options)
895  if self.schedule:
896  pathNames = [p.label_() for p in self.schedule]
897  config +=options.indentation()+'schedule = {'+','.join(pathNames)+'}\n'
898 
899 # config+=self._dumpConfigNamedList(self.vpsets.items(),
900 # 'VPSet',
901 # options)
902  config += "}\n"
903  options.unindent()
904  return config
905 
906  def _dumpConfigESPrefers(self, options):
907  result = ''
908  for item in self.es_prefers_().values():
909  result +=options.indentation()+'es_prefer '+item.targetLabel_()+' = '+item.dumpConfig(options)
910  return result
911 
912  def _dumpPythonSubProcesses(self, l, options):
913  returnValue = ''
914  for item in l:
915  returnValue += item.dumpPython(options)+'\n\n'
916  return returnValue
917 
918  def _dumpPythonList(self, d, options):
919  returnValue = ''
920  if isinstance(d, DictTypes.SortedKeysDict):
921  for name,item in d.items():
922  returnValue +='process.'+name+' = '+item.dumpPython(options)+'\n\n'
923  else:
924  for name,item in sorted(d.items()):
925  returnValue +='process.'+name+' = '+item.dumpPython(options)+'\n\n'
926  return returnValue
927 
928  def _splitPythonList(self, subfolder, d, options):
929  parts = DictTypes.SortedKeysDict()
930  for name, item in d.items() if isinstance(d, DictTypes.SortedKeysDict) else sorted(d.items()):
931  code = ''
932  dependencies = item.directDependencies()
933  for module_subfolder, module in dependencies:
934  module = module + '_cfi'
935  if options.useSubdirectories and module_subfolder:
936  module = module_subfolder + '.' + module
937  if options.targetDirectory is not None:
938  if options.useSubdirectories and subfolder:
939  module = '..' + module
940  else:
941  module = '.' + module
942  code += 'from ' + module + ' import *\n'
943  if dependencies:
944  code += '\n'
945  code += name + ' = ' + item.dumpPython(options)
946  parts[name] = subfolder, code
947  return parts
948 
949  def _validateSequence(self, sequence, label):
950  # See if every module has been inserted into the process
951  try:
952  l = set()
953  visitor = NodeNameVisitor(l)
954  sequence.visit(visitor)
955  except Exception as e:
956  raise RuntimeError("An entry in sequence {} has no label\n Seen entries: {}\n Error: {}".format(label, l, e))
957 
958  def _validateTask(self, task, label):
959  # See if every module and service has been inserted into the process
960  try:
961  l = set()
962  visitor = NodeNameVisitor(l)
963  task.visit(visitor)
964  except:
965  raise RuntimeError("An entry in task " + label + ' has not been attached to the process')
966  def _validateConditionalTask(self, task, label):
967  # See if every module and service has been inserted into the process
968  try:
969  l = set()
970  visitor = NodeNameVisitor(l)
971  task.visit(visitor)
972  except:
973  raise RuntimeError("An entry in task " + label + ' has not been attached to the process')
974 
975  def _itemsInDependencyOrder(self, processDictionaryOfItems):
976  # The items can be Sequences or Tasks and the input
977  # argument should either be the dictionary of sequences
978  # or the dictionary of tasks from the process.
979 
980  returnValue=DictTypes.SortedKeysDict()
981 
982  # For each item, see what other items it depends upon
983  # For our purpose here, an item depends on the items it contains.
984  dependencies = {}
985  for label,item in processDictionaryOfItems.items():
986  containedItems = []
987  if isinstance(item, Task):
988  v = TaskVisitor(containedItems)
989  elif isinstance(item, ConditionalTask):
990  v = ConditionalTaskVisitor(containedItems)
991  else:
992  v = SequenceVisitor(containedItems)
993  try:
994  item.visit(v)
995  except RuntimeError:
996  if isinstance(item, Task):
997  raise RuntimeError("Failed in a Task visitor. Probably " \
998  "a circular dependency discovered in Task with label " + label)
999  elif isinstance(item, ConditionalTask):
1000  raise RuntimeError("Failed in a ConditionalTask visitor. Probably " \
1001  "a circular dependency discovered in ConditionalTask with label " + label)
1002  else:
1003  raise RuntimeError("Failed in a Sequence visitor. Probably a " \
1004  "circular dependency discovered in Sequence with label " + label)
1005  for containedItem in containedItems:
1006  # Check for items that both have labels and are not in the process.
1007  # This should not normally occur unless someone explicitly assigns a
1008  # label without putting the item in the process (which should not ever
1009  # be done). We check here because this problem could cause the code
1010  # in the 'while' loop below to go into an infinite loop.
1011  if containedItem.hasLabel_():
1012  testItem = processDictionaryOfItems.get(containedItem.label_())
1013  if testItem is None or containedItem != testItem:
1014  if isinstance(item, Task):
1015  raise RuntimeError("Task has a label, but using its label to get an attribute" \
1016  " from the process yields a different object or None\n"+
1017  "label = " + containedItem.label_())
1018  if isinstance(item, ConditionalTask):
1019  raise RuntimeError("ConditionalTask has a label, but using its label to get an attribute" \
1020  " from the process yields a different object or None\n"+
1021  "label = " + containedItem.label_())
1022  else:
1023  raise RuntimeError("Sequence has a label, but using its label to get an attribute" \
1024  " from the process yields a different object or None\n"+
1025  "label = " + containedItem.label_())
1026  dependencies[label]=[dep.label_() for dep in containedItems if dep.hasLabel_()]
1027 
1028  # keep looping until we get rid of all dependencies
1029  while dependencies:
1030  oldDeps = dict(dependencies)
1031  for label,deps in oldDeps.items():
1032  if len(deps)==0:
1033  returnValue[label]=processDictionaryOfItems[label]
1034  #remove this as a dependency for all other tasks
1035  del dependencies[label]
1036  for lb2,deps2 in dependencies.items():
1037  while deps2.count(label):
1038  deps2.remove(label)
1039  return returnValue
1040 
1041  def _dumpPython(self, d, options):
1042  result = ''
1043  for name, value in sorted(d.items()):
1044  result += value.dumpPythonAs(name,options)+'\n'
1045  return result
1046 
1047  def _splitPython(self, subfolder, d, options):
1048  result = {}
1049  for name, value in sorted(d.items()):
1050  result[name] = subfolder, value.dumpPythonAs(name, options) + '\n'
1051  return result
1052 
1053  def dumpPython(self, options=PrintOptions()):
1054  """return a string containing the equivalent process defined using python"""
1055  specialImportRegistry._reset()
1056  header = "import FWCore.ParameterSet.Config as cms"
1057  result = "process = cms.Process(\""+self.__name+"\")\n\n"
1058  if self.source_():
1059  result += "process.source = "+self.source_().dumpPython(options)
1060  if self.looper_():
1061  result += "process.looper = "+self.looper_().dumpPython()
1062  result+=self._dumpPythonList(self.psets, options)
1063  result+=self._dumpPythonList(self.vpsets, options)
1064  result+=self._dumpPythonSubProcesses(self.subProcesses_(), options)
1065  result+=self._dumpPythonList(self.producers_(), options)
1066  result+=self._dumpPythonList(self.switchProducers_(), options)
1067  result+=self._dumpPythonList(self.filters_() , options)
1068  result+=self._dumpPythonList(self.analyzers_(), options)
1069  result+=self._dumpPythonList(self.outputModules_(), options)
1070  result+=self._dumpPythonList(self.services_(), options)
1071  result+=self._dumpPythonList(self.processAccelerators_(), options)
1072  result+=self._dumpPythonList(self.es_producers_(), options)
1073  result+=self._dumpPythonList(self.es_sources_(), options)
1074  result+=self._dumpPython(self.es_prefers_(), options)
1075  result+=self._dumpPythonList(self._itemsInDependencyOrder(self.tasks), options)
1076  result+=self._dumpPythonList(self._itemsInDependencyOrder(self.conditionaltasks), options)
1077  result+=self._dumpPythonList(self._itemsInDependencyOrder(self.sequences), options)
1078  result+=self._dumpPythonList(self.paths_(), options)
1079  result+=self._dumpPythonList(self.endpaths_(), options)
1080  result+=self._dumpPythonList(self.finalpaths_(), options)
1081  result+=self._dumpPythonList(self.aliases_(), options)
1082  if not self.schedule_() == None:
1083  result += 'process.schedule = ' + self.schedule.dumpPython(options)
1084  imports = specialImportRegistry.getSpecialImports()
1085  if len(imports) > 0:
1086  header += "\n" + "\n".join(imports)
1087  header += "\n\n"
1088  return header+result
1089 
1090  def splitPython(self, options = PrintOptions()):
1091  """return a map of file names to python configuration fragments"""
1092  specialImportRegistry._reset()
1093  # extract individual fragments
1094  options.isCfg = False
1095  header = "import FWCore.ParameterSet.Config as cms"
1096  result = ''
1097  parts = {}
1098  files = {}
1099 
1100  result = 'process = cms.Process("' + self.__name + '")\n\n'
1101 
1102  if self.source_():
1103  parts['source'] = (None, 'source = ' + self.source_().dumpPython(options))
1104 
1105  if self.looper_():
1106  parts['looper'] = (None, 'looper = ' + self.looper_().dumpPython())
1107 
1108  parts.update(self._splitPythonList('psets', self.psets, options))
1109  parts.update(self._splitPythonList('psets', self.vpsets, options))
1110  # FIXME
1111  #parts.update(self._splitPythonSubProcesses(self.subProcesses_(), options))
1112  if len(self.subProcesses_()):
1113  sys.stderr.write("error: subprocesses are not supported yet\n\n")
1114  parts.update(self._splitPythonList('modules', self.producers_(), options))
1115  parts.update(self._splitPythonList('modules', self.switchProducers_(), options))
1116  parts.update(self._splitPythonList('modules', self.filters_() , options))
1117  parts.update(self._splitPythonList('modules', self.analyzers_(), options))
1118  parts.update(self._splitPythonList('modules', self.outputModules_(), options))
1119  parts.update(self._splitPythonList('services', self.services_(), options))
1120  parts.update(self._splitPythonList('eventsetup', self.es_producers_(), options))
1121  parts.update(self._splitPythonList('eventsetup', self.es_sources_(), options))
1122  parts.update(self._splitPython('eventsetup', self.es_prefers_(), options))
1123  parts.update(self._splitPythonList('tasks', self._itemsInDependencyOrder(self.tasks), options))
1124  parts.update(self._splitPythonList('sequences', self._itemsInDependencyOrder(self.sequences), options))
1125  parts.update(self._splitPythonList('paths', self.paths_(), options))
1126  parts.update(self._splitPythonList('paths', self.endpaths_(), options))
1127  parts.update(self._splitPythonList('paths', self.finalpaths_(), options))
1128  parts.update(self._splitPythonList('modules', self.aliases_(), options))
1129 
1130  if options.targetDirectory is not None:
1131  files[options.targetDirectory + '/__init__.py'] = ''
1132 
1133  if options.useSubdirectories:
1134  for sub in 'psets', 'modules', 'services', 'eventsetup', 'tasks', 'sequences', 'paths':
1135  if options.targetDirectory is not None:
1136  sub = options.targetDirectory + '/' + sub
1137  files[sub + '/__init__.py'] = ''
1138 
1139  # case insensitive sort by subfolder and module name
1140  parts = sorted(parts.items(), key = lambda nsc: (nsc[1][0].lower() if nsc[1][0] else '', nsc[0].lower()))
1141 
1142  for (name, (subfolder, code)) in parts:
1143  filename = name + '_cfi'
1144  if options.useSubdirectories and subfolder:
1145  filename = subfolder + '/' + filename
1146  if options.targetDirectory is not None:
1147  filename = options.targetDirectory + '/' + filename
1148  result += 'process.load("%s")\n' % filename
1149  files[filename + '.py'] = header + '\n\n' + code
1150 
1151  if self.schedule_() is not None:
1152  options.isCfg = True
1153  result += '\nprocess.schedule = ' + self.schedule.dumpPython(options)
1154 
1155  imports = specialImportRegistry.getSpecialImports()
1156  if len(imports) > 0:
1157  header += '\n' + '\n'.join(imports)
1158  files['-'] = header + '\n\n' + result
1159  return files
1160 
1161  def _replaceInSequences(self, label, new):
1162  old = getattr(self,label)
1163  #TODO - replace by iterator concatenation
1164  #to ovoid dependency problems between sequences, first modify
1165  # process known sequences to do a non-recursive change. Then do
1166  # a recursive change to get cases where a sub-sequence unknown to
1167  # the process has the item to be replaced
1168  for sequenceable in self.sequences.values():
1169  sequenceable._replaceIfHeldDirectly(old,new)
1170  for sequenceable in self.sequences.values():
1171  sequenceable.replace(old,new)
1172  for sequenceable in self.paths.values():
1173  sequenceable.replace(old,new)
1174  for sequenceable in self.endpaths.values():
1175  sequenceable.replace(old,new)
1176  for sequenceable in self.finalpaths.values():
1177  sequenceable.replace(old,new)
1178  def _replaceInTasks(self, label, new):
1179  old = getattr(self,label)
1180  for task in self.tasks.values():
1181  task.replace(old, new)
1182  def _replaceInConditionalTasks(self, label, new):
1183  old = getattr(self,label)
1184  for task in self.conditionaltasks.values():
1185  task.replace(old, new)
1186  def _replaceInSchedule(self, label, new):
1187  if self.schedule_() == None:
1188  return
1189  old = getattr(self,label)
1190  for task in self.schedule_()._tasks:
1191  task.replace(old, new)
1192  def _replaceInScheduleDirectly(self, label, new):
1193  if self.schedule_() == None:
1194  return
1195  old = getattr(self,label)
1196  self.schedule_()._replaceIfHeldDirectly(old, new)
1197  def globalReplace(self,label,new):
1198  """ Replace the item with label 'label' by object 'new' in the process and all sequences/paths/tasks"""
1199  if not hasattr(self,label):
1200  raise LookupError("process has no item of label "+label)
1201  setattr(self,label,new)
1202  def _insertInto(self, parameterSet, itemDict):
1203  for name,value in itemDict.items():
1204  value.insertInto(parameterSet, name)
1205  def _insertOneInto(self, parameterSet, label, item, tracked):
1206  vitems = []
1207  if not item == None:
1208  newlabel = item.nameInProcessDesc_(label)
1209  vitems = [newlabel]
1210  item.insertInto(parameterSet, newlabel)
1211  parameterSet.addVString(tracked, label, vitems)
1212  def _insertManyInto(self, parameterSet, label, itemDict, tracked):
1213  l = []
1214  for name,value in itemDict.items():
1215  value.appendToProcessDescList_(l, name)
1216  value.insertInto(parameterSet, name)
1217  # alphabetical order is easier to compare with old language
1218  l.sort()
1219  parameterSet.addVString(tracked, label, l)
1220  def _insertSwitchProducersInto(self, parameterSet, labelModules, labelAliases, itemDict, tracked):
1221  modules = parameterSet.getVString(tracked, labelModules)
1222  aliases = parameterSet.getVString(tracked, labelAliases)
1223  accelerators = parameterSet.getVString(False, "@selected_accelerators")
1224  for name,value in itemDict.items():
1225  value.appendToProcessDescLists_(modules, aliases, name)
1226  value.insertInto(parameterSet, name, accelerators)
1227  modules.sort()
1228  aliases.sort()
1229  parameterSet.addVString(tracked, labelModules, modules)
1230  parameterSet.addVString(tracked, labelAliases, aliases)
1231  def _insertSubProcessesInto(self, parameterSet, label, itemList, tracked):
1232  l = []
1233  subprocs = []
1234  for value in itemList:
1235  name = value.getProcessName()
1236  newLabel = value.nameInProcessDesc_(name)
1237  l.append(newLabel)
1238  pset = value.getSubProcessPSet(parameterSet)
1239  subprocs.append(pset)
1240  # alphabetical order is easier to compare with old language
1241  l.sort()
1242  parameterSet.addVString(tracked, label, l)
1243  parameterSet.addVPSet(False,"subProcesses",subprocs)
1244  def _insertPaths(self, processPSet, nodeVisitor):
1245  scheduledPaths = []
1246  triggerPaths = []
1247  endpaths = []
1248  finalpaths = []
1249  if self.schedule_() == None:
1250  # make one from triggerpaths & endpaths
1251  for name in self.paths_():
1252  scheduledPaths.append(name)
1253  triggerPaths.append(name)
1254  for name in self.endpaths_():
1255  scheduledPaths.append(name)
1256  endpaths.append(name)
1257  for name in self.finalpaths_():
1258  finalpaths.append(name)
1259  else:
1260  for path in self.schedule_():
1261  pathname = path.label_()
1262  if pathname in self.endpaths_():
1263  endpaths.append(pathname)
1264  scheduledPaths.append(pathname)
1265  elif pathname in self.finalpaths_():
1266  finalpaths.append(pathname)
1267  else:
1268  scheduledPaths.append(pathname)
1269  triggerPaths.append(pathname)
1270  for task in self.schedule_()._tasks:
1271  task.resolve(self.__dict__)
1272  scheduleTaskValidator = ScheduleTaskValidator()
1273  task.visit(scheduleTaskValidator)
1274  task.visit(nodeVisitor)
1275  # consolidate all final_paths into one EndPath
1276  endPathWithFinalPathModulesName ="@finalPath"
1277  finalPathEndPath = EndPath()
1278  if finalpaths:
1279  endpaths.append(endPathWithFinalPathModulesName)
1280  scheduledPaths.append(endPathWithFinalPathModulesName)
1281  finalpathValidator = FinalPathValidator()
1282  modulesOnFinalPath = []
1283  for finalpathname in finalpaths:
1284  iFinalPath = self.finalpaths_()[finalpathname]
1285  iFinalPath.resolve(self.__dict__)
1286  finalpathValidator.setLabel(finalpathname)
1287  iFinalPath.visit(finalpathValidator)
1288  if finalpathValidator.filtersOnFinalpaths or finalpathValidator.producersOnFinalpaths:
1289  names = [p.label_ for p in finalpathValidator.filtersOnFinalpaths]
1290  names.extend( [p.label_ for p in finalpathValidator.producersOnFinalpaths])
1291  raise RuntimeError("FinalPath %s has non OutputModules %s" % (finalpathname, ",".join(names)))
1292  modulesOnFinalPath.extend(iFinalPath.moduleNames())
1293  for m in modulesOnFinalPath:
1294  mod = getattr(self, m)
1295  setattr(mod, "@onFinalPath", untracked.bool(True))
1296  finalPathEndPath += mod
1297 
1298  processPSet.addVString(True, "@end_paths", endpaths)
1299  processPSet.addVString(True, "@paths", scheduledPaths)
1300  # trigger_paths are a little different
1301  p = processPSet.newPSet()
1302  p.addVString(True, "@trigger_paths", triggerPaths)
1303  processPSet.addPSet(True, "@trigger_paths", p)
1304  # add all these paths
1305  pathValidator = PathValidator()
1306  endpathValidator = EndPathValidator()
1307  decoratedList = []
1308  lister = DecoratedNodeNameVisitor(decoratedList)
1309  condTaskModules = []
1310  condTaskVistor = ModuleNodeOnConditionalTaskVisitor(condTaskModules)
1311  pathCompositeVisitor = CompositeVisitor(pathValidator, nodeVisitor, lister, condTaskVistor)
1312  endpathCompositeVisitor = CompositeVisitor(endpathValidator, nodeVisitor, lister)
1313  for triggername in triggerPaths:
1314  iPath = self.paths_()[triggername]
1315  iPath.resolve(self.__dict__)
1316  pathValidator.setLabel(triggername)
1317  lister.initialize()
1318  condTaskModules[:] = []
1319  iPath.visit(pathCompositeVisitor)
1320  if condTaskModules:
1321  decoratedList.append("#")
1322  l = list({x.label_() for x in condTaskModules})
1323  l.sort()
1324  decoratedList.extend(l)
1325  decoratedList.append("@")
1326  iPath.insertInto(processPSet, triggername, decoratedList[:])
1327  for endpathname in endpaths:
1328  if endpathname is not endPathWithFinalPathModulesName:
1329  iEndPath = self.endpaths_()[endpathname]
1330  else:
1331  iEndPath = finalPathEndPath
1332  iEndPath.resolve(self.__dict__)
1333  endpathValidator.setLabel(endpathname)
1334  lister.initialize()
1335  iEndPath.visit(endpathCompositeVisitor)
1336  iEndPath.insertInto(processPSet, endpathname, decoratedList[:])
1337  processPSet.addVString(False, "@filters_on_endpaths", endpathValidator.filtersOnEndpaths)
1338 
1339 
1340  def resolve(self,keepUnresolvedSequencePlaceholders=False):
1341  for x in self.paths.values():
1342  x.resolve(self.__dict__,keepUnresolvedSequencePlaceholders)
1343  for x in self.endpaths.values():
1344  x.resolve(self.__dict__,keepUnresolvedSequencePlaceholders)
1345  for x in self.finalpaths.values():
1346  x.resolve(self.__dict__,keepUnresolvedSequencePlaceholders)
1347  if not self.schedule_() == None:
1348  for task in self.schedule_()._tasks:
1349  task.resolve(self.__dict__,keepUnresolvedSequencePlaceholders)
1350 
1351  def prune(self,verbose=False,keepUnresolvedSequencePlaceholders=False):
1352  """ Remove clutter from the process that we think is unnecessary:
1353  tracked PSets, VPSets and unused modules and sequences. If a Schedule has been set, then Paths and EndPaths
1354  not in the schedule will also be removed, along with an modules and sequences used only by
1355  those removed Paths and EndPaths. The keepUnresolvedSequencePlaceholders keeps also unresolved TaskPlaceholders."""
1356 # need to update this to only prune psets not on refToPSets
1357 # but for now, remove the delattr
1358 # for name in self.psets_():
1359 # if getattr(self,name).isTracked():
1360 # delattr(self, name)
1361  for name in self.vpsets_():
1362  delattr(self, name)
1363  #first we need to resolve any SequencePlaceholders being used
1364  self.resolve(keepUnresolvedSequencePlaceholders)
1365  usedModules = set()
1366  unneededPaths = set()
1367  tasks = list()
1368  tv = TaskVisitor(tasks)
1369  if self.schedule_():
1370  usedModules=set(self.schedule_().moduleNames())
1371  #get rid of unused paths
1372  schedNames = set(( x.label_() for x in self.schedule_()))
1373  names = set(self.paths)
1374  names.update(set(self.endpaths))
1375  names.update(set(self.finalpaths))
1376  unneededPaths = names - schedNames
1377  for n in unneededPaths:
1378  delattr(self,n)
1379  for t in self.schedule_().tasks():
1380  tv.enter(t)
1381  t.visit(tv)
1382  tv.leave(t)
1383  else:
1384  pths = list(self.paths.values())
1385  pths.extend(self.endpaths.values())
1386  pths.extend(self.finalpaths.values())
1387  temp = Schedule(*pths)
1388  usedModules=set(temp.moduleNames())
1389  unneededModules = self._pruneModules(self.producers_(), usedModules)
1390  unneededModules.update(self._pruneModules(self.switchProducers_(), usedModules))
1391  unneededModules.update(self._pruneModules(self.filters_(), usedModules))
1392  unneededModules.update(self._pruneModules(self.analyzers_(), usedModules))
1393  #remove sequences and tasks that do not appear in remaining paths and endpaths
1394  seqs = list()
1395  sv = SequenceVisitor(seqs)
1396  for p in self.paths.values():
1397  p.visit(sv)
1398  p.visit(tv)
1399  for p in self.endpaths.values():
1400  p.visit(sv)
1401  p.visit(tv)
1402  for p in self.finalpaths.values():
1403  p.visit(sv)
1404  p.visit(tv)
1405  def removeUnneeded(seqOrTasks, allSequencesOrTasks):
1406  _keepSet = set(( s for s in seqOrTasks if s.hasLabel_()))
1407  _availableSet = set(allSequencesOrTasks.values())
1408  _unneededSet = _availableSet-_keepSet
1409  _unneededLabels = []
1410  for s in _unneededSet:
1411  _unneededLabels.append(s.label_())
1412  delattr(self,s.label_())
1413  return _unneededLabels
1414  unneededSeqLabels = removeUnneeded(seqs, self.sequences)
1415  unneededTaskLabels = removeUnneeded(tasks, self.tasks)
1416  if verbose:
1417  print("prune removed the following:")
1418  print(" modules:"+",".join(unneededModules))
1419  print(" tasks:"+",".join(unneededTaskLabels))
1420  print(" sequences:"+",".join(unneededSeqLabels))
1421  print(" paths/endpaths/finalpaths:"+",".join(unneededPaths))
1422  def _pruneModules(self, d, scheduledNames):
1423  moduleNames = set(d.keys())
1424  junk = moduleNames - scheduledNames
1425  for name in junk:
1426  delattr(self, name)
1427  return junk
1428 
1429  def fillProcessDesc(self, processPSet):
1430  """Used by the framework to convert python to C++ objects"""
1431  class ServiceInjectorAdaptor(object):
1432  def __init__(self,ppset,thelist):
1433  self.__thelist = thelist
1434  self.__processPSet = ppset
1435  def addService(self,pset):
1436  self.__thelist.append(pset)
1437  def newPSet(self):
1438  return self.__processPSet.newPSet()
1439  #This adaptor is used to 'add' the method 'getTopPSet_'
1440  # to the ProcessDesc and PythonParameterSet C++ classes.
1441  # This method is needed for the PSet refToPSet_ functionality.
1442  class TopLevelPSetAcessorAdaptor(object):
1443  def __init__(self,ppset,process):
1444  self.__ppset = ppset
1445  self.__process = process
1446  def __getattr__(self,attr):
1447  return getattr(self.__ppset,attr)
1448  def getTopPSet_(self,label):
1449  return getattr(self.__process,label)
1450  def newPSet(self):
1451  return TopLevelPSetAcessorAdaptor(self.__ppset.newPSet(),self.__process)
1452  def addPSet(self,tracked,name,ppset):
1453  return self.__ppset.addPSet(tracked,name,self.__extractPSet(ppset))
1454  def addVPSet(self,tracked,name,vpset):
1455  return self.__ppset.addVPSet(tracked,name,[self.__extractPSet(x) for x in vpset])
1456  def __extractPSet(self,pset):
1457  if isinstance(pset,TopLevelPSetAcessorAdaptor):
1458  return pset.__ppset
1459  return pset
1460 
1461  self.validate()
1462  processPSet.addString(True, "@process_name", self.name_())
1463  self.handleProcessAccelerators(processPSet)
1464  all_modules = self.producers_().copy()
1465  all_modules.update(self.filters_())
1466  all_modules.update(self.analyzers_())
1467  all_modules.update(self.outputModules_())
1468  if hasattr(self.options,"modulesToCallForTryToContinue") :
1469  shouldTryToContinue = set(self.options.modulesToCallForTryToContinue)
1470  for m in all_modules:
1471  if m in shouldTryToContinue:
1472  setattr(getattr(self,m),"@shouldTryToContinue",untracked.bool(True))
1473  missing = shouldTryToContinue.difference(all_modules)
1474  if missing:
1475  print("Warning: The following modules appear in options.modulesToCallForTryToContinue but are not in the Process: {} ".format(",".join(missing)))
1476  adaptor = TopLevelPSetAcessorAdaptor(processPSet,self)
1477  self._insertInto(adaptor, self.psets_())
1478  self._insertInto(adaptor, self.vpsets_())
1479  self._insertOneInto(adaptor, "@all_sources", self.source_(), True)
1480  self._insertOneInto(adaptor, "@all_loopers", self.looper_(), True)
1481  self._insertSubProcessesInto(adaptor, "@all_subprocesses", self.subProcesses_(), False)
1482  self._insertManyInto(adaptor, "@all_esprefers", self.es_prefers_(), True)
1483  self._insertManyInto(adaptor, "@all_aliases", self.aliases_(), True)
1484  # This will visit all the paths and endpaths that are scheduled to run,
1485  # as well as the Tasks associated to them and the schedule. It remembers
1486  # the modules, ESSources, ESProducers, and services it visits.
1487  nodeVisitor = NodeVisitor()
1488  self._insertPaths(adaptor, nodeVisitor)
1489  all_modules_onTasksOrScheduled = { key:value for key, value in all_modules.items() if value in nodeVisitor.modules }
1490  self._insertManyInto(adaptor, "@all_modules", all_modules_onTasksOrScheduled, True)
1491  all_switches = self.switchProducers_().copy()
1492  all_switches_onTasksOrScheduled = {key:value for key, value in all_switches.items() if value in nodeVisitor.modules }
1493  self._insertSwitchProducersInto(adaptor, "@all_modules", "@all_aliases", all_switches_onTasksOrScheduled, True)
1494  # Same as nodeVisitor except this one visits all the Tasks attached
1495  # to the process.
1496  processNodeVisitor = NodeVisitor()
1497  for pTask in self.tasks.values():
1498  pTask.visit(processNodeVisitor)
1499  esProducersToEnable = {}
1500  for esProducerName, esProducer in self.es_producers_().items():
1501  if esProducer in nodeVisitor.esProducers or not (esProducer in processNodeVisitor.esProducers):
1502  esProducersToEnable[esProducerName] = esProducer
1503  self._insertManyInto(adaptor, "@all_esmodules", esProducersToEnable, True)
1504  esSourcesToEnable = {}
1505  for esSourceName, esSource in self.es_sources_().items():
1506  if esSource in nodeVisitor.esSources or not (esSource in processNodeVisitor.esSources):
1507  esSourcesToEnable[esSourceName] = esSource
1508  self._insertManyInto(adaptor, "@all_essources", esSourcesToEnable, True)
1509  #handle services differently
1510  services = []
1511  for serviceName, serviceObject in self.services_().items():
1512  if serviceObject in nodeVisitor.services or not (serviceObject in processNodeVisitor.services):
1513  serviceObject.insertInto(ServiceInjectorAdaptor(adaptor,services))
1514  adaptor.addVPSet(False,"services",services)
1515  return processPSet
1516 
1517  def validate(self):
1518  # check if there's some input
1519  # Breaks too many unit tests for now
1520  #if self.source_() == None and self.looper_() == None:
1521  # raise RuntimeError("No input source was found for this process")
1522  pass
1523 
1524  def handleProcessAccelerators(self, parameterSet):
1525  # 'cpu' accelerator is always implicitly there
1526  allAccelerators = set(["cpu"])
1527  availableAccelerators = set(["cpu"])
1528  for acc in self.__dict__['_Process__accelerators'].values():
1529  allAccelerators.update(acc.labels())
1530  availableAccelerators.update(acc.enabledLabels())
1531  availableAccelerators = sorted(list(availableAccelerators))
1532  parameterSet.addVString(False, "@available_accelerators", availableAccelerators)
1533 
1534  # Resolve wildcards
1535  selectedAccelerators = []
1536  if "*" in self.options.accelerators:
1537  if len(self.options.accelerators) >= 2:
1538  raise ValueError("process.options.accelerators may contain '*' only as the only element, now it has {} elements".format(len(self.options.accelerators)))
1539  selectedAccelerators = availableAccelerators
1540  else:
1541  import fnmatch
1542  resolved = set()
1543  invalid = []
1544  for pattern in self.options.accelerators:
1545  acc = [a for a in availableAccelerators if fnmatch.fnmatchcase(a, pattern)]
1546  if len(acc) == 0:
1547  if not any(fnmatch.fnmatchcase(a, pattern) for a in allAccelerators):
1548  invalid.append(pattern)
1549  else:
1550  resolved.update(acc)
1551  # Sanity check
1552  if len(invalid) != 0:
1553  raise ValueError("Invalid pattern{} of '{}' in process.options.accelerators, valid values are '{}' or a pattern matching some of them.".format(
1554  "s" if len(invalid) > 2 else "",
1555  "', '".join(invalid),
1556  "', '".join(sorted(list(allAccelerators)))))
1557  selectedAccelerators = sorted(list(resolved))
1558  parameterSet.addVString(False, "@selected_accelerators", selectedAccelerators)
1559 
1560  # Get and apply module type resolver
1561  moduleTypeResolver = None
1562  moduleTypeResolverPlugin = ""
1563  for acc in self.__dict__['_Process__accelerators'].values():
1564  resolver = acc.moduleTypeResolver(selectedAccelerators)
1565  if resolver is not None:
1566  if moduleTypeResolver is not None:
1567  raise RuntimeError("Module type resolver was already set to {} when {} tried to set it to {}. A job can have at most one ProcessAccelerator that sets module type resolver.".format(
1568  moduleTypeResolver.__class__.__name__,
1569  acc.__class__.__name__,
1570  resolver.__class__.__name__))
1571  moduleTypeResolver = resolver
1572  if moduleTypeResolver is not None:
1573  # Plugin name and its configuration
1574  moduleTypeResolverPlugin = moduleTypeResolver.plugin()
1575 
1576  # Customize modules
1577  for modlist in [self.producers_, self.filters_, self.analyzers_,
1578  self.es_producers_, self.es_sources_]:
1579  for module in modlist().values():
1580  moduleTypeResolver.setModuleVariant(module)
1581 
1582  parameterSet.addString(False, "@module_type_resolver", moduleTypeResolverPlugin)
1583 
1584  # Customize process
1585  wrapped = ProcessForProcessAccelerator(self)
1586  for acc in self.__dict__['_Process__accelerators'].values():
1587  acc.apply(wrapped, selectedAccelerators)
1588 
1589  def prefer(self, esmodule,*args,**kargs):
1590  """Prefer this ES source or producer. The argument can
1591  either be an object label, e.g.,
1592  process.prefer(process.juicerProducer) (not supported yet)
1593  or a name of an ESSource or ESProducer
1594  process.prefer("juicer")
1595  or a type of unnamed ESSource or ESProducer
1596  process.prefer("JuicerProducer")
1597  In addition, you can pass as a labelled arguments the name of the Record you wish to
1598  prefer where the type passed is a cms.vstring and that vstring can contain the
1599  name of the C++ types in the Record that are being preferred, e.g.,
1600  #prefer all data in record 'OrangeRecord' from 'juicer'
1601  process.prefer("juicer", OrangeRecord=cms.vstring())
1602  or
1603  #prefer only "Orange" data in "OrangeRecord" from "juicer"
1604  process.prefer("juicer", OrangeRecord=cms.vstring("Orange"))
1605  or
1606  #prefer only "Orange" data with label "ExtraPulp" in "OrangeRecord" from "juicer"
1607  ESPrefer("ESJuicerProd", OrangeRecord=cms.vstring("Orange/ExtraPulp"))
1608  """
1609  # see if this refers to a named ESProducer
1610  if isinstance(esmodule, ESSource) or isinstance(esmodule, ESProducer):
1611  raise RuntimeError("Syntax of process.prefer(process.esmodule) not supported yet")
1612  elif self._findPreferred(esmodule, self.es_producers_(),*args,**kargs) or \
1613  self._findPreferred(esmodule, self.es_sources_(),*args,**kargs):
1614  pass
1615  else:
1616  raise RuntimeError("Cannot resolve prefer for "+repr(esmodule))
1617 
1618  def _findPreferred(self, esname, d,*args,**kargs):
1619  # is esname a name in the dictionary?
1620  if esname in d:
1621  typ = d[esname].type_()
1622  if typ == esname:
1623  self.__setattr__( esname+"_prefer", ESPrefer(typ,*args,**kargs) )
1624  else:
1625  self.__setattr__( esname+"_prefer", ESPrefer(typ, esname,*args,**kargs) )
1626  return True
1627  else:
1628  # maybe it's an unnamed ESModule?
1629  found = False
1630  for name, value in d.items():
1631  if value.type_() == esname:
1632  if found:
1633  raise RuntimeError("More than one ES module for "+esname)
1634  found = True
1635  self.__setattr__(esname+"_prefer", ESPrefer(d[esname].type_()) )
1636  return found
1637 
1638 
1640  def __init__(self, process):
1641  if isinstance(process, Process):
1642  self.__process = process
1643  elif isinstance(process, str):
1644  self.__process = Process(process)
1645  #make sure we do not override the defaults
1646  del self.__process.options
1647  del self.__process.maxEvents
1648  del self.__process.maxLuminosityBlocks
1649  else:
1650  raise TypeError('a ProcessFragment can only be constructed from an existig Process or from process name')
1651  def __dir__(self):
1652  return [ x for x in dir(self.__process) if isinstance(getattr(self.__process, x), _ConfigureComponent) ]
1653  def __getattribute__(self, name):
1654  if name == '_ProcessFragment__process':
1655  return object.__getattribute__(self, '_ProcessFragment__process')
1656  else:
1657  return getattr(self.__process, name)
1658  def __setattr__(self, name, value):
1659  if name == '_ProcessFragment__process':
1660  object.__setattr__(self, name, value)
1661  else:
1662  setattr(self.__process, name, value)
1663  def __delattr__(self, name):
1664  if name == '_ProcessFragment__process':
1665  pass
1666  else:
1667  return delattr(self.__process, name)
1668 
1669 
1670 class FilteredStream(dict):
1671  """a dictionary with fixed keys"""
1673  raise AttributeError("An FilteredStream defintion cannot be modified after creation.")
1674  _blocked_attribute = property(_blocked_attribute)
1675  __setattr__ = __delitem__ = __setitem__ = clear = _blocked_attribute
1676  pop = popitem = setdefault = update = _blocked_attribute
1677  def __new__(cls, *args, **kw):
1678  new = dict.__new__(cls)
1679  dict.__init__(new, *args, **kw)
1680  keys = sorted(kw.keys())
1681  if keys != ['content', 'dataTier', 'name', 'paths', 'responsible', 'selectEvents']:
1682  raise ValueError("The needed parameters are: content, dataTier, name, paths, responsible, selectEvents")
1683  if not isinstance(kw['name'],str):
1684  raise ValueError("name must be of type string")
1685  if not isinstance(kw['content'], vstring) and not isinstance(kw['content'],str):
1686  raise ValueError("content must be of type vstring or string")
1687  if not isinstance(kw['dataTier'], string):
1688  raise ValueError("dataTier must be of type string")
1689  if not isinstance(kw['selectEvents'], PSet):
1690  raise ValueError("selectEvents must be of type PSet")
1691  if not isinstance(kw['paths'],(tuple, Path)):
1692  raise ValueError("'paths' must be a tuple of paths")
1693  return new
1694  def __init__(self, *args, **kw):
1695  pass
1696  def __repr__(self):
1697  return "FilteredStream object: %s" %self["name"]
1698  def __getattr__(self,attr):
1699  return self[attr]
1700 
1702  """Allows embedding another process within a parent process. This allows one to
1703  chain processes together directly in one cmsRun job rather than having to run
1704  separate jobs that are connected via a temporary file.
1705  """
1706  def __init__(self,process, SelectEvents = untracked.PSet(), outputCommands = untracked.vstring()):
1707  """
1708  """
1709  if not isinstance(process, Process):
1710  raise ValueError("the 'process' argument must be of type cms.Process")
1711  if not isinstance(SelectEvents,PSet):
1712  raise ValueError("the 'SelectEvents' argument must be of type cms.untracked.PSet")
1713  if not isinstance(outputCommands,vstring):
1714  raise ValueError("the 'outputCommands' argument must be of type cms.untracked.vstring")
1715  self.__process = process
1716  self.__SelectEvents = SelectEvents
1717  self.__outputCommands = outputCommands
1718  # Need to remove MessageLogger from the subprocess now that MessageLogger is always present
1719  if self.__process.MessageLogger is not MessageLogger:
1720  print("""Warning: You have reconfigured service
1721 'edm::MessageLogger' in a subprocess.
1722 This service has already been configured.
1723 This particular service may not be reconfigured in a subprocess.
1724 The reconfiguration will be ignored.""")
1725  del self.__process.MessageLogger
1726  def dumpPython(self, options=PrintOptions()):
1727  out = "parentProcess"+str(hash(self))+" = process\n"
1728  out += self.__process.dumpPython()
1729  out += "childProcess = process\n"
1730  out += "process = parentProcess"+str(hash(self))+"\n"
1731  out += "process.addSubProcess(cms.SubProcess(process = childProcess, SelectEvents = "+self.__SelectEvents.dumpPython(options) +", outputCommands = "+self.__outputCommands.dumpPython(options) +"))"
1732  return out
1733  def getProcessName(self):
1734  return self.__process.name_()
1735  def process(self):
1736  return self.__process
1737  def SelectEvents(self):
1738  return self.__SelectEvents
1739  def outputCommands(self):
1740  return self.__outputCommands
1741  def type_(self):
1742  return 'subProcess'
1743  def nameInProcessDesc_(self,label):
1744  return label
1745  def _place(self,label,process):
1746  process._placeSubProcess('subProcess',self)
1747  def getSubProcessPSet(self,parameterSet):
1748  topPSet = parameterSet.newPSet()
1749  self.__process.fillProcessDesc(topPSet)
1750  subProcessPSet = parameterSet.newPSet()
1751  self.__SelectEvents.insertInto(subProcessPSet,"SelectEvents")
1752  self.__outputCommands.insertInto(subProcessPSet,"outputCommands")
1753  subProcessPSet.addPSet(False,"process",topPSet)
1754  return subProcessPSet
1755 
1757  """Helper class for Modifier that takes key/value pairs and uses them to reset parameters of the object"""
1758  def __init__(self,args):
1759  self.__args = args
1760  def __call__(self,obj):
1761  params = {}
1762  for k in self.__args.keys():
1763  if hasattr(obj,k):
1764  params[k] = getattr(obj,k)
1766  for k in self.__args.keys():
1767  if k in params:
1768  setattr(obj,k,params[k])
1769  else:
1770  #the parameter must have been removed
1771  delattr(obj,k)
1772  @staticmethod
1774  raise KeyError("Unknown parameter name "+key+" specified while calling Modifier")
1775 
1777  """A helper base class for _AndModifier, _InvertModifier, and _OrModifier to contain the common code"""
1778  def __init__(self, lhs, rhs=None):
1779  self._lhs = lhs
1780  if rhs is not None:
1781  self._rhs = rhs
1782  def toModify(self,obj, func=None,**kw):
1783  Modifier._toModifyCheck(obj,func,**kw)
1784  if self._isChosen():
1785  Modifier._toModify(obj,func,**kw)
1786  return self
1787  def toReplaceWith(self,toObj,fromObj):
1788  Modifier._toReplaceWithCheck(toObj,fromObj)
1789  if self._isChosen():
1790  Modifier._toReplaceWith(toObj,fromObj)
1791  return self
1792  def makeProcessModifier(self,func):
1793  """This is used to create a ProcessModifer that can perform actions on the process as a whole.
1794  This takes as argument a callable object (e.g. function) that takes as its sole argument an instance of Process.
1795  In order to work, the value returned from this function must be assigned to a uniquely named variable."""
1796  return ProcessModifier(self,func)
1797  def __and__(self, other):
1798  return _AndModifier(self,other)
1799  def __invert__(self):
1800  return _InvertModifier(self)
1801  def __or__(self, other):
1802  return _OrModifier(self,other)
1803 
1805  """A modifier which only applies if multiple Modifiers are chosen"""
1806  def __init__(self, lhs, rhs):
1807  super(_AndModifier,self).__init__(lhs, rhs)
1808  def _isChosen(self):
1809  return self._lhs._isChosen() and self._rhs._isChosen()
1810 
1812  """A modifier which only applies if a Modifier is not chosen"""
1813  def __init__(self, lhs):
1814  super(_InvertModifier,self).__init__(lhs)
1815  def _isChosen(self):
1816  return not self._lhs._isChosen()
1817 
1819  """A modifier which only applies if at least one of multiple Modifiers is chosen"""
1820  def __init__(self, lhs, rhs):
1821  super(_OrModifier,self).__init__(lhs, rhs)
1822  def _isChosen(self):
1823  return self._lhs._isChosen() or self._rhs._isChosen()
1824 
1825 
1827  """This class is used to define standard modifications to a Process.
1828  An instance of this class is declared to denote a specific modification,e.g. era2017 could
1829  reconfigure items in a process to match our expectation of running in 2017. Once declared,
1830  these Modifier instances are imported into a configuration and items that need to be modified
1831  are then associated with the Modifier and with the action to do the modification.
1832  The registered modifications will only occur if the Modifier was passed to
1833  the cms.Process' constructor.
1834  """
1835  def __init__(self):
1837  self.__chosen = False
1838  def makeProcessModifier(self,func):
1839  """This is used to create a ProcessModifer that can perform actions on the process as a whole.
1840  This takes as argument a callable object (e.g. function) that takes as its sole argument an instance of Process.
1841  In order to work, the value returned from this function must be assigned to a uniquely named variable.
1842  """
1843  return ProcessModifier(self,func)
1844  @staticmethod
1845  def _toModifyCheck(obj,func,**kw):
1846  if func is not None and len(kw) != 0:
1847  raise TypeError("toModify takes either two arguments or one argument and key/value pairs")
1848  def toModify(self,obj, func=None,**kw):
1849  """This is used to register an action to be performed on the specific object. Two different forms are allowed
1850  Form 1: A callable object (e.g. function) can be passed as the second. This callable object is expected to take one argument
1851  that will be the object passed in as the first argument.
1852  Form 2: A list of parameter name, value pairs can be passed
1853  mod.toModify(foo, fred=cms.int32(7), barney = cms.double(3.14))
1854  This form can also be used to remove a parameter by passing the value of None
1855  #remove the parameter foo.fred
1856  mod.toModify(foo, fred = None)
1857  Additionally, parameters embedded within PSets can also be modified using a dictionary
1858  #change foo.fred.pebbles to 3 and foo.fred.friend to "barney"
1859  mod.toModify(foo, fred = dict(pebbles = 3, friend = "barney)) )
1860  """
1861  Modifier._toModifyCheck(obj,func,**kw)
1862  if self._isChosen():
1863  Modifier._toModify(obj,func,**kw)
1864  return self
1865  @staticmethod
1866  def _toModify(obj,func,**kw):
1867  if func is not None:
1868  func(obj)
1869  else:
1870  temp =_ParameterModifier(kw)
1871  temp(obj)
1872  @staticmethod
1873  def _toReplaceWithCheck(toObj,fromObj):
1874  if not isinstance(fromObj, type(toObj)):
1875  raise TypeError("toReplaceWith requires both arguments to be the same class type")
1876  def toReplaceWith(self,toObj,fromObj):
1877  """If the Modifier is chosen the internals of toObj will be associated with the internals of fromObj
1878  """
1879  Modifier._toReplaceWithCheck(toObj,fromObj)
1880  if self._isChosen():
1881  Modifier._toReplaceWith(toObj,fromObj)
1882  return self
1883  @staticmethod
1884  def _toReplaceWith(toObj,fromObj):
1885  if isinstance(fromObj,_ModuleSequenceType):
1886  toObj._seq = fromObj._seq
1887  toObj._tasks = fromObj._tasks
1888  elif isinstance(fromObj,Task):
1889  toObj._collection = fromObj._collection
1890  elif isinstance(fromObj,ConditionalTask):
1891  toObj._collection = fromObj._collection
1892  elif isinstance(fromObj,_Parameterizable):
1893  #clear old items just incase fromObj is not a complete superset of toObj
1894  for p in toObj.parameterNames_():
1895  delattr(toObj,p)
1896  for p in fromObj.parameterNames_():
1897  setattr(toObj,p,getattr(fromObj,p))
1898  if isinstance(fromObj,_TypedParameterizable):
1899  toObj._TypedParameterizable__type = fromObj._TypedParameterizable__type
1900 
1901  else:
1902  raise TypeError("toReplaceWith does not work with type "+str(type(toObj)))
1903 
1904  def _setChosen(self):
1905  """Should only be called by cms.Process instances"""
1906  self.__chosen = True
1907  def _isChosen(self):
1908  return self.__chosen
1909  def __and__(self, other):
1910  return _AndModifier(self,other)
1911  def __invert__(self):
1912  return _InvertModifier(self)
1913  def __or__(self, other):
1914  return _OrModifier(self,other)
1915  def _isOrContains(self, other):
1916  return self == other
1917 
1918 
1920  """A Modifier made up of a list of Modifiers
1921  """
1922  def __init__(self, *chainedModifiers):
1923  self.__chosen = False
1924  self.__chain = chainedModifiers
1925  def _applyNewProcessModifiers(self,process):
1926  """Should only be called by cms.Process instances
1927  applies list of accumulated changes to the process"""
1928  for m in self.__chain:
1929  m._applyNewProcessModifiers(process)
1930  def _setChosen(self):
1931  """Should only be called by cms.Process instances"""
1932  self.__chosen = True
1933  for m in self.__chain:
1934  m._setChosen()
1935  def _isChosen(self):
1936  return self.__chosen
1937  def copyAndExclude(self, toExclude):
1938  """Creates a new ModifierChain which is a copy of
1939  this ModifierChain but excludes any Modifier or
1940  ModifierChain in the list toExclude.
1941  The exclusion is done recursively down the chain.
1942  """
1943  newMods = []
1944  for m in self.__chain:
1945  if m not in toExclude:
1946  s = m
1947  if isinstance(m,ModifierChain):
1948  s = m.__copyIfExclude(toExclude)
1949  newMods.append(s)
1950  return ModifierChain(*newMods)
1951  def __copyIfExclude(self,toExclude):
1952  shouldCopy = False
1953  for m in toExclude:
1954  if self._isOrContains(m):
1955  shouldCopy = True
1956  break
1957  if shouldCopy:
1958  return self.copyAndExclude(toExclude)
1959  return self
1960  def _isOrContains(self, other):
1961  if self is other:
1962  return True
1963  for m in self.__chain:
1964  if m._isOrContains(other):
1965  return True
1966  return False
1967 
1969  """A class used by a Modifier to affect an entire Process instance.
1970  When a Process 'loads' a module containing a ProcessModifier, that
1971  ProcessModifier will be applied to the Process if and only if the
1972  Modifier passed to the constructor has been chosen.
1973  """
1974  def __init__(self, modifier, func):
1975  self.__modifier = modifier
1976  self.__func = func
1977  self.__seenProcesses = set()
1978  def apply(self,process):
1979  if self.__modifier._isChosen():
1980  if process not in self.__seenProcesses:
1981  self.__func(process)
1982  self.__seenProcesses.add(process)
1983 
1985  """A class used to specify possible compute accelerators in a Process
1986  instance. It is intended to be derived for any
1987  accelerator/portability technology, and provides hooks such that a
1988  specific customization can be applied to the Process on a worker
1989  node at the point where the python configuration is serialized for C++.
1990 
1991  The customization must not change the configuration hash. To
1992  enforce this reuirement, the customization gets a
1993  ProcessForProcessAccelerator wrapper that gives access to only
1994  those parts of the configuration that can be changed. Nevertheless
1995  it would be good to have specific unit test for each deriving
1996  class to ensure that all combinations of the enabled accelerators
1997  give the same configuration hash.
1998 
1999  The deriving class must do its checks for hardware availability
2000  only in enabledLabels(), and possibly in apply() if any further
2001  fine-tuning is needed, because those two are the only functions
2002  that are guaranteed to be called at the worker node.
2003  """
2004  def __init__(self):
2005  pass
2006  def _place(self, name, proc):
2007  proc._placeAccelerator(self.type_(), self)
2008  def type_(self):
2009  return type(self).__name__
2010  def dumpPython(self, options=PrintOptions()):
2011  specialImportRegistry.registerUse(self)
2012  result = self.__class__.__name__+"(" # not including cms. since the deriving classes are not in cms "namespace"
2013  options.indent()
2014  res = self.dumpPythonImpl(options)
2015  options.unindent()
2016  if len(res) > 0:
2017  result += "\n"+res+"\n"
2018  result += ")\n"
2019  return result
2020 
2021  # The following methods are hooks to be overridden (if needed) in the deriving class
2022  def dumpPythonImpl(self, options):
2023  """Override if need to add any 'body' content to dumpPython(). Returns a string."""
2024  return ""
2025  def labels(self):
2026  """Override to return a list of strings for the accelerator labels."""
2027  return []
2028  def enabledLabels(self):
2029  """Override to return a list of strings for the accelerator labels
2030  that are enabled in the system the job is being run on."""
2031  return []
2032  def moduleTypeResolver(self, accelerators):
2033  """Override to return an object that implements "module type resolver"
2034  in python. The object should have the following methods
2035  - __init__(self, accelerators)
2036  * accelerators = list of selected accelerators
2037  - plugin(self):
2038  * should return a string for the type resolver plugin name
2039  - setModuleVariant(self, module):
2040  * Called for each ED and ES module. Should act only if
2041  module.type_() contains the magic identifier
2042 
2043  At most one of the ProcessAccelerators in a job can return a
2044 non-None object
2045  """
2046  return None
2047  def apply(self, process, accelerators):
2048  """Override if need to customize the Process at worker node. The
2049  selected available accelerator labels are given in the
2050  'accelerators' argument (the patterns, e.g. '*' have been
2051  expanded to concrete labels).
2052 
2053  This function may touch only untracked parameters.
2054  """
2055  pass
2056 
2057 class ProcessForProcessAccelerator(object):
2058  """This class is inteded to wrap the Process object to constrain the
2059  available functionality for ProcessAccelerator.apply()"""
2060  def __init__(self, process):
2061  self.__process = process
2062  def __getattr__(self, label):
2063  value = getattr(self.__process, label)
2064  if not isinstance(value, Service):
2065  raise TypeError("ProcessAccelerator.apply() can get only Services. Tried to get {} with label {}".format(str(type(value)), label))
2066  return value
2067  def __setattr__(self, label, value):
2068  if label == "_ProcessForProcessAccelerator__process":
2069  super().__setattr__(label, value)
2070  else:
2071  if not isinstance(value, Service):
2072  raise TypeError("ProcessAccelerator.apply() can only set Services. Tried to set {} with label {}".format(str(type(value)), label))
2073  setattr(self.__process, label, value)
2074  def __delattr__(self, label):
2075  value = getattr(self.__process, label)
2076  if not isinstance(value, Service):
2077  raise TypeError("ProcessAccelerator.apply() can delete only Services. Tried to del {} with label {}".format(str(type(value)), label))
2078  delattr(self.__process, label)
2079  def add_(self, value):
2080  if not isinstance(value, Service):
2081  raise TypeError("ProcessAccelerator.apply() can only add Services. Tried to set {} with label {}".format(str(type(value)), label))
2082  self.__process.add_(value)
2083 
2084 # Need to be a module-level function for the configuration with a
2085 # SwitchProducer to be pickleable.
2087  return ("test1" in accelerators, -10)
2089  return ("test2" in accelerators, -9)
2090 
2091 if __name__=="__main__":
2092  import unittest
2093  import copy
2094 
2095  def _lineDiff(newString, oldString):
2096  newString = ( x for x in newString.split('\n') if len(x) > 0)
2097  oldString = [ x for x in oldString.split('\n') if len(x) > 0]
2098  diff = []
2099  oldStringLine = 0
2100  for l in newString:
2101  if oldStringLine >= len(oldString):
2102  diff.append(l)
2103  continue
2104  if l == oldString[oldStringLine]:
2105  oldStringLine +=1
2106  continue
2107  diff.append(l)
2108  return "\n".join( diff )
2109 
2111  """Has same interface as the C++ object that creates PSets
2112  """
2113  def __init__(self):
2114  self.values = dict()
2115  def __insertValue(self,tracked,label,value):
2116  self.values[label]=(tracked,value)
2117  def __getValue(self,tracked,label):
2118  pair = self.values[label]
2119  if pair[0] != tracked:
2120  raise Exception("Asked for %s parameter '%s', but it is %s" % ("tracked" if tracked else "untracked",
2121  label,
2122  "tracked" if pair[0] else "untracked"))
2123  return pair[1]
2124  def addInt32(self,tracked,label,value):
2125  self.__insertValue(tracked,label,value)
2126  def addVInt32(self,tracked,label,value):
2127  self.__insertValue(tracked,label,value)
2128  def addUInt32(self,tracked,label,value):
2129  self.__insertValue(tracked,label,value)
2130  def addVUInt32(self,tracked,label,value):
2131  self.__insertValue(tracked,label,value)
2132  def addInt64(self,tracked,label,value):
2133  self.__insertValue(tracked,label,value)
2134  def addVInt64(self,tracked,label,value):
2135  self.__insertValue(tracked,label,value)
2136  def addUInt64(self,tracked,label,value):
2137  self.__insertValue(tracked,label,value)
2138  def addVUInt64(self,tracked,label,value):
2139  self.__insertValue(tracked,label,value)
2140  def addDouble(self,tracked,label,value):
2141  self.__insertValue(tracked,label,value)
2142  def addVDouble(self,tracked,label,value):
2143  self.__insertValue(tracked,label,value)
2144  def addBool(self,tracked,label,value):
2145  self.__insertValue(tracked,label,value)
2146  def addString(self,tracked,label,value):
2147  self.__insertValue(tracked,label,value)
2148  def addVString(self,tracked,label,value):
2149  self.__insertValue(tracked,label,value)
2150  def getVString(self,tracked,label):
2151  return self.__getValue(tracked, label)
2152  def addInputTag(self,tracked,label,value):
2153  self.__insertValue(tracked,label,value)
2154  def addVInputTag(self,tracked,label,value):
2155  self.__insertValue(tracked,label,value)
2156  def addESInputTag(self,tracked,label,value):
2157  self.__insertValue(tracked,label,value)
2158  def addVESInputTag(self,tracked,label,value):
2159  self.__insertValue(tracked,label,value)
2160  def addEventID(self,tracked,label,value):
2161  self.__insertValue(tracked,label,value)
2162  def addVEventID(self,tracked,label,value):
2163  self.__insertValue(tracked,label,value)
2164  def addLuminosityBlockID(self,tracked,label,value):
2165  self.__insertValue(tracked,label,value)
2166  def addLuminosityBlockID(self,tracked,label,value):
2167  self.__insertValue(tracked,label,value)
2168  def addEventRange(self,tracked,label,value):
2169  self.__insertValue(tracked,label,value)
2170  def addVEventRange(self,tracked,label,value):
2171  self.__insertValue(tracked,label,value)
2172  def addPSet(self,tracked,label,value):
2173  self.__insertValue(tracked,label,value)
2174  def addVPSet(self,tracked,label,value):
2175  self.__insertValue(tracked,label,value)
2176  def addFileInPath(self,tracked,label,value):
2177  self.__insertValue(tracked,label,value)
2178  def newPSet(self):
2179  return TestMakePSet()
2180 
2182  def __init__(self, **kargs):
2183  super(SwitchProducerTest,self).__init__(
2184  dict(
2185  test1 = lambda accelerators: (True, -10),
2186  test2 = lambda accelerators: (True, -9),
2187  test3 = lambda accelerators: (True, -8),
2188  test4 = lambda accelerators: (True, -7)
2189  ), **kargs)
2190  specialImportRegistry.registerSpecialImportForType(SwitchProducerTest, "from test import SwitchProducerTest")
2191 
2193  def __init__(self, **kargs):
2194  super(SwitchProducerTest2,self).__init__(
2195  dict(
2196  test1 = _switchproducer_test2_case1,
2197  test2 = _switchproducer_test2_case2,
2198  ), **kargs)
2199  specialImportRegistry.registerSpecialImportForType(SwitchProducerTest2, "from test import SwitchProducerTest2")
2200 
2202  def __init__(self, accelerators):
2203  # first element is used as the default is nothing is set
2205  if "test1" in accelerators:
2206  self._valid_backends.append("test1_backend")
2207  if "test2" in accelerators:
2208  self._valid_backends.append("test2_backend")
2209  if len(self._valid_backends) == 0:
2210  raise EDMException(edm.errors.UnavailableAccelerator, "Machine has no accelerators that Test supports (has {})".format(", ".join(accelerators)))
2211 
2212  def plugin(self):
2213  return "TestModuleTypeResolver"
2214 
2215  def setModuleVariant(self, module):
2216  if "@test" in module.type_():
2217  defaultBackend = self._valid_backends[0]
2218  if hasattr(module, "test"):
2219  if hasattr(module.test, "backend"):
2220  if module.test.backend.value() not in self._valid_backends:
2221  raise EDMException(edm.errors.UnavailableAccelerator, "Module {} has the Test backend set explicitly, but its accelerator is not available for the job".format(module.label_()))
2222  else:
2223  module.test.backend = untracked.string(defaultBackend)
2224  else:
2225  module.test = untracked.PSet(
2226  backend = untracked.string(defaultBackend)
2227  )
2228 
2230  def __init__(self, enabled=["test1", "test2", "anothertest3"], moduleTypeResolverMaker=None):
2231  super().__init__()
2232  self._labels = ["test1", "test2", "anothertest3"]
2233  self.setEnabled(enabled)
2234  self._moduleTypeResolverMaker = moduleTypeResolverMaker
2235  def setEnabled(self, enabled):
2236  invalid = set(enabled).difference(set(self._labels))
2237  if len(invalid) > 0:
2238  raise Exception("Tried to enabled nonexistent test accelerators {}".format(",".join(invalid)))
2239  self._enabled = enabled[:]
2240  def dumpPythonImpl(self,options):
2241  result = "{}enabled = [{}]".format(options.indentation(),
2242  ", ".join(["'{}'".format(e) for e in self._enabled]))
2243  return result
2244  def labels(self):
2245  return self._labels
2246  def enabledLabels(self):
2247  return self._enabled
2248  def moduleTypeResolver(self, accelerators):
2249  if not self._moduleTypeResolverMaker:
2250  return super().moduleTypeResolver(accelerators)
2251  return self._moduleTypeResolverMaker(accelerators)
2252  def apply(self, process, accelerators):
2253  process.AcceleratorTestService = Service("AcceleratorTestService")
2254  if hasattr(process, "AcceleratorTestServiceRemove"):
2255  del process.AcceleratorTestServiceRemove
2256  specialImportRegistry.registerSpecialImportForType(ProcessAcceleratorTest, "from test import ProcessAcceleratorTest")
2257 
2259  def __init__(self, enabled=["anothertest3", "anothertest4"], moduleTypeResolverMaker=None):
2260  super().__init__()
2261  self._labels = ["anothertest3", "anothertest4"]
2262  self.setEnabled(enabled)
2263  self._moduleTypeResolverMaker = moduleTypeResolverMaker
2264  def setEnabled(self, enabled):
2265  invalid = set(enabled).difference(set(self._labels))
2266  if len(invalid) > 0:
2267  raise Exception("Tried to enabled nonexistent test accelerators {}".format(",".join(invalid)))
2268  self._enabled = enabled[:]
2269  def dumpPythonImpl(self,options):
2270  result = "{}enabled = [{}]".format(options.indentation(),
2271  ", ".join(["'{}'".format(e) for e in self._enabled]))
2272  return result
2273  def labels(self):
2274  return self._labels
2275  def enabledLabels(self):
2276  return self._enabled
2277  def moduleTypeResolver(self, accelerators):
2278  if not self._moduleTypeResolverMaker:
2279  return super().moduleTypeResolver(accelerators)
2280  return self._moduleTypeResolverMaker(accelerators)
2281  def apply(self, process, accelerators):
2282  pass
2283  specialImportRegistry.registerSpecialImportForType(ProcessAcceleratorTest2, "from test import ProcessAcceleratorTest2")
2284 
2285  class TestModuleCommand(unittest.TestCase):
2286  def setUp(self):
2287  """Nothing to do """
2288  None
2290  p = _Parameterizable()
2291  self.assertEqual(len(p.parameterNames_()),0)
2292  p.a = int32(1)
2293  self.assertTrue('a' in p.parameterNames_())
2294  self.assertEqual(p.a.value(), 1)
2295  p.a = 10
2296  self.assertEqual(p.a.value(), 10)
2297  p.a = untracked(int32(1))
2298  self.assertEqual(p.a.value(), 1)
2299  self.assertFalse(p.a.isTracked())
2300  p.a = untracked.int32(1)
2301  self.assertEqual(p.a.value(), 1)
2302  self.assertFalse(p.a.isTracked())
2303  p = _Parameterizable(foo=int32(10), bar = untracked(double(1.0)))
2304  self.assertEqual(p.foo.value(), 10)
2305  self.assertEqual(p.bar.value(),1.0)
2306  self.assertFalse(p.bar.isTracked())
2307  self.assertRaises(TypeError,setattr,(p,'c',1))
2308  p = _Parameterizable(a=PSet(foo=int32(10), bar = untracked(double(1.0))))
2309  self.assertEqual(p.a.foo.value(),10)
2310  self.assertEqual(p.a.bar.value(),1.0)
2311  p.b = untracked(PSet(fii = int32(1)))
2312  self.assertEqual(p.b.fii.value(),1)
2313  self.assertFalse(p.b.isTracked())
2314  #test the fact that values can be shared
2315  v = int32(10)
2316  p=_Parameterizable(a=v)
2317  v.setValue(11)
2318  self.assertEqual(p.a.value(),11)
2319  p.a = 12
2320  self.assertEqual(p.a.value(),12)
2321  self.assertEqual(v.value(),12)
2323  p = _TypedParameterizable("blah", b=int32(1))
2324  #see if copy works deeply
2325  other = p.copy()
2326  other.b = 2
2327  self.assertNotEqual(p.b,other.b)
2328 
2330  p = Process("test")
2331  p.a = EDAnalyzer("MyAnalyzer")
2332  self.assertTrue( 'a' in p.analyzers_() )
2333  self.assertTrue( 'a' in p.analyzers)
2334  p.add_(Service("SomeService"))
2335  self.assertTrue('SomeService' in p.services_())
2336  self.assertEqual(p.SomeService.type_(), "SomeService")
2337  p.Tracer = Service("Tracer")
2338  self.assertTrue('Tracer' in p.services_())
2339  self.assertRaises(TypeError, setattr, *(p,'b',"this should fail"))
2340  self.assertRaises(TypeError, setattr, *(p,'bad',Service("MessageLogger")))
2341  self.assertRaises(ValueError, setattr, *(p,'bad',Source("PoolSource")))
2342  p.out = OutputModule("Outer")
2343  self.assertEqual(p.out.type_(), 'Outer')
2344  self.assertTrue( 'out' in p.outputModules_() )
2345 
2346  p.geom = ESSource("GeomProd")
2347  self.assertTrue('geom' in p.es_sources_())
2348  p.add_(ESSource("ConfigDB"))
2349  self.assertTrue('ConfigDB' in p.es_sources_())
2350 
2351  p.aliasfoo1 = EDAlias(foo1 = VPSet(PSet(type = string("Foo1"))))
2352  self.assertTrue('aliasfoo1' in p.aliases_())
2353 
2355  class FromArg(object):
2356  def __init__(self,*arg,**args):
2357  for name in args.keys():
2358  self.__dict__[name]=args[name]
2359 
2360  a=EDAnalyzer("MyAnalyzer")
2361  t=EDAnalyzer("MyAnalyzer")
2362  t.setLabel("foo")
2363  s1 = Sequence(a)
2364  s2 = Sequence(s1)
2365  s3 = Sequence(s2)
2366  d = FromArg(
2367  a=a,
2368  b=Service("Full"),
2369  c=Path(a),
2370  d=s2,
2371  e=s1,
2372  f=s3,
2373  g=Sequence(s1+s2+s3)
2374  )
2375  p = Process("Test")
2376  p.extend(d)
2377  self.assertEqual(p.a.type_(),"MyAnalyzer")
2378  self.assertEqual(p.a.label_(),"a")
2379  self.assertRaises(AttributeError,getattr,p,'b')
2380  self.assertEqual(p.Full.type_(),"Full")
2381  self.assertEqual(str(p.c),'a')
2382  self.assertEqual(str(p.d),'a')
2383 
2384  z1 = FromArg(
2385  a=a,
2386  b=Service("Full"),
2387  c=Path(a),
2388  d=s2,
2389  e=s1,
2390  f=s3,
2391  s4=s3,
2392  g=Sequence(s1+s2+s3)
2393  )
2394 
2395  p1 = Process("Test")
2396  #p1.extend(z1)
2397  self.assertRaises(ValueError, p1.extend, z1)
2398 
2399  z2 = FromArg(
2400  a=a,
2401  b=Service("Full"),
2402  c=Path(a),
2403  d=s2,
2404  e=s1,
2405  f=s3,
2406  aaa=copy.deepcopy(a),
2407  s4=copy.deepcopy(s3),
2408  g=Sequence(s1+s2+s3),
2409  t=t
2410  )
2411  p2 = Process("Test")
2412  p2.extend(z2)
2413  #self.assertRaises(ValueError, p2.extend, z2)
2414  self.assertEqual(p2.s4.label_(),"s4")
2415  #p2.s4.setLabel("foo")
2416  self.assertRaises(ValueError, p2.s4.setLabel, "foo")
2417  p2.s4.setLabel("s4")
2418  p2.s4.setLabel(None)
2419  p2.s4.setLabel("foo")
2420  p2._Process__setObjectLabel(p2.s4, "foo")
2421  p2._Process__setObjectLabel(p2.s4, None)
2422  p2._Process__setObjectLabel(p2.s4, "bar")
2423 
2424 
2425  p = Process('test')
2426  p.a = EDProducer("MyProducer")
2427  p.t = Task(p.a)
2428  p.p = Path(p.t)
2429  self.assertRaises(ValueError, p.extend, FromArg(a = EDProducer("YourProducer")))
2430  self.assertRaises(ValueError, p.extend, FromArg(a = EDAlias()))
2431  self.assertRaises(ValueError, p.__setattr__, "a", EDAlias())
2432 
2433  p = Process('test')
2434  p.a = EDProducer("MyProducer")
2435  p.t = ConditionalTask(p.a)
2436  p.p = Path(p.t)
2437  self.assertRaises(ValueError, p.extend, FromArg(a = EDProducer("YourProducer")))
2438  self.assertRaises(ValueError, p.extend, FromArg(a = EDAlias()))
2439  self.assertRaises(ValueError, p.__setattr__, "a", EDAlias())
2440 
2441  p = Process('test')
2442  p.a = EDProducer("MyProducer")
2443  p.s = Sequence(p.a)
2444  p.p = Path(p.s)
2445  self.assertRaises(ValueError, p.extend, FromArg(a = EDProducer("YourProducer")))
2446  self.assertRaises(ValueError, p.extend, FromArg(a = EDAlias()))
2447  self.assertRaises(ValueError, p.__setattr__, "a", EDAlias())
2448 
2450  self.assertEqual(Process("test").dumpPython(),
2451 """import FWCore.ParameterSet.Config as cms
2452 
2453 process = cms.Process("test")
2454 
2455 process.maxEvents = cms.untracked.PSet(
2456  input = cms.optional.untracked.int32,
2457  output = cms.optional.untracked.allowed(cms.int32,cms.PSet)
2458 )
2459 
2460 process.maxLuminosityBlocks = cms.untracked.PSet(
2461  input = cms.untracked.int32(-1)
2462 )
2463 
2464 process.options = cms.untracked.PSet(
2465  IgnoreCompletely = cms.untracked.vstring(),
2466  Rethrow = cms.untracked.vstring(),
2467  TryToContinue = cms.untracked.vstring(),
2468  accelerators = cms.untracked.vstring('*'),
2469  allowUnscheduled = cms.obsolete.untracked.bool,
2470  canDeleteEarly = cms.untracked.vstring(),
2471  deleteNonConsumedUnscheduledModules = cms.untracked.bool(True),
2472  dumpOptions = cms.untracked.bool(False),
2473  emptyRunLumiMode = cms.obsolete.untracked.string,
2474  eventSetup = cms.untracked.PSet(
2475  forceNumberOfConcurrentIOVs = cms.untracked.PSet(
2476  allowAnyLabel_=cms.required.untracked.uint32
2477  ),
2478  numberOfConcurrentIOVs = cms.untracked.uint32(0)
2479  ),
2480  fileMode = cms.untracked.string('FULLMERGE'),
2481  forceEventSetupCacheClearOnNewRun = cms.untracked.bool(False),
2482  holdsReferencesToDeleteEarly = cms.untracked.VPSet(),
2483  makeTriggerResults = cms.obsolete.untracked.bool,
2484  modulesToCallForTryToContinue = cms.untracked.vstring(),
2485  modulesToIgnoreForDeleteEarly = cms.untracked.vstring(),
2486  numberOfConcurrentLuminosityBlocks = cms.untracked.uint32(0),
2487  numberOfConcurrentRuns = cms.untracked.uint32(1),
2488  numberOfStreams = cms.untracked.uint32(0),
2489  numberOfThreads = cms.untracked.uint32(1),
2490  printDependencies = cms.untracked.bool(False),
2491  sizeOfStackForThreadsInKB = cms.optional.untracked.uint32,
2492  throwIfIllegalParameter = cms.untracked.bool(True),
2493  wantSummary = cms.untracked.bool(False)
2494 )
2495 
2496 process.MessageLogger = cms.Service("MessageLogger",
2497  cerr = cms.untracked.PSet(
2498  FwkReport = cms.untracked.PSet(
2499  limit = cms.untracked.int32(10000000),
2500  reportEvery = cms.untracked.int32(1)
2501  ),
2502  FwkSummary = cms.untracked.PSet(
2503  limit = cms.untracked.int32(10000000),
2504  reportEvery = cms.untracked.int32(1)
2505  ),
2506  INFO = cms.untracked.PSet(
2507  limit = cms.untracked.int32(0)
2508  ),
2509  Root_NoDictionary = cms.untracked.PSet(
2510  limit = cms.untracked.int32(0)
2511  ),
2512  default = cms.untracked.PSet(
2513  limit = cms.untracked.int32(10000000)
2514  ),
2515  enable = cms.untracked.bool(True),
2516  enableStatistics = cms.untracked.bool(False),
2517  lineLength = cms.optional.untracked.int32,
2518  noLineBreaks = cms.optional.untracked.bool,
2519  noTimeStamps = cms.untracked.bool(False),
2520  resetStatistics = cms.untracked.bool(False),
2521  statisticsThreshold = cms.untracked.string('WARNING'),
2522  threshold = cms.untracked.string('INFO'),
2523  allowAnyLabel_=cms.optional.untracked.PSetTemplate(
2524  limit = cms.optional.untracked.int32,
2525  reportEvery = cms.untracked.int32(1),
2526  timespan = cms.optional.untracked.int32
2527  )
2528  ),
2529  cout = cms.untracked.PSet(
2530  enable = cms.untracked.bool(False),
2531  enableStatistics = cms.untracked.bool(False),
2532  lineLength = cms.optional.untracked.int32,
2533  noLineBreaks = cms.optional.untracked.bool,
2534  noTimeStamps = cms.optional.untracked.bool,
2535  resetStatistics = cms.untracked.bool(False),
2536  statisticsThreshold = cms.optional.untracked.string,
2537  threshold = cms.optional.untracked.string,
2538  allowAnyLabel_=cms.optional.untracked.PSetTemplate(
2539  limit = cms.optional.untracked.int32,
2540  reportEvery = cms.untracked.int32(1),
2541  timespan = cms.optional.untracked.int32
2542  )
2543  ),
2544  debugModules = cms.untracked.vstring(),
2545  default = cms.untracked.PSet(
2546  limit = cms.optional.untracked.int32,
2547  lineLength = cms.untracked.int32(80),
2548  noLineBreaks = cms.untracked.bool(False),
2549  noTimeStamps = cms.untracked.bool(False),
2550  reportEvery = cms.untracked.int32(1),
2551  statisticsThreshold = cms.untracked.string('INFO'),
2552  threshold = cms.untracked.string('INFO'),
2553  timespan = cms.optional.untracked.int32,
2554  allowAnyLabel_=cms.optional.untracked.PSetTemplate(
2555  limit = cms.optional.untracked.int32,
2556  reportEvery = cms.untracked.int32(1),
2557  timespan = cms.optional.untracked.int32
2558  )
2559  ),
2560  files = cms.untracked.PSet(
2561  allowAnyLabel_=cms.optional.untracked.PSetTemplate(
2562  enableStatistics = cms.untracked.bool(False),
2563  extension = cms.optional.untracked.string,
2564  filename = cms.optional.untracked.string,
2565  lineLength = cms.optional.untracked.int32,
2566  noLineBreaks = cms.optional.untracked.bool,
2567  noTimeStamps = cms.optional.untracked.bool,
2568  output = cms.optional.untracked.string,
2569  resetStatistics = cms.untracked.bool(False),
2570  statisticsThreshold = cms.optional.untracked.string,
2571  threshold = cms.optional.untracked.string,
2572  allowAnyLabel_=cms.optional.untracked.PSetTemplate(
2573  limit = cms.optional.untracked.int32,
2574  reportEvery = cms.untracked.int32(1),
2575  timespan = cms.optional.untracked.int32
2576  )
2577  )
2578  ),
2579  suppressDebug = cms.untracked.vstring(),
2580  suppressFwkInfo = cms.untracked.vstring(),
2581  suppressInfo = cms.untracked.vstring(),
2582  suppressWarning = cms.untracked.vstring(),
2583  allowAnyLabel_=cms.optional.untracked.PSetTemplate(
2584  limit = cms.optional.untracked.int32,
2585  reportEvery = cms.untracked.int32(1),
2586  timespan = cms.optional.untracked.int32
2587  )
2588 )
2589 
2590 
2591 """)
2592  p = Process("test")
2593  p.a = EDAnalyzer("MyAnalyzer")
2594  p.p = Path(p.a)
2595  p.s = Sequence(p.a)
2596  p.r = Sequence(p.s)
2597  p.p2 = Path(p.s)
2598  p.schedule = Schedule(p.p2,p.p)
2599  d=p.dumpPython()
2600  self.assertEqual(_lineDiff(d,Process("test").dumpPython()),
2601 """process.a = cms.EDAnalyzer("MyAnalyzer")
2602 process.s = cms.Sequence(process.a)
2603 process.r = cms.Sequence(process.s)
2604 process.p = cms.Path(process.a)
2605 process.p2 = cms.Path(process.s)
2606 process.schedule = cms.Schedule(*[ process.p2, process.p ])""")
2607  #Reverse order of 'r' and 's'
2608  p = Process("test")
2609  p.a = EDAnalyzer("MyAnalyzer")
2610  p.p = Path(p.a)
2611  p.r = Sequence(p.a)
2612  p.s = Sequence(p.r)
2613  p.p2 = Path(p.r)
2614  p.schedule = Schedule(p.p2,p.p)
2615  p.b = EDAnalyzer("YourAnalyzer")
2616  d=p.dumpPython()
2617  self.assertEqual(_lineDiff(d,Process("test").dumpPython()),
2618 """process.a = cms.EDAnalyzer("MyAnalyzer")
2619 process.b = cms.EDAnalyzer("YourAnalyzer")
2620 process.r = cms.Sequence(process.a)
2621 process.s = cms.Sequence(process.r)
2622 process.p = cms.Path(process.a)
2623 process.p2 = cms.Path(process.r)
2624 process.schedule = cms.Schedule(*[ process.p2, process.p ])""")
2625  #use an anonymous sequence
2626  p = Process("test")
2627  p.a = EDAnalyzer("MyAnalyzer")
2628  p.p = Path(p.a)
2629  s = Sequence(p.a)
2630  p.r = Sequence(s)
2631  p.p2 = Path(p.r)
2632  p.schedule = Schedule(p.p2,p.p)
2633  d=p.dumpPython()
2634  self.assertEqual(_lineDiff(d,Process("test").dumpPython()),
2635 """process.a = cms.EDAnalyzer("MyAnalyzer")
2636 process.r = cms.Sequence((process.a))
2637 process.p = cms.Path(process.a)
2638 process.p2 = cms.Path(process.r)
2639 process.schedule = cms.Schedule(*[ process.p2, process.p ])""")
2640 
2641  # include some tasks
2642  p = Process("test")
2643  p.a = EDAnalyzer("MyAnalyzer")
2644  p.b = EDProducer("bProducer")
2645  p.c = EDProducer("cProducer")
2646  p.d = EDProducer("dProducer")
2647  p.e = EDProducer("eProducer")
2648  p.f = EDProducer("fProducer")
2649  p.g = EDProducer("gProducer")
2650  p.task5 = Task()
2651  p.task3 = Task()
2652  p.task2 = Task(p.c, p.task3)
2653  p.task4 = Task(p.f, p.task2)
2654  p.task1 = Task(p.task5)
2655  p.task3.add(p.task1)
2656  p.p = Path(p.a)
2657  s = Sequence(p.a)
2658  p.r = Sequence(s)
2659  p.p2 = Path(p.r, p.task1, p.task2)
2660  p.schedule = Schedule(p.p2,p.p,tasks=[p.task3,p.task4, p.task5])
2661  d=p.dumpPython()
2662  self.assertEqual(_lineDiff(d,Process("test").dumpPython()),
2663 """process.b = cms.EDProducer("bProducer")
2664 process.c = cms.EDProducer("cProducer")
2665 process.d = cms.EDProducer("dProducer")
2666 process.e = cms.EDProducer("eProducer")
2667 process.f = cms.EDProducer("fProducer")
2668 process.g = cms.EDProducer("gProducer")
2669 process.a = cms.EDAnalyzer("MyAnalyzer")
2670 process.task5 = cms.Task()
2671 process.task1 = cms.Task(process.task5)
2672 process.task3 = cms.Task(process.task1)
2673 process.task2 = cms.Task(process.c, process.task3)
2674 process.task4 = cms.Task(process.f, process.task2)
2675 process.r = cms.Sequence((process.a))
2676 process.p = cms.Path(process.a)
2677 process.p2 = cms.Path(process.r, process.task1, process.task2)
2678 process.schedule = cms.Schedule(*[ process.p2, process.p ], tasks=[process.task3, process.task4, process.task5])""")
2679  # include some conditional tasks
2680  p = Process("test")
2681  p.a = EDAnalyzer("MyAnalyzer")
2682  p.b = EDProducer("bProducer")
2683  p.c = EDProducer("cProducer")
2684  p.d = EDProducer("dProducer")
2685  p.e = EDProducer("eProducer")
2686  p.f = EDProducer("fProducer")
2687  p.g = EDProducer("gProducer")
2688  p.task5 = Task()
2689  p.task3 = Task()
2690  p.task2 = ConditionalTask(p.c, p.task3)
2691  p.task1 = ConditionalTask(p.task5)
2692  p.p = Path(p.a)
2693  s = Sequence(p.a)
2694  p.r = Sequence(s)
2695  p.p2 = Path(p.r, p.task1, p.task2)
2696  p.schedule = Schedule(p.p2,p.p,tasks=[p.task5])
2697  d=p.dumpPython()
2698  self.assertEqual(_lineDiff(d,Process("test").dumpPython()),
2699 """process.b = cms.EDProducer("bProducer")
2700 process.c = cms.EDProducer("cProducer")
2701 process.d = cms.EDProducer("dProducer")
2702 process.e = cms.EDProducer("eProducer")
2703 process.f = cms.EDProducer("fProducer")
2704 process.g = cms.EDProducer("gProducer")
2705 process.a = cms.EDAnalyzer("MyAnalyzer")
2706 process.task5 = cms.Task()
2707 process.task3 = cms.Task()
2708 process.task2 = cms.ConditionalTask(process.c, process.task3)
2709 process.task1 = cms.ConditionalTask(process.task5)
2710 process.r = cms.Sequence((process.a))
2711 process.p = cms.Path(process.a)
2712 process.p2 = cms.Path(process.r, process.task1, process.task2)
2713 process.schedule = cms.Schedule(*[ process.p2, process.p ], tasks=[process.task5])""")
2714  # only tasks
2715  p = Process("test")
2716  p.d = EDProducer("dProducer")
2717  p.e = EDProducer("eProducer")
2718  p.f = EDProducer("fProducer")
2719  p.g = EDProducer("gProducer")
2720  p.task1 = Task(p.d, p.e)
2721  task2 = Task(p.f, p.g)
2722  p.schedule = Schedule(tasks=[p.task1,task2])
2723  d=p.dumpPython()
2724  self.assertEqual(_lineDiff(d,Process("test").dumpPython()),
2725 """process.d = cms.EDProducer("dProducer")
2726 process.e = cms.EDProducer("eProducer")
2727 process.f = cms.EDProducer("fProducer")
2728 process.g = cms.EDProducer("gProducer")
2729 process.task1 = cms.Task(process.d, process.e)
2730 process.schedule = cms.Schedule(tasks=[cms.Task(process.f, process.g), process.task1])""")
2731  # empty schedule
2732  p = Process("test")
2733  p.schedule = Schedule()
2734  d=p.dumpPython()
2735  self.assertEqual(_lineDiff(d,Process('test').dumpPython()),
2736 """process.schedule = cms.Schedule()""")
2737 
2738  s = Sequence()
2739  a = EDProducer("A")
2740  s2 = Sequence(a)
2741  s2 += s
2742  process = Process("DUMP")
2743  process.a = a
2744  process.s2 = s2
2745  d=process.dumpPython()
2746  self.assertEqual(_lineDiff(d,Process('DUMP').dumpPython()),
2747 """process.a = cms.EDProducer("A")
2748 process.s2 = cms.Sequence(process.a)""")
2749  s = Sequence()
2750  s1 = Sequence(s)
2751  a = EDProducer("A")
2752  s3 = Sequence(a+a)
2753  s2 = Sequence(a+s3)
2754  s2 += s1
2755  process = Process("DUMP")
2756  process.a = a
2757  process.s2 = s2
2758  d=process.dumpPython()
2759  self.assertEqual(_lineDiff(d,Process('DUMP').dumpPython()),
2760 """process.a = cms.EDProducer("A")
2761 process.s2 = cms.Sequence(process.a+(process.a+process.a))""")
2762 
2763  def testSecSource(self):
2764  p = Process('test')
2765  p.a = SecSource("MySecSource")
2766  self.assertEqual(_lineDiff(p.dumpPython(),Process('test').dumpPython()),'process.a = cms.SecSource("MySecSource")')
2767 
2769  p = Process('test')
2770  p.a = EDAnalyzer("MyAnalyzer")
2771  old = p.a
2772  p.b = EDAnalyzer("YourAnalyzer")
2773  p.c = EDAnalyzer("OurAnalyzer")
2774  p.d = EDProducer("MyProducer")
2775  old2 = p.d
2776  p.t1 = Task(p.d)
2777  t2 = Task(p.d)
2778  t3 = Task(p.d)
2779  t4 = Task(p.d)
2780  t5 = Task(p.d)
2781  t6 = Task(p.d)
2782  p.ct1 = ConditionalTask(p.d)
2783  s = Sequence(p.a*p.b)
2784  p.s4 = Sequence(p.a*p.b, p.ct1)
2785  s.associate(t2)
2786  p.s4.associate(t2)
2787  p.p = Path(p.c+s+p.a)
2788  p.p2 = Path(p.c+p.s4+p.a, p.ct1)
2789  p.e3 = EndPath(p.c+s+p.a)
2790  new = EDAnalyzer("NewAnalyzer")
2791  new2 = EDProducer("NewProducer")
2792  visitor1 = NodeVisitor()
2793  p.p.visit(visitor1)
2794  self.assertTrue(visitor1.modules == set([old,old2,p.b,p.c]))
2795  p.schedule = Schedule(tasks=[t6])
2796  p.globalReplace("a",new)
2797  p.globalReplace("d",new2)
2798  visitor2 = NodeVisitor()
2799  p.p.visit(visitor2)
2800  self.assertTrue(visitor2.modules == set([new,new2,p.b,p.c]))
2801  self.assertEqual(p.p.dumpPython()[:-1], "cms.Path(process.c+process.a+process.b+process.a, cms.Task(process.d))")
2802  visitor_p2 = NodeVisitor()
2803  p.p2.visit(visitor_p2)
2804  self.assertTrue(visitor_p2.modules == set([new,new2,p.b,p.c]))
2805  self.assertEqual(p.p2.dumpPython()[:-1], "cms.Path(process.c+process.s4+process.a, process.ct1)")
2806  visitor3 = NodeVisitor()
2807  p.e3.visit(visitor3)
2808  self.assertTrue(visitor3.modules == set([new,new2,p.b,p.c]))
2809  visitor4 = NodeVisitor()
2810  p.s4.visit(visitor4)
2811  self.assertTrue(visitor4.modules == set([new,new2,p.b]))
2812  self.assertEqual(p.s4.dumpPython()[:-1],"cms.Sequence(process.a+process.b, cms.Task(process.d), process.ct1)")
2813  visitor5 = NodeVisitor()
2814  p.t1.visit(visitor5)
2815  self.assertTrue(visitor5.modules == set([new2]))
2816  visitor6 = NodeVisitor()
2817  listOfTasks = list(p.schedule._tasks)
2818  listOfTasks[0].visit(visitor6)
2819  self.assertTrue(visitor6.modules == set([new2]))
2820  visitor7 = NodeVisitor()
2821  p.ct1.visit(visitor7)
2822  self.assertTrue(visitor7.modules == set([new2]))
2823  visitor8 = NodeVisitor()
2824  listOfConditionalTasks = list(p.conditionaltasks.values())
2825  listOfConditionalTasks[0].visit(visitor8)
2826  self.assertTrue(visitor8.modules == set([new2]))
2827 
2828 
2829  p.d2 = EDProducer("YourProducer")
2830  p.schedule = Schedule(p.p, p.p2, p.e3, tasks=[p.t1])
2831  self.assertEqual(p.schedule.dumpPython()[:-1], "cms.Schedule(*[ process.p, process.p2, process.e3 ], tasks=[process.t1])")
2832  p.p = Path(p.c+s)
2833  self.assertEqual(p.schedule.dumpPython()[:-1], "cms.Schedule(*[ process.p, process.p2, process.e3 ], tasks=[process.t1])")
2834  p.e3 = EndPath(p.c)
2835  self.assertEqual(p.schedule.dumpPython()[:-1], "cms.Schedule(*[ process.p, process.p2, process.e3 ], tasks=[process.t1])")
2836  p.t1 = Task(p.d2)
2837  self.assertEqual(p.schedule.dumpPython()[:-1], "cms.Schedule(*[ process.p, process.p2, process.e3 ], tasks=[process.t1])")
2838 
2839  def testSequence(self):
2840  p = Process('test')
2841  p.a = EDAnalyzer("MyAnalyzer")
2842  p.b = EDAnalyzer("YourAnalyzer")
2843  p.c = EDAnalyzer("OurAnalyzer")
2844  p.s = Sequence(p.a*p.b)
2845  self.assertEqual(str(p.s),'a+b')
2846  self.assertEqual(p.s.label_(),'s')
2847  path = Path(p.c+p.s)
2848  self.assertEqual(str(path),'c+a+b')
2849  p._validateSequence(path, 'p1')
2850  notInProcess = EDAnalyzer('NotInProcess')
2851  p2 = Path(p.c+p.s*notInProcess)
2852  self.assertRaises(RuntimeError, p._validateSequence, p2, 'p2')
2853 
2854  def testSequence2(self):
2855  p = Process('test')
2856  p.a = EDAnalyzer("MyAnalyzer")
2857  p.b = EDAnalyzer("YourAnalyzer")
2858  p.c = EDAnalyzer("OurAnalyzer")
2859  testseq = Sequence(p.a*p.b)
2860  p.s = testseq
2861  #p.y = testseq
2862  self.assertRaises(ValueError, p.__setattr__, "y", testseq)
2863 
2865  service = Service("d")
2866  self.assertFalse(service._inProcess)
2867  process = Process("test")
2868  process.d = service
2869  self.assertTrue(service._inProcess)
2870  service2 = Service("d")
2871  process.d = service2
2872  self.assertFalse(service._inProcess)
2873  self.assertTrue(service2._inProcess)
2874  del process.d
2875  self.assertFalse(service2._inProcess)
2876 
2877  def testTask(self):
2878 
2879  # create some objects to use in tests
2880  edanalyzer = EDAnalyzer("a")
2881  edproducer = EDProducer("b")
2882  edproducer2 = EDProducer("b2")
2883  edproducer3 = EDProducer("b3")
2884  edproducer4 = EDProducer("b4")
2885  edproducer8 = EDProducer("b8")
2886  edproducer9 = EDProducer("b9")
2887  edfilter = EDFilter("c")
2888  service = Service("d")
2889  service3 = Service("d", v = untracked.uint32(3))
2890  essource = ESSource("e")
2891  esproducer = ESProducer("f")
2892  testTask2 = Task()
2893 
2894  # test adding things to Tasks
2895  testTask1 = Task(edproducer, edfilter)
2896  self.assertRaises(RuntimeError, testTask1.add, edanalyzer)
2897  testTask1.add(essource, service)
2898  testTask1.add(essource, esproducer)
2899  testTask1.add(testTask2)
2900  coll = testTask1._collection
2901  self.assertTrue(edproducer in coll)
2902  self.assertTrue(edfilter in coll)
2903  self.assertTrue(service in coll)
2904  self.assertTrue(essource in coll)
2905  self.assertTrue(esproducer in coll)
2906  self.assertTrue(testTask2 in coll)
2907  self.assertTrue(len(coll) == 6)
2908  self.assertTrue(len(testTask2._collection) == 0)
2909 
2910  taskContents = []
2911  for i in testTask1:
2912  taskContents.append(i)
2913  self.assertTrue(taskContents == [edproducer, edfilter, essource, service, esproducer, testTask2])
2914 
2915  # test attaching Task to Process
2916  process = Process("test")
2917 
2918  process.mproducer = edproducer
2919  process.mproducer2 = edproducer2
2920  process.mfilter = edfilter
2921  process.messource = essource
2922  process.mesproducer = esproducer
2923  process.d = service
2924 
2925  testTask3 = Task(edproducer, edproducer2)
2926  testTask1.add(testTask3)
2927  process.myTask1 = testTask1
2928 
2929  # test the validation that occurs when attaching a Task to a Process
2930  # first a case that passes, then one the fails on an EDProducer
2931  # then one that fails on a service
2932  l = set()
2933  visitor = NodeNameVisitor(l)
2934  testTask1.visit(visitor)
2935  self.assertTrue(l == set(['mesproducer', 'mproducer', 'mproducer2', 'mfilter', 'd', 'messource']))
2936  l2 = testTask1.moduleNames
2937  self.assertTrue(l == set(['mesproducer', 'mproducer', 'mproducer2', 'mfilter', 'd', 'messource']))
2938 
2939  testTask4 = Task(edproducer3)
2940  l.clear()
2941  self.assertRaises(RuntimeError, testTask4.visit, visitor)
2942  try:
2943  process.myTask4 = testTask4
2944  self.assertTrue(False)
2945  except RuntimeError:
2946  pass
2947 
2948  testTask5 = Task(service3)
2949  l.clear()
2950  self.assertRaises(RuntimeError, testTask5.visit, visitor)
2951  try:
2952  process.myTask5 = testTask5
2953  self.assertTrue(False)
2954  except RuntimeError:
2955  pass
2956 
2957  process.d = service3
2958  process.myTask5 = testTask5
2959 
2960  # test placement into the Process and the tasks property
2961  expectedDict = { 'myTask1' : testTask1, 'myTask5' : testTask5 }
2962  expectedFixedDict = DictTypes.FixedKeysDict(expectedDict);
2963  self.assertTrue(process.tasks == expectedFixedDict)
2964  self.assertTrue(process.tasks['myTask1'] == testTask1)
2965  self.assertTrue(process.myTask1 == testTask1)
2966 
2967  # test replacing an EDProducer in a Task when calling __settattr__
2968  # for the EDProducer on the Process.
2969  process.mproducer2 = edproducer4
2970  process.d = service
2971  l = list()
2972  visitor1 = ModuleNodeVisitor(l)
2973  testTask1.visit(visitor1)
2974  l.sort(key=lambda mod: mod.__str__())
2975  expectedList = sorted([edproducer,essource,esproducer,service,edfilter,edproducer,edproducer4],key=lambda mod: mod.__str__())
2976  self.assertTrue(expectedList == l)
2977  process.myTask6 = Task()
2978  process.myTask7 = Task()
2979  process.mproducer8 = edproducer8
2980  process.myTask8 = Task(process.mproducer8)
2981  process.myTask6.add(process.myTask7)
2982  process.myTask7.add(process.myTask8)
2983  process.myTask1.add(process.myTask6)
2984  process.myTask8.add(process.myTask5)
2985 
2986  testDict = process._itemsInDependencyOrder(process.tasks)
2987  expectedLabels = ["myTask5", "myTask8", "myTask7", "myTask6", "myTask1"]
2988  expectedTasks = [process.myTask5, process.myTask8, process.myTask7, process.myTask6, process.myTask1]
2989  index = 0
2990  for testLabel, testTask in testDict.items():
2991  self.assertTrue(testLabel == expectedLabels[index])
2992  self.assertTrue(testTask == expectedTasks[index])
2993  index += 1
2994 
2995  pythonDump = testTask1.dumpPython(PrintOptions())
2996 
2997 
2998  expectedPythonDump = 'cms.Task(process.d, process.mesproducer, process.messource, process.mfilter, process.mproducer, process.mproducer2, process.myTask6)\n'
2999  self.assertTrue(pythonDump == expectedPythonDump)
3000 
3001  process.myTask5 = Task()
3002  process.myTask100 = Task()
3003  process.mproducer9 = edproducer9
3004  sequence1 = Sequence(process.mproducer8, process.myTask1, process.myTask5, testTask2, testTask3)
3005  sequence2 = Sequence(process.mproducer8 + process.mproducer9)
3006  process.sequence3 = Sequence((process.mproducer8 + process.mfilter))
3007  sequence4 = Sequence()
3008  process.path1 = Path(process.mproducer+process.mproducer8+sequence1+sequence2+process.sequence3+sequence4)
3009  process.path1.associate(process.myTask1, process.myTask5, testTask2, testTask3)
3010  process.path11 = Path(process.mproducer+process.mproducer8+sequence1+sequence2+process.sequence3+ sequence4,process.myTask1, process.myTask5, testTask2, testTask3, process.myTask100)
3011  process.path2 = Path(process.mproducer)
3012  process.path3 = Path(process.mproducer9+process.mproducer8,testTask2)
3013 
3014  self.assertTrue(process.path1.dumpPython(PrintOptions()) == 'cms.Path(process.mproducer+process.mproducer8+cms.Sequence(process.mproducer8, cms.Task(), cms.Task(process.None, process.mproducer), process.myTask1, process.myTask5)+(process.mproducer8+process.mproducer9)+process.sequence3, cms.Task(), cms.Task(process.None, process.mproducer), process.myTask1, process.myTask5)\n')
3015 
3016  self.assertTrue(process.path11.dumpPython(PrintOptions()) == 'cms.Path(process.mproducer+process.mproducer8+cms.Sequence(process.mproducer8, cms.Task(), cms.Task(process.None, process.mproducer), process.myTask1, process.myTask5)+(process.mproducer8+process.mproducer9)+process.sequence3, cms.Task(), cms.Task(process.None, process.mproducer), process.myTask1, process.myTask100, process.myTask5)\n')
3017 
3018  # test NodeNameVisitor and moduleNames
3019  l = set()
3020  nameVisitor = NodeNameVisitor(l)
3021  process.path1.visit(nameVisitor)
3022  self.assertTrue(l == set(['mproducer', 'd', 'mesproducer', None, 'mproducer9', 'mproducer8', 'messource', 'mproducer2', 'mfilter']))
3023  self.assertTrue(process.path1.moduleNames() == set(['mproducer', 'd', 'mesproducer', None, 'mproducer9', 'mproducer8', 'messource', 'mproducer2', 'mfilter']))
3024 
3025  # test copy
3026  process.mproducer10 = EDProducer("b10")
3027  process.path21 = process.path11.copy()
3028  process.path21.replace(process.mproducer, process.mproducer10)
3029 
3030  self.assertTrue(process.path11.dumpPython(PrintOptions()) == 'cms.Path(process.mproducer+process.mproducer8+cms.Sequence(process.mproducer8, cms.Task(), cms.Task(process.None, process.mproducer), process.myTask1, process.myTask5)+(process.mproducer8+process.mproducer9)+process.sequence3, cms.Task(), cms.Task(process.None, process.mproducer), process.myTask1, process.myTask100, process.myTask5)\n')
3031 
3032  # Some peculiarities of the way things work show up here. dumpPython sorts tasks and
3033  # removes duplication at the level of strings. The Task and Sequence objects themselves
3034  # remove duplicate tasks in their contents if the instances are the same (exact same python
3035  # object id which is not the same as the string representation being the same).
3036  # Also note that the mutating visitor replaces sequences and tasks that have
3037  # modified contents with their modified contents, it does not modify the sequence
3038  # or task itself.
3039  self.assertTrue(process.path21.dumpPython(PrintOptions()) == 'cms.Path(process.mproducer10+process.mproducer8+process.mproducer8+(process.mproducer8+process.mproducer9)+process.sequence3, cms.Task(), cms.Task(process.None, process.mproducer10), cms.Task(process.d, process.mesproducer, process.messource, process.mfilter, process.mproducer10, process.mproducer2, process.mproducer8, process.myTask5), process.myTask100, process.myTask5)\n')
3040 
3041  process.path22 = process.path21.copyAndExclude([process.d, process.mesproducer, process.mfilter])
3042  self.assertTrue(process.path22.dumpPython(PrintOptions()) == 'cms.Path(process.mproducer10+process.mproducer8+process.mproducer8+(process.mproducer8+process.mproducer9)+process.mproducer8, cms.Task(), cms.Task(process.None, process.mproducer10), cms.Task(process.messource, process.mproducer10, process.mproducer2, process.mproducer8, process.myTask5), process.myTask100, process.myTask5)\n')
3043 
3044  process.path23 = process.path22.copyAndExclude([process.messource, process.mproducer10])
3045  self.assertTrue(process.path23.dumpPython(PrintOptions()) == 'cms.Path(process.mproducer8+process.mproducer8+(process.mproducer8+process.mproducer9)+process.mproducer8, cms.Task(), cms.Task(process.None), cms.Task(process.mproducer2, process.mproducer8, process.myTask5), process.myTask100, process.myTask5)\n')
3046 
3047  process.a = EDAnalyzer("MyAnalyzer")
3048  process.b = OutputModule("MyOutputModule")
3049  process.c = EDFilter("MyFilter")
3050  process.d = EDProducer("MyProducer")
3051  process.e = ESProducer("MyESProducer")
3052  process.f = ESSource("MyESSource")
3053  process.g = ESProducer("g")
3054  process.path24 = Path(process.a+process.b+process.c+process.d)
3055  process.path25 = process.path24.copyAndExclude([process.a,process.b,process.c])
3056  self.assertTrue(process.path25.dumpPython() == 'cms.Path(process.d)\n')
3057  #print process.path3
3058  #print process.dumpPython()
3059 
3060  process.path200 = EndPath(Sequence(process.c,Task(process.e)))
3061  process.path200.replace(process.c,process.b)
3062  process.path200.replace(process.e,process.f)
3063  self.assertEqual(process.path200.dumpPython(), "cms.EndPath(process.b, cms.Task(process.f))\n")
3064  process.path200.replace(process.b,process.c)
3065  process.path200.replace(process.f,process.e)
3066  self.assertEqual(process.path200.dumpPython(), "cms.EndPath(process.c, cms.Task(process.e))\n")
3067  process.path200.replace(process.c,process.a)
3068  process.path200.replace(process.e,process.g)
3069  self.assertEqual(process.path200.dumpPython(), "cms.EndPath(process.a, cms.Task(process.g))\n")
3070  process.path200.replace(process.a,process.c)
3071  process.path200.replace(process.g,process.e)
3072  self.assertEqual(process.path200.dumpPython(), "cms.EndPath(process.c, cms.Task(process.e))\n")
3073 
3075 
3076  # create some objects to use in tests
3077  edanalyzer = EDAnalyzer("a")
3078  edproducer = EDProducer("b")
3079  edproducer2 = EDProducer("b2")
3080  edproducer3 = EDProducer("b3")
3081  edproducer4 = EDProducer("b4")
3082  edproducer8 = EDProducer("b8")
3083  edproducer9 = EDProducer("b9")
3084  edfilter = EDFilter("c")
3085  service = Service("d")
3086  service3 = Service("d", v = untracked.uint32(3))
3087  essource = ESSource("e")
3088  esproducer = ESProducer("f")
3089  testTask2 = Task()
3090  testCTask2 = ConditionalTask()
3091 
3092  # test adding things to Tasks
3093  testTask1 = ConditionalTask(edproducer, edfilter)
3094  self.assertRaises(RuntimeError, testTask1.add, edanalyzer)
3095  testTask1.add(essource, service)
3096  testTask1.add(essource, esproducer)
3097  testTask1.add(testTask2)
3098  testTask1.add(testCTask2)
3099  coll = testTask1._collection
3100  self.assertTrue(edproducer in coll)
3101  self.assertTrue(edfilter in coll)
3102  self.assertTrue(service in coll)
3103  self.assertTrue(essource in coll)
3104  self.assertTrue(esproducer in coll)
3105  self.assertTrue(testTask2 in coll)
3106  self.assertTrue(testCTask2 in coll)
3107  self.assertTrue(len(coll) == 7)
3108  self.assertTrue(len(testTask2._collection) == 0)
3109 
3110  taskContents = []
3111  for i in testTask1:
3112  taskContents.append(i)
3113  self.assertEqual(taskContents, [edproducer, edfilter, essource, service, esproducer, testTask2, testCTask2])
3114 
3115  # test attaching Task to Process
3116  process = Process("test")
3117 
3118  process.mproducer = edproducer
3119  process.mproducer2 = edproducer2
3120  process.mfilter = edfilter
3121  process.messource = essource
3122  process.mesproducer = esproducer
3123  process.d = service
3124 
3125  testTask3 = ConditionalTask(edproducer, edproducer2)
3126  testTask1.add(testTask3)
3127  process.myTask1 = testTask1
3128 
3129  # test the validation that occurs when attaching a ConditionalTask to a Process
3130  # first a case that passes, then one the fails on an EDProducer
3131  # then one that fails on a service
3132  l = set()
3133  visitor = NodeNameVisitor(l)
3134  testTask1.visit(visitor)
3135  self.assertEqual(l, set(['mesproducer', 'mproducer', 'mproducer2', 'mfilter', 'd', 'messource']))
3136  l2 = testTask1.moduleNames()
3137  self.assertEqual(l2, set(['mesproducer', 'mproducer', 'mproducer2', 'mfilter', 'd', 'messource']))
3138 
3139  testTask4 = ConditionalTask(edproducer3)
3140  l.clear()
3141  self.assertRaises(RuntimeError, testTask4.visit, visitor)
3142  try:
3143  process.myTask4 = testTask4
3144  self.assertTrue(False)
3145  except RuntimeError:
3146  pass
3147 
3148  testTask5 = ConditionalTask(service3)
3149  l.clear()
3150  self.assertRaises(RuntimeError, testTask5.visit, visitor)
3151  try:
3152  process.myTask5 = testTask5
3153  self.assertTrue(False)
3154  except RuntimeError:
3155  pass
3156 
3157  process.d = service3
3158  process.myTask5 = testTask5
3159 
3160  # test placement into the Process and the tasks property
3161  expectedDict = { 'myTask1' : testTask1, 'myTask5' : testTask5 }
3162  expectedFixedDict = DictTypes.FixedKeysDict(expectedDict);
3163  self.assertEqual(process.conditionaltasks, expectedFixedDict)
3164  self.assertEqual(process.conditionaltasks['myTask1'], testTask1)
3165  self.assertEqual(process.myTask1, testTask1)
3166 
3167  # test replacing an EDProducer in a ConditionalTask when calling __settattr__
3168  # for the EDProducer on the Process.
3169  process.mproducer2 = edproducer4
3170  process.d = service
3171  l = list()
3172  visitor1 = ModuleNodeVisitor(l)
3173  testTask1.visit(visitor1)
3174  l.sort(key=lambda mod: mod.__str__())
3175  expectedList = sorted([edproducer,essource,esproducer,service,edfilter,edproducer,edproducer4],key=lambda mod: mod.__str__())
3176  self.assertEqual(expectedList, l)
3177  process.myTask6 = ConditionalTask()
3178  process.myTask7 = ConditionalTask()
3179  process.mproducer8 = edproducer8
3180  process.myTask8 = ConditionalTask(process.mproducer8)
3181  process.myTask6.add(process.myTask7)
3182  process.myTask7.add(process.myTask8)
3183  process.myTask1.add(process.myTask6)
3184  process.myTask8.add(process.myTask5)
3185  self.assertEqual(process.myTask8.dumpPython(), "cms.ConditionalTask(process.mproducer8, process.myTask5)\n")
3186 
3187  testDict = process._itemsInDependencyOrder(process.conditionaltasks)
3188  expectedLabels = ["myTask5", "myTask8", "myTask7", "myTask6", "myTask1"]
3189  expectedTasks = [process.myTask5, process.myTask8, process.myTask7, process.myTask6, process.myTask1]
3190  index = 0
3191  for testLabel, testTask in testDict.items():
3192  self.assertEqual(testLabel, expectedLabels[index])
3193  self.assertEqual(testTask, expectedTasks[index])
3194  index += 1
3195 
3196  pythonDump = testTask1.dumpPython(PrintOptions())
3197 
3198 
3199  expectedPythonDump = 'cms.ConditionalTask(process.d, process.mesproducer, process.messource, process.mfilter, process.mproducer, process.mproducer2, process.myTask6)\n'
3200  self.assertEqual(pythonDump, expectedPythonDump)
3201 
3202  process.myTask5 = ConditionalTask()
3203  self.assertEqual(process.myTask8.dumpPython(), "cms.ConditionalTask(process.mproducer8, process.myTask5)\n")
3204  process.myTask100 = ConditionalTask()
3205  process.mproducer9 = edproducer9
3206  sequence1 = Sequence(process.mproducer8, process.myTask1, process.myTask5, testTask2, testTask3)
3207  sequence2 = Sequence(process.mproducer8 + process.mproducer9)
3208  process.sequence3 = Sequence((process.mproducer8 + process.mfilter))
3209  sequence4 = Sequence()
3210  process.path1 = Path(process.mproducer+process.mproducer8+sequence1+sequence2+process.sequence3+sequence4)
3211  process.path1.associate(process.myTask1, process.myTask5, testTask2, testTask3)
3212  process.path11 = Path(process.mproducer+process.mproducer8+sequence1+sequence2+process.sequence3+ sequence4,process.myTask1, process.myTask5, testTask2, testTask3, process.myTask100)
3213  process.path2 = Path(process.mproducer)
3214  process.path3 = Path(process.mproducer9+process.mproducer8,testTask2)
3215 
3216  self.assertEqual(process.path1.dumpPython(PrintOptions()), 'cms.Path(process.mproducer+process.mproducer8+cms.Sequence(process.mproducer8, cms.ConditionalTask(process.None, process.mproducer), cms.Task(), process.myTask1, process.myTask5)+(process.mproducer8+process.mproducer9)+process.sequence3, cms.ConditionalTask(process.None, process.mproducer), cms.Task(), process.myTask1, process.myTask5)\n')
3217 
3218  self.assertEqual(process.path11.dumpPython(PrintOptions()), 'cms.Path(process.mproducer+process.mproducer8+cms.Sequence(process.mproducer8, cms.ConditionalTask(process.None, process.mproducer), cms.Task(), process.myTask1, process.myTask5)+(process.mproducer8+process.mproducer9)+process.sequence3, cms.ConditionalTask(process.None, process.mproducer), cms.Task(), process.myTask1, process.myTask100, process.myTask5)\n')
3219 
3220  # test NodeNameVisitor and moduleNames
3221  l = set()
3222  nameVisitor = NodeNameVisitor(l)
3223  process.path1.visit(nameVisitor)
3224  self.assertTrue(l == set(['mproducer', 'd', 'mesproducer', None, 'mproducer9', 'mproducer8', 'messource', 'mproducer2', 'mfilter']))
3225  self.assertTrue(process.path1.moduleNames() == set(['mproducer', 'd', 'mesproducer', None, 'mproducer9', 'mproducer8', 'messource', 'mproducer2', 'mfilter']))
3226 
3227  # test copy
3228  process.mproducer10 = EDProducer("b10")
3229  process.path21 = process.path11.copy()
3230  process.path21.replace(process.mproducer, process.mproducer10)
3231 
3232  self.assertEqual(process.path11.dumpPython(PrintOptions()), 'cms.Path(process.mproducer+process.mproducer8+cms.Sequence(process.mproducer8, cms.ConditionalTask(process.None, process.mproducer), cms.Task(), process.myTask1, process.myTask5)+(process.mproducer8+process.mproducer9)+process.sequence3, cms.ConditionalTask(process.None, process.mproducer), cms.Task(), process.myTask1, process.myTask100, process.myTask5)\n')
3233 
3234  # Some peculiarities of the way things work show up here. dumpPython sorts tasks and
3235  # removes duplication at the level of strings. The Task and Sequence objects themselves
3236  # remove duplicate tasks in their contents if the instances are the same (exact same python
3237  # object id which is not the same as the string representation being the same).
3238  # Also note that the mutating visitor replaces sequences and tasks that have
3239  # modified contents with their modified contents, it does not modify the sequence
3240  # or task itself.
3241  self.assertEqual(process.path21.dumpPython(PrintOptions()), 'cms.Path(process.mproducer10+process.mproducer8+process.mproducer8+(process.mproducer8+process.mproducer9)+process.sequence3, cms.ConditionalTask(process.None, process.mproducer10), cms.ConditionalTask(process.d, process.mesproducer, process.messource, process.mfilter, process.mproducer10, process.mproducer2, process.mproducer8, process.myTask5), cms.Task(), process.myTask100, process.myTask5)\n')
3242 
3243  process.path22 = process.path21.copyAndExclude([process.d, process.mesproducer, process.mfilter])
3244  self.assertEqual(process.path22.dumpPython(PrintOptions()), 'cms.Path(process.mproducer10+process.mproducer8+process.mproducer8+(process.mproducer8+process.mproducer9)+process.mproducer8, cms.ConditionalTask(process.None, process.mproducer10), cms.ConditionalTask(process.messource, process.mproducer10, process.mproducer2, process.mproducer8, process.myTask5), cms.Task(), process.myTask100, process.myTask5)\n')
3245 
3246  process.path23 = process.path22.copyAndExclude([process.messource, process.mproducer10])
3247  self.assertEqual(process.path23.dumpPython(PrintOptions()), 'cms.Path(process.mproducer8+process.mproducer8+(process.mproducer8+process.mproducer9)+process.mproducer8, cms.ConditionalTask(process.None), cms.ConditionalTask(process.mproducer2, process.mproducer8, process.myTask5), cms.Task(), process.myTask100, process.myTask5)\n')
3248 
3249  process = Process("Test")
3250 
3251  process.b = EDProducer("b")
3252  process.b2 = EDProducer("b2")
3253  process.b3 = EDProducer("b3")
3254  process.p = Path(process.b, ConditionalTask(process.b3, process.b2))
3255  p = TestMakePSet()
3256  process.fillProcessDesc(p)
3257  self.assertEqual(p.values["@all_modules"], (True, ['b', 'b2', 'b3']))
3258  self.assertEqual(p.values["@paths"], (True, ['p']))
3259  self.assertEqual(p.values["p"], (True, ['b','#','b2','b3','@']))
3260 
3261 
3262  def testPath(self):
3263  p = Process("test")
3264  p.a = EDAnalyzer("MyAnalyzer")
3265  p.b = EDAnalyzer("YourAnalyzer")
3266  p.c = EDAnalyzer("OurAnalyzer")
3267  path = Path(p.a)
3268  path *= p.b
3269  path += p.c
3270  self.assertEqual(str(path),'a+b+c')
3271  path = Path(p.a*p.b+p.c)
3272  self.assertEqual(str(path),'a+b+c')
3273 # path = Path(p.a)*p.b+p.c #This leads to problems with sequences
3274 # self.assertEqual(str(path),'((a*b)+c)')
3275  path = Path(p.a+ p.b*p.c)
3276  self.assertEqual(str(path),'a+b+c')
3277  path = Path(p.a*(p.b+p.c))
3278  self.assertEqual(str(path),'a+b+c')
3279  path = Path(p.a*(p.b+~p.c))
3280  pathx = Path(p.a*(p.b+ignore(p.c)))
3281  self.assertEqual(str(path),'a+b+~c')
3282  p.es = ESProducer("AnESProducer")
3283  self.assertRaises(TypeError,Path,p.es)
3284 
3285  t = Path()
3286  self.assertEqual(t.dumpPython(PrintOptions()), 'cms.Path()\n')
3287 
3288  t = Path(p.a)
3289  self.assertEqual(t.dumpPython(PrintOptions()), 'cms.Path(process.a)\n')
3290 
3291  t = Path(Task())
3292  self.assertEqual(t.dumpPython(PrintOptions()), 'cms.Path(cms.Task())\n')
3293 
3294  t = Path(p.a, Task())
3295  self.assertEqual(t.dumpPython(PrintOptions()), 'cms.Path(process.a, cms.Task())\n')
3296 
3297  p.prod = EDProducer("prodName")
3298  p.t1 = Task(p.prod)
3299  t = Path(p.a, p.t1, Task(), p.t1)
3300  self.assertEqual(t.dumpPython(PrintOptions()), 'cms.Path(process.a, cms.Task(), process.t1)\n')
3301 
3302  t = Path(ConditionalTask())
3303  self.assertEqual(t.dumpPython(PrintOptions()), 'cms.Path(cms.ConditionalTask())\n')
3304 
3305  t = Path(p.a, ConditionalTask())
3306  self.assertEqual(t.dumpPython(PrintOptions()), 'cms.Path(process.a, cms.ConditionalTask())\n')
3307 
3308  p.prod = EDProducer("prodName")
3309  p.t1 = ConditionalTask(p.prod)
3310  t = Path(p.a, p.t1, Task(), p.t1)
3311  self.assertEqual(t.dumpPython(PrintOptions()), 'cms.Path(process.a, cms.Task(), process.t1)\n')
3312 
3313  def testFinalPath(self):
3314  p = Process("test")
3315  p.a = OutputModule("MyOutputModule")
3316  p.b = OutputModule("YourOutputModule")
3317  p.c = OutputModule("OurOutputModule")
3318  path = FinalPath(p.a)
3319  path *= p.b
3320  path += p.c
3321  self.assertEqual(str(path),'a+b+c')
3322  path = FinalPath(p.a*p.b+p.c)
3323  self.assertEqual(str(path),'a+b+c')
3324  path = FinalPath(p.a+ p.b*p.c)
3325  self.assertEqual(str(path),'a+b+c')
3326  path = FinalPath(p.a*(p.b+p.c))
3327  self.assertEqual(str(path),'a+b+c')
3328  p.es = ESProducer("AnESProducer")
3329  self.assertRaises(TypeError,FinalPath,p.es)
3330 
3331  t = FinalPath()
3332  self.assertEqual(t.dumpPython(PrintOptions()), 'cms.FinalPath()\n')
3333 
3334  t = FinalPath(p.a)
3335  self.assertEqual(t.dumpPython(PrintOptions()), 'cms.FinalPath(process.a)\n')
3336 
3337  self.assertRaises(TypeError, FinalPath, Task())
3338  self.assertRaises(TypeError, FinalPath, p.a, Task())
3339 
3340  p.prod = EDProducer("prodName")
3341  p.t1 = Task(p.prod)
3342  self.assertRaises(TypeError, FinalPath, p.a, p.t1, Task(), p.t1)
3343 
3344  p.prod = EDProducer("prodName")
3345  p.t1 = ConditionalTask(p.prod)
3346  self.assertRaises(TypeError, FinalPath, p.a, p.t1, ConditionalTask(), p.t1)
3347 
3348  p.t = FinalPath(p.a)
3349  p.a = OutputModule("ReplacedOutputModule")
3350  self.assertEqual(p.t.dumpPython(PrintOptions()), 'cms.FinalPath(process.a)\n')
3351 
3353  p = Process("test")
3354  a = EDAnalyzer("MyAnalyzer")
3355  p.a = a
3356  a.setLabel("a")
3357  b = EDAnalyzer("YOurAnalyzer")
3358  p.b = b
3359  b.setLabel("b")
3360  path = Path(a * b)
3361  p.path = Path(p.a*p.b)
3362  lookuptable = {id(a): p.a, id(b): p.b}
3363  #self.assertEqual(str(path),str(path._postProcessFixup(lookuptable)))
3364  #lookuptable = p._cloneToObjectDict
3365  #self.assertEqual(str(path),str(path._postProcessFixup(lookuptable)))
3366  self.assertEqual(str(path),str(p.path))
3367 
3368  def testContains(self):
3369 
3370  a = EDProducer("a")
3371  b = EDProducer("b")
3372  c = EDProducer("c")
3373  d = EDProducer("d")
3374  e = EDProducer("e")
3375  f = EDProducer("f")
3376  g = EDProducer("g")
3377  h = EDProducer("h")
3378  i = EDProducer("i")
3379  j = EDProducer("j")
3380  k = EDProducer("k")
3381  l = EDProducer("l")
3382  m = EDProducer("m")
3383  n = EDProducer("n")
3384 
3385  seq1 = Sequence(e)
3386  task1 = Task(g)
3387  ctask1 = ConditionalTask(h)
3388  path = Path(a * c * seq1, task1, ctask1)
3389 
3390  self.assertTrue(path.contains(a))
3391  self.assertFalse(path.contains(b))
3392  self.assertTrue(path.contains(c))
3393  self.assertFalse(path.contains(d))
3394  self.assertTrue(path.contains(e))
3395  self.assertFalse(path.contains(f))
3396  self.assertTrue(path.contains(g))
3397  self.assertTrue(path.contains(h))
3398 
3399  endpath = EndPath(h * i)
3400  self.assertFalse(endpath.contains(b))
3401  self.assertTrue(endpath.contains(i))
3402 
3403  seq = Sequence(a * c)
3404  self.assertFalse(seq.contains(b))
3405  self.assertTrue(seq.contains(c))
3406 
3407  task2 = Task(l)
3408  task = Task(j, k, task2)
3409  self.assertFalse(task.contains(b))
3410  self.assertTrue(task.contains(j))
3411  self.assertTrue(task.contains(k))
3412  self.assertTrue(task.contains(l))
3413 
3414  task3 = Task(m)
3415  path2 = Path(n)
3416  sch = Schedule(path, path2, tasks=[task,task3])
3417  self.assertFalse(sch.contains(b))
3418  self.assertTrue(sch.contains(a))
3419  self.assertTrue(sch.contains(c))
3420  self.assertTrue(sch.contains(e))
3421  self.assertTrue(sch.contains(g))
3422  self.assertTrue(sch.contains(n))
3423  self.assertTrue(sch.contains(j))
3424  self.assertTrue(sch.contains(k))
3425  self.assertTrue(sch.contains(l))
3426  self.assertTrue(sch.contains(m))
3427 
3428  ctask2 = ConditionalTask(l, task1)
3429  ctask = ConditionalTask(j, k, ctask2)
3430  self.assertFalse(ctask.contains(b))
3431  self.assertTrue(ctask.contains(j))
3432  self.assertTrue(ctask.contains(k))
3433  self.assertTrue(ctask.contains(l))
3434  self.assertTrue(ctask.contains(g))
3435 
3436  def testSchedule(self):
3437  p = Process("test")
3438  p.a = EDAnalyzer("MyAnalyzer")
3439  p.b = EDAnalyzer("YourAnalyzer")
3440  p.c = EDAnalyzer("OurAnalyzer")
3441  p.d = EDAnalyzer("OurAnalyzer")
3442  p.path1 = Path(p.a)
3443  p.path2 = Path(p.b)
3444  p.path3 = Path(p.d)
3445 
3446  s = Schedule(p.path1,p.path2)
3447  self.assertEqual(s[0],p.path1)
3448  self.assertEqual(s[1],p.path2)
3449  p.schedule = s
3450  self.assertTrue('b' in p.schedule.moduleNames())
3451  self.assertTrue(hasattr(p, 'b'))
3452  self.assertTrue(hasattr(p, 'c'))
3453  self.assertTrue(hasattr(p, 'd'))
3454  self.assertTrue(hasattr(p, 'path1'))
3455  self.assertTrue(hasattr(p, 'path2'))
3456  self.assertTrue(hasattr(p, 'path3'))
3457  p.prune()
3458  self.assertTrue('b' in p.schedule.moduleNames())
3459  self.assertTrue(hasattr(p, 'b'))
3460  self.assertTrue(not hasattr(p, 'c'))
3461  self.assertTrue(not hasattr(p, 'd'))
3462  self.assertTrue(hasattr(p, 'path1'))
3463  self.assertTrue(hasattr(p, 'path2'))
3464  self.assertTrue(not hasattr(p, 'path3'))
3465 
3466  self.assertTrue(len(p.schedule._tasks) == 0)
3467 
3468  p = Process("test")
3469  p.a = EDAnalyzer("MyAnalyzer")
3470  p.b = EDAnalyzer("YourAnalyzer")
3471  p.c = EDAnalyzer("OurAnalyzer")
3472  p.d = EDAnalyzer("dAnalyzer")
3473  p.e = EDProducer("eProducer")
3474  p.f = EDProducer("fProducer")
3475  p.Tracer = Service("Tracer")
3476  p.path1 = Path(p.a)
3477  p.path2 = Path(p.b)
3478  p.path3 = Path(p.d)
3479  p.task1 = Task(p.e)
3480  p.task2 = Task(p.f, p.Tracer)
3481  s = Schedule(p.path1,p.path2,tasks=[p.task1,p.task2,p.task1])
3482  self.assertEqual(s[0],p.path1)
3483  self.assertEqual(s[1],p.path2)
3484  self.assertTrue(len(s._tasks) == 2)
3485  self.assertTrue(p.task1 in s._tasks)
3486  self.assertTrue(p.task2 in s._tasks)
3487  listOfTasks = list(s._tasks)
3488  self.assertTrue(len(listOfTasks) == 2)
3489  self.assertTrue(p.task1 == listOfTasks[0])
3490  self.assertTrue(p.task2 == listOfTasks[1])
3491  p.schedule = s
3492  self.assertTrue('b' in p.schedule.moduleNames())
3493 
3494  process2 = Process("test")
3495  process2.a = EDAnalyzer("MyAnalyzer")
3496  process2.e = EDProducer("eProducer")
3497  process2.path1 = Path(process2.a)
3498  process2.task1 = Task(process2.e)
3499  process2.schedule = Schedule(process2.path1,tasks=process2.task1)
3500  listOfTasks = list(process2.schedule._tasks)
3501  self.assertTrue(listOfTasks[0] == process2.task1)
3502 
3503  # test Schedule copy
3504  s2 = s.copy()
3505  self.assertEqual(s2[0],p.path1)
3506  self.assertEqual(s2[1],p.path2)
3507  self.assertTrue(len(s2._tasks) == 2)
3508  self.assertTrue(p.task1 in s2._tasks)
3509  self.assertTrue(p.task2 in s2._tasks)
3510  listOfTasks = list(s2._tasks)
3511  self.assertTrue(len(listOfTasks) == 2)
3512  self.assertTrue(p.task1 == listOfTasks[0])
3513  self.assertTrue(p.task2 == listOfTasks[1])
3514 
3515  names = s.moduleNames()
3516  self.assertTrue(names == set(['a', 'b', 'e', 'Tracer', 'f']))
3517  #adding a path not attached to the Process should cause an exception
3518  p = Process("test")
3519  p.a = EDAnalyzer("MyAnalyzer")
3520  path1 = Path(p.a)
3521  s = Schedule(path1)
3522  self.assertRaises(RuntimeError, lambda : p.setSchedule_(s) )
3523 
3524  #make sure anonymous sequences work
3525  p = Process("test")
3526  p.a = EDAnalyzer("MyAnalyzer")
3527  p.b = EDAnalyzer("MyOtherAnalyzer")
3528  p.c = EDProducer("MyProd")
3529  path1 = Path(p.c*Sequence(p.a+p.b))
3530  s = Schedule(path1)
3531  self.assertTrue('a' in s.moduleNames())
3532  self.assertTrue('b' in s.moduleNames())
3533  self.assertTrue('c' in s.moduleNames())
3534  p.path1 = path1
3535  p.schedule = s
3536  p.prune()
3537  self.assertTrue('a' in s.moduleNames())
3538  self.assertTrue('b' in s.moduleNames())
3539  self.assertTrue('c' in s.moduleNames())
3540 
3542  p = Process("test")
3543  p.a = EDAnalyzer("MyAnalyzer")
3544  p.b = EDAnalyzer("YourAnalyzer")
3545  p.c = EDAnalyzer("OurAnalyzer")
3546  p.path1 = Path(p.a)
3547  p.path2 = Path(p.b)
3548  self.assertTrue(p.schedule is None)
3549  pths = p.paths
3550  keys = pths.keys()
3551  self.assertEqual(pths[keys[0]],p.path1)
3552  self.assertEqual(pths[keys[1]],p.path2)
3553  p.prune()
3554  self.assertTrue(hasattr(p, 'a'))
3555  self.assertTrue(hasattr(p, 'b'))
3556  self.assertTrue(not hasattr(p, 'c'))
3557  self.assertTrue(hasattr(p, 'path1'))
3558  self.assertTrue(hasattr(p, 'path2'))
3559 
3560 
3561  p = Process("test")
3562  p.a = EDAnalyzer("MyAnalyzer")
3563  p.b = EDAnalyzer("YourAnalyzer")
3564  p.c = EDAnalyzer("OurAnalyzer")
3565  p.path2 = Path(p.b)
3566  p.path1 = Path(p.a)
3567  self.assertTrue(p.schedule is None)
3568  pths = p.paths
3569  keys = pths.keys()
3570  self.assertEqual(pths[keys[1]],p.path1)
3571  self.assertEqual(pths[keys[0]],p.path2)
3572 
3573 
3574  def testUsing(self):
3575  p = Process('test')
3576  p.block = PSet(a = int32(1))
3577  p.modu = EDAnalyzer('Analyzer', p.block, b = int32(2))
3578  self.assertEqual(p.modu.a.value(),1)
3579  self.assertEqual(p.modu.b.value(),2)
3580 
3581  def testOverride(self):
3582  p = Process('test')
3583  a = EDProducer("A", a1=int32(0))
3584  self.assertTrue(not a.isModified())
3585  a.a1 = 1
3586  self.assertTrue(a.isModified())
3587  p.a = a
3588  self.assertEqual(p.a.a1.value(), 1)
3589  # try adding an unmodified module.
3590  # should accept it
3591  p.a = EDProducer("A", a1=int32(2))
3592  self.assertEqual(p.a.a1.value(), 2)
3593  # try adding a modified module. Should throw
3594  # no longer, since the same (modified) say, geometry
3595  # could come from more than one cff
3596  b = EDProducer("A", a1=int32(3))
3597  b.a1 = 4
3598  #self.assertRaises(RuntimeError, setattr, *(p,'a',b))
3599  ps1 = PSet(a = int32(1))
3600  ps2 = PSet(a = int32(2))
3601  self.assertRaises(ValueError, EDProducer, 'C', ps1, ps2)
3602  self.assertRaises(ValueError, EDProducer, 'C', ps1, a=int32(3))
3603 
3604  def testOptions(self):
3605  p = Process('test')
3606  self.assertEqual(p.options.numberOfThreads.value(),1)
3607  p.options.numberOfThreads = 8
3608  self.assertEqual(p.options.numberOfThreads.value(),8)
3609  p.options = PSet()
3610  self.assertEqual(p.options.numberOfThreads.value(),1)
3611  p.options = dict(numberOfStreams =2,
3612  numberOfThreads =2)
3613  self.assertEqual(p.options.numberOfThreads.value(),2)
3614  self.assertEqual(p.options.numberOfStreams.value(),2)
3615  del p.options
3616  self.assertRaises(TypeError, setattr, p, 'options', untracked.PSet(numberOfThreads = int32(-1)))
3617  p.options = untracked.PSet(numberOfThreads = untracked.uint32(4))
3618  self.assertEqual(p.options.numberOfThreads.value(), 4)
3619 
3620  def testMaxEvents(self):
3621  p = Process("Test")
3622  p.maxEvents.input = 10
3623  self.assertEqual(p.maxEvents.input.value(),10)
3624  p = Process("Test")
3625  p.maxEvents.output = 10
3626  self.assertEqual(p.maxEvents.output.value(),10)
3627  p = Process("Test")
3628  p.maxEvents.output = PSet(out=untracked.int32(10))
3629  self.assertEqual(p.maxEvents.output.out.value(), 10)
3630  p = Process("Test")
3631  p.maxEvents = untracked.PSet(input = untracked.int32(5))
3632  self.assertEqual(p.maxEvents.input.value(), 5)
3633  del p.maxEvents
3634  self.assertRaises(TypeError, setattr, p, 'maxEvents', untracked.PSet(input = untracked.uint32(1)))
3635  p.maxEvents = untracked.PSet(input = untracked.int32(1))
3636  self.assertEqual(p.maxEvents.input.value(), 1)
3637 
3638  def testExamples(self):
3639  p = Process("Test")
3640  p.source = Source("PoolSource",fileNames = untracked(string("file:reco.root")))
3641  p.foos = EDProducer("FooProducer")
3642  p.bars = EDProducer("BarProducer", foos=InputTag("foos"))
3643  p.out = OutputModule("PoolOutputModule",fileName=untracked(string("file:foos.root")))
3644  p.bars.foos = 'Foosball'
3645  self.assertEqual(p.bars.foos, InputTag('Foosball'))
3646  p.p = Path(p.foos*p.bars)
3647  p.e = EndPath(p.out)
3648  p.add_(Service("MessageLogger"))
3649 
3650  def testPrefers(self):
3651  p = Process("Test")
3652  p.add_(ESSource("ForceSource"))
3653  p.juicer = ESProducer("JuicerProducer")
3654  p.prefer("ForceSource")
3655  p.prefer("juicer")
3656  self.assertEqual(_lineDiff(p.dumpPython(), Process('Test').dumpPython()),
3657 """process.juicer = cms.ESProducer("JuicerProducer")
3658 process.ForceSource = cms.ESSource("ForceSource")
3659 process.prefer("ForceSource")
3660 process.prefer("juicer")""")
3661  p.prefer("juicer",fooRcd=vstring("Foo"))
3662  self.assertEqual(_lineDiff(p.dumpPython(), Process('Test').dumpPython()),
3663 """process.juicer = cms.ESProducer("JuicerProducer")
3664 process.ForceSource = cms.ESSource("ForceSource")
3665 process.prefer("ForceSource")
3666 process.prefer("juicer",
3667  fooRcd = cms.vstring('Foo')
3668 )""")
3669 
3670  def testFreeze(self):
3671  process = Process("Freeze")
3672  m = EDProducer("M", p=PSet(i = int32(1)))
3673  m.p.i = 2
3674  process.m = m
3675  # should be frozen
3676  #self.assertRaises(ValueError, setattr, m.p, 'i', 3)
3677  #self.assertRaises(ValueError, setattr, m, 'p', PSet(i=int32(1)))
3678  #self.assertRaises(ValueError, setattr, m.p, 'j', 1)
3679  #self.assertRaises(ValueError, setattr, m, 'j', 1)
3680  # But OK to change through the process
3681  process.m.p.i = 4
3682  self.assertEqual(process.m.p.i.value(), 4)
3683  process.m.p = PSet(j=int32(1))
3684  # should work to clone it, though
3685  m2 = m.clone(p = PSet(i = int32(5)), j = int32(8))
3686  m2.p.i = 6
3687  m2.j = 8
3688  def testSubProcess(self):
3689  process = Process("Parent")
3690  subProcess = Process("Child")
3691  subProcess.a = EDProducer("A")
3692  subProcess.p = Path(subProcess.a)
3693  subProcess.add_(Service("Foo"))
3694  process.addSubProcess(SubProcess(subProcess))
3695  d = process.dumpPython()
3696  equalD ="""parentProcess = process
3697 process.a = cms.EDProducer("A")
3698 process.Foo = cms.Service("Foo")
3699 process.p = cms.Path(process.a)
3700 childProcess = process
3701 process = parentProcess
3702 process.addSubProcess(cms.SubProcess(process = childProcess, SelectEvents = cms.untracked.PSet(
3703 ), outputCommands = cms.untracked.vstring()))"""
3704  equalD = equalD.replace("parentProcess","parentProcess"+str(hash(process.subProcesses_()[0])))
3705  # SubProcesses are dumped before Services, so in order to
3706  # craft the dump of the Parent and Child manually the dump
3707  # of the Parent needs to be split at the MessageLogger
3708  # boundary (now when it is part of Process by default),
3709  # and insert the dump of the Child between the top part of
3710  # the Parent (before MessageLogger) and the bottom part of
3711  # the Parent (after and including MessageLogger)
3712  messageLoggerSplit = 'process.MessageLogger = cms.Service'
3713  parentDumpSplit = Process('Parent').dumpPython().split(messageLoggerSplit)
3714  childProcess = Process('Child')
3715  del childProcess.MessageLogger
3716  combinedDump = parentDumpSplit[0] + childProcess.dumpPython() + messageLoggerSplit + parentDumpSplit[1]
3717  self.assertEqual(_lineDiff(d, combinedDump), equalD)
3718  p = TestMakePSet()
3719  process.fillProcessDesc(p)
3720  self.assertEqual((True,['a']),p.values["subProcesses"][1][0].values["process"][1].values['@all_modules'])
3721  self.assertEqual((True,['p']),p.values["subProcesses"][1][0].values["process"][1].values['@paths'])
3722  self.assertEqual({'@service_type':(True,'Foo')}, p.values["subProcesses"][1][0].values["process"][1].values["services"][1][0].values)
3723  def testRefToPSet(self):
3724  proc = Process("test")
3725  proc.top = PSet(a = int32(1))
3726  proc.ref = PSet(refToPSet_ = string("top"))
3727  proc.ref2 = PSet( a = int32(1), b = PSet( refToPSet_ = string("top")))
3728  proc.ref3 = PSet(refToPSet_ = string("ref"))
3729  proc.ref4 = VPSet(PSet(refToPSet_ = string("top")),
3730  PSet(refToPSet_ = string("ref2")))
3731  p = TestMakePSet()
3732  proc.fillProcessDesc(p)
3733  self.assertEqual((True,1),p.values["ref"][1].values["a"])
3734  self.assertEqual((True,1),p.values["ref3"][1].values["a"])
3735  self.assertEqual((True,1),p.values["ref2"][1].values["a"])
3736  self.assertEqual((True,1),p.values["ref2"][1].values["b"][1].values["a"])
3737  self.assertEqual((True,1),p.values["ref4"][1][0].values["a"])
3738  self.assertEqual((True,1),p.values["ref4"][1][1].values["a"])
3740  proc = Process("test")
3741  proc.sp = SwitchProducerTest(test2 = EDProducer("Foo",
3742  a = int32(1),
3743  b = PSet(c = int32(2))),
3744  test1 = EDProducer("Bar",
3745  aa = int32(11),
3746  bb = PSet(cc = int32(12))))
3747  self.assertEqual(proc.sp.label_(), "sp")
3748  self.assertEqual(proc.sp.test1.label_(), "sp@test1")
3749  self.assertEqual(proc.sp.test2.label_(), "sp@test2")
3750 
3751  proc.a = EDProducer("A")
3752  proc.s = Sequence(proc.a + proc.sp)
3753  proc.t = Task(proc.a, proc.sp)
3754  proc.p = Path()
3755  proc.p.associate(proc.t)
3756  p = TestMakePSet()
3757  proc.fillProcessDesc(p)
3758  self.assertEqual((True,"EDProducer"), p.values["sp"][1].values["@module_edm_type"])
3759  self.assertEqual((True, "SwitchProducer"), p.values["sp"][1].values["@module_type"])
3760  self.assertEqual((True, "sp"), p.values["sp"][1].values["@module_label"])
3761  all_cases = copy.deepcopy(p.values["sp"][1].values["@all_cases"])
3762  all_cases[1].sort() # names of all cases come via dict, i.e. their order is undefined
3763  self.assertEqual((True, ["sp@test1", "sp@test2"]), all_cases)
3764  self.assertEqual((False, "sp@test2"), p.values["sp"][1].values["@chosen_case"])
3765  self.assertEqual(["a", "sp", "sp@test1", "sp@test2"], p.values["@all_modules"][1])
3766  self.assertEqual((True,"EDProducer"), p.values["sp@test1"][1].values["@module_edm_type"])
3767  self.assertEqual((True,"Bar"), p.values["sp@test1"][1].values["@module_type"])
3768  self.assertEqual((True,"EDProducer"), p.values["sp@test2"][1].values["@module_edm_type"])
3769  self.assertEqual((True,"Foo"), p.values["sp@test2"][1].values["@module_type"])
3770  dump = proc.dumpPython()
3771  self.assertEqual(dump.find('@'), -1)
3772  self.assertEqual(specialImportRegistry.getSpecialImports(), ["from test import SwitchProducerTest"])
3773  self.assertTrue(dump.find("\nfrom test import SwitchProducerTest\n") != -1)
3774 
3775  # EDAlias as non-chosen case
3776  proc = Process("test")
3777  proc.sp = SwitchProducerTest(test2 = EDProducer("Foo",
3778  a = int32(1),
3779  b = PSet(c = int32(2))),
3780  test1 = EDAlias(a = VPSet(PSet(type = string("Bar")))))
3781  proc.a = EDProducer("A")
3782  proc.s = Sequence(proc.a + proc.sp)
3783  proc.t = Task(proc.a, proc.sp)
3784  proc.p = Path()
3785  proc.p.associate(proc.t)
3786  p = TestMakePSet()
3787  proc.fillProcessDesc(p)
3788  self.assertEqual((True,"EDProducer"), p.values["sp"][1].values["@module_edm_type"])
3789  self.assertEqual((True, "SwitchProducer"), p.values["sp"][1].values["@module_type"])
3790  self.assertEqual((True, "sp"), p.values["sp"][1].values["@module_label"])
3791  all_cases = copy.deepcopy(p.values["sp"][1].values["@all_cases"])
3792  all_cases[1].sort()
3793  self.assertEqual((True, ["sp@test1", "sp@test2"]), all_cases)
3794  self.assertEqual((False, "sp@test2"), p.values["sp"][1].values["@chosen_case"])
3795  self.assertEqual(["a", "sp", "sp@test2"], p.values["@all_modules"][1])
3796  self.assertEqual(["sp@test1"], p.values["@all_aliases"][1])
3797  self.assertEqual((True,"EDProducer"), p.values["sp@test2"][1].values["@module_edm_type"])
3798  self.assertEqual((True,"Foo"), p.values["sp@test2"][1].values["@module_type"])
3799  self.assertEqual((True,"EDAlias"), p.values["sp@test1"][1].values["@module_edm_type"])
3800  self.assertEqual((True,"Bar"), p.values["sp@test1"][1].values["a"][1][0].values["type"])
3801 
3802  # EDAlias as chosen case
3803  proc = Process("test")
3804  proc.sp = SwitchProducerTest(test1 = EDProducer("Foo",
3805  a = int32(1),
3806  b = PSet(c = int32(2))),
3807  test2 = EDAlias(a = VPSet(PSet(type = string("Bar")))))
3808  proc.a = EDProducer("A")
3809  proc.s = Sequence(proc.a + proc.sp)
3810  proc.t = Task(proc.a, proc.sp)
3811  proc.p = Path()
3812  proc.p.associate(proc.t)
3813  p = TestMakePSet()
3814  proc.fillProcessDesc(p)
3815  self.assertEqual((True,"EDProducer"), p.values["sp"][1].values["@module_edm_type"])
3816  self.assertEqual((True, "SwitchProducer"), p.values["sp"][1].values["@module_type"])
3817  self.assertEqual((True, "sp"), p.values["sp"][1].values["@module_label"])
3818  self.assertEqual((True, ["sp@test1", "sp@test2"]), p.values["sp"][1].values["@all_cases"])
3819  self.assertEqual((False, "sp@test2"), p.values["sp"][1].values["@chosen_case"])
3820  self.assertEqual(["a", "sp", "sp@test1"], p.values["@all_modules"][1])
3821  self.assertEqual(["sp@test2"], p.values["@all_aliases"][1])
3822  self.assertEqual((True,"EDProducer"), p.values["sp@test1"][1].values["@module_edm_type"])
3823  self.assertEqual((True,"Foo"), p.values["sp@test1"][1].values["@module_type"])
3824  self.assertEqual((True,"EDAlias"), p.values["sp@test2"][1].values["@module_edm_type"])
3825  self.assertEqual((True,"Bar"), p.values["sp@test2"][1].values["a"][1][0].values["type"])
3826 
3827  # ConditionalTask
3828  proc = Process("test")
3829  proc.spct = SwitchProducerTest(test2 = EDProducer("Foo",
3830  a = int32(1),
3831  b = PSet(c = int32(2))),
3832  test1 = EDProducer("Bar",
3833  aa = int32(11),
3834  bb = PSet(cc = int32(12))),
3835  test3 = EDAlias(a = VPSet(PSet(type = string("Bar")))))
3836  proc.spp = proc.spct.clone()
3837  proc.a = EDProducer("A")
3838  proc.ct = ConditionalTask(proc.spct)
3839  proc.p = Path(proc.a, proc.ct)
3840  proc.pp = Path(proc.a + proc.spp)
3841  p = TestMakePSet()
3842  proc.fillProcessDesc(p)
3843  self.assertEqual(["a", "spct", "spct@test1", "spct@test2", "spp", "spp@test1", "spp@test2"], p.values["@all_modules"][1])
3844  self.assertEqual(["a", "#", "spct", "spct@test1", "spct@test2", "@"], p.values["p"][1])
3845  self.assertEqual(["a", "spp", "#", "spp@test1", "spp@test2", "@"], p.values["pp"][1])
3846 
3847  def testPrune(self):
3848  p = Process("test")
3849  p.a = EDAnalyzer("MyAnalyzer")
3850  p.b = EDAnalyzer("YourAnalyzer")
3851  p.c = EDAnalyzer("OurAnalyzer")
3852  p.d = EDAnalyzer("OurAnalyzer")
3853  p.e = EDProducer("MyProducer")
3854  p.f = EDProducer("YourProducer")
3855  p.g = EDProducer("TheirProducer")
3856  p.h = EDProducer("OnesProducer")
3857  p.s = Sequence(p.d)
3858  p.t1 = Task(p.e)
3859  p.t2 = Task(p.f)
3860  p.t3 = Task(p.g, p.t1)
3861  p.ct1 = ConditionalTask(p.h)
3862  p.ct2 = ConditionalTask(p.f)
3863  p.ct3 = ConditionalTask(p.ct1)
3864  p.path1 = Path(p.a, p.t3, p.ct3)
3865  p.path2 = Path(p.b)
3866  self.assertTrue(p.schedule is None)
3867  pths = p.paths
3868  keys = pths.keys()
3869  self.assertEqual(pths[keys[0]],p.path1)
3870  self.assertEqual(pths[keys[1]],p.path2)
3871  p.pset1 = PSet(parA = string("pset1"))
3872  p.pset2 = untracked.PSet(parA = string("pset2"))
3873  p.vpset1 = VPSet()
3874  p.vpset2 = untracked.VPSet()
3875  p.prune()
3876  self.assertTrue(hasattr(p, 'a'))
3877  self.assertTrue(hasattr(p, 'b'))
3878  self.assertTrue(not hasattr(p, 'c'))
3879  self.assertTrue(not hasattr(p, 'd'))
3880  self.assertTrue(hasattr(p, 'e'))
3881  self.assertTrue(not hasattr(p, 'f'))
3882  self.assertTrue(hasattr(p, 'g'))
3883  self.assertTrue(hasattr(p, 'h'))
3884  self.assertTrue(not hasattr(p, 's'))
3885  self.assertTrue(hasattr(p, 't1'))
3886  self.assertTrue(not hasattr(p, 't2'))
3887  self.assertTrue(hasattr(p, 't3'))
3888  self.assertTrue(hasattr(p, 'path1'))
3889  self.assertTrue(hasattr(p, 'path2'))
3890 # self.assertTrue(not hasattr(p, 'pset1'))
3891 # self.assertTrue(hasattr(p, 'pset2'))
3892 # self.assertTrue(not hasattr(p, 'vpset1'))
3893 # self.assertTrue(not hasattr(p, 'vpset2'))
3894 
3895  p = Process("test")
3896  p.a = EDAnalyzer("MyAnalyzer")
3897  p.b = EDAnalyzer("YourAnalyzer")
3898  p.c = EDAnalyzer("OurAnalyzer")
3899  p.d = EDAnalyzer("OurAnalyzer")
3900  p.e = EDAnalyzer("OurAnalyzer")
3901  p.f = EDProducer("MyProducer")
3902  p.g = EDProducer("YourProducer")
3903  p.h = EDProducer("TheirProducer")
3904  p.i = EDProducer("OurProducer")
3905  p.j = EDProducer("OurProducer")
3906  p.k = EDProducer("OurProducer")
3907  p.l = EDProducer("OurProducer")
3908  p.t1 = Task(p.f)
3909  p.t2 = Task(p.g)
3910  p.t3 = Task(p.h)
3911  p.t4 = Task(p.i)
3912  p.ct1 = Task(p.f)
3913  p.ct2 = Task(p.j)
3914  p.ct3 = Task(p.k)
3915  p.ct4 = Task(p.l)
3916  p.s = Sequence(p.d, p.t1, p.ct1)
3917  p.s2 = Sequence(p.b, p.t2, p.ct2)
3918  p.s3 = Sequence(p.e)
3919  p.path1 = Path(p.a, p.t3, p.ct3)
3920  p.path2 = Path(p.b)
3921  p.path3 = Path(p.b+p.s2)
3922  p.path4 = Path(p.b+p.s3)
3923  p.schedule = Schedule(p.path1,p.path2,p.path3)
3924  p.schedule.associate(p.t4)
3925  pths = p.paths
3926  keys = pths.keys()
3927  self.assertEqual(pths[keys[0]],p.path1)
3928  self.assertEqual(pths[keys[1]],p.path2)
3929  p.prune()
3930  self.assertTrue(hasattr(p, 'a'))
3931  self.assertTrue(hasattr(p, 'b'))
3932  self.assertTrue(not hasattr(p, 'c'))
3933  self.assertTrue(not hasattr(p, 'd'))
3934  self.assertTrue(not hasattr(p, 'e'))
3935  self.assertTrue(not hasattr(p, 'f'))
3936  self.assertTrue(hasattr(p, 'g'))
3937  self.assertTrue(hasattr(p, 'h'))
3938  self.assertTrue(hasattr(p, 'i'))
3939  self.assertTrue(hasattr(p, 'j'))
3940  self.assertTrue(hasattr(p, 'k'))
3941  self.assertTrue(not hasattr(p, 'l'))
3942  self.assertTrue(not hasattr(p, 't1'))
3943  self.assertTrue(hasattr(p, 't2'))
3944  self.assertTrue(hasattr(p, 't3'))
3945  self.assertTrue(hasattr(p, 't4'))
3946  self.assertTrue(not hasattr(p, 'ct1'))
3947  self.assertTrue(hasattr(p, 'ct2'))
3948  self.assertTrue(hasattr(p, 'ct3'))
3949  self.assertTrue(not hasattr(p, 'ct4'))
3950  self.assertTrue(not hasattr(p, 's'))
3951  self.assertTrue(hasattr(p, 's2'))
3952  self.assertTrue(not hasattr(p, 's3'))
3953  self.assertTrue(hasattr(p, 'path1'))
3954  self.assertTrue(hasattr(p, 'path2'))
3955  self.assertTrue(hasattr(p, 'path3'))
3956  self.assertTrue(not hasattr(p, 'path4'))
3957  #test SequencePlaceholder
3958  p = Process("test")
3959  p.a = EDAnalyzer("MyAnalyzer")
3960  p.b = EDAnalyzer("YourAnalyzer")
3961  p.s = Sequence(SequencePlaceholder("a")+p.b)
3962  p.pth = Path(p.s)
3963  p.prune()
3964  self.assertTrue(hasattr(p, 'a'))
3965  self.assertTrue(hasattr(p, 'b'))
3966  self.assertTrue(hasattr(p, 's'))
3967  self.assertTrue(hasattr(p, 'pth'))
3968  #test unresolved SequencePlaceholder
3969  p = Process("test")
3970  p.b = EDAnalyzer("YourAnalyzer")
3971  p.s = Sequence(SequencePlaceholder("a")+p.b)
3972  p.pth = Path(p.s)
3973  p.prune(keepUnresolvedSequencePlaceholders=True)
3974  self.assertTrue(hasattr(p, 'b'))
3975  self.assertTrue(hasattr(p, 's'))
3976  self.assertTrue(hasattr(p, 'pth'))
3977  self.assertEqual(p.s.dumpPython(),'cms.Sequence(cms.SequencePlaceholder("a")+process.b)\n')
3978  #test TaskPlaceholder
3979  p = Process("test")
3980  p.a = EDProducer("MyProducer")
3981  p.b = EDProducer("YourProducer")
3982  p.s = Task(TaskPlaceholder("a"),p.b)
3983  p.pth = Path(p.s)
3984  p.prune()
3985  self.assertTrue(hasattr(p, 'a'))
3986  self.assertTrue(hasattr(p, 'b'))
3987  self.assertTrue(hasattr(p, 's'))
3988  self.assertTrue(hasattr(p, 'pth'))
3989  #test ConditionalTaskPlaceholder
3990  p = Process("test")
3991  p.a = EDProducer("MyProducer")
3992  p.b = EDProducer("YourProducer")
3994  p.pth = Path(p.s)
3995  p.prune()
3996  self.assertTrue(hasattr(p, 'a'))
3997  self.assertTrue(hasattr(p, 'b'))
3998  self.assertTrue(hasattr(p, 's'))
3999  self.assertTrue(hasattr(p, 'pth'))
4000  #test unresolved SequencePlaceholder
4001  p = Process("test")
4002  p.b = EDProducer("YourAnalyzer")
4003  p.s = Task(TaskPlaceholder("a"),p.b)
4004  p.pth = Path(p.s)
4005  p.prune(keepUnresolvedSequencePlaceholders=True)
4006  self.assertTrue(hasattr(p, 'b'))
4007  self.assertTrue(hasattr(p, 's'))
4008  self.assertTrue(hasattr(p, 'pth'))
4009  self.assertEqual(p.s.dumpPython(),'cms.Task(cms.TaskPlaceholder("a"), process.b)\n')
4011  p = Process("test")
4012  p.a = EDProducer("ma")
4013  p.b = EDAnalyzer("mb")
4014  p.t1 = Task(TaskPlaceholder("c"))
4015  p.t2 = Task(p.a, TaskPlaceholder("d"), p.t1)
4016  p.t3 = Task(TaskPlaceholder("e"))
4017  p.path1 = Path(p.b, p.t2, p.t3)
4018  p.t5 = Task(p.a, TaskPlaceholder("g"), TaskPlaceholder("t4"))
4019  p.t4 = Task(TaskPlaceholder("f"))
4020  p.endpath1 = EndPath(p.b, p.t5)
4021  p.t6 = Task(TaskPlaceholder("h"))
4022  p.t7 = Task(p.a, TaskPlaceholder("i"), p.t6)
4023  p.t8 = Task(TaskPlaceholder("j"))
4024  p.schedule = Schedule(p.path1, p.endpath1,tasks=[p.t7,p.t8])
4025  p.c = EDProducer("mc")
4026  p.d = EDProducer("md")
4027  p.e = EDProducer("me")
4028  p.f = EDProducer("mf")
4029  p.g = EDProducer("mg")
4030  p.h = EDProducer("mh")
4031  p.i = EDProducer("mi")
4032  p.j = EDProducer("mj")
4033  self.assertEqual(_lineDiff(p.dumpPython(),Process('test').dumpPython()),
4034 """process.a = cms.EDProducer("ma")
4035 process.c = cms.EDProducer("mc")
4036 process.d = cms.EDProducer("md")
4037 process.e = cms.EDProducer("me")
4038 process.f = cms.EDProducer("mf")
4039 process.g = cms.EDProducer("mg")
4040 process.h = cms.EDProducer("mh")
4041 process.i = cms.EDProducer("mi")
4042 process.j = cms.EDProducer("mj")
4043 process.b = cms.EDAnalyzer("mb")
4044 process.t1 = cms.Task(cms.TaskPlaceholder("c"))
4045 process.t2 = cms.Task(cms.TaskPlaceholder("d"), process.a, process.t1)
4046 process.t3 = cms.Task(cms.TaskPlaceholder("e"))
4047 process.t5 = cms.Task(cms.TaskPlaceholder("g"), cms.TaskPlaceholder("t4"), process.a)
4048 process.t4 = cms.Task(cms.TaskPlaceholder("f"))
4049 process.t6 = cms.Task(cms.TaskPlaceholder("h"))
4050 process.t7 = cms.Task(cms.TaskPlaceholder("i"), process.a, process.t6)
4051 process.t8 = cms.Task(cms.TaskPlaceholder("j"))
4052 process.path1 = cms.Path(process.b, process.t2, process.t3)
4053 process.endpath1 = cms.EndPath(process.b, process.t5)
4054 process.schedule = cms.Schedule(*[ process.path1, process.endpath1 ], tasks=[process.t7, process.t8])""")
4055  p.resolve()
4056  self.assertEqual(_lineDiff(p.dumpPython(),Process('test').dumpPython()),
4057 """process.a = cms.EDProducer("ma")
4058 process.c = cms.EDProducer("mc")
4059 process.d = cms.EDProducer("md")
4060 process.e = cms.EDProducer("me")
4061 process.f = cms.EDProducer("mf")
4062 process.g = cms.EDProducer("mg")
4063 process.h = cms.EDProducer("mh")
4064 process.i = cms.EDProducer("mi")
4065 process.j = cms.EDProducer("mj")
4066 process.b = cms.EDAnalyzer("mb")
4067 process.t1 = cms.Task(process.c)
4068 process.t2 = cms.Task(process.a, process.d, process.t1)
4069 process.t3 = cms.Task(process.e)
4070 process.t4 = cms.Task(process.f)
4071 process.t6 = cms.Task(process.h)
4072 process.t7 = cms.Task(process.a, process.i, process.t6)
4073 process.t8 = cms.Task(process.j)
4074 process.t5 = cms.Task(process.a, process.g, process.t4)
4075 process.path1 = cms.Path(process.b, process.t2, process.t3)
4076 process.endpath1 = cms.EndPath(process.b, process.t5)
4077 process.schedule = cms.Schedule(*[ process.path1, process.endpath1 ], tasks=[process.t7, process.t8])""")
4079  p = Process("test")
4080  p.a = EDProducer("ma")
4081  p.b = EDAnalyzer("mb")
4083  p.t2 = ConditionalTask(p.a, ConditionalTaskPlaceholder("d"), p.t1)
4085  p.path1 = Path(p.b, p.t2, p.t3)
4088  p.path2 = Path(p.b, p.t5)
4089  p.schedule = Schedule(p.path1, p.path2)
4090  p.c = EDProducer("mc")
4091  p.d = EDProducer("md")
4092  p.e = EDProducer("me")
4093  p.f = EDProducer("mf")
4094  p.g = EDProducer("mg")
4095  p.h = EDProducer("mh")
4096  p.i = EDProducer("mi")
4097  p.j = EDProducer("mj")
4098  self.assertEqual(_lineDiff(p.dumpPython(),Process('test').dumpPython()),
4099 """process.a = cms.EDProducer("ma")
4100 process.c = cms.EDProducer("mc")
4101 process.d = cms.EDProducer("md")
4102 process.e = cms.EDProducer("me")
4103 process.f = cms.EDProducer("mf")
4104 process.g = cms.EDProducer("mg")
4105 process.h = cms.EDProducer("mh")
4106 process.i = cms.EDProducer("mi")
4107 process.j = cms.EDProducer("mj")
4108 process.b = cms.EDAnalyzer("mb")
4109 process.t1 = cms.ConditionalTask(cms.ConditionalTaskPlaceholder("c"))
4110 process.t2 = cms.ConditionalTask(cms.ConditionalTaskPlaceholder("d"), process.a, process.t1)
4111 process.t3 = cms.ConditionalTask(cms.ConditionalTaskPlaceholder("e"))
4112 process.t5 = cms.ConditionalTask(cms.ConditionalTaskPlaceholder("g"), cms.ConditionalTaskPlaceholder("t4"), process.a)
4113 process.t4 = cms.ConditionalTask(cms.ConditionalTaskPlaceholder("f"))
4114 process.path1 = cms.Path(process.b, process.t2, process.t3)
4115 process.path2 = cms.Path(process.b, process.t5)
4116 process.schedule = cms.Schedule(*[ process.path1, process.path2 ])""")
4117  p.resolve()
4118  self.assertEqual(_lineDiff(p.dumpPython(),Process('test').dumpPython()),
4119 """process.a = cms.EDProducer("ma")
4120 process.c = cms.EDProducer("mc")
4121 process.d = cms.EDProducer("md")
4122 process.e = cms.EDProducer("me")
4123 process.f = cms.EDProducer("mf")
4124 process.g = cms.EDProducer("mg")
4125 process.h = cms.EDProducer("mh")
4126 process.i = cms.EDProducer("mi")
4127 process.j = cms.EDProducer("mj")
4128 process.b = cms.EDAnalyzer("mb")
4129 process.t1 = cms.ConditionalTask(process.c)
4130 process.t2 = cms.ConditionalTask(process.a, process.d, process.t1)
4131 process.t3 = cms.ConditionalTask(process.e)
4132 process.t4 = cms.ConditionalTask(process.f)
4133 process.t5 = cms.ConditionalTask(process.a, process.g, process.t4)
4134 process.path1 = cms.Path(process.b, process.t2, process.t3)
4135 process.path2 = cms.Path(process.b, process.t5)
4136 process.schedule = cms.Schedule(*[ process.path1, process.path2 ])""")
4137 
4138  def testDelete(self):
4139  p = Process("test")
4140  p.a = EDAnalyzer("MyAnalyzer")
4141  p.b = EDAnalyzer("YourAnalyzer")
4142  p.c = EDAnalyzer("OurAnalyzer")
4143  p.d = EDAnalyzer("OurAnalyzer")
4144  p.e = EDAnalyzer("OurAnalyzer")
4145  p.f = EDAnalyzer("OurAnalyzer")
4146  p.g = EDProducer("OurProducer")
4147  p.h = EDProducer("YourProducer")
4148  p.i = SwitchProducerTest(
4149  test1 = EDProducer("OneProducer"),
4150  test2 = EDProducer("TwoProducer")
4151  )
4152  p.t1 = Task(p.g, p.h, p.i)
4153  t2 = Task(p.g, p.h, p.i)
4154  t3 = Task(p.g, p.h)
4155  p.t4 = Task(p.h)
4156  p.ct1 = ConditionalTask(p.g, p.h, p.i)
4157  ct2 = ConditionalTask(p.g, p.h)
4158  ct3 = ConditionalTask(p.g, p.h)
4159  p.ct4 = ConditionalTask(p.h)
4160  p.s = Sequence(p.d+p.e)
4161  p.path1 = Path(p.a+p.f+p.s,t2,ct2)
4162  p.path2 = Path(p.a)
4163  p.path3 = Path(ct3, p.ct4)
4164  p.endpath2 = EndPath(p.b)
4165  p.endpath1 = EndPath(p.b+p.f)
4166  p.schedule = Schedule(p.path2, p.path3, p.endpath2, tasks=[t3, p.t4])
4167  self.assertTrue(hasattr(p, 'f'))
4168  self.assertTrue(hasattr(p, 'g'))
4169  self.assertTrue(hasattr(p, 'i'))
4170  del p.e
4171  del p.f
4172  del p.g
4173  del p.i
4174  self.assertFalse(hasattr(p, 'f'))
4175  self.assertFalse(hasattr(p, 'g'))
4176  self.assertEqual(p.t1.dumpPython(), 'cms.Task(process.h)\n')
4177  self.assertEqual(p.ct1.dumpPython(), 'cms.ConditionalTask(process.h)\n')
4178  self.assertEqual(p.s.dumpPython(), 'cms.Sequence(process.d)\n')
4179  self.assertEqual(p.path1.dumpPython(), 'cms.Path(process.a+process.s, cms.ConditionalTask(process.h), cms.Task(process.h))\n')
4180  self.assertEqual(p.endpath1.dumpPython(), 'cms.EndPath(process.b)\n')
4181  self.assertEqual(p.path3.dumpPython(), 'cms.Path(cms.ConditionalTask(process.h), process.ct4)\n')
4182  del p.s
4183  self.assertEqual(p.path1.dumpPython(), 'cms.Path(process.a+(process.d), cms.ConditionalTask(process.h), cms.Task(process.h))\n')
4184  self.assertEqual(p.schedule_().dumpPython(), 'cms.Schedule(*[ process.path2, process.path3, process.endpath2 ], tasks=[cms.Task(process.h), process.t4])\n')
4185  del p.path2
4186  self.assertEqual(p.schedule_().dumpPython(), 'cms.Schedule(*[ process.path3, process.endpath2 ], tasks=[cms.Task(process.h), process.t4])\n')
4187  del p.path3
4188  self.assertEqual(p.schedule_().dumpPython(), 'cms.Schedule(*[ process.endpath2 ], tasks=[cms.Task(process.h), process.t4])\n')
4189  del p.endpath2
4190  self.assertEqual(p.schedule_().dumpPython(), 'cms.Schedule(tasks=[cms.Task(process.h), process.t4])\n')
4191  del p.t4
4192  self.assertEqual(p.schedule_().dumpPython(), 'cms.Schedule(tasks=[cms.Task(process.h)])\n')
4193  def testModifier(self):
4194  m1 = Modifier()
4195  Process._firstProcess = True
4196  p = Process("test")
4197  self.assertRaises(RuntimeError, lambda: Process("test2", m1))
4198  m1 = Modifier()
4199  Process._firstProcess = True
4200  p = Process("test",m1)
4201  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1))
4202  def _mod_fred(obj):
4203  obj.fred = 2
4204  m1.toModify(p.a,_mod_fred)
4205  self.assertEqual(p.a.fred.value(),2)
4206  p.b = EDAnalyzer("YourAnalyzer", wilma = int32(1))
4207  m1.toModify(p.b, wilma = 2)
4208  self.assertEqual(p.b.wilma.value(),2)
4209  self.assertTrue(p.isUsingModifier(m1))
4210  #check that Modifier not attached to a process doesn't run
4211  m1 = Modifier()
4212  Process._firstProcess = True
4213  p = Process("test")
4214  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1))
4215  m1.toModify(p.a,_mod_fred)
4216  p.b = EDAnalyzer("YourAnalyzer", wilma = int32(1))
4217  m1.toModify(p.b, wilma = 2)
4218  self.assertEqual(p.a.fred.value(),1)
4219  self.assertEqual(p.b.wilma.value(),1)
4220  self.assertEqual(p.isUsingModifier(m1),False)
4221  #make sure clones get the changes
4222  m1 = Modifier()
4223  Process._firstProcess = True
4224  p = Process("test",m1)
4225  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
4226  m1.toModify(p.a, fred = int32(2))
4227  p.b = p.a.clone(wilma = int32(3))
4228  self.assertEqual(p.a.fred.value(),2)
4229  self.assertEqual(p.a.wilma.value(),1)
4230  self.assertEqual(p.b.fred.value(),2)
4231  self.assertEqual(p.b.wilma.value(),3)
4232  #test removal of parameter
4233  m1 = Modifier()
4234  Process._firstProcess = True
4235  p = Process("test",m1)
4236  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1), fintstones = PSet(fred = int32(1)))
4237  m1.toModify(p.a, fred = None, fintstones = dict(fred = None))
4238  self.assertEqual(hasattr(p.a, "fred"), False)
4239  self.assertEqual(hasattr(p.a.fintstones, "fred"), False)
4240  self.assertEqual(p.a.wilma.value(),1)
4241  #test adding a parameter
4242  m1 = Modifier()
4243  Process._firstProcess = True
4244  p = Process("test",m1)
4245  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1))
4246  m1.toModify(p.a, wilma = int32(2))
4247  self.assertEqual(p.a.fred.value(), 1)
4248  self.assertEqual(p.a.wilma.value(),2)
4249  #test setting of value in PSet
4250  m1 = Modifier()
4251  Process._firstProcess = True
4252  p = Process("test",m1)
4253  p.a = EDAnalyzer("MyAnalyzer", flintstones = PSet(fred = int32(1), wilma = int32(1)))
4254  m1.toModify(p.a, flintstones = dict(fred = int32(2)))
4255  self.assertEqual(p.a.flintstones.fred.value(),2)
4256  self.assertEqual(p.a.flintstones.wilma.value(),1)
4257  #test proper exception from nonexisting parameter name
4258  m1 = Modifier()
4259  Process._firstProcess = True
4260  p = Process("test",m1)
4261  p.a = EDAnalyzer("MyAnalyzer", flintstones = PSet(fred = PSet(wilma = int32(1))))
4262  self.assertRaises(KeyError, lambda: m1.toModify(p.a, flintstones = dict(imnothere = dict(wilma=2))))
4263  self.assertRaises(KeyError, lambda: m1.toModify(p.a, foo = 1))
4264  #test setting a value in a VPSet
4265  m1 = Modifier()
4266  Process._firstProcess = True
4267  p = Process("test",m1)
4268  p.a = EDAnalyzer("MyAnalyzer", flintstones = VPSet(PSet(fred = int32(1)), PSet(wilma = int32(1))))
4269  m1.toModify(p.a, flintstones = {1:dict(wilma = int32(2))})
4270  self.assertEqual(p.a.flintstones[0].fred.value(),1)
4271  self.assertEqual(p.a.flintstones[1].wilma.value(),2)
4272  #test setting a value in a list of values
4273  m1 = Modifier()
4274  Process._firstProcess = True
4275  p = Process("test",m1)
4276  p.a = EDAnalyzer("MyAnalyzer", fred = vuint32(1,2,3))
4277  m1.toModify(p.a, fred = {1:7})
4278  self.assertEqual(p.a.fred[0],1)
4279  self.assertEqual(p.a.fred[1],7)
4280  self.assertEqual(p.a.fred[2],3)
4281  #test IndexError setting a value in a list to an item key not in the list
4282  m1 = Modifier()
4283  Process._firstProcess = True
4284  p = Process("test",m1)
4285  p.a = EDAnalyzer("MyAnalyzer", fred = vuint32(1,2,3))
4286  raised = False
4287  try: m1.toModify(p.a, fred = {5:7})
4288  except IndexError as e: raised = True
4289  self.assertEqual(raised, True)
4290  #test TypeError setting a value in a list using a key that is not an int
4291  m1 = Modifier()
4292  Process._firstProcess = True
4293  p = Process("test",m1)
4294  p.a = EDAnalyzer("MyAnalyzer", flintstones = VPSet(PSet(fred = int32(1)), PSet(wilma = int32(1))))
4295  raised = False
4296  try: m1.toModify(p.a, flintstones = dict(bogus = int32(37)))
4297  except TypeError as e: raised = True
4298  self.assertEqual(raised, True)
4299  #test that load causes process wide methods to run
4300  def _rem_a(proc):
4301  del proc.a
4302  class ProcModifierMod(object):
4303  def __init__(self,modifier,func):
4304  self.proc_mod_ = modifier.makeProcessModifier(func)
4305  class DummyMod(object):
4306  def __init__(self):
4307  self.a = EDAnalyzer("Dummy")
4308  testMod = DummyMod()
4309  p.extend(testMod)
4310  self.assertTrue(hasattr(p,"a"))
4311  m1 = Modifier()
4312  Process._firstProcess = True
4313  p = Process("test",m1)
4314  testProcMod = ProcModifierMod(m1,_rem_a)
4315  p.extend(testMod)
4316  p.extend(testProcMod)
4317  self.assertTrue(not hasattr(p,"a"))
4318  #test ModifierChain
4319  m1 = Modifier()
4320  mc = ModifierChain(m1)
4321  Process._firstProcess = True
4322  p = Process("test",mc)
4323  self.assertTrue(p.isUsingModifier(m1))
4324  self.assertTrue(p.isUsingModifier(mc))
4325  testMod = DummyMod()
4326  p.b = EDAnalyzer("Dummy2", fred = int32(1))
4327  m1.toModify(p.b, fred = int32(3))
4328  p.extend(testMod)
4329  testProcMod = ProcModifierMod(m1,_rem_a)
4330  p.extend(testProcMod)
4331  self.assertTrue(not hasattr(p,"a"))
4332  self.assertEqual(p.b.fred.value(),3)
4333  #check cloneAndExclude
4334  m1 = Modifier()
4335  m2 = Modifier()
4336  mc = ModifierChain(m1,m2)
4337  mclone = mc.copyAndExclude([m2])
4338  self.assertTrue(not mclone._isOrContains(m2))
4339  self.assertTrue(mclone._isOrContains(m1))
4340  m3 = Modifier()
4341  mc2 = ModifierChain(mc,m3)
4342  mclone = mc2.copyAndExclude([m2])
4343  self.assertTrue(not mclone._isOrContains(m2))
4344  self.assertTrue(mclone._isOrContains(m1))
4345  self.assertTrue(mclone._isOrContains(m3))
4346  #check combining
4347  m1 = Modifier()
4348  m2 = Modifier()
4349  Process._firstProcess = True
4350  p = Process("test",m1)
4351  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
4352  (m1 & m2).toModify(p.a, fred = int32(2))
4353  self.assertRaises(TypeError, lambda: (m1 & m2).toModify(p.a, 1, wilma=2))
4354  self.assertEqual(p.a.fred, 1)
4355  m1 = Modifier()
4356  m2 = Modifier()
4357  Process._firstProcess = True
4358  p = Process("test",m1,m2)
4359  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
4360  (m1 & m2).toModify(p.a, fred = int32(2))
4361  self.assertEqual(p.a.fred, 2)
4362  m1 = Modifier()
4363  m2 = Modifier()
4364  m3 = Modifier()
4365  Process._firstProcess = True
4366  p = Process("test",m1,m2,m3)
4367  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
4368  (m1 & m2 & m3).toModify(p.a, fred = int32(2))
4369  self.assertEqual(p.a.fred, 2)
4370  (m1 & (m2 & m3)).toModify(p.a, fred = int32(3))
4371  self.assertEqual(p.a.fred, 3)
4372  ((m1 & m2) & m3).toModify(p.a, fred = int32(4))
4373  self.assertEqual(p.a.fred, 4)
4374  #check inverse
4375  m1 = Modifier()
4376  m2 = Modifier()
4377  Process._firstProcess = True
4378  p = Process("test", m1)
4379  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
4380  (~m1).toModify(p.a, fred=2)
4381  self.assertEqual(p.a.fred, 1)
4382  (~m2).toModify(p.a, wilma=2)
4383  self.assertEqual(p.a.wilma, 2)
4384  self.assertRaises(TypeError, lambda: (~m1).toModify(p.a, 1, wilma=2))
4385  self.assertRaises(TypeError, lambda: (~m2).toModify(p.a, 1, wilma=2))
4386  # check or
4387  m1 = Modifier()
4388  m2 = Modifier()
4389  m3 = Modifier()
4390  Process._firstProcess = True
4391  p = Process("test", m1)
4392  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
4393  (m1 | m2).toModify(p.a, fred=2)
4394  self.assertEqual(p.a.fred, 2)
4395  (m1 | m2 | m3).toModify(p.a, fred=3)
4396  self.assertEqual(p.a.fred, 3)
4397  (m3 | m2 | m1).toModify(p.a, fred=4)
4398  self.assertEqual(p.a.fred, 4)
4399  ((m1 | m2) | m3).toModify(p.a, fred=5)
4400  self.assertEqual(p.a.fred, 5)
4401  (m1 | (m2 | m3)).toModify(p.a, fred=6)
4402  self.assertEqual(p.a.fred, 6)
4403  (m2 | m3).toModify(p.a, fred=7)
4404  self.assertEqual(p.a.fred, 6)
4405  self.assertRaises(TypeError, lambda: (m1 | m2).toModify(p.a, 1, wilma=2))
4406  self.assertRaises(TypeError, lambda: (m2 | m3).toModify(p.a, 1, wilma=2))
4407  # check combinations
4408  m1 = Modifier()
4409  m2 = Modifier()
4410  m3 = Modifier()
4411  m4 = Modifier()
4412  Process._firstProcess = True
4413  p = Process("test", m1, m2)
4414  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
4415  (m1 & ~m2).toModify(p.a, fred=2)
4416  self.assertEqual(p.a.fred, 1)
4417  (m1 & ~m3).toModify(p.a, fred=2)
4418  self.assertEqual(p.a.fred, 2)
4419  (m1 | ~m2).toModify(p.a, fred=3)
4420  self.assertEqual(p.a.fred, 3)
4421  (~m1 | ~m2).toModify(p.a, fred=4)
4422  self.assertEqual(p.a.fred, 3)
4423  (~m3 & ~m4).toModify(p.a, fred=4)
4424  self.assertEqual(p.a.fred, 4)
4425  ((m1 & m3) | ~m4).toModify(p.a, fred=5)
4426  self.assertEqual(p.a.fred, 5)
4427  #check toReplaceWith
4428  m1 = Modifier()
4429  Process._firstProcess = True
4430  p = Process("test",m1)
4431  p.a =EDAnalyzer("MyAnalyzer", fred = int32(1))
4432  m1.toReplaceWith(p.a, EDAnalyzer("YourAnalyzer", wilma = int32(3)))
4433  self.assertRaises(TypeError, lambda: m1.toReplaceWith(p.a, EDProducer("YourProducer")))
4434  #Task
4435  p.b =EDAnalyzer("BAn")
4436  p.c =EDProducer("c")
4437  p.d =EDProducer("d")
4438  p.tc = Task(p.c)
4439  p.td = Task(p.d)
4440  p.s = Sequence(p.a, p.tc)
4441  m1.toReplaceWith(p.s, Sequence(p.a+p.b, p.td))
4442  self.assertEqual(p.a.wilma.value(),3)
4443  self.assertEqual(p.a.type_(),"YourAnalyzer")
4444  self.assertEqual(hasattr(p,"fred"),False)
4445  self.assertTrue(p.s.dumpPython() == "cms.Sequence(process.a+process.b, process.td)\n")
4446  p.e =EDProducer("e")
4447  m1.toReplaceWith(p.td, Task(p.e))
4448  self.assertTrue(p.td._collection == OrderedSet([p.e]))
4449  #ConditionalTask
4450  p.b =EDAnalyzer("BAn")
4451  p.c =EDProducer("c")
4452  p.d =EDProducer("d")
4453  del p.tc
4454  del p.td
4455  p.tc = ConditionalTask(p.c)
4456  p.td = ConditionalTask(p.d)
4457  p.s = Sequence(p.a, p.tc)
4458  m1.toReplaceWith(p.s, Sequence(p.a+p.b, p.td))
4459  self.assertEqual(p.a.wilma.value(),3)
4460  self.assertEqual(p.a.type_(),"YourAnalyzer")
4461  self.assertEqual(hasattr(p,"fred"),False)
4462  self.assertTrue(p.s.dumpPython() == "cms.Sequence(process.a+process.b, process.td)\n")
4463  p.e =EDProducer("e")
4464  m1.toReplaceWith(p.td, ConditionalTask(p.e))
4465  self.assertTrue(p.td._collection == OrderedSet([p.e]))
4466  #check toReplaceWith doesn't activate not chosen
4467  m1 = Modifier()
4468  Process._firstProcess = True
4469  p = Process("test")
4470  p.a =EDAnalyzer("MyAnalyzer", fred = int32(1))
4471  m1.toReplaceWith(p.a, EDAnalyzer("YourAnalyzer", wilma = int32(3)))
4472  self.assertEqual(p.a.type_(),"MyAnalyzer")
4473  #check toReplaceWith and and/not/or combinations
4474  m1 = Modifier()
4475  m2 = Modifier()
4476  m3 = Modifier()
4477  m4 = Modifier()
4478  Process._firstProcess = True
4479  p = Process("test", m1, m2)
4480  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
4481  self.assertRaises(TypeError, lambda: (m1 & m2).toReplaceWith(p.a, EDProducer("YourProducer")))
4482  self.assertRaises(TypeError, lambda: (m3 & m4).toReplaceWith(p.a, EDProducer("YourProducer")))
4483  self.assertRaises(TypeError, lambda: (~m3).toReplaceWith(p.a, EDProducer("YourProducer")))
4484  self.assertRaises(TypeError, lambda: (~m1).toReplaceWith(p.a, EDProducer("YourProducer")))
4485  self.assertRaises(TypeError, lambda: (m1 | m3).toReplaceWith(p.a, EDProducer("YourProducer")))
4486  self.assertRaises(TypeError, lambda: (m3 | m4).toReplaceWith(p.a, EDProducer("YourProducer")))
4487  (m1 & m2).toReplaceWith(p.a, EDAnalyzer("YourAnalyzer1"))
4488  self.assertEqual(p.a.type_(), "YourAnalyzer1")
4489  (m1 & m3).toReplaceWith(p.a, EDAnalyzer("YourAnalyzer2"))
4490  self.assertEqual(p.a.type_(), "YourAnalyzer1")
4491  (~m1).toReplaceWith(p.a, EDAnalyzer("YourAnalyzer2"))
4492  self.assertEqual(p.a.type_(), "YourAnalyzer1")
4493  (~m3).toReplaceWith(p.a, EDAnalyzer("YourAnalyzer2"))
4494  self.assertEqual(p.a.type_(), "YourAnalyzer2")
4495  (m1 | m3).toReplaceWith(p.a, EDAnalyzer("YourAnalyzer3"))
4496  self.assertEqual(p.a.type_(), "YourAnalyzer3")
4497  (m3 | m4).toReplaceWith(p.a, EDAnalyzer("YourAnalyzer4"))
4498  self.assertEqual(p.a.type_(), "YourAnalyzer3")
4499  #check chaining of toModify and toReplaceWith
4500  m1 = Modifier()
4501  m2 = Modifier()
4502  m3 = Modifier()
4503  Process._firstProcess = True
4504  p = Process("test", m1, m2)
4505  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
4506  p.b = EDProducer("MyProducer", barney = int32(1), betty = int32(1))
4507  (m1 & m2).toModify(p.a, fred = 2).toModify(p.b, betty = 3)
4508  self.assertEqual(p.a.fred, 2)
4509  self.assertEqual(p.a.wilma, 1)
4510  self.assertEqual(p.b.barney, 1)
4511  self.assertEqual(p.b.betty, 3)
4512  (m1 | m3).toModify(p.a, wilma = 4).toModify(p.b, barney = 5)
4513  self.assertEqual(p.a.fred, 2)
4514  self.assertEqual(p.a.wilma, 4)
4515  self.assertEqual(p.b.barney, 5)
4516  self.assertEqual(p.b.betty, 3)
4517  (m2 & ~m3).toReplaceWith(p.a, EDAnalyzer("YourAnalyzer")).toModify(p.b, barney = 6)
4518  self.assertEqual(p.a.type_(), "YourAnalyzer")
4519  self.assertEqual(p.b.barney, 6)
4520  self.assertEqual(p.b.betty, 3)
4521  (m1 & ~m3).toModify(p.a, param=int32(42)).toReplaceWith(p.b, EDProducer("YourProducer"))
4522  self.assertEqual(p.a.type_(), "YourAnalyzer")
4523  self.assertEqual(p.a.param, 42)
4524  self.assertEqual(p.b.type_(), "YourProducer")
4525 
4526  # EDAlias
4527  a = EDAlias(foo2 = VPSet(PSet(type = string("Foo2"))))
4528  m = Modifier()
4529  m._setChosen()
4530  # Modify parameters
4531  m.toModify(a, foo2 = {0: dict(type = "Foo3")})
4532  self.assertEqual(a.foo2[0].type, "Foo3")
4533  # Add an alias
4534  m.toModify(a, foo4 = VPSet(PSet(type = string("Foo4"))))
4535  self.assertEqual(a.foo2[0].type, "Foo3")
4536  self.assertEqual(a.foo4[0].type, "Foo4")
4537  # Remove an alias
4538  m.toModify(a, foo2 = None)
4539  self.assertFalse(hasattr(a, "foo2"))
4540  self.assertEqual(a.foo4[0].type, "Foo4")
4541  # Replace (doesn't work out of the box because EDAlias is not _Parameterizable
4542  m.toReplaceWith(a, EDAlias(bar = VPSet(PSet(type = string("Bar")))))
4543  self.assertFalse(hasattr(a, "foo2"))
4544  self.assertFalse(hasattr(a, "foo4"))
4545  self.assertTrue(hasattr(a, "bar"))
4546  self.assertEqual(a.bar[0].type, "Bar")
4547 
4548  # SwitchProducer
4549  sp = SwitchProducerTest(test1 = EDProducer("Foo",
4550  a = int32(1),
4551  b = PSet(c = int32(2))),
4552  test2 = EDProducer("Bar",
4553  aa = int32(11),
4554  bb = PSet(cc = int32(12))))
4555  m = Modifier()
4556  m._setChosen()
4557  # Modify parameters
4558  m.toModify(sp,
4559  test1 = dict(a = 4, b = dict(c = None)),
4560  test2 = dict(aa = 15, bb = dict(cc = 45, dd = string("foo"))))
4561  self.assertEqual(sp.test1.a.value(), 4)
4562  self.assertEqual(sp.test1.b.hasParameter("c"), False)
4563  self.assertEqual(sp.test2.aa.value(), 15)
4564  self.assertEqual(sp.test2.bb.cc.value(), 45)
4565  self.assertEqual(sp.test2.bb.dd.value(), "foo")
4566  # Replace a producer
4567  m.toReplaceWith(sp.test1, EDProducer("Fred", x = int32(42)))
4568  self.assertEqual(sp.test1.type_(), "Fred")
4569  self.assertEqual(sp.test1.x.value(), 42)
4570  self.assertRaises(TypeError, lambda: m.toReplaceWith(sp.test1, EDAnalyzer("Foo")))
4571  # Alternative way (only to be allow same syntax to be used as for adding)
4572  m.toModify(sp, test2 = EDProducer("Xyzzy", x = int32(24)))
4573  self.assertEqual(sp.test2.type_(), "Xyzzy")
4574  self.assertEqual(sp.test2.x.value(), 24)
4575  self.assertRaises(TypeError, lambda: m.toModify(sp, test2 = EDAnalyzer("Foo")))
4576  # Add a producer
4577  m.toModify(sp, test3 = EDProducer("Wilma", y = int32(24)))
4578  self.assertEqual(sp.test3.type_(), "Wilma")
4579  self.assertEqual(sp.test3.y.value(), 24)
4580  self.assertRaises(TypeError, lambda: m.toModify(sp, test4 = EDAnalyzer("Foo")))
4581  # Remove a producer
4582  m.toModify(sp, test2 = None)
4583  self.assertEqual(hasattr(sp, "test2"), False)
4584  # Add an alias
4585  m.toModify(sp, test2 = EDAlias(foo = VPSet(PSet(type = string("int")))))
4586  self.assertTrue(hasattr(sp.test2, "foo"))
4587  # Replace an alias
4588  m.toReplaceWith(sp.test2, EDAlias(bar = VPSet(PSet(type = string("int")))))
4589  self.assertTrue(hasattr(sp.test2, "bar"))
4590  # Alternative way
4591  m.toModify(sp, test2 = EDAlias(xyzzy = VPSet(PSet(type = string("int")))))
4592  self.assertTrue(hasattr(sp.test2, "xyzzy"))
4593  # Replace an alias with EDProducer
4594  self.assertRaises(TypeError, lambda: m.toReplaceWith(sp.test2, EDProducer("Foo")))
4595  m.toModify(sp, test2 = EDProducer("Foo"))
4597  #check defaults are not overwritten
4598  f = ProcessFragment('Fragment')
4599  p = Process('PROCESS')
4600  p.maxEvents.input = 10
4601  p.options.numberOfThreads = 4
4602  p.maxLuminosityBlocks.input = 2
4603  p.extend(f)
4604  self.assertEqual(p.maxEvents.input.value(),10)
4605  self.assertEqual(p.options.numberOfThreads.value(), 4)
4606  self.assertEqual(p.maxLuminosityBlocks.input.value(),2)
4607  #general checks
4608  f = ProcessFragment("Fragment")
4609  f.fltr = EDFilter("Foo")
4610  p = Process('PROCESS')
4611  p.extend(f)
4612  self.assertTrue(hasattr(p,'fltr'))
4614  proc = Process("TEST")
4616  p.TestService = Service("TestService")
4617  self.assertTrue(hasattr(proc, "TestService"))
4618  self.assertEqual(proc.TestService.type_(), "TestService")
4619  self.assertRaises(TypeError, setattr, p, "a", EDProducer("Foo"))
4620  p.add_(Service("TestServiceTwo"))
4621  self.assertTrue(hasattr(proc, "TestServiceTwo"))
4622  self.assertEqual(proc.TestServiceTwo.type_(), "TestServiceTwo")
4623  p.TestService.foo = untracked.uint32(42)
4624  self.assertEqual(proc.TestService.foo.value(), 42)
4625  proc.mod = EDProducer("Producer")
4626  self.assertRaises(TypeError, getattr, p, "mod")
4628  proc = Process("TEST")
4629  p = TestMakePSet()
4630  proc.fillProcessDesc(p)
4631  self.assertTrue(["cpu"], p.values["@available_accelerators"][1])
4632  self.assertFalse(p.values["@selected_accelerators"][0])
4633  self.assertTrue(["cpu"], p.values["@selected_accelerators"][1])
4634  self.assertFalse(p.values["@module_type_resolver"][0])
4635  self.assertEqual("", p.values["@module_type_resolver"][1])
4636 
4637  proc = Process("TEST")
4638  self.assertRaises(TypeError, setattr, proc, "processAcceleratorTest", ProcessAcceleratorTest())
4639  proc.ProcessAcceleratorTest = ProcessAcceleratorTest()
4640  del proc.MessageLogger # remove boilerplate unnecessary for this test case
4641  self.maxDiff = None
4642  self.assertEqual(proc.dumpPython(),
4643 """import FWCore.ParameterSet.Config as cms
4644 from test import ProcessAcceleratorTest
4645 
4646 process = cms.Process("TEST")
4647 
4648 process.maxEvents = cms.untracked.PSet(
4649  input = cms.optional.untracked.int32,
4650  output = cms.optional.untracked.allowed(cms.int32,cms.PSet)
4651 )
4652 
4653 process.maxLuminosityBlocks = cms.untracked.PSet(
4654  input = cms.untracked.int32(-1)
4655 )
4656 
4657 process.options = cms.untracked.PSet(
4658  IgnoreCompletely = cms.untracked.vstring(),
4659  Rethrow = cms.untracked.vstring(),
4660  TryToContinue = cms.untracked.vstring(),
4661  accelerators = cms.untracked.vstring('*'),
4662  allowUnscheduled = cms.obsolete.untracked.bool,
4663  canDeleteEarly = cms.untracked.vstring(),
4664  deleteNonConsumedUnscheduledModules = cms.untracked.bool(True),
4665  dumpOptions = cms.untracked.bool(False),
4666  emptyRunLumiMode = cms.obsolete.untracked.string,
4667  eventSetup = cms.untracked.PSet(
4668  forceNumberOfConcurrentIOVs = cms.untracked.PSet(
4669  allowAnyLabel_=cms.required.untracked.uint32
4670  ),
4671  numberOfConcurrentIOVs = cms.untracked.uint32(0)
4672  ),
4673  fileMode = cms.untracked.string('FULLMERGE'),
4674  forceEventSetupCacheClearOnNewRun = cms.untracked.bool(False),
4675  holdsReferencesToDeleteEarly = cms.untracked.VPSet(),
4676  makeTriggerResults = cms.obsolete.untracked.bool,
4677  modulesToCallForTryToContinue = cms.untracked.vstring(),
4678  modulesToIgnoreForDeleteEarly = cms.untracked.vstring(),
4679  numberOfConcurrentLuminosityBlocks = cms.untracked.uint32(0),
4680  numberOfConcurrentRuns = cms.untracked.uint32(1),
4681  numberOfStreams = cms.untracked.uint32(0),
4682  numberOfThreads = cms.untracked.uint32(1),
4683  printDependencies = cms.untracked.bool(False),
4684  sizeOfStackForThreadsInKB = cms.optional.untracked.uint32,
4685  throwIfIllegalParameter = cms.untracked.bool(True),
4686  wantSummary = cms.untracked.bool(False)
4687 )
4688 
4689 process.ProcessAcceleratorTest = ProcessAcceleratorTest(
4690  enabled = ['test1', 'test2', 'anothertest3']
4691 )
4692 
4693 
4694 """)
4695  p = TestMakePSet()
4696  proc.fillProcessDesc(p)
4697  self.assertEqual(["*"], p.values["options"][1].values["accelerators"][1])
4698  self.assertFalse(p.values["options"][1].values["accelerators"][0])
4699  self.assertTrue(["anothertest3", "cpu", "test1", "test2"], p.values["@selected_accelerators"][1])
4700  self.assertEqual("AcceleratorTestService", p.values["services"][1][0].values["@service_type"][1])
4701  self.assertFalse(p.values["@available_accelerators"][0])
4702  self.assertTrue(["anothertest3", "cpu", "test1", "test2"], p.values["@available_accelerators"][1])
4703  self.assertFalse(p.values["@module_type_resolver"][0])
4704  self.assertEqual("", p.values["@module_type_resolver"][1])
4705 
4706  proc = Process("TEST")
4707  proc.ProcessAcceleratorTest = ProcessAcceleratorTest()
4708  proc.add_(Service("AcceleratorTestServiceRemove"))
4709  p = TestMakePSet()
4710  proc.fillProcessDesc(p)
4711  services = [x.values["@service_type"][1] for x in p.values["services"][1]]
4712  self.assertTrue("AcceleratorTestService" in services)
4713  self.assertFalse("AcceleratorTestServiceRemove" in services)
4714 
4715  proc = Process("TEST")
4716  proc.ProcessAcceleratorTest = ProcessAcceleratorTest(enabled=["test1"])
4717  p = TestMakePSet()
4718  proc.fillProcessDesc(p)
4719  self.assertEqual(["cpu", "test1"], p.values["@selected_accelerators"][1])
4720  self.assertEqual(["cpu", "test1"], p.values["@available_accelerators"][1])
4721 
4722  proc = Process("TEST")
4723  proc.ProcessAcceleratorTest = ProcessAcceleratorTest()
4724  proc.options.accelerators = ["test2"]
4725  p = TestMakePSet()
4726  proc.fillProcessDesc(p)
4727  self.assertEqual(["test2"], p.values["@selected_accelerators"][1])
4728  self.assertEqual(["anothertest3", "cpu", "test1", "test2"], p.values["@available_accelerators"][1])
4729 
4730  proc = Process("TEST")
4731  proc.ProcessAcceleratorTest = ProcessAcceleratorTest()
4732  proc.options.accelerators = ["test*"]
4733  proc.fillProcessDesc(p)
4734  self.assertEqual(["test1", "test2"], p.values["@selected_accelerators"][1])
4735  self.assertEqual(["anothertest3", "cpu", "test1", "test2"], p.values["@available_accelerators"][1])
4736 
4737  proc = Process("TEST")
4738  proc.ProcessAcceleratorTest = ProcessAcceleratorTest(enabled=["test1"])
4739  proc.options.accelerators = ["test2"]
4740  p = TestMakePSet()
4741  proc.fillProcessDesc(p)
4742  self.assertEqual([], p.values["@selected_accelerators"][1])
4743  self.assertEqual(["cpu", "test1"], p.values["@available_accelerators"][1])
4744 
4745  proc = Process("TEST")
4746  proc.ProcessAcceleratorTest = ProcessAcceleratorTest()
4747  proc.options.accelerators = ["cpu*"]
4748  p = TestMakePSet()
4749  proc.fillProcessDesc(p)
4750  self.assertEqual(["cpu"], p.values["@selected_accelerators"][1])
4751  self.assertEqual(["anothertest3", "cpu", "test1", "test2"], p.values["@available_accelerators"][1])
4752 
4753  proc = Process("TEST")
4754  proc.ProcessAcceleratorTest = ProcessAcceleratorTest()
4755  proc.options.accelerators = ["test3"]
4756  p = TestMakePSet()
4757  self.assertRaises(ValueError, proc.fillProcessDesc, p)
4758 
4759  proc = Process("TEST")
4760  proc.ProcessAcceleratorTest = ProcessAcceleratorTest()
4761  proc.options.accelerators = ["*", "test1"]
4762  p = TestMakePSet()
4763  self.assertRaises(ValueError, proc.fillProcessDesc, p)
4764 
4765  proc = Process("TEST")
4766  proc.ProcessAcceleratorTest = ProcessAcceleratorTest()
4767  proc.ProcessAcceleratorTest2 = ProcessAcceleratorTest2()
4768  p = TestMakePSet()
4769  proc.fillProcessDesc(p)
4770  self.assertEqual(["anothertest3", "anothertest4", "cpu", "test1", "test2"], p.values["@selected_accelerators"][1])
4771  self.assertEqual(["anothertest3", "anothertest4", "cpu", "test1", "test2"], p.values["@available_accelerators"][1])
4772 
4773  proc = Process("TEST")
4774  proc.ProcessAcceleratorTest = ProcessAcceleratorTest()
4775  proc.ProcessAcceleratorTest2 = ProcessAcceleratorTest2()
4776  proc.options.accelerators = ["*test3", "c*"]
4777  p = TestMakePSet()
4778  proc.fillProcessDesc(p)
4779  self.assertEqual(["anothertest3", "cpu"], p.values["@selected_accelerators"][1])
4780  self.assertEqual(["anothertest3", "anothertest4", "cpu", "test1", "test2"], p.values["@available_accelerators"][1])
4781 
4782  proc = Process("TEST")
4783  proc.ProcessAcceleratorTest = ProcessAcceleratorTest()
4784  proc.sp = SwitchProducerTest2(test2 = EDProducer("Foo",
4785  a = int32(1),
4786  b = PSet(c = int32(2))),
4787  test1 = EDProducer("Bar",
4788  aa = int32(11),
4789  bb = PSet(cc = int32(12))))
4790  proc.p = Path(proc.sp)
4791  p = TestMakePSet()
4792  proc.fillProcessDesc(p)
4793  self.assertEqual((False, "sp@test2"), p.values["sp"][1].values["@chosen_case"])
4794 
4795  proc = Process("TEST")
4796  proc.ProcessAcceleratorTest = ProcessAcceleratorTest(enabled=["test1"])
4797  proc.sp = SwitchProducerTest2(test2 = EDProducer("Foo",
4798  a = int32(1),
4799  b = PSet(c = int32(2))),
4800  test1 = EDProducer("Bar",
4801  aa = int32(11),
4802  bb = PSet(cc = int32(12))))
4803  proc.p = Path(proc.sp)
4804  p = TestMakePSet()
4805  proc.fillProcessDesc(p)
4806  self.assertEqual((False, "sp@test1"), p.values["sp"][1].values["@chosen_case"])
4807 
4808  proc = Process("TEST")
4809  proc.ProcessAcceleratorTest = ProcessAcceleratorTest()
4810  proc.options.accelerators = ["test1"]
4811  proc.sp = SwitchProducerTest2(test2 = EDProducer("Foo",
4812  a = int32(1),
4813  b = PSet(c = int32(2))),
4814  test1 = EDProducer("Bar",
4815  aa = int32(11),
4816  bb = PSet(cc = int32(12))))
4817  proc.p = Path(proc.sp)
4818  p = TestMakePSet()
4819  proc.fillProcessDesc(p)
4820  self.assertEqual((False, "sp@test1"), p.values["sp"][1].values["@chosen_case"])
4821 
4822  proc = Process("TEST")
4823  proc.ProcessAcceleratorTest = ProcessAcceleratorTest()
4824  proc.options.accelerators = ["test*"]
4825  proc.sp = SwitchProducerTest2(test2 = EDProducer("Foo",
4826  a = int32(1),
4827  b = PSet(c = int32(2))),
4828  test1 = EDProducer("Bar",
4829  aa = int32(11),
4830  bb = PSet(cc = int32(12))))
4831  proc.p = Path(proc.sp)
4832  p = TestMakePSet()
4833  proc.fillProcessDesc(p)
4834  self.assertEqual((False, "sp@test2"), p.values["sp"][1].values["@chosen_case"])
4835 
4836  proc = Process("TEST")
4837  proc.ProcessAcceleratorTest = ProcessAcceleratorTest()
4838  proc.options.accelerators = ["anothertest3"]
4839  proc.sp = SwitchProducerTest2(test2 = EDProducer("Foo",
4840  a = int32(1),
4841  b = PSet(c = int32(2))),
4842  test1 = EDProducer("Bar",
4843  aa = int32(11),
4844  bb = PSet(cc = int32(12))))
4845  proc.p = Path(proc.sp)
4846  p = TestMakePSet()
4847  self.assertRaises(RuntimeError, proc.fillProcessDesc, p)
4848 
4849  proc = Process("TEST")
4850  proc.ProcessAcceleratorTest = ProcessAcceleratorTest(
4851  moduleTypeResolverMaker=lambda accelerators: TestModuleTypeResolver(accelerators))
4852  proc.ProcessAcceleratorTest2 = ProcessAcceleratorTest2()
4853  proc.normalProducer = EDProducer("FooProducer")
4854  proc.testProducer = EDProducer("BarProducer@test")
4855  proc.test2Producer = EDProducer("BarProducer@test", test=untracked.PSet(backend=untracked.string("test2_backend")))
4856  proc.testAnalyzer = EDAnalyzer("Analyzer@test")
4857  proc.testFilter = EDAnalyzer("Filter@test")
4858  proc.testESProducer = ESProducer("ESProducer@test")
4859  proc.testESSource = ESSource("ESSource@test")
4860  proc.p = Path(proc.normalProducer+proc.testProducer+proc.test2Producer+proc.testAnalyzer+proc.testFilter)
4861  p = TestMakePSet()
4862  proc.fillProcessDesc(p)
4863  self.assertEqual("TestModuleTypeResolver", p.values["@module_type_resolver"][1])
4864  self.assertEqual("FooProducer", p.values["normalProducer"][1].values["@module_type"][1])
4865  self.assertEqual(len(list(filter(lambda x: not "@" in x, p.values["normalProducer"][1].values.keys()))), 0)
4866  self.assertEqual("BarProducer@test", p.values["testProducer"][1].values["@module_type"][1])
4867  self.assertEqual(False, p.values["testProducer"][1].values["test"][0])
4868  self.assertEqual(False, p.values["testProducer"][1].values["test"][1].values["backend"][0])
4869  self.assertEqual("test1_backend", p.values["testProducer"][1].values["test"][1].values["backend"][1])
4870  self.assertEqual("BarProducer@test", p.values["test2Producer"][1].values["@module_type"][1])
4871  self.assertEqual("test2_backend", p.values["test2Producer"][1].values["test"][1].values["backend"][1])
4872  self.assertEqual("Analyzer@test", p.values["testAnalyzer"][1].values["@module_type"][1])
4873  self.assertEqual("test1_backend", p.values["testAnalyzer"][1].values["test"][1].values["backend"][1])
4874  self.assertEqual("Filter@test", p.values["testFilter"][1].values["@module_type"][1])
4875  self.assertEqual("test1_backend", p.values["testFilter"][1].values["test"][1].values["backend"][1])
4876  self.assertEqual("ESProducer@test", p.values["ESProducer@test@testESProducer"][1].values["@module_type"][1])
4877  self.assertEqual("test1_backend", p.values["ESProducer@test@testESProducer"][1].values["test"][1].values["backend"][1])
4878  self.assertEqual("ESSource@test", p.values["ESSource@test@testESSource"][1].values["@module_type"][1])
4879  self.assertEqual("test1_backend", p.values["ESSource@test@testESSource"][1].values["test"][1].values["backend"][1])
4880 
4881  # No required accelerators available
4882  proc = Process("Test")
4883  proc.ProcessAcceleratorTest = ProcessAcceleratorTest(
4884  moduleTypeResolverMaker=lambda accelerators: TestModuleTypeResolver(accelerators))
4885  proc.options.accelerators = []
4886  self.assertRaises(EDMException, proc.fillProcessDesc, p)
4887 
4888  proc = Process("Test")
4889  proc.ProcessAcceleratorTest = ProcessAcceleratorTest(
4890  moduleTypeResolverMaker=lambda accelerators: TestModuleTypeResolver(accelerators))
4891  proc.options.accelerators = ["test1"]
4892  proc.test2Producer = EDProducer("BarProducer@test", test=untracked.PSet(backend=untracked.string("test2_backend")))
4893  proc.p = Path(proc.test2Producer)
4894  self.assertRaises(EDMException, proc.fillProcessDesc, p)
4895 
4896  # Two ProcessAccelerators return type resolver
4897  proc = Process("TEST")
4898  proc.ProcessAcceleratorTest = ProcessAcceleratorTest(
4899  moduleTypeResolverMaker=lambda accelerators: TestModuleTypeResolver(accelerators))
4900  proc.ProcessAcceleratorTest2 = ProcessAcceleratorTest2(
4901  moduleTypeResolverMaker=lambda accelerators: TestModuleTypeResolver(accelerators))
4902  p = TestMakePSet()
4903  self.assertRaises(RuntimeError, proc.fillProcessDesc, p)
4904 
4905  import pickle
4906  proc = Process("TEST")
4907  proc.ProcessAcceleratorTest = ProcessAcceleratorTest()
4908  proc.sp = SwitchProducerTest2(test2 = EDProducer("Foo",
4909  a = int32(1),
4910  b = PSet(c = int32(2))),
4911  test1 = EDProducer("Bar",
4912  aa = int32(11),
4913  bb = PSet(cc = int32(12))))
4914  proc.p = Path(proc.sp)
4915  pkl = pickle.dumps(proc)
4916  unpkl = pickle.loads(pkl)
4917  p = TestMakePSet()
4918  unpkl.fillProcessDesc(p)
4919  self.assertEqual((False, "sp@test2"), p.values["sp"][1].values["@chosen_case"])
4920  self.assertEqual(["anothertest3", "cpu", "test1", "test2"], p.values["@available_accelerators"][1])
4921  unpkl = pickle.loads(pkl)
4922  unpkl.ProcessAcceleratorTest.setEnabled(["test1"])
4923  p = TestMakePSet()
4924  unpkl.fillProcessDesc(p)
4925  self.assertEqual((False, "sp@test1"), p.values["sp"][1].values["@chosen_case"])
4926  self.assertEqual(["cpu", "test1"], p.values["@available_accelerators"][1])
4927 
4928  unittest.main()
def __setstate__(self, pkldict)
Definition: Config.py:192
def conditionaltasks_(self)
Definition: Config.py:329
def addVString(self, tracked, label, value)
Definition: Config.py:2148
def testProcessAccelerator(self)
Definition: Config.py:4627
def _dumpConfigOptionallyNamedList(self, items, typeName, options)
Definition: Config.py:829
def testConditionalTaskPlaceholder(self)
Definition: Config.py:4078
def addEventRange(self, tracked, label, value)
Definition: Config.py:2168
def __init__(self, lhs, rhs)
Definition: Config.py:1820
def __init__(self, enabled=["anothertest3", anothertest4, moduleTypeResolverMaker=None)
Definition: Config.py:2259
def testExamples(self)
Definition: Config.py:3638
def __getattribute__(self, name)
Definition: Config.py:1653
def _place(self, label, process)
Definition: Config.py:1745
def getProcessName(self)
Definition: Config.py:1733
def testServiceInProcess(self)
Definition: Config.py:2864
def __or__(self, other)
Definition: Config.py:1913
def outputCommands(self)
Definition: Config.py:1739
def _setChosen(self)
Definition: Config.py:1930
def producerNames(self)
Definition: Config.py:176
def _dumpConfigUnnamedList(self, items, typeName, options)
Definition: Config.py:823
def newPSet(self)
Definition: Config.py:2178
def _placeAnalyzer(self, name, mod)
Definition: Config.py:689
def addString(self, tracked, label, value)
Definition: Config.py:2146
def __findFirstUsingModule(self, seqsOrTasks, mod)
Definition: Config.py:571
def subProcesses_(self)
Definition: Config.py:297
def __repr__(self)
Definition: Config.py:1696
def _pruneModules(self, d, scheduledNames)
Definition: Config.py:1422
def _modifyParametersFromDict(params, newParams, errorRaiser, keyDepth="")
Definition: Mixins.py:713
def vpsets_(self)
Definition: Config.py:380
def setName_(self, name)
Definition: Config.py:215
def _placeESPrefer(self, name, mod)
Definition: Config.py:717
def __init__(self, process)
Definition: Config.py:2060
def testSequence2(self)
Definition: Config.py:2854
def __updateMaxEvents(self, ps)
Definition: Config.py:285
def _placeSwitchProducer(self, name, mod)
Definition: Config.py:685
def _insertPaths(self, processPSet, nodeVisitor)
Definition: Config.py:1244
def es_producers_(self)
Definition: Config.py:360
def apply(self, process, accelerators)
Definition: Config.py:2047
def _placeESProducer(self, name, mod)
Definition: Config.py:715
def __invert__(self)
Definition: Config.py:1911
def _splitPythonList(self, subfolder, d, options)
Definition: Config.py:928
bool any(const std::vector< T > &v, const T &what)
Definition: ECalSD.cc:37
def pathNames(self)
Definition: Config.py:188
def addVESInputTag(self, tracked, label, value)
Definition: Config.py:2158
def _switchproducer_test2_case2(accelerators)
Definition: Config.py:2088
def __and__(self, other)
Definition: Config.py:1909
def _placeSequence(self, name, mod)
Definition: Config.py:712
def __call__(self, obj)
Definition: Config.py:1760
def _setChosen(self)
Definition: Config.py:1904
untracked
Definition: Types.py:34
def __init__(self, dataset, job_number, job_id, job_name, isDA, isMC, applyBOWS, applyEXTRACOND, extraconditions, runboundary, lumilist, intlumi, maxevents, gt, allFromGT, alignmentDB, alignmentTAG, apeDB, apeTAG, bowDB, bowTAG, vertextype, tracktype, refittertype, ttrhtype, applyruncontrol, ptcut, CMSSW_dir, the_dir)
def _validateSequence(self, sequence, label)
Definition: Config.py:949
def __getattr__(self, attr)
Definition: Config.py:1698
def tasks_(self)
Definition: Config.py:325
def setStrict(self, value)
Definition: Config.py:171
def addDouble(self, tracked, label, value)
Definition: Config.py:2140
def dumpPythonImpl(self, options)
Definition: Config.py:2022
def moduleTypeResolver(self, accelerators)
Definition: Config.py:2248
def producers_(self)
Definition: Config.py:220
def _findPreferred(self, esname, d, args, kargs)
Definition: Config.py:1618
def apply(self, process, accelerators)
Definition: Config.py:2281
def __init__(self, kargs)
Definition: Config.py:2193
def testModifier(self)
Definition: Config.py:4193
def apply(self, process, accelerators)
Definition: Config.py:2252
def _insertOneInto(self, parameterSet, label, item, tracked)
Definition: Config.py:1205
def __setattr__(self, label, value)
Definition: Config.py:2067
def _isChosen(self)
Definition: Config.py:1815
def filterNames(self)
Definition: Config.py:185
def __updateOptions(self, opt)
Definition: Config.py:272
def __delattr__(self, name)
Definition: Config.py:601
def _placePath(self, name, mod)
Definition: Config.py:691
def addVUInt64(self, tracked, label, value)
Definition: Config.py:2138
def _isChosen(self)
Definition: Config.py:1808
def _placeEndPath(self, name, mod)
Definition: Config.py:698
def testProcessForProcessAccelerator(self)
Definition: Config.py:4613
def es_sources_(self)
Definition: Config.py:364
def __init__(self, name, Mods)
Definition: Config.py:116
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:19
def testTypedParameterizable(self)
Definition: Config.py:2322
def addUInt64(self, tracked, label, value)
Definition: Config.py:2136
def _itemsInDependencyOrder(self, processDictionaryOfItems)
Definition: Config.py:975
def source_(self)
Definition: Config.py:228
def addVPSet(self, tracked, label, value)
Definition: Config.py:2174
def nameInProcessDesc_(self, label)
Definition: Config.py:1743
def __init__(self, accelerators)
Definition: Config.py:2202
def psets_(self)
Definition: Config.py:376
def _lineDiff(newString, oldString)
Definition: Config.py:2095
def testSecSource(self)
Definition: Config.py:2763
def dumpPythonImpl(self, options)
Definition: Config.py:2240
def __init__(self, args)
Definition: Config.py:1758
def format_outerframe(number)
def __init__(self, args, kw)
Definition: Config.py:1694
def load(self, moduleName)
Definition: Config.py:759
def _insertSubProcessesInto(self, parameterSet, label, itemList, tracked)
Definition: Config.py:1231
def addUInt32(self, tracked, label, value)
Definition: Config.py:2128
def __init__(self, error, message)
Definition: Config.py:37
def _dumpConfigESPrefers(self, options)
Definition: Config.py:906
def __setattr__(self, name, value)
Definition: Config.py:1658
def setLooper_(self, lpr)
Definition: Config.py:237
def setSource_(self, src)
Definition: Config.py:231
def __init__(self, process)
Definition: Config.py:1640
def extend(self, other, items=())
Definition: Config.py:763
def _okToPlace(self, name, mod, d)
Definition: Config.py:652
def __injectValidValue(self, name, value, newValue=None)
Definition: Config.py:561
def __or__(self, other)
Definition: Config.py:1801
def _replaceInTasks(self, label, new)
Definition: Config.py:1178
def addVInt32(self, tracked, label, value)
Definition: Config.py:2126
def _placeFilter(self, name, mod)
Definition: Config.py:687
def testFinalPath(self)
Definition: Config.py:3313
def handleProcessAccelerators(self, parameterSet)
Definition: Config.py:1524
def schedule_(self)
Definition: Config.py:333
def validate(self)
Definition: Config.py:1517
def addVInputTag(self, tracked, label, value)
Definition: Config.py:2154
def _applyNewProcessModifiers(self, process)
Definition: Config.py:1925
def analyzerNames(self)
Definition: Config.py:182
def testSchedule(self)
Definition: Config.py:3436
def addLuminosityBlockID(self, tracked, label, value)
Definition: Config.py:2164
def addESInputTag(self, tracked, label, value)
Definition: Config.py:2156
def __init__(self, lhs)
Definition: Config.py:1813
def __new__(cls, args, kw)
Definition: Config.py:1677
def testContains(self)
Definition: Config.py:3368
def endpaths_(self)
Definition: Config.py:313
def toModify(self, obj, func=None, kw)
Definition: Config.py:1782
def SelectEvents(self)
Definition: Config.py:1737
def setEnabled(self, enabled)
Definition: Config.py:2235
def __setattr__(self, name, value)
Definition: Config.py:420
def _placeESSource(self, name, mod)
Definition: Config.py:719
def addVInt64(self, tracked, label, value)
Definition: Config.py:2134
def addVEventID(self, tracked, label, value)
Definition: Config.py:2162
def setEnabled(self, enabled)
Definition: Config.py:2264
def toModify(self, obj, func=None, kw)
Definition: Config.py:1848
def testGlobalReplace(self)
Definition: Config.py:2768
def testSwitchProducer(self)
Definition: Config.py:3739
def getVString(self, tracked, label)
Definition: Config.py:2150
def moduleTypeResolver(self, accelerators)
Definition: Config.py:2032
def defaultMaxLuminosityBlocks_()
Definition: Config.py:295
def testProcessFragment(self)
Definition: Config.py:4596
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def toReplaceWith(self, toObj, fromObj)
Definition: Config.py:1787
def _placeOutputModule(self, name, mod)
Definition: Config.py:681
def addFileInPath(self, tracked, label, value)
Definition: Config.py:2176
def testRefToPSet(self)
Definition: Config.py:3723
def testOverride(self)
Definition: Config.py:3581
def _placeSource(self, name, mod)
Definition: Config.py:733
def __init__(self)
Definition: Config.py:1835
def __init__(self, lhs, rhs=None)
Definition: Config.py:1778
def _dumpPythonSubProcesses(self, l, options)
Definition: Config.py:912
def _insertSwitchProducersInto(self, parameterSet, labelModules, labelAliases, itemDict, tracked)
Definition: Config.py:1220
def moduleTypeResolver(self, accelerators)
Definition: Config.py:2277
def checkImportPermission(minLevel=2, allowedPatterns=[])
Definition: Config.py:41
def ignore(seq)
def _toModify(obj, func, kw)
Definition: Config.py:1866
def __init__(self, modifier, func)
Definition: Config.py:1974
def _toReplaceWith(toObj, fromObj)
Definition: Config.py:1884
def _toModifyCheck(obj, func, kw)
Definition: Config.py:1845
def isUsingModifier(self, mod)
Definition: Config.py:385
def dumpPython(self, options=PrintOptions())
Definition: Config.py:1726
def __copyIfExclude(self, toExclude)
Definition: Config.py:1951
def sequences_(self)
Definition: Config.py:321
def _validateTask(self, task, label)
Definition: Config.py:958
def testParameterizable(self)
Definition: Config.py:2289
def testSubProcess(self)
Definition: Config.py:3688
def _placeSubProcess(self, name, mod)
Definition: Config.py:746
def __init__(self, enabled=["test1", test2, anothertest3, moduleTypeResolverMaker=None)
Definition: Config.py:2230
def setPartialSchedule_(self, sch, label)
Definition: Config.py:336
def addPSet(self, tracked, label, value)
Definition: Config.py:2172
def testProcessDumpPython(self)
Definition: Config.py:2449
def _placeService(self, typeName, mod)
Definition: Config.py:751
def resolve(self, keepUnresolvedSequencePlaceholders=False)
Definition: Config.py:1340
def looper_(self)
Definition: Config.py:234
def _switchproducer_test2_case1(accelerators)
Definition: Config.py:2086
def es_prefers_(self)
Definition: Config.py:368
static std::string join(char **cmd)
Definition: RemoteFile.cc:19
def _isChosen(self)
Definition: Config.py:1907
def _isOrContains(self, other)
Definition: Config.py:1915
def getSubProcessPSet(self, parameterSet)
Definition: Config.py:1747
def _validateConditionalTask(self, task, label)
Definition: Config.py:966
def copyAndExclude(self, toExclude)
Definition: Config.py:1937
def addVUInt32(self, tracked, label, value)
Definition: Config.py:2130
def addVEventRange(self, tracked, label, value)
Definition: Config.py:2170
def _splitPython(self, subfolder, d, options)
Definition: Config.py:1047
def defaultMaxEvents_()
Definition: Config.py:282
def __init__(self, lhs, rhs)
Definition: Config.py:1806
def filters_(self)
Definition: Config.py:209
def _placeAccelerator(self, typeName, mod)
Definition: Config.py:756
def dumpPython(process, name)
def __setObjectLabel(self, object, newLabel)
Definition: Config.py:393
def testConditionalTask(self)
Definition: Config.py:3074
def _delHelper(self, name)
Definition: Config.py:584
def _placeAlias(self, name, mod)
Definition: Config.py:727
def dumpPython(self, options=PrintOptions())
Definition: Config.py:1053
def _replaceInSequences(self, label, new)
Definition: Config.py:1161
def setSchedule_(self, sch)
Definition: Config.py:341
def analyzers_(self)
Definition: Config.py:301
def finalpaths_(self)
Definition: Config.py:317
def dumpPython(self, options=PrintOptions())
Definition: Config.py:2010
def _toReplaceWithCheck(toObj, fromObj)
Definition: Config.py:1873
def defaultOptions_()
Definition: Config.py:241
def testSequence(self)
Definition: Config.py:2839
def switchProducerNames(self)
Definition: Config.py:179
def toReplaceWith(self, toObj, fromObj)
Definition: Config.py:1876
def _placeProducer(self, name, mod)
Definition: Config.py:683
def prefer(self, esmodule, args, kargs)
Definition: Config.py:1589
def __delattr__(self, name)
Definition: Config.py:1663
def _dumpConfigNamedList(self, items, typeName, options)
Definition: Config.py:817
void add(std::map< std::string, TH1 *> &h, TH1 *hist)
#define update(a, b)
def addInputTag(self, tracked, label, value)
Definition: Config.py:2152
def add_(self, value)
Definition: Config.py:638
def _isChosen(self)
Definition: Config.py:1822
def _insertManyInto(self, parameterSet, label, itemDict, tracked)
Definition: Config.py:1212
def dumpConfig(self, options=PrintOptions())
Definition: Config.py:837
def apply(self, process)
Definition: Config.py:1978
def testCloneSequence(self)
Definition: Config.py:3352
def process(self)
Definition: Config.py:1735
def _placeTask(self, name, task)
Definition: Config.py:721
def makeProcessModifier(self, func)
Definition: Config.py:1792
def addSubProcess(self, mod)
Definition: Config.py:749
def switchProducers_(self)
Definition: Config.py:224
def _placePSet(self, name, mod)
Definition: Config.py:729
def _placeFinalPath(self, name, mod)
Definition: Config.py:705
def _isOrContains(self, other)
Definition: Config.py:1960
def addInt64(self, tracked, label, value)
Definition: Config.py:2132
def addService(process, multirun=False)
Definition: FastTimer.py:3
def name_(self)
Definition: Config.py:213
def _place(self, name, mod, d)
Definition: Config.py:673
def testProcessExtend(self)
Definition: Config.py:2354
def _dumpPythonList(self, d, options)
Definition: Config.py:918
def __insertValue(self, tracked, label, value)
Definition: Config.py:2115
def splitPython(self, options=PrintOptions())
Definition: Config.py:1090
def __init__(self, kargs)
Definition: Config.py:2182
def setModuleVariant(self, module)
Definition: Config.py:2215
def __getValue(self, tracked, label)
Definition: Config.py:2117
def _place(self, name, proc)
Definition: Config.py:2006
def _placeVPSet(self, name, mod)
Definition: Config.py:731
def processAccelerators_(self)
Definition: Config.py:356
def __and__(self, other)
Definition: Config.py:1797
def globalReplace(self, label, new)
Definition: Config.py:1197
#define str(s)
def addBool(self, tracked, label, value)
Definition: Config.py:2144
def testMaxEvents(self)
Definition: Config.py:3620
def paths_(self)
Definition: Config.py:309
def addEventID(self, tracked, label, value)
Definition: Config.py:2160
def outputModules_(self)
Definition: Config.py:305
def _placeLooper(self, name, mod)
Definition: Config.py:741
def testImplicitSchedule(self)
Definition: Config.py:3541
def prune(self, verbose=False, keepUnresolvedSequencePlaceholders=False)
Definition: Config.py:1351
def addVDouble(self, tracked, label, value)
Definition: Config.py:2142
def _insertInto(self, parameterSet, itemDict)
Definition: Config.py:1202
def _delattrFromSetattr(self, name)
Definition: Config.py:629
def _replaceInConditionalTasks(self, label, new)
Definition: Config.py:1182
def makeProcessModifier(self, func)
Definition: Config.py:1838
def __init__(self, process, SelectEvents=untracked.PSet(), outputCommands=untracked.vstring())
Definition: Config.py:1706
def _placeConditionalTask(self, name, task)
Definition: Config.py:724
def _replaceInScheduleDirectly(self, label, new)
Definition: Config.py:1192
def type_(self)
Definition: Config.py:1741
def __init__(self, chainedModifiers)
Definition: Config.py:1922
def testTaskPlaceholder(self)
Definition: Config.py:4010
def services_(self)
Definition: Config.py:352
def _replaceInSchedule(self, label, new)
Definition: Config.py:1186
def dumpPythonImpl(self, options)
Definition: Config.py:2269
def _dumpPython(self, d, options)
Definition: Config.py:1041
def addInt32(self, tracked, label, value)
Definition: Config.py:2124
def _isChosen(self)
Definition: Config.py:1935
def fillProcessDesc(self, processPSet)
Definition: Config.py:1429
def findProcess(module)
Definition: Config.py:94
def testProcessInsertion(self)
Definition: Config.py:2329
def __init__(self)
Definition: Config.py:2113
def aliases_(self)
Definition: Config.py:372