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