CMS 3D CMS Logo

Config.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 ### command line options helper
4 import six
5 from Options import Options
6 options = Options()
7 
8 
9 ## imports
10 import sys
11 from Mixins import PrintOptions,_ParameterTypeBase,_SimpleParameterTypeBase, _Parameterizable, _ConfigureComponent, _TypedParameterizable, _Labelable, _Unlabelable, _ValidatingListBase, _modifyParametersFromDict
12 from Mixins import *
13 from Types import *
14 from Modules import *
15 from Modules import _Module
16 from SequenceTypes import *
17 from SequenceTypes import _ModuleSequenceType, _Sequenceable #extend needs it
18 from SequenceVisitors import PathValidator, EndPathValidator, ScheduleTaskValidator, NodeVisitor, CompositeVisitor, ModuleNamesFromGlobalsVisitor
19 import DictTypes
20 
21 from ExceptionHandling import *
22 
23 #when building RECO paths we have hit the default recursion limit
24 if sys.getrecursionlimit()<5000:
25  sys.setrecursionlimit(5000)
26 
27 def checkImportPermission(minLevel = 2, allowedPatterns = []):
28  """
29  Raise an exception if called by special config files. This checks
30  the call or import stack for the importing file. An exception is raised if
31  the importing module is not in allowedPatterns and if it is called too deeply:
32  minLevel = 2: inclusion by top lvel cfg only
33  minLevel = 1: No inclusion allowed
34  allowedPatterns = ['Module1','Module2/SubModule1'] allows import
35  by any module in Module1 or Submodule1
36  """
37 
38  import inspect
39  import os
40 
41  ignorePatterns = ['FWCore/ParameterSet/Config.py','<string>']
42  CMSSWPath = [os.environ['CMSSW_BASE'],os.environ['CMSSW_RELEASE_BASE']]
43 
44  # Filter the stack to things in CMSSWPath and not in ignorePatterns
45  trueStack = []
46  for item in inspect.stack():
47  inPath = False
48  ignore = False
49 
50  for pattern in CMSSWPath:
51  if item[1].find(pattern) != -1:
52  inPath = True
53  break
54  if item[1].find('/') == -1: # The base file, no path
55  inPath = True
56 
57  for pattern in ignorePatterns:
58  if item[1].find(pattern) != -1:
59  ignore = True
60  break
61 
62  if inPath and not ignore:
63  trueStack.append(item[1])
64 
65  importedFile = trueStack[0]
66  importedBy = ''
67  if len(trueStack) > 1:
68  importedBy = trueStack[1]
69 
70  for pattern in allowedPatterns:
71  if importedBy.find(pattern) > -1:
72  return True
73 
74  if len(trueStack) <= minLevel: # Imported directly
75  return True
76 
77  raise ImportError("Inclusion of %s is allowed only by cfg or specified cfi files."
78  % importedFile)
79 
80 def findProcess(module):
81  """Look inside the module and find the Processes it contains"""
82  class Temp(object):
83  pass
84  process = None
85  if isinstance(module,dict):
86  if 'process' in module:
87  p = module['process']
88  module = Temp()
89  module.process = p
90  if hasattr(module,'process'):
91  if isinstance(module.process,Process):
92  process = module.process
93  else:
94  raise RuntimeError("The attribute named 'process' does not inherit from the Process class")
95  else:
96  raise RuntimeError("no 'process' attribute found in the module, please add one")
97  return process
98 
99 class Process(object):
100  """Root class for a CMS configuration process"""
101  def __init__(self,name,*Mods):
102  """The argument 'name' will be the name applied to this Process
103  Can optionally pass as additional arguments cms.Modifier instances
104  that will be used to modify the Process as it is built
105  """
106  self.__dict__['_Process__name'] = name
107  if not name.isalnum():
108  raise RuntimeError("Error: The process name is an empty string or contains non-alphanumeric characters")
109  self.__dict__['_Process__filters'] = {}
110  self.__dict__['_Process__producers'] = {}
111  self.__dict__['_Process__source'] = None
112  self.__dict__['_Process__looper'] = None
113  self.__dict__['_Process__subProcesses'] = []
114  self.__dict__['_Process__schedule'] = None
115  self.__dict__['_Process__analyzers'] = {}
116  self.__dict__['_Process__outputmodules'] = {}
117  self.__dict__['_Process__paths'] = DictTypes.SortedKeysDict() # have to keep the order
118  self.__dict__['_Process__endpaths'] = DictTypes.SortedKeysDict() # of definition
119  self.__dict__['_Process__sequences'] = {}
120  self.__dict__['_Process__tasks'] = {}
121  self.__dict__['_Process__services'] = {}
122  self.__dict__['_Process__essources'] = {}
123  self.__dict__['_Process__esproducers'] = {}
124  self.__dict__['_Process__esprefers'] = {}
125  self.__dict__['_Process__aliases'] = {}
126  self.__dict__['_Process__psets']={}
127  self.__dict__['_Process__vpsets']={}
128  self.__dict__['_cloneToObjectDict'] = {}
129  # policy switch to avoid object overwriting during extend/load
130  self.__dict__['_Process__InExtendCall'] = False
131  self.__dict__['_Process__partialschedules'] = {}
132  self.__isStrict = False
133  self.__dict__['_Process__modifiers'] = Mods
134  for m in self.__modifiers:
135  m._setChosen()
136 
137  def setStrict(self, value):
138  self.__isStrict = value
139  _Module.__isStrict__ = True
140 
141  # some user-friendly methods for command-line browsing
142  def producerNames(self):
143  """Returns a string containing all the EDProducer labels separated by a blank"""
144  return ' '.join(self.producers_().keys())
145  def analyzerNames(self):
146  """Returns a string containing all the EDAnalyzer labels separated by a blank"""
147  return ' '.join(self.analyzers_().keys())
148  def filterNames(self):
149  """Returns a string containing all the EDFilter labels separated by a blank"""
150  return ' '.join(self.filters_().keys())
151  def pathNames(self):
152  """Returns a string containing all the Path names separated by a blank"""
153  return ' '.join(self.paths_().keys())
154 
155  def __setstate__(self, pkldict):
156  """
157  Unpickling hook.
158 
159  Since cloneToObjectDict stores a hash of objects by their
160  id() it needs to be updated when unpickling to use the
161  new object id values instantiated during the unpickle.
162 
163  """
164  self.__dict__.update(pkldict)
165  tmpDict = {}
166  for value in self._cloneToObjectDict.values():
167  tmpDict[id(value)] = value
168  self.__dict__['_cloneToObjectDict'] = tmpDict
169 
170 
171 
172  def filters_(self):
173  """returns a dict of the filters that have been added to the Process"""
174  return DictTypes.FixedKeysDict(self.__filters)
175  filters = property(filters_, doc="dictionary containing the filters for the process")
176  def name_(self):
177  return self.__name
178  def setName_(self,name):
179  if not name.isalnum():
180  raise RuntimeError("Error: The process name is an empty string or contains non-alphanumeric characters")
181  self.__dict__['_Process__name'] = name
182  process = property(name_,setName_, doc="name of the process")
183  def producers_(self):
184  """returns a dict of the producers that have been added to the Process"""
185  return DictTypes.FixedKeysDict(self.__producers)
186  producers = property(producers_,doc="dictionary containing the producers for the process")
187  def source_(self):
188  """returns the source that has been added to the Process or None if none have been added"""
189  return self.__source
190  def setSource_(self,src):
191  self._placeSource('source',src)
192  source = property(source_,setSource_,doc='the main source or None if not set')
193  def looper_(self):
194  """returns the looper that has been added to the Process or None if none have been added"""
195  return self.__looper
196  def setLooper_(self,lpr):
197  self._placeLooper('looper',lpr)
198  looper = property(looper_,setLooper_,doc='the main looper or None if not set')
199  def subProcesses_(self):
200  """returns a list of the subProcesses that have been added to the Process"""
201  return self.__subProcesses
202  subProcesses = property(subProcesses_,doc='the SubProcesses that have been added to the Process')
203  def analyzers_(self):
204  """returns a dict of the analyzers that have been added to the Process"""
205  return DictTypes.FixedKeysDict(self.__analyzers)
206  analyzers = property(analyzers_,doc="dictionary containing the analyzers for the process")
207  def outputModules_(self):
208  """returns a dict of the output modules that have been added to the Process"""
209  return DictTypes.FixedKeysDict(self.__outputmodules)
210  outputModules = property(outputModules_,doc="dictionary containing the output_modules for the process")
211  def paths_(self):
212  """returns a dict of the paths that have been added to the Process"""
213  return DictTypes.SortedAndFixedKeysDict(self.__paths)
214  paths = property(paths_,doc="dictionary containing the paths for the process")
215  def endpaths_(self):
216  """returns a dict of the endpaths that have been added to the Process"""
217  return DictTypes.SortedAndFixedKeysDict(self.__endpaths)
218  endpaths = property(endpaths_,doc="dictionary containing the endpaths for the process")
219  def sequences_(self):
220  """returns a dict of the sequences that have been added to the Process"""
221  return DictTypes.FixedKeysDict(self.__sequences)
222  sequences = property(sequences_,doc="dictionary containing the sequences for the process")
223  def tasks_(self):
224  """returns a dict of the tasks that have been added to the Process"""
225  return DictTypes.FixedKeysDict(self.__tasks)
226  tasks = property(tasks_,doc="dictionary containing the tasks for the process")
227  def schedule_(self):
228  """returns the schedule that has been added to the Process or None if none have been added"""
229  return self.__schedule
230  def setPartialSchedule_(self,sch,label):
231  if label == "schedule":
232  self.setSchedule_(sch)
233  else:
234  self._place(label, sch, self.__partialschedules)
235  def setSchedule_(self,sch):
236  # See if every path and endpath has been inserted into the process
237  index = 0
238  try:
239  for p in sch:
240  p.label_()
241  index +=1
242  except:
243  raise RuntimeError("The path at index "+str(index)+" in the Schedule was not attached to the process.")
244  self.__dict__['_Process__schedule'] = sch
245  schedule = property(schedule_,setSchedule_,doc='the schedule or None if not set')
246  def services_(self):
247  """returns a dict of the services that have been added to the Process"""
248  return DictTypes.FixedKeysDict(self.__services)
249  services = property(services_,doc="dictionary containing the services for the process")
250  def es_producers_(self):
251  """returns a dict of the esproducers that have been added to the Process"""
252  return DictTypes.FixedKeysDict(self.__esproducers)
253  es_producers = property(es_producers_,doc="dictionary containing the es_producers for the process")
254  def es_sources_(self):
255  """returns a the es_sources that have been added to the Process"""
256  return DictTypes.FixedKeysDict(self.__essources)
257  es_sources = property(es_sources_,doc="dictionary containing the es_sources for the process")
258  def es_prefers_(self):
259  """returns a dict of the es_prefers that have been added to the Process"""
260  return DictTypes.FixedKeysDict(self.__esprefers)
261  es_prefers = property(es_prefers_,doc="dictionary containing the es_prefers for the process")
262  def aliases_(self):
263  """returns a dict of the aliases that have been added to the Process"""
264  return DictTypes.FixedKeysDict(self.__aliases)
265  aliases = property(aliases_,doc="dictionary containing the aliases for the process")
266  def psets_(self):
267  """returns a dict of the PSets that have been added to the Process"""
268  return DictTypes.FixedKeysDict(self.__psets)
269  psets = property(psets_,doc="dictionary containing the PSets for the process")
270  def vpsets_(self):
271  """returns a dict of the VPSets that have been added to the Process"""
272  return DictTypes.FixedKeysDict(self.__vpsets)
273  vpsets = property(vpsets_,doc="dictionary containing the PSets for the process")
274 
275  def isUsingModifier(self,mod):
276  """returns True if the Modifier is in used by this Process"""
277  if mod.isChosen():
278  for m in self.__modifiers:
279  if m._isOrContains(mod):
280  return True
281  return False
282 
283  def __setObjectLabel(self, object, newLabel) :
284  if not object.hasLabel_() :
285  object.setLabel(newLabel)
286  return
287  if newLabel == object.label_() :
288  return
289  if newLabel is None :
290  object.setLabel(None)
291  return
292  if (hasattr(self, object.label_()) and id(getattr(self, object.label_())) == id(object)) :
293  msg100 = "Attempting to change the label of an attribute of the Process\n"
294  msg101 = "Old label = "+object.label_()+" New label = "+newLabel+"\n"
295  msg102 = "Type = "+str(type(object))+"\n"
296  msg103 = "Some possible solutions:\n"
297  msg104 = " 1. Clone modules instead of using simple assignment. Cloning is\n"
298  msg105 = " also preferred for other types when possible.\n"
299  msg106 = " 2. Declare new names starting with an underscore if they are\n"
300  msg107 = " for temporaries you do not want propagated into the Process. The\n"
301  msg108 = " underscore tells \"from x import *\" and process.load not to import\n"
302  msg109 = " the name.\n"
303  msg110 = " 3. Reorganize so the assigment is not necessary. Giving a second\n"
304  msg111 = " name to the same object usually causes confusion and problems.\n"
305  msg112 = " 4. Compose Sequences: newName = cms.Sequence(oldName)\n"
306  raise ValueError(msg100+msg101+msg102+msg103+msg104+msg105+msg106+msg107+msg108+msg109+msg110+msg111+msg112)
307  object.setLabel(None)
308  object.setLabel(newLabel)
309 
310  def __setattr__(self,name,value):
311  # check if the name is well-formed (only _ and alphanumerics are allowed)
312  if not name.replace('_','').isalnum():
313  raise ValueError('The label '+name+' contains forbiden characters')
314 
315  # private variable exempt from all this
316  if name.startswith('_Process__'):
317  self.__dict__[name]=value
318  return
319  if not isinstance(value,_ConfigureComponent):
320  raise TypeError("can only assign labels to an object that inherits from '_ConfigureComponent'\n"
321  +"an instance of "+str(type(value))+" will not work - requested label is "+name)
322  if not isinstance(value,_Labelable) and not isinstance(value,Source) and not isinstance(value,Looper) and not isinstance(value,Schedule):
323  if name == value.type_():
324  # Only Services get handled here
325  self.add_(value)
326  return
327  else:
328  raise TypeError("an instance of "+str(type(value))+" can not be assigned the label '"+name+"'.\n"+
329  "Please either use the label '"+value.type_()+" or use the 'add_' method instead.")
330  #clone the item
331  if self.__isStrict:
332  newValue =value.copy()
333  try:
334  newValue._filename = value._filename
335  except:
336  pass
337  value.setIsFrozen()
338  else:
339  newValue =value
340  if not self._okToPlace(name, value, self.__dict__):
341  newFile='top level config'
342  if hasattr(value,'_filename'):
343  newFile = value._filename
344  oldFile='top level config'
345  oldValue = getattr(self,name)
346  if hasattr(oldValue,'_filename'):
347  oldFile = oldValue._filename
348  msg = "Trying to override definition of process."+name
349  msg += "\n new object defined in: "+newFile
350  msg += "\n existing object defined in: "+oldFile
351  raise ValueError(msg)
352  # remove the old object of the name (if there is one)
353  if hasattr(self,name) and not (getattr(self,name)==newValue):
354  # Complain if items in sequences or tasks from load() statements have
355  # degenerate names, but if the user overwrites a name in the
356  # main config, replace it everywhere
357  if newValue._isTaskComponent():
358  if not self.__InExtendCall:
359  self._replaceInTasks(name, newValue)
360  self._replaceInSchedule(name, newValue)
361  else:
362  if not isinstance(newValue, Task):
363  #should check to see if used in task before complaining
364  newFile='top level config'
365  if hasattr(value,'_filename'):
366  newFile = value._filename
367  oldFile='top level config'
368  oldValue = getattr(self,name)
369  if hasattr(oldValue,'_filename'):
370  oldFile = oldValue._filename
371  msg1 = "Trying to override definition of "+name+" while it is used by the task "
372  msg2 = "\n new object defined in: "+newFile
373  msg2 += "\n existing object defined in: "+oldFile
374  s = self.__findFirstUsingModule(self.tasks,oldValue)
375  if s is not None:
376  raise ValueError(msg1+s.label_()+msg2)
377 
378  if isinstance(newValue, _Sequenceable) or newValue._isTaskComponent():
379  if not self.__InExtendCall:
380  self._replaceInSequences(name, newValue)
381  else:
382  #should check to see if used in sequence before complaining
383  newFile='top level config'
384  if hasattr(value,'_filename'):
385  newFile = value._filename
386  oldFile='top level config'
387  oldValue = getattr(self,name)
388  if hasattr(oldValue,'_filename'):
389  oldFile = oldValue._filename
390  msg1 = "Trying to override definition of "+name+" while it is used by the "
391  msg2 = "\n new object defined in: "+newFile
392  msg2 += "\n existing object defined in: "+oldFile
393  s = self.__findFirstUsingModule(self.sequences,oldValue)
394  if s is not None:
395  raise ValueError(msg1+"sequence "+s.label_()+msg2)
396  s = self.__findFirstUsingModule(self.paths,oldValue)
397  if s is not None:
398  raise ValueError(msg1+"path "+s.label_()+msg2)
399  s = self.__findFirstUsingModule(self.endpaths,oldValue)
400  if s is not None:
401  raise ValueError(msg1+"endpath "+s.label_()+msg2)
402  self._delattrFromSetattr(name)
403  self.__dict__[name]=newValue
404  if isinstance(newValue,_Labelable):
405  self.__setObjectLabel(newValue, name)
406  self._cloneToObjectDict[id(value)] = newValue
407  self._cloneToObjectDict[id(newValue)] = newValue
408  #now put in proper bucket
409  newValue._place(name,self)
410  def __findFirstUsingModule(self, seqsOrTasks, mod):
411  """Given a container of sequences or tasks, find the first sequence or task
412  containing mod and return it. If none is found, return None"""
413  from FWCore.ParameterSet.SequenceTypes import ModuleNodeVisitor
414  l = list()
415  for seqOrTask in six.itervalues(seqsOrTasks):
416  l[:] = []
417  v = ModuleNodeVisitor(l)
418  seqOrTask.visit(v)
419  if mod in l:
420  return seqOrTask
421  return None
422 
423  def _delHelper(self,name):
424  if not hasattr(self,name):
425  raise KeyError('process does not know about '+name)
426  elif name.startswith('_Process__'):
427  raise ValueError('this attribute cannot be deleted')
428 
429  # we have to remove it from all dictionaries/registries
430  dicts = [item for item in self.__dict__.values() if (isinstance(item, dict) or isinstance(item, DictTypes.SortedKeysDict))]
431  for reg in dicts:
432  if name in reg: del reg[name]
433  # if it was a labelable object, the label needs to be removed
434  obj = getattr(self,name)
435  if isinstance(obj,_Labelable):
436  obj.setLabel(None)
437  if isinstance(obj,Service):
438  obj._inProcess = False
439 
440  def __delattr__(self,name):
441  self._delHelper(name)
442  obj = getattr(self,name)
443  if not obj is None:
444  if not isinstance(obj, Sequence) and not isinstance(obj, Task):
445  # For modules, ES modules and services we can also remove
446  # the deleted object from Sequences, Paths, EndPaths, and
447  # Tasks. Note that for Sequences and Tasks that cannot be done
448  # reliably as the places where the Sequence or Task was used
449  # might have been expanded so we do not even try. We considered
450  # raising an exception if a Sequences or Task was explicitly
451  # deleted, but did not because when done carefully deletion
452  # is sometimes OK (for example in the prune function where it
453  # has been checked that the deleted Sequence is not used).
454  if obj._isTaskComponent():
455  self._replaceInTasks(name, None)
456  self._replaceInSchedule(name, None)
457  if isinstance(obj, _Sequenceable) or obj._isTaskComponent():
458  self._replaceInSequences(name, None)
459  # now remove it from the process itself
460  try:
461  del self.__dict__[name]
462  except:
463  pass
464 
465  def _delattrFromSetattr(self,name):
466  """Similar to __delattr__ but we need different behavior when called from __setattr__"""
467  self._delHelper(name)
468  # now remove it from the process itself
469  try:
470  del self.__dict__[name]
471  except:
472  pass
473 
474  def add_(self,value):
475  """Allows addition of components that do not have to have a label, e.g. Services"""
476  if not isinstance(value,_ConfigureComponent):
477  raise TypeError
478  if not isinstance(value,_Unlabelable):
479  raise TypeError
480  #clone the item
481  #clone the item
482  if self.__isStrict:
483  newValue =value.copy()
484  value.setIsFrozen()
485  else:
486  newValue =value
487  newValue._place('',self)
488 
489  def _okToPlace(self, name, mod, d):
490  if not self.__InExtendCall:
491  # if going
492  return True
493  elif not self.__isStrict:
494  return True
495  elif name in d:
496  # if there's an old copy, and the new one
497  # hasn't been modified, we're done. Still
498  # not quite safe if something has been defined twice.
499  # Need to add checks
500  if mod._isModified:
501  if d[name]._isModified:
502  return False
503  else:
504  return True
505  else:
506  return True
507  else:
508  return True
509 
510  def _place(self, name, mod, d):
511  if self._okToPlace(name, mod, d):
512  if self.__isStrict and isinstance(mod, _ModuleSequenceType):
513  d[name] = mod._postProcessFixup(self._cloneToObjectDict)
514  else:
515  d[name] = mod
516  if isinstance(mod,_Labelable):
517  self.__setObjectLabel(mod, name)
518  def _placeOutputModule(self,name,mod):
519  self._place(name, mod, self.__outputmodules)
520  def _placeProducer(self,name,mod):
521  self._place(name, mod, self.__producers)
522  def _placeFilter(self,name,mod):
523  self._place(name, mod, self.__filters)
524  def _placeAnalyzer(self,name,mod):
525  self._place(name, mod, self.__analyzers)
526  def _placePath(self,name,mod):
527  self._validateSequence(mod, name)
528  try:
529  self._place(name, mod, self.__paths)
530  except ModuleCloneError as msg:
531  context = format_outerframe(4)
532  raise Exception("%sThe module %s in path %s is unknown to the process %s." %(context, msg, name, self._Process__name))
533  def _placeEndPath(self,name,mod):
534  self._validateSequence(mod, name)
535  try:
536  self._place(name, mod, self.__endpaths)
537  except ModuleCloneError as msg:
538  context = format_outerframe(4)
539  raise Exception("%sThe module %s in endpath %s is unknown to the process %s." %(context, msg, name, self._Process__name))
540  def _placeSequence(self,name,mod):
541  self._validateSequence(mod, name)
542  self._place(name, mod, self.__sequences)
543  def _placeESProducer(self,name,mod):
544  self._place(name, mod, self.__esproducers)
545  def _placeESPrefer(self,name,mod):
546  self._place(name, mod, self.__esprefers)
547  def _placeESSource(self,name,mod):
548  self._place(name, mod, self.__essources)
549  def _placeTask(self,name,task):
550  self._validateTask(task, name)
551  self._place(name, task, self.__tasks)
552  def _placeAlias(self,name,mod):
553  self._place(name, mod, self.__aliases)
554  def _placePSet(self,name,mod):
555  self._place(name, mod, self.__psets)
556  def _placeVPSet(self,name,mod):
557  self._place(name, mod, self.__vpsets)
558  def _placeSource(self,name,mod):
559  """Allow the source to be referenced by 'source' or by type name"""
560  if name != 'source':
561  raise ValueError("The label '"+name+"' can not be used for a Source. Only 'source' is allowed.")
562  if self.__dict__['_Process__source'] is not None :
563  del self.__dict__[self.__dict__['_Process__source'].type_()]
564  self.__dict__['_Process__source'] = mod
565  self.__dict__[mod.type_()] = mod
566  def _placeLooper(self,name,mod):
567  if name != 'looper':
568  raise ValueError("The label '"+name+"' can not be used for a Looper. Only 'looper' is allowed.")
569  self.__dict__['_Process__looper'] = mod
570  self.__dict__[mod.type_()] = mod
571  def _placeSubProcess(self,name,mod):
572  self.__dict__['_Process__subProcess'] = mod
573  self.__dict__[mod.type_()] = mod
574  def addSubProcess(self,mod):
575  self.__subProcesses.append(mod)
576  def _placeService(self,typeName,mod):
577  self._place(typeName, mod, self.__services)
578  if typeName in self.__dict__:
579  self.__dict__[typeName]._inProcess = False
580  self.__dict__[typeName]=mod
581  def load(self, moduleName):
582  moduleName = moduleName.replace("/",".")
583  module = __import__(moduleName)
584  self.extend(sys.modules[moduleName])
585  def extend(self,other,items=()):
586  """Look in other and find types that we can use"""
587  # enable explicit check to avoid overwriting of existing objects
588  self.__dict__['_Process__InExtendCall'] = True
589 
590  seqs = dict()
591  tasksToAttach = dict()
592  mods = []
593  for name in dir(other):
594  #'from XX import *' ignores these, and so should we.
595  if name.startswith('_'):
596  continue
597  item = getattr(other,name)
598  if name == "source" or name == "looper":
599  # In these cases 'item' could be None if the specific object was not defined
600  if item is not None:
601  self.__setattr__(name,item)
602  elif isinstance(item,_ModuleSequenceType):
603  seqs[name]=item
604  elif isinstance(item,Task):
605  tasksToAttach[name] = item
606  elif isinstance(item,_Labelable):
607  self.__setattr__(name,item)
608  if not item.hasLabel_() :
609  item.setLabel(name)
610  elif isinstance(item,Schedule):
611  self.__setattr__(name,item)
612  elif isinstance(item,_Unlabelable):
613  self.add_(item)
614  elif isinstance(item,ProcessModifier):
615  mods.append(item)
616  elif isinstance(item,ProcessFragment):
617  self.extend(item)
618 
619  #now create a sequence that uses the newly made items
620  for name in seqs.iterkeys():
621  seq = seqs[name]
622  #newSeq = seq.copy()
623  #
624  if id(seq) not in self._cloneToObjectDict:
625  self.__setattr__(name,seq)
626  else:
627  newSeq = self._cloneToObjectDict[id(seq)]
628  self.__dict__[name]=newSeq
629  self.__setObjectLabel(newSeq, name)
630  #now put in proper bucket
631  newSeq._place(name,self)
632 
633  for name in tasksToAttach.iterkeys():
634  task = tasksToAttach[name]
635  self.__setattr__(name, task)
636 
637  #apply modifiers now that all names have been added
638  for item in mods:
639  item.apply(self)
640 
641  self.__dict__['_Process__InExtendCall'] = False
642 
643  def _dumpConfigNamedList(self,items,typeName,options):
644  returnValue = ''
645  for name,item in items:
646  returnValue +=options.indentation()+typeName+' '+name+' = '+item.dumpConfig(options)
647  return returnValue
648  def _dumpConfigUnnamedList(self,items,typeName,options):
649  returnValue = ''
650  for name,item in items:
651  returnValue +=options.indentation()+typeName+' = '+item.dumpConfig(options)
652  return returnValue
653  def _dumpConfigOptionallyNamedList(self,items,typeName,options):
654  returnValue = ''
655  for name,item in items:
656  if name == item.type_():
657  name = ''
658  returnValue +=options.indentation()+typeName+' '+name+' = '+item.dumpConfig(options)
659  return returnValue
660  def dumpConfig(self, options=PrintOptions()):
661  """return a string containing the equivalent process defined using the old configuration language"""
662  config = "process "+self.__name+" = {\n"
663  options.indent()
664  if self.source_():
665  config += options.indentation()+"source = "+self.source_().dumpConfig(options)
666  if self.looper_():
667  config += options.indentation()+"looper = "+self.looper_().dumpConfig(options)
668 
669  config+=self._dumpConfigNamedList(self.subProcesses_(),
670  'subProcess',
671  options)
672  config+=self._dumpConfigNamedList(six.iteritems(self.producers_()),
673  'module',
674  options)
675  config+=self._dumpConfigNamedList(six.iteritems(self.filters_()),
676  'module',
677  options)
678  config+=self._dumpConfigNamedList(six.iteritems(self.analyzers_()),
679  'module',
680  options)
681  config+=self._dumpConfigNamedList(six.iteritems(self.outputModules_()),
682  'module',
683  options)
684  config+=self._dumpConfigNamedList(six.iteritems(self.sequences_()),
685  'sequence',
686  options)
687  config+=self._dumpConfigNamedList(six.iteritems(self.paths_()),
688  'path',
689  options)
690  config+=self._dumpConfigNamedList(six.iteritems(self.endpaths_()),
691  'endpath',
692  options)
693  config+=self._dumpConfigUnnamedList(six.iteritems(self.services_()),
694  'service',
695  options)
696  config+=self._dumpConfigNamedList(six.iteritems(self.aliases_()),
697  'alias',
698  options)
699  config+=self._dumpConfigOptionallyNamedList(
700  six.iteritems(self.es_producers_()),
701  'es_module',
702  options)
703  config+=self._dumpConfigOptionallyNamedList(
704  six.iteritems(self.es_sources_()),
705  'es_source',
706  options)
707  config += self._dumpConfigESPrefers(options)
708  for name,item in six.iteritems(self.psets):
709  config +=options.indentation()+item.configTypeName()+' '+name+' = '+item.configValue(options)
710  for name,item in six.iteritems(self.vpsets):
711  config +=options.indentation()+'VPSet '+name+' = '+item.configValue(options)
712  if self.schedule:
713  pathNames = [p.label_() for p in self.schedule]
714  config +=options.indentation()+'schedule = {'+','.join(pathNames)+'}\n'
715 
716 # config+=self._dumpConfigNamedList(six.iteritems(self.vpsets),
717 # 'VPSet',
718 # options)
719  config += "}\n"
720  options.unindent()
721  return config
722  def _dumpConfigESPrefers(self, options):
723  result = ''
724  for item in six.itervalues(self.es_prefers_()):
725  result +=options.indentation()+'es_prefer '+item.targetLabel_()+' = '+item.dumpConfig(options)
726  return result
727  def _dumpPythonSubProcesses(self, l, options):
728  returnValue = ''
729  for item in l:
730  returnValue += item.dumpPython(options)+'\n\n'
731  return returnValue
732  def _dumpPythonList(self, d, options):
733  returnValue = ''
734  if isinstance(d, DictTypes.SortedKeysDict):
735  for name,item in d.items():
736  returnValue +='process.'+name+' = '+item.dumpPython(options)+'\n\n'
737  else:
738  for name,item in sorted(d.items()):
739  returnValue +='process.'+name+' = '+item.dumpPython(options)+'\n\n'
740  return returnValue
741  def _validateSequence(self, sequence, label):
742  # See if every module has been inserted into the process
743  try:
744  l = set()
745  visitor = NodeNameVisitor(l)
746  sequence.visit(visitor)
747  except:
748  raise RuntimeError("An entry in sequence "+label + ' has no label')
749  def _validateTask(self, task, label):
750  # See if every module and service has been inserted into the process
751  try:
752  l = set()
753  visitor = NodeNameVisitor(l)
754  task.visit(visitor)
755  except:
756  raise RuntimeError("An entry in task " + label + ' has not been attached to the process')
757  def _itemsInDependencyOrder(self, processDictionaryOfItems):
758  # The items can be Sequences or Tasks and the input
759  # argument should either be the dictionary of sequences
760  # or the dictionary of tasks from the process.
761 
762  returnValue=DictTypes.SortedKeysDict()
763 
764  # For each item, see what other items it depends upon
765  # For our purpose here, an item depends on the items it contains.
766  dependencies = {}
767  for label,item in six.iteritems(processDictionaryOfItems):
768  containedItems = []
769  if isinstance(item, Task):
770  v = TaskVisitor(containedItems)
771  else:
772  v = SequenceVisitor(containedItems)
773  try:
774  item.visit(v)
775  except RuntimeError:
776  if isinstance(item, Task):
777  raise RuntimeError("Failed in a Task visitor. Probably " \
778  "a circular dependency discovered in Task with label " + label)
779  else:
780  raise RuntimeError("Failed in a Sequence visitor. Probably a " \
781  "circular dependency discovered in Sequence with label " + label)
782  for containedItem in containedItems:
783  # Check for items that both have labels and are not in the process.
784  # This should not normally occur unless someone explicitly assigns a
785  # label without putting the item in the process (which should not ever
786  # be done). We check here because this problem could cause the code
787  # in the 'while' loop below to go into an infinite loop.
788  if containedItem.hasLabel_():
789  testItem = processDictionaryOfItems.get(containedItem.label_())
790  if testItem is None or containedItem != testItem:
791  if isinstance(item, Task):
792  raise RuntimeError("Task has a label, but using its label to get an attribute" \
793  " from the process yields a different object or None\n"+
794  "label = " + containedItem.label_())
795  else:
796  raise RuntimeError("Sequence has a label, but using its label to get an attribute" \
797  " from the process yields a different object or None\n"+
798  "label = " + containedItem.label_())
799  dependencies[label]=[dep.label_() for dep in containedItems if dep.hasLabel_()]
800 
801  # keep looping until we get rid of all dependencies
802  while dependencies:
803  oldDeps = dict(dependencies)
804  for label,deps in six.iteritems(oldDeps):
805  if len(deps)==0:
806  returnValue[label]=processDictionaryOfItems[label]
807  #remove this as a dependency for all other tasks
808  del dependencies[label]
809  for lb2,deps2 in six.iteritems(dependencies):
810  while deps2.count(label):
811  deps2.remove(label)
812  return returnValue
813  def _dumpPython(self, d, options):
814  result = ''
815  for name, value in sorted(six.iteritems(d)):
816  result += value.dumpPythonAs(name,options)+'\n'
817  return result
818  def dumpPython(self, options=PrintOptions()):
819  """return a string containing the equivalent process defined using python"""
820  result = "import FWCore.ParameterSet.Config as cms\n\n"
821  result += "process = cms.Process(\""+self.__name+"\")\n\n"
822  if self.source_():
823  result += "process.source = "+self.source_().dumpPython(options)
824  if self.looper_():
825  result += "process.looper = "+self.looper_().dumpPython()
826  result+=self._dumpPythonList(self.psets, options)
827  result+=self._dumpPythonList(self.vpsets, options)
828  result+=self._dumpPythonSubProcesses(self.subProcesses_(), options)
829  result+=self._dumpPythonList(self.producers_(), options)
830  result+=self._dumpPythonList(self.filters_() , options)
831  result+=self._dumpPythonList(self.analyzers_(), options)
832  result+=self._dumpPythonList(self.outputModules_(), options)
833  result+=self._dumpPythonList(self.services_(), options)
834  result+=self._dumpPythonList(self.es_producers_(), options)
835  result+=self._dumpPythonList(self.es_sources_(), options)
836  result+=self._dumpPython(self.es_prefers_(), options)
837  result+=self._dumpPythonList(self._itemsInDependencyOrder(self.tasks), options)
838  result+=self._dumpPythonList(self._itemsInDependencyOrder(self.sequences), options)
839  result+=self._dumpPythonList(self.paths_(), options)
840  result+=self._dumpPythonList(self.endpaths_(), options)
841  result+=self._dumpPythonList(self.aliases_(), options)
842  if not self.schedule_() == None:
843  result += 'process.schedule = ' + self.schedule.dumpPython(options)
844  return result
845  def _replaceInSequences(self, label, new):
846  old = getattr(self,label)
847  #TODO - replace by iterator concatenation
848  for sequenceable in six.itervalues(self.sequences):
849  sequenceable.replace(old,new)
850  for sequenceable in six.itervalues(self.paths):
851  sequenceable.replace(old,new)
852  for sequenceable in six.itervalues(self.endpaths):
853  sequenceable.replace(old,new)
854  def _replaceInTasks(self, label, new):
855  old = getattr(self,label)
856  for task in six.itervalues(self.tasks):
857  task.replace(old, new)
858  def _replaceInSchedule(self, label, new):
859  if self.schedule_() == None:
860  return
861  old = getattr(self,label)
862  for task in self.schedule_()._tasks:
863  task.replace(old, new)
864  def globalReplace(self,label,new):
865  """ Replace the item with label 'label' by object 'new' in the process and all sequences/paths/tasks"""
866  if not hasattr(self,label):
867  raise LookupError("process has no item of label "+label)
868  setattr(self,label,new)
869  def _insertInto(self, parameterSet, itemDict):
870  for name,value in six.iteritems(itemDict):
871  value.insertInto(parameterSet, name)
872  def _insertOneInto(self, parameterSet, label, item, tracked):
873  vitems = []
874  if not item == None:
875  newlabel = item.nameInProcessDesc_(label)
876  vitems = [newlabel]
877  item.insertInto(parameterSet, newlabel)
878  parameterSet.addVString(tracked, label, vitems)
879  def _insertManyInto(self, parameterSet, label, itemDict, tracked):
880  l = []
881  for name,value in six.iteritems(itemDict):
882  newLabel = value.nameInProcessDesc_(name)
883  l.append(newLabel)
884  value.insertInto(parameterSet, name)
885  # alphabetical order is easier to compare with old language
886  l.sort()
887  parameterSet.addVString(tracked, label, l)
888  def _insertSubProcessesInto(self, parameterSet, label, itemList, tracked):
889  l = []
890  subprocs = []
891  for value in itemList:
892  name = value.getProcessName()
893  newLabel = value.nameInProcessDesc_(name)
894  l.append(newLabel)
895  pset = value.getSubProcessPSet(parameterSet)
896  subprocs.append(pset)
897  # alphabetical order is easier to compare with old language
898  l.sort()
899  parameterSet.addVString(tracked, label, l)
900  parameterSet.addVPSet(False,"subProcesses",subprocs)
901  def _insertPaths(self, processPSet, nodeVisitor):
902  scheduledPaths = []
903  triggerPaths = []
904  endpaths = []
905  if self.schedule_() == None:
906  # make one from triggerpaths & endpaths
907  for name in self.paths_():
908  scheduledPaths.append(name)
909  triggerPaths.append(name)
910  for name in self.endpaths_():
911  scheduledPaths.append(name)
912  endpaths.append(name)
913  else:
914  for path in self.schedule_():
915  pathname = path.label_()
916  scheduledPaths.append(pathname)
917  if pathname in self.endpaths_():
918  endpaths.append(pathname)
919  else:
920  triggerPaths.append(pathname)
921  for task in self.schedule_()._tasks:
922  task.resolve(self.__dict__)
923  scheduleTaskValidator = ScheduleTaskValidator()
924  task.visit(scheduleTaskValidator)
925  task.visit(nodeVisitor)
926  processPSet.addVString(True, "@end_paths", endpaths)
927  processPSet.addVString(True, "@paths", scheduledPaths)
928  # trigger_paths are a little different
929  p = processPSet.newPSet()
930  p.addVString(True, "@trigger_paths", triggerPaths)
931  processPSet.addPSet(True, "@trigger_paths", p)
932  # add all these paths
933  pathValidator = PathValidator()
934  endpathValidator = EndPathValidator()
935  decoratedList = []
936  lister = DecoratedNodeNameVisitor(decoratedList)
937  pathCompositeVisitor = CompositeVisitor(pathValidator, nodeVisitor, lister)
938  endpathCompositeVisitor = CompositeVisitor(endpathValidator, nodeVisitor, lister)
939  for triggername in triggerPaths:
940  iPath = self.paths_()[triggername]
941  iPath.resolve(self.__dict__)
942  pathValidator.setLabel(triggername)
943  lister.initialize()
944  iPath.visit(pathCompositeVisitor)
945  iPath.insertInto(processPSet, triggername, decoratedList)
946  for endpathname in endpaths:
947  iEndPath = self.endpaths_()[endpathname]
948  iEndPath.resolve(self.__dict__)
949  endpathValidator.setLabel(endpathname)
950  lister.initialize()
951  iEndPath.visit(endpathCompositeVisitor)
952  iEndPath.insertInto(processPSet, endpathname, decoratedList)
953  processPSet.addVString(False, "@filters_on_endpaths", endpathValidator.filtersOnEndpaths)
954 
955  def resolve(self,keepUnresolvedSequencePlaceholders=False):
956  for x in six.itervalues(self.paths):
957  x.resolve(self.__dict__,keepUnresolvedSequencePlaceholders)
958  for x in six.itervalues(self.endpaths):
959  x.resolve(self.__dict__,keepUnresolvedSequencePlaceholders)
960  if not self.schedule_() == None:
961  for task in self.schedule_()._tasks:
962  task.resolve(self.__dict__,keepUnresolvedSequencePlaceholders)
963 
964  def prune(self,verbose=False,keepUnresolvedSequencePlaceholders=False):
965  """ Remove clutter from the process that we think is unnecessary:
966  tracked PSets, VPSets and unused modules and sequences. If a Schedule has been set, then Paths and EndPaths
967  not in the schedule will also be removed, along with an modules and sequences used only by
968  those removed Paths and EndPaths."""
969 # need to update this to only prune psets not on refToPSets
970 # but for now, remove the delattr
971 # for name in self.psets_():
972 # if getattr(self,name).isTracked():
973 # delattr(self, name)
974  for name in self.vpsets_():
975  delattr(self, name)
976  #first we need to resolve any SequencePlaceholders being used
977  self.resolve(keepUnresolvedSequencePlaceholders)
978  usedModules = set()
979  unneededPaths = set()
980  if self.schedule_():
981  usedModules=set(self.schedule_().moduleNames())
982  #get rid of unused paths
983  schedNames = set(( x.label_() for x in self.schedule_()))
984  names = set(self.paths)
985  names.update(set(self.endpaths))
986  unneededPaths = names - schedNames
987  for n in unneededPaths:
988  delattr(self,n)
989  else:
990  pths = list(six.itervalues(self.paths))
991  pths.extend(six.itervalues(self.endpaths))
992  temp = Schedule(*pths)
993  usedModules=set(temp.moduleNames())
994  unneededModules = self._pruneModules(self.producers_(), usedModules)
995  unneededModules.update(self._pruneModules(self.filters_(), usedModules))
996  unneededModules.update(self._pruneModules(self.analyzers_(), usedModules))
997  #remove sequences that do not appear in remaining paths and endpaths
998  seqs = list()
999  sv = SequenceVisitor(seqs)
1000  for p in six.itervalues(self.paths):
1001  p.visit(sv)
1002  for p in six.itervalues(self.endpaths):
1003  p.visit(sv)
1004  keepSeqSet = set(( s for s in seqs if s.hasLabel_()))
1005  availableSeqs = set(six.itervalues(self.sequences))
1006  unneededSeqs = availableSeqs-keepSeqSet
1007  unneededSeqLabels = []
1008  for s in unneededSeqs:
1009  unneededSeqLabels.append(s.label_())
1010  delattr(self,s.label_())
1011  if verbose:
1012  print "prune removed the following:"
1013  print " modules:"+",".join(unneededModules)
1014  print " sequences:"+",".join(unneededSeqLabels)
1015  print " paths/endpaths:"+",".join(unneededPaths)
1016  def _pruneModules(self, d, scheduledNames):
1017  moduleNames = set(d.keys())
1018  junk = moduleNames - scheduledNames
1019  for name in junk:
1020  delattr(self, name)
1021  return junk
1022 
1023  def fillProcessDesc(self, processPSet):
1024  """Used by the framework to convert python to C++ objects"""
1025  class ServiceInjectorAdaptor(object):
1026  def __init__(self,ppset,thelist):
1027  self.__thelist = thelist
1028  self.__processPSet = ppset
1029  def addService(self,pset):
1030  self.__thelist.append(pset)
1031  def newPSet(self):
1032  return self.__processPSet.newPSet()
1033  #This adaptor is used to 'add' the method 'getTopPSet_'
1034  # to the ProcessDesc and PythonParameterSet C++ classes.
1035  # This method is needed for the PSet refToPSet_ functionality.
1036  class TopLevelPSetAcessorAdaptor(object):
1037  def __init__(self,ppset,process):
1038  self.__ppset = ppset
1039  self.__process = process
1040  def __getattr__(self,attr):
1041  return getattr(self.__ppset,attr)
1042  def getTopPSet_(self,label):
1043  return getattr(self.__process,label)
1044  def newPSet(self):
1045  return TopLevelPSetAcessorAdaptor(self.__ppset.newPSet(),self.__process)
1046  def addPSet(self,tracked,name,ppset):
1047  return self.__ppset.addPSet(tracked,name,self.__extractPSet(ppset))
1048  def addVPSet(self,tracked,name,vpset):
1049  return self.__ppset.addVPSet(tracked,name,[self.__extractPSet(x) for x in vpset])
1050  def __extractPSet(self,pset):
1051  if isinstance(pset,TopLevelPSetAcessorAdaptor):
1052  return pset.__ppset
1053  return pset
1054 
1055  self.validate()
1056  processPSet.addString(True, "@process_name", self.name_())
1057  all_modules = self.producers_().copy()
1058  all_modules.update(self.filters_())
1059  all_modules.update(self.analyzers_())
1060  all_modules.update(self.outputModules_())
1061  adaptor = TopLevelPSetAcessorAdaptor(processPSet,self)
1062  self._insertInto(adaptor, self.psets_())
1063  self._insertInto(adaptor, self.vpsets_())
1064  self._insertOneInto(adaptor, "@all_sources", self.source_(), True)
1065  self._insertOneInto(adaptor, "@all_loopers", self.looper_(), True)
1066  self._insertSubProcessesInto(adaptor, "@all_subprocesses", self.subProcesses_(), False)
1067  self._insertManyInto(adaptor, "@all_esprefers", self.es_prefers_(), True)
1068  self._insertManyInto(adaptor, "@all_aliases", self.aliases_(), True)
1069  # This will visit all the paths and endpaths that are scheduled to run,
1070  # as well as the Tasks associated to them and the schedule. It remembers
1071  # the modules, ESSources, ESProducers, and services it visits.
1072  nodeVisitor = NodeVisitor()
1073  self._insertPaths(adaptor, nodeVisitor)
1074  all_modules_onTasksOrScheduled = { key:value for key, value in six.iteritems(all_modules) if value in nodeVisitor.modules }
1075  self._insertManyInto(adaptor, "@all_modules", all_modules_onTasksOrScheduled, True)
1076  # Same as nodeVisitor except this one visits all the Tasks attached
1077  # to the process.
1078  processNodeVisitor = NodeVisitor()
1079  for pTask in six.itervalues(self.tasks):
1080  pTask.visit(processNodeVisitor)
1081  esProducersToEnable = {}
1082  for esProducerName, esProducer in six.iteritems(self.es_producers_()):
1083  if esProducer in nodeVisitor.esProducers or not (esProducer in processNodeVisitor.esProducers):
1084  esProducersToEnable[esProducerName] = esProducer
1085  self._insertManyInto(adaptor, "@all_esmodules", esProducersToEnable, True)
1086  esSourcesToEnable = {}
1087  for esSourceName, esSource in six.iteritems(self.es_sources_()):
1088  if esSource in nodeVisitor.esSources or not (esSource in processNodeVisitor.esSources):
1089  esSourcesToEnable[esSourceName] = esSource
1090  self._insertManyInto(adaptor, "@all_essources", esSourcesToEnable, True)
1091  #handle services differently
1092  services = []
1093  for serviceName, serviceObject in six.iteritems(self.services_()):
1094  if serviceObject in nodeVisitor.services or not (serviceObject in processNodeVisitor.services):
1095  serviceObject.insertInto(ServiceInjectorAdaptor(adaptor,services))
1096  adaptor.addVPSet(False,"services",services)
1097  return processPSet
1098 
1099  def validate(self):
1100  # check if there's some input
1101  # Breaks too many unit tests for now
1102  #if self.source_() == None and self.looper_() == None:
1103  # raise RuntimeError("No input source was found for this process")
1104  pass
1105 
1106  def prefer(self, esmodule,*args,**kargs):
1107  """Prefer this ES source or producer. The argument can
1108  either be an object label, e.g.,
1109  process.prefer(process.juicerProducer) (not supported yet)
1110  or a name of an ESSource or ESProducer
1111  process.prefer("juicer")
1112  or a type of unnamed ESSource or ESProducer
1113  process.prefer("JuicerProducer")
1114  In addition, you can pass as a labelled arguments the name of the Record you wish to
1115  prefer where the type passed is a cms.vstring and that vstring can contain the
1116  name of the C++ types in the Record that are being preferred, e.g.,
1117  #prefer all data in record 'OrangeRecord' from 'juicer'
1118  process.prefer("juicer", OrangeRecord=cms.vstring())
1119  or
1120  #prefer only "Orange" data in "OrangeRecord" from "juicer"
1121  process.prefer("juicer", OrangeRecord=cms.vstring("Orange"))
1122  or
1123  #prefer only "Orange" data with label "ExtraPulp" in "OrangeRecord" from "juicer"
1124  ESPrefer("ESJuicerProd", OrangeRecord=cms.vstring("Orange/ExtraPulp"))
1125  """
1126  # see if this refers to a named ESProducer
1127  if isinstance(esmodule, ESSource) or isinstance(esmodule, ESProducer):
1128  raise RuntimeError("Syntax of process.prefer(process.esmodule) not supported yet")
1129  elif self._findPreferred(esmodule, self.es_producers_(),*args,**kargs) or \
1130  self._findPreferred(esmodule, self.es_sources_(),*args,**kargs):
1131  pass
1132  else:
1133  raise RuntimeError("Cannot resolve prefer for "+repr(esmodule))
1134 
1135  def _findPreferred(self, esname, d,*args,**kargs):
1136  # is esname a name in the dictionary?
1137  if esname in d:
1138  typ = d[esname].type_()
1139  if typ == esname:
1140  self.__setattr__( esname+"_prefer", ESPrefer(typ,*args,**kargs) )
1141  else:
1142  self.__setattr__( esname+"_prefer", ESPrefer(typ, esname,*args,**kargs) )
1143  return True
1144  else:
1145  # maybe it's an unnamed ESModule?
1146  found = False
1147  for name, value in six.iteritems(d):
1148  if value.type_() == esname:
1149  if found:
1150  raise RuntimeError("More than one ES module for "+esname)
1151  found = True
1152  self.__setattr__(esname+"_prefer", ESPrefer(d[esname].type_()) )
1153  return found
1154 
1155 
1157  def __init__(self, process):
1158  if isinstance(process, Process):
1159  self.__process = process
1160  elif isinstance(process, str):
1161  self.__process = Process(process)
1162  else:
1163  raise TypeError('a ProcessFragment can only be constructed from an existig Process or from process name')
1164  def __dir__(self):
1165  return [ x for x in dir(self.__process) if isinstance(getattr(self.__process, x), _ConfigureComponent) ]
1166  def __getattribute__(self, name):
1167  if name == '_ProcessFragment__process':
1168  return object.__getattribute__(self, '_ProcessFragment__process')
1169  else:
1170  return getattr(self.__process, name)
1171  def __setattr__(self, name, value):
1172  if name == '_ProcessFragment__process':
1173  object.__setattr__(self, name, value)
1174  else:
1175  setattr(self.__process, name, value)
1176  def __delattr__(self, name):
1177  if name == '_ProcessFragment__process':
1178  pass
1179  else:
1180  return delattr(self.__process, name)
1181 
1182 
1184  """a dictionary with fixed keys"""
1186  raise AttributeError("An FilteredStream defintion cannot be modified after creation.")
1187  _blocked_attribute = property(_blocked_attribute)
1188  __setattr__ = __delitem__ = __setitem__ = clear = _blocked_attribute
1189  pop = popitem = setdefault = update = _blocked_attribute
1190  def __new__(cls, *args, **kw):
1191  new = dict.__new__(cls)
1192  dict.__init__(new, *args, **kw)
1193  keys = sorted(kw.keys())
1194  if keys != ['content', 'dataTier', 'name', 'paths', 'responsible', 'selectEvents']:
1195  raise ValueError("The needed parameters are: content, dataTier, name, paths, responsible, selectEvents")
1196  if not isinstance(kw['name'],str):
1197  raise ValueError("name must be of type string")
1198  if not isinstance(kw['content'], vstring) and not isinstance(kw['content'],str):
1199  raise ValueError("content must be of type vstring or string")
1200  if not isinstance(kw['dataTier'], string):
1201  raise ValueError("dataTier must be of type string")
1202  if not isinstance(kw['selectEvents'], PSet):
1203  raise ValueError("selectEvents must be of type PSet")
1204  if not isinstance(kw['paths'],(tuple, Path)):
1205  raise ValueError("'paths' must be a tuple of paths")
1206  return new
1207  def __init__(self, *args, **kw):
1208  pass
1209  def __repr__(self):
1210  return "FilteredStream object: %s" %self["name"]
1211  def __getattr__(self,attr):
1212  return self[attr]
1213 
1215  """Allows embedding another process within a parent process. This allows one to
1216  chain processes together directly in one cmsRun job rather than having to run
1217  separate jobs that are connected via a temporary file.
1218  """
1219  def __init__(self,process, SelectEvents = untracked.PSet(), outputCommands = untracked.vstring()):
1220  """
1221  """
1222  if not isinstance(process, Process):
1223  raise ValueError("the 'process' argument must be of type cms.Process")
1224  if not isinstance(SelectEvents,PSet):
1225  raise ValueError("the 'SelectEvents' argument must be of type cms.untracked.PSet")
1226  if not isinstance(outputCommands,vstring):
1227  raise ValueError("the 'outputCommands' argument must be of type cms.untracked.vstring")
1228  self.__process = process
1229  self.__SelectEvents = SelectEvents
1230  self.__outputCommands = outputCommands
1231  def dumpPython(self,options=PrintOptions()):
1232  out = "parentProcess"+str(hash(self))+" = process\n"
1233  out += self.__process.dumpPython()
1234  out += "childProcess = process\n"
1235  out += "process = parentProcess"+str(hash(self))+"\n"
1236  out += "process.addSubProcess(cms.SubProcess(process = childProcess, SelectEvents = "+self.__SelectEvents.dumpPython(options) +", outputCommands = "+self.__outputCommands.dumpPython(options) +"))"
1237  return out
1238  def getProcessName(self):
1239  return self.__process.name_()
1240  def process(self):
1241  return self.__process
1242  def SelectEvents(self):
1243  return self.__SelectEvents
1244  def outputCommands(self):
1245  return self.__outputCommands
1246  def type_(self):
1247  return 'subProcess'
1248  def nameInProcessDesc_(self,label):
1249  return label
1250  def _place(self,label,process):
1251  process._placeSubProcess('subProcess',self)
1252  def getSubProcessPSet(self,parameterSet):
1253  topPSet = parameterSet.newPSet()
1254  self.__process.fillProcessDesc(topPSet)
1255  subProcessPSet = parameterSet.newPSet()
1256  self.__SelectEvents.insertInto(subProcessPSet,"SelectEvents")
1257  self.__outputCommands.insertInto(subProcessPSet,"outputCommands")
1258  subProcessPSet.addPSet(False,"process",topPSet)
1259  return subProcessPSet
1260 
1262  """Helper class for Modifier that takes key/value pairs and uses them to reset parameters of the object"""
1263  def __init__(self,args):
1264  self.__args = args
1265  def __call__(self,obj):
1266  params = {}
1267  for k in self.__args.iterkeys():
1268  if hasattr(obj,k):
1269  params[k] = getattr(obj,k)
1271  for k in self.__args.iterkeys():
1272  if k in params:
1273  setattr(obj,k,params[k])
1274  else:
1275  #the parameter must have been removed
1276  delattr(obj,k)
1277  @staticmethod
1279  raise KeyError("Unknown parameter name "+key+" specified while calling Modifier")
1280 
1282  """A helper base class for _AndModifier, _InvertModifier, and _OrModifier to contain the common code"""
1283  def __init__(self, lhs, rhs=None):
1284  self._lhs = lhs
1285  if rhs is not None:
1286  self._rhs = rhs
1287  def toModify(self,obj, func=None,**kw):
1288  Modifier._toModifyCheck(obj,func,**kw)
1289  if not self.isChosen():
1290  return
1291  Modifier._toModify(obj,func,**kw)
1292  def toReplaceWith(self,toObj,fromObj):
1293  Modifier._toReplaceWithCheck(toObj,fromObj)
1294  if not self.isChosen():
1295  return
1296  Modifier._toReplaceWith(toObj,fromObj)
1297  def makeProcessModifier(self,func):
1298  """This is used to create a ProcessModifer that can perform actions on the process as a whole.
1299  This takes as argument a callable object (e.g. function) that takes as its sole argument an instance of Process.
1300  In order to work, the value returned from this function must be assigned to a uniquely named variable."""
1301  return ProcessModifier(self,func)
1302  def __and__(self, other):
1303  return _AndModifier(self,other)
1304  def __invert__(self):
1305  return _InvertModifier(self)
1306  def __or__(self, other):
1307  return _OrModifier(self,other)
1308 
1310  """A modifier which only applies if multiple Modifiers are chosen"""
1311  def __init__(self, lhs, rhs):
1312  super(_AndModifier,self).__init__(lhs, rhs)
1313  def isChosen(self):
1314  return self._lhs.isChosen() and self._rhs.isChosen()
1315 
1317  """A modifier which only applies if a Modifier is not chosen"""
1318  def __init__(self, lhs):
1319  super(_InvertModifier,self).__init__(lhs)
1320  def isChosen(self):
1321  return not self._lhs.isChosen()
1322 
1324  """A modifier which only applies if at least one of multiple Modifiers is chosen"""
1325  def __init__(self, lhs, rhs):
1326  super(_OrModifier,self).__init__(lhs, rhs)
1327  def isChosen(self):
1328  return self._lhs.isChosen() or self._rhs.isChosen()
1329 
1330 
1332  """This class is used to define standard modifications to a Process.
1333  An instance of this class is declared to denote a specific modification,e.g. era2017 could
1334  reconfigure items in a process to match our expectation of running in 2017. Once declared,
1335  these Modifier instances are imported into a configuration and items that need to be modified
1336  are then associated with the Modifier and with the action to do the modification.
1337  The registered modifications will only occur if the Modifier was passed to
1338  the cms.Process' constructor.
1339  """
1340  def __init__(self):
1342  self.__chosen = False
1343  def makeProcessModifier(self,func):
1344  """This is used to create a ProcessModifer that can perform actions on the process as a whole.
1345  This takes as argument a callable object (e.g. function) that takes as its sole argument an instance of Process.
1346  In order to work, the value returned from this function must be assigned to a uniquely named variable.
1347  """
1348  return ProcessModifier(self,func)
1349  @staticmethod
1350  def _toModifyCheck(obj,func,**kw):
1351  if func is not None and len(kw) != 0:
1352  raise TypeError("toModify takes either two arguments or one argument and key/value pairs")
1353  def toModify(self,obj, func=None,**kw):
1354  """This is used to register an action to be performed on the specific object. Two different forms are allowed
1355  Form 1: A callable object (e.g. function) can be passed as the second. This callable object is expected to take one argument
1356  that will be the object passed in as the first argument.
1357  Form 2: A list of parameter name, value pairs can be passed
1358  mod.toModify(foo, fred=cms.int32(7), barney = cms.double(3.14))
1359  This form can also be used to remove a parameter by passing the value of None
1360  #remove the parameter foo.fred
1361  mod.toModify(foo, fred = None)
1362  Additionally, parameters embedded within PSets can also be modified using a dictionary
1363  #change foo.fred.pebbles to 3 and foo.fred.friend to "barney"
1364  mod.toModify(foo, fred = dict(pebbles = 3, friend = "barney)) )
1365  """
1366  Modifier._toModifyCheck(obj,func,**kw)
1367  if not self.isChosen():
1368  return
1369  Modifier._toModify(obj,func,**kw)
1370  @staticmethod
1371  def _toModify(obj,func,**kw):
1372  if func is not None:
1373  func(obj)
1374  else:
1375  temp =_ParameterModifier(kw)
1376  temp(obj)
1377  @staticmethod
1378  def _toReplaceWithCheck(toObj,fromObj):
1379  if not isinstance(fromObj, type(toObj)):
1380  raise TypeError("toReplaceWith requires both arguments to be the same class type")
1381  def toReplaceWith(self,toObj,fromObj):
1382  """If the Modifier is chosen the internals of toObj will be associated with the internals of fromObj
1383  """
1384  Modifier._toReplaceWithCheck(toObj,fromObj)
1385  if not self.isChosen():
1386  return
1387  Modifier._toReplaceWith(toObj,fromObj)
1388  @staticmethod
1389  def _toReplaceWith(toObj,fromObj):
1390  if isinstance(fromObj,_ModuleSequenceType):
1391  toObj._seq = fromObj._seq
1392  toObj._tasks = fromObj._tasks
1393  elif isinstance(fromObj,Task):
1394  toObj._collection = fromObj._collection
1395  elif isinstance(fromObj,_Parameterizable):
1396  #clear old items just incase fromObj is not a complete superset of toObj
1397  for p in toObj.parameterNames_():
1398  delattr(toObj,p)
1399  for p in fromObj.parameterNames_():
1400  setattr(toObj,p,getattr(fromObj,p))
1401  if isinstance(fromObj,_TypedParameterizable):
1402  toObj._TypedParameterizable__type = fromObj._TypedParameterizable__type
1403 
1404  else:
1405  raise TypeError("toReplaceWith does not work with type "+str(type(toObj)))
1406 
1407  def _setChosen(self):
1408  """Should only be called by cms.Process instances"""
1409  self.__chosen = True
1410  def isChosen(self):
1411  return self.__chosen
1412  def __and__(self, other):
1413  return _AndModifier(self,other)
1414  def __invert__(self):
1415  return _InvertModifier(self)
1416  def __or__(self, other):
1417  return _OrModifier(self,other)
1418  def _isOrContains(self, other):
1419  return self == other
1420 
1421 
1423  """A Modifier made up of a list of Modifiers
1424  """
1425  def __init__(self, *chainedModifiers):
1426  self.__chosen = False
1427  self.__chain = chainedModifiers
1428  def _applyNewProcessModifiers(self,process):
1429  """Should only be called by cms.Process instances
1430  applies list of accumulated changes to the process"""
1431  for m in self.__chain:
1432  m._applyNewProcessModifiers(process)
1433  def _setChosen(self):
1434  """Should only be called by cms.Process instances"""
1435  self.__chosen = True
1436  for m in self.__chain:
1437  m._setChosen()
1438  def isChosen(self):
1439  return self.__chosen
1440  def copyAndExclude(self, toExclude):
1441  """Creates a new ModifierChain which is a copy of
1442  this ModifierChain but excludes any Modifier or
1443  ModifierChain in the list toExclude.
1444  The exclusion is done recursively down the chain.
1445  """
1446  newMods = []
1447  for m in self.__chain:
1448  if m not in toExclude:
1449  s = m
1450  if isinstance(m,ModifierChain):
1451  s = m.__copyIfExclude(toExclude)
1452  newMods.append(s)
1453  return ModifierChain(*newMods)
1454  def __copyIfExclude(self,toExclude):
1455  shouldCopy = False
1456  for m in toExclude:
1457  if self._isOrContains(m):
1458  shouldCopy = True
1459  break
1460  if shouldCopy:
1461  return self.copyAndExclude(toExclude)
1462  return self
1463  def _isOrContains(self, other):
1464  if self is other:
1465  return True
1466  for m in self.__chain:
1467  if m._isOrContains(other):
1468  return True
1469  return False
1470 
1472  """A class used by a Modifier to affect an entire Process instance.
1473  When a Process 'loads' a module containing a ProcessModifier, that
1474  ProcessModifier will be applied to the Process if and only if the
1475  Modifier passed to the constructor has been chosen.
1476  """
1477  def __init__(self, modifier, func):
1478  self.__modifier = modifier
1479  self.__func = func
1480  self.__seenProcesses = set()
1481  def apply(self,process):
1482  if self.__modifier.isChosen():
1483  if process not in self.__seenProcesses:
1484  self.__func(process)
1485  self.__seenProcesses.add(process)
1486 
1487 if __name__=="__main__":
1488  import unittest
1489  import copy
1490 
1492  """Has same interface as the C++ object that creates PSets
1493  """
1494  def __init__(self):
1495  self.values = dict()
1496  def __insertValue(self,tracked,label,value):
1497  self.values[label]=(tracked,value)
1498  def addInt32(self,tracked,label,value):
1499  self.__insertValue(tracked,label,value)
1500  def addVInt32(self,tracked,label,value):
1501  self.__insertValue(tracked,label,value)
1502  def addUInt32(self,tracked,label,value):
1503  self.__insertValue(tracked,label,value)
1504  def addVUInt32(self,tracked,label,value):
1505  self.__insertValue(tracked,label,value)
1506  def addInt64(self,tracked,label,value):
1507  self.__insertValue(tracked,label,value)
1508  def addVInt64(self,tracked,label,value):
1509  self.__insertValue(tracked,label,value)
1510  def addUInt64(self,tracked,label,value):
1511  self.__insertValue(tracked,label,value)
1512  def addVUInt64(self,tracked,label,value):
1513  self.__insertValue(tracked,label,value)
1514  def addDouble(self,tracked,label,value):
1515  self.__insertValue(tracked,label,value)
1516  def addVDouble(self,tracked,label,value):
1517  self.__insertValue(tracked,label,value)
1518  def addBool(self,tracked,label,value):
1519  self.__insertValue(tracked,label,value)
1520  def addString(self,tracked,label,value):
1521  self.__insertValue(tracked,label,value)
1522  def addVString(self,tracked,label,value):
1523  self.__insertValue(tracked,label,value)
1524  def addInputTag(self,tracked,label,value):
1525  self.__insertValue(tracked,label,value)
1526  def addVInputTag(self,tracked,label,value):
1527  self.__insertValue(tracked,label,value)
1528  def addESInputTag(self,tracked,label,value):
1529  self.__insertValue(tracked,label,value)
1530  def addVESInputTag(self,tracked,label,value):
1531  self.__insertValue(tracked,label,value)
1532  def addEventID(self,tracked,label,value):
1533  self.__insertValue(tracked,label,value)
1534  def addVEventID(self,tracked,label,value):
1535  self.__insertValue(tracked,label,value)
1536  def addLuminosityBlockID(self,tracked,label,value):
1537  self.__insertValue(tracked,label,value)
1538  def addLuminosityBlockID(self,tracked,label,value):
1539  self.__insertValue(tracked,label,value)
1540  def addEventRange(self,tracked,label,value):
1541  self.__insertValue(tracked,label,value)
1542  def addVEventRange(self,tracked,label,value):
1543  self.__insertValue(tracked,label,value)
1544  def addPSet(self,tracked,label,value):
1545  self.__insertValue(tracked,label,value)
1546  def addVPSet(self,tracked,label,value):
1547  self.__insertValue(tracked,label,value)
1548  def addFileInPath(self,tracked,label,value):
1549  self.__insertValue(tracked,label,value)
1550  def newPSet(self):
1551  return TestMakePSet()
1552 
1553  class TestModuleCommand(unittest.TestCase):
1554  def setUp(self):
1555  """Nothing to do """
1556  None
1558  p = _Parameterizable()
1559  self.assertEqual(len(p.parameterNames_()),0)
1560  p.a = int32(1)
1561  self.assert_('a' in p.parameterNames_())
1562  self.assertEqual(p.a.value(), 1)
1563  p.a = 10
1564  self.assertEqual(p.a.value(), 10)
1565  p.a = untracked(int32(1))
1566  self.assertEqual(p.a.value(), 1)
1567  self.failIf(p.a.isTracked())
1568  p.a = untracked.int32(1)
1569  self.assertEqual(p.a.value(), 1)
1570  self.failIf(p.a.isTracked())
1571  p = _Parameterizable(foo=int32(10), bar = untracked(double(1.0)))
1572  self.assertEqual(p.foo.value(), 10)
1573  self.assertEqual(p.bar.value(),1.0)
1574  self.failIf(p.bar.isTracked())
1575  self.assertRaises(TypeError,setattr,(p,'c',1))
1576  p = _Parameterizable(a=PSet(foo=int32(10), bar = untracked(double(1.0))))
1577  self.assertEqual(p.a.foo.value(),10)
1578  self.assertEqual(p.a.bar.value(),1.0)
1579  p.b = untracked(PSet(fii = int32(1)))
1580  self.assertEqual(p.b.fii.value(),1)
1581  self.failIf(p.b.isTracked())
1582  #test the fact that values can be shared
1583  v = int32(10)
1584  p=_Parameterizable(a=v)
1585  v.setValue(11)
1586  self.assertEqual(p.a.value(),11)
1587  p.a = 12
1588  self.assertEqual(p.a.value(),12)
1589  self.assertEqual(v.value(),12)
1591  p = _TypedParameterizable("blah", b=int32(1))
1592  #see if copy works deeply
1593  other = p.copy()
1594  other.b = 2
1595  self.assertNotEqual(p.b,other.b)
1596 
1598  p = Process("test")
1599  p.a = EDAnalyzer("MyAnalyzer")
1600  self.assert_( 'a' in p.analyzers_() )
1601  self.assert_( 'a' in p.analyzers)
1602  p.add_(Service("MessageLogger"))
1603  self.assert_('MessageLogger' in p.services_())
1604  self.assertEqual(p.MessageLogger.type_(), "MessageLogger")
1605  p.Tracer = Service("Tracer")
1606  self.assert_('Tracer' in p.services_())
1607  self.assertRaises(TypeError, setattr, *(p,'b',"this should fail"))
1608  self.assertRaises(TypeError, setattr, *(p,'bad',Service("MessageLogger")))
1609  self.assertRaises(ValueError, setattr, *(p,'bad',Source("PoolSource")))
1610  p.out = OutputModule("Outer")
1611  self.assertEqual(p.out.type_(), 'Outer')
1612  self.assert_( 'out' in p.outputModules_() )
1613 
1614  p.geom = ESSource("GeomProd")
1615  self.assert_('geom' in p.es_sources_())
1616  p.add_(ESSource("ConfigDB"))
1617  self.assert_('ConfigDB' in p.es_sources_())
1618 
1619  p.aliasfoo1 = EDAlias(foo1 = VPSet(PSet(type = string("Foo1"))))
1620  self.assert_('aliasfoo1' in p.aliases_())
1621 
1623  class FromArg(object):
1624  def __init__(self,*arg,**args):
1625  for name in args.iterkeys():
1626  self.__dict__[name]=args[name]
1627 
1628  a=EDAnalyzer("MyAnalyzer")
1629  t=EDAnalyzer("MyAnalyzer")
1630  t.setLabel("foo")
1631  s1 = Sequence(a)
1632  s2 = Sequence(s1)
1633  s3 = Sequence(s2)
1634  d = FromArg(
1635  a=a,
1636  b=Service("Full"),
1637  c=Path(a),
1638  d=s2,
1639  e=s1,
1640  f=s3,
1641  g=Sequence(s1+s2+s3)
1642  )
1643  p = Process("Test")
1644  p.extend(d)
1645  self.assertEqual(p.a.type_(),"MyAnalyzer")
1646  self.assertEqual(p.a.label_(),"a")
1647  self.assertRaises(AttributeError,getattr,p,'b')
1648  self.assertEqual(p.Full.type_(),"Full")
1649  self.assertEqual(str(p.c),'a')
1650  self.assertEqual(str(p.d),'a')
1651 
1652  z1 = FromArg(
1653  a=a,
1654  b=Service("Full"),
1655  c=Path(a),
1656  d=s2,
1657  e=s1,
1658  f=s3,
1659  s4=s3,
1660  g=Sequence(s1+s2+s3)
1661  )
1662 
1663  p1 = Process("Test")
1664  #p1.extend(z1)
1665  self.assertRaises(ValueError, p1.extend, z1)
1666 
1667  z2 = FromArg(
1668  a=a,
1669  b=Service("Full"),
1670  c=Path(a),
1671  d=s2,
1672  e=s1,
1673  f=s3,
1674  aaa=copy.deepcopy(a),
1675  s4=copy.deepcopy(s3),
1676  g=Sequence(s1+s2+s3),
1677  t=t
1678  )
1679  p2 = Process("Test")
1680  p2.extend(z2)
1681  #self.assertRaises(ValueError, p2.extend, z2)
1682  self.assertEqual(p2.s4.label_(),"s4")
1683  #p2.s4.setLabel("foo")
1684  self.assertRaises(ValueError, p2.s4.setLabel, "foo")
1685  p2.s4.setLabel("s4")
1686  p2.s4.setLabel(None)
1687  p2.s4.setLabel("foo")
1688  p2._Process__setObjectLabel(p2.s4, "foo")
1689  p2._Process__setObjectLabel(p2.s4, None)
1690  p2._Process__setObjectLabel(p2.s4, "bar")
1691 
1693  p = Process("test")
1694  p.a = EDAnalyzer("MyAnalyzer")
1695  p.p = Path(p.a)
1696  p.s = Sequence(p.a)
1697  p.r = Sequence(p.s)
1698  p.p2 = Path(p.s)
1699  p.schedule = Schedule(p.p2,p.p)
1700  d=p.dumpPython()
1701  self.assertEqual(d,
1702 """import FWCore.ParameterSet.Config as cms
1703 
1704 process = cms.Process("test")
1705 
1706 process.a = cms.EDAnalyzer("MyAnalyzer")
1707 
1708 
1709 process.s = cms.Sequence(process.a)
1710 
1711 
1712 process.r = cms.Sequence(process.s)
1713 
1714 
1715 process.p = cms.Path(process.a)
1716 
1717 
1718 process.p2 = cms.Path(process.s)
1719 
1720 
1721 process.schedule = cms.Schedule(*[ process.p2, process.p ])
1722 """)
1723  #Reverse order of 'r' and 's'
1724  p = Process("test")
1725  p.a = EDAnalyzer("MyAnalyzer")
1726  p.p = Path(p.a)
1727  p.r = Sequence(p.a)
1728  p.s = Sequence(p.r)
1729  p.p2 = Path(p.r)
1730  p.schedule = Schedule(p.p2,p.p)
1731  p.b = EDAnalyzer("YourAnalyzer")
1732  d=p.dumpPython()
1733  self.assertEqual(d,
1734 """import FWCore.ParameterSet.Config as cms
1735 
1736 process = cms.Process("test")
1737 
1738 process.a = cms.EDAnalyzer("MyAnalyzer")
1739 
1740 
1741 process.b = cms.EDAnalyzer("YourAnalyzer")
1742 
1743 
1744 process.r = cms.Sequence(process.a)
1745 
1746 
1747 process.s = cms.Sequence(process.r)
1748 
1749 
1750 process.p = cms.Path(process.a)
1751 
1752 
1753 process.p2 = cms.Path(process.r)
1754 
1755 
1756 process.schedule = cms.Schedule(*[ process.p2, process.p ])
1757 """)
1758  #use an anonymous sequence
1759  p = Process("test")
1760  p.a = EDAnalyzer("MyAnalyzer")
1761  p.p = Path(p.a)
1762  s = Sequence(p.a)
1763  p.r = Sequence(s)
1764  p.p2 = Path(p.r)
1765  p.schedule = Schedule(p.p2,p.p)
1766  d=p.dumpPython()
1767  self.assertEqual(d,
1768  """import FWCore.ParameterSet.Config as cms
1769 
1770 process = cms.Process("test")
1771 
1772 process.a = cms.EDAnalyzer("MyAnalyzer")
1773 
1774 
1775 process.r = cms.Sequence((process.a))
1776 
1777 
1778 process.p = cms.Path(process.a)
1779 
1780 
1781 process.p2 = cms.Path(process.r)
1782 
1783 
1784 process.schedule = cms.Schedule(*[ process.p2, process.p ])
1785 """)
1786 
1787  # include some tasks
1788  p = Process("test")
1789  p.a = EDAnalyzer("MyAnalyzer")
1790  p.b = EDProducer("bProducer")
1791  p.c = EDProducer("cProducer")
1792  p.d = EDProducer("dProducer")
1793  p.e = EDProducer("eProducer")
1794  p.f = EDProducer("fProducer")
1795  p.g = EDProducer("gProducer")
1796  p.task5 = Task()
1797  p.task3 = Task()
1798  p.task2 = Task(p.c, p.task3)
1799  p.task4 = Task(p.f, p.task2)
1800  p.task1 = Task(p.task5)
1801  p.task3.add(p.task1)
1802  p.p = Path(p.a)
1803  s = Sequence(p.a)
1804  p.r = Sequence(s)
1805  p.p2 = Path(p.r, p.task1, p.task2)
1806  p.schedule = Schedule(p.p2,p.p,tasks=[p.task3,p.task4, p.task5])
1807  d=p.dumpPython()
1808  self.assertEqual(d,
1809  """import FWCore.ParameterSet.Config as cms
1810 
1811 process = cms.Process("test")
1812 
1813 process.b = cms.EDProducer("bProducer")
1814 
1815 
1816 process.c = cms.EDProducer("cProducer")
1817 
1818 
1819 process.d = cms.EDProducer("dProducer")
1820 
1821 
1822 process.e = cms.EDProducer("eProducer")
1823 
1824 
1825 process.f = cms.EDProducer("fProducer")
1826 
1827 
1828 process.g = cms.EDProducer("gProducer")
1829 
1830 
1831 process.a = cms.EDAnalyzer("MyAnalyzer")
1832 
1833 
1834 process.task5 = cms.Task()
1835 
1836 
1837 process.task1 = cms.Task(process.task5)
1838 
1839 
1840 process.task3 = cms.Task(process.task1)
1841 
1842 
1843 process.task2 = cms.Task(process.c, process.task3)
1844 
1845 
1846 process.task4 = cms.Task(process.f, process.task2)
1847 
1848 
1849 process.r = cms.Sequence((process.a))
1850 
1851 
1852 process.p = cms.Path(process.a)
1853 
1854 
1855 process.p2 = cms.Path(process.r, process.task1, process.task2)
1856 
1857 
1858 process.schedule = cms.Schedule(*[ process.p2, process.p ], tasks=[process.task3, process.task4, process.task5])
1859 """)
1860  # only tasks
1861  p = Process("test")
1862  p.d = EDProducer("dProducer")
1863  p.e = EDProducer("eProducer")
1864  p.f = EDProducer("fProducer")
1865  p.g = EDProducer("gProducer")
1866  p.task1 = Task(p.d, p.e)
1867  task2 = Task(p.f, p.g)
1868  p.schedule = Schedule(tasks=[p.task1,task2])
1869  d=p.dumpPython()
1870  self.assertEqual(d,
1871  """import FWCore.ParameterSet.Config as cms
1872 
1873 process = cms.Process("test")
1874 
1875 process.d = cms.EDProducer("dProducer")
1876 
1877 
1878 process.e = cms.EDProducer("eProducer")
1879 
1880 
1881 process.f = cms.EDProducer("fProducer")
1882 
1883 
1884 process.g = cms.EDProducer("gProducer")
1885 
1886 
1887 process.task1 = cms.Task(process.d, process.e)
1888 
1889 
1890 process.schedule = cms.Schedule(tasks=[cms.Task(process.f, process.g), process.task1])
1891 """)
1892  # empty schedule
1893  p = Process("test")
1894  p.schedule = Schedule()
1895  d=p.dumpPython()
1896  self.assertEqual(d,
1897  """import FWCore.ParameterSet.Config as cms
1898 
1899 process = cms.Process("test")
1900 
1901 process.schedule = cms.Schedule()
1902 """)
1903 
1904  s = Sequence()
1905  a = EDProducer("A")
1906  s2 = Sequence(a)
1907  s2 += s
1908  process = Process("DUMP")
1909  process.a = a
1910  process.s2 = s2
1911  d=process.dumpPython()
1912  self.assertEqual(d,
1913  """import FWCore.ParameterSet.Config as cms
1914 
1915 process = cms.Process("DUMP")
1916 
1917 process.a = cms.EDProducer("A")
1918 
1919 
1920 process.s2 = cms.Sequence(process.a)
1921 
1922 
1923 """)
1924  s = Sequence()
1925  s1 = Sequence(s)
1926  a = EDProducer("A")
1927  s3 = Sequence(a+a)
1928  s2 = Sequence(a+s3)
1929  s2 += s1
1930  process = Process("DUMP")
1931  process.a = a
1932  process.s2 = s2
1933  d=process.dumpPython()
1934  self.assertEqual(d,
1935  """import FWCore.ParameterSet.Config as cms
1936 
1937 process = cms.Process("DUMP")
1938 
1939 process.a = cms.EDProducer("A")
1940 
1941 
1942 process.s2 = cms.Sequence(process.a+(process.a+process.a))
1943 
1944 
1945 """)
1946 
1947  def testSecSource(self):
1948  p = Process('test')
1949  p.a = SecSource("MySecSource")
1950  self.assertEqual(p.dumpPython().replace('\n',''),'import FWCore.ParameterSet.Config as cmsprocess = cms.Process("test")process.a = cms.SecSource("MySecSource")')
1951 
1953  p = Process('test')
1954  p.a = EDAnalyzer("MyAnalyzer")
1955  old = p.a
1956  p.b = EDAnalyzer("YourAnalyzer")
1957  p.c = EDAnalyzer("OurAnalyzer")
1958  p.d = EDProducer("MyProducer")
1959  old2 = p.d
1960  p.t1 = Task(p.d)
1961  t2 = Task(p.d)
1962  t3 = Task(p.d)
1963  t4 = Task(p.d)
1964  t5 = Task(p.d)
1965  t6 = Task(p.d)
1966  s = Sequence(p.a*p.b)
1967  p.s4 = Sequence(p.a*p.b)
1968  s.associate(t2)
1969  p.s4.associate(t2)
1970  p.p = Path(p.c+s+p.a)
1971  p.e3 = EndPath(p.c+s+p.a)
1972  new = EDAnalyzer("NewAnalyzer")
1973  new2 = EDProducer("NewProducer")
1974  visitor1 = NodeVisitor()
1975  p.p.visit(visitor1)
1976  self.assertTrue(visitor1.modules == set([old,old2,p.b,p.c]))
1977  p.schedule = Schedule(tasks=[t6])
1978  p.globalReplace("a",new)
1979  p.globalReplace("d",new2)
1980  visitor2 = NodeVisitor()
1981  p.p.visit(visitor2)
1982  self.assertTrue(visitor2.modules == set([new,new2,p.b,p.c]))
1983  visitor3 = NodeVisitor()
1984  p.e3.visit(visitor3)
1985  self.assertTrue(visitor3.modules == set([new,new2,p.b,p.c]))
1986  visitor4 = NodeVisitor()
1987  p.s4.visit(visitor4)
1988  self.assertTrue(visitor4.modules == set([new,new2,p.b]))
1989  visitor5 = NodeVisitor()
1990  p.t1.visit(visitor5)
1991  self.assertTrue(visitor5.modules == set([new2]))
1992  visitor6 = NodeVisitor()
1993  listOfTasks = list(p.schedule._tasks)
1994  listOfTasks[0].visit(visitor6)
1995  self.assertTrue(visitor6.modules == set([new2]))
1996 
1997  def testSequence(self):
1998  p = Process('test')
1999  p.a = EDAnalyzer("MyAnalyzer")
2000  p.b = EDAnalyzer("YourAnalyzer")
2001  p.c = EDAnalyzer("OurAnalyzer")
2002  p.s = Sequence(p.a*p.b)
2003  self.assertEqual(str(p.s),'a+b')
2004  self.assertEqual(p.s.label_(),'s')
2005  path = Path(p.c+p.s)
2006  self.assertEqual(str(path),'c+a+b')
2007  p._validateSequence(path, 'p1')
2008  notInProcess = EDAnalyzer('NotInProcess')
2009  p2 = Path(p.c+p.s*notInProcess)
2010  self.assertRaises(RuntimeError, p._validateSequence, p2, 'p2')
2011 
2012  def testSequence2(self):
2013  p = Process('test')
2014  p.a = EDAnalyzer("MyAnalyzer")
2015  p.b = EDAnalyzer("YourAnalyzer")
2016  p.c = EDAnalyzer("OurAnalyzer")
2017  testseq = Sequence(p.a*p.b)
2018  p.s = testseq
2019  #p.y = testseq
2020  self.assertRaises(ValueError, p.__setattr__, "y", testseq)
2021 
2023  service = Service("d")
2024  self.assertFalse(service._inProcess)
2025  process = Process("test")
2026  process.d = service
2027  self.assertTrue(service._inProcess)
2028  service2 = Service("d")
2029  process.d = service2
2030  self.assertFalse(service._inProcess)
2031  self.assertTrue(service2._inProcess)
2032  del process.d
2033  self.assertFalse(service2._inProcess)
2034 
2035  def testTask(self):
2036 
2037  # create some objects to use in tests
2038  edanalyzer = EDAnalyzer("a")
2039  edproducer = EDProducer("b")
2040  edproducer2 = EDProducer("b2")
2041  edproducer3 = EDProducer("b3")
2042  edproducer4 = EDProducer("b4")
2043  edproducer8 = EDProducer("b8")
2044  edproducer9 = EDProducer("b9")
2045  edfilter = EDFilter("c")
2046  service = Service("d")
2047  service3 = Service("d")
2048  essource = ESSource("e")
2049  esproducer = ESProducer("f")
2050  testTask2 = Task()
2051 
2052  # test adding things to Tasks
2053  testTask1 = Task(edproducer, edfilter)
2054  self.assertRaises(RuntimeError, testTask1.add, edanalyzer)
2055  testTask1.add(essource, service)
2056  testTask1.add(essource, esproducer)
2057  testTask1.add(testTask2)
2058  coll = testTask1._collection
2059  self.assertTrue(edproducer in coll)
2060  self.assertTrue(edfilter in coll)
2061  self.assertTrue(service in coll)
2062  self.assertTrue(essource in coll)
2063  self.assertTrue(esproducer in coll)
2064  self.assertTrue(testTask2 in coll)
2065  self.assertTrue(len(coll) == 6)
2066  self.assertTrue(len(testTask2._collection) == 0)
2067 
2068  taskContents = []
2069  for i in testTask1:
2070  taskContents.append(i)
2071  self.assertTrue(taskContents == [edproducer, edfilter, essource, service, esproducer, testTask2])
2072 
2073  # test attaching Task to Process
2074  process = Process("test")
2075 
2076  process.mproducer = edproducer
2077  process.mproducer2 = edproducer2
2078  process.mfilter = edfilter
2079  process.messource = essource
2080  process.mesproducer = esproducer
2081  process.d = service
2082 
2083  testTask3 = Task(edproducer, edproducer2)
2084  testTask1.add(testTask3)
2085  process.myTask1 = testTask1
2086 
2087  # test the validation that occurs when attaching a Task to a Process
2088  # first a case that passes, then one the fails on an EDProducer
2089  # then one that fails on a service
2090  l = set()
2091  visitor = NodeNameVisitor(l)
2092  testTask1.visit(visitor)
2093  self.assertTrue(l == set(['mesproducer', 'mproducer', 'mproducer2', 'mfilter', 'd', 'messource']))
2094  l2 = testTask1.moduleNames
2095  self.assertTrue(l == set(['mesproducer', 'mproducer', 'mproducer2', 'mfilter', 'd', 'messource']))
2096 
2097  testTask4 = Task(edproducer3)
2098  l.clear()
2099  self.assertRaises(RuntimeError, testTask4.visit, visitor)
2100  try:
2101  process.myTask4 = testTask4
2102  self.assertTrue(False)
2103  except RuntimeError:
2104  pass
2105 
2106  testTask5 = Task(service3)
2107  l.clear()
2108  self.assertRaises(RuntimeError, testTask5.visit, visitor)
2109  try:
2110  process.myTask5 = testTask5
2111  self.assertTrue(False)
2112  except RuntimeError:
2113  pass
2114 
2115  process.d = service3
2116  process.myTask5 = testTask5
2117 
2118  # test placement into the Process and the tasks property
2119  expectedDict = { 'myTask1' : testTask1, 'myTask5' : testTask5 }
2120  expectedFixedDict = DictTypes.FixedKeysDict(expectedDict);
2121  self.assertTrue(process.tasks == expectedFixedDict)
2122  self.assertTrue(process.tasks['myTask1'] == testTask1)
2123  self.assertTrue(process.myTask1 == testTask1)
2124 
2125  # test replacing an EDProducer in a Task when calling __settattr__
2126  # for the EDProducer on the Process.
2127  process.mproducer2 = edproducer4
2128  process.d = service
2129  l = list()
2130  visitor1 = ModuleNodeVisitor(l)
2131  testTask1.visit(visitor1)
2132  l.sort()
2133  expectedList = sorted([edproducer,essource,esproducer,service,edfilter,edproducer,edproducer4])
2134  self.assertTrue(expectedList == l)
2135 
2136  process.myTask6 = Task()
2137  process.myTask7 = Task()
2138  process.mproducer8 = edproducer8
2139  process.myTask8 = Task(process.mproducer8)
2140  process.myTask6.add(process.myTask7)
2141  process.myTask7.add(process.myTask8)
2142  process.myTask1.add(process.myTask6)
2143  process.myTask8.add(process.myTask5)
2144 
2145  testDict = process._itemsInDependencyOrder(process.tasks)
2146  expectedLabels = ["myTask5", "myTask8", "myTask7", "myTask6", "myTask1"]
2147  expectedTasks = [process.myTask5, process.myTask8, process.myTask7, process.myTask6, process.myTask1]
2148  index = 0
2149  for testLabel, testTask in testDict.items():
2150  self.assertTrue(testLabel == expectedLabels[index])
2151  self.assertTrue(testTask == expectedTasks[index])
2152  index += 1
2153 
2154  pythonDump = testTask1.dumpPython(PrintOptions())
2155 
2156 
2157  expectedPythonDump = 'cms.Task(process.d, process.mesproducer, process.messource, process.mfilter, process.mproducer, process.mproducer2, process.myTask6)\n'
2158  self.assertTrue(pythonDump == expectedPythonDump)
2159 
2160  process.myTask5 = Task()
2161  process.myTask100 = Task()
2162  process.mproducer9 = edproducer9
2163  sequence1 = Sequence(process.mproducer8, process.myTask1, process.myTask5, testTask2, testTask3)
2164  sequence2 = Sequence(process.mproducer8 + process.mproducer9)
2165  process.sequence3 = Sequence((process.mproducer8 + process.mfilter))
2166  sequence4 = Sequence()
2167  process.path1 = Path(process.mproducer+process.mproducer8+sequence1+sequence2+process.sequence3+sequence4)
2168  process.path1.associate(process.myTask1, process.myTask5, testTask2, testTask3)
2169  process.path11 = Path(process.mproducer+process.mproducer8+sequence1+sequence2+process.sequence3+ sequence4,process.myTask1, process.myTask5, testTask2, testTask3, process.myTask100)
2170  process.path2 = Path(process.mproducer)
2171  process.path3 = Path(process.mproducer9+process.mproducer8,testTask2)
2172 
2173  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')
2174 
2175  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')
2176 
2177  # test NodeNameVisitor and moduleNames
2178  l = set()
2179  nameVisitor = NodeNameVisitor(l)
2180  process.path1.visit(nameVisitor)
2181  self.assertTrue(l == set(['mproducer', 'd', 'mesproducer', None, 'mproducer9', 'mproducer8', 'messource', 'mproducer2', 'mfilter']))
2182  self.assertTrue(process.path1.moduleNames() == set(['mproducer', 'd', 'mesproducer', None, 'mproducer9', 'mproducer8', 'messource', 'mproducer2', 'mfilter']))
2183 
2184  # test copy
2185  process.mproducer10 = EDProducer("b10")
2186  process.path21 = process.path11.copy()
2187  process.path21.replace(process.mproducer, process.mproducer10)
2188 
2189  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')
2190 
2191  # Some peculiarities of the way things work show up here. dumpPython sorts tasks and
2192  # removes duplication at the level of strings. The Task and Sequence objects themselves
2193  # remove duplicate tasks in their contents if the instances are the same (exact same python
2194  # object id which is not the same as the string representation being the same).
2195  # Also note that the mutating visitor replaces sequences and tasks that have
2196  # modified contents with their modified contents, it does not modify the sequence
2197  # or task itself.
2198  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.myTask6), process.myTask100, process.myTask5)\n')
2199 
2200  process.path22 = process.path21.copyAndExclude([process.d, process.mesproducer, process.mfilter])
2201  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.myTask6), process.myTask100, process.myTask5)\n')
2202 
2203  process.path23 = process.path22.copyAndExclude([process.messource, process.mproducer10])
2204  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.myTask6), process.myTask100, process.myTask5)\n')
2205 
2206  process.a = EDAnalyzer("MyAnalyzer")
2207  process.b = OutputModule("MyOutputModule")
2208  process.c = EDFilter("MyFilter")
2209  process.d = EDProducer("MyProducer")
2210  process.e = ESProducer("MyESProducer")
2211  process.f = ESSource("MyESSource")
2212  process.g = ESProducer("g")
2213  process.path24 = Path(process.a+process.b+process.c+process.d)
2214  process.path25 = process.path24.copyAndExclude([process.a,process.b,process.c])
2215  self.assertTrue(process.path25.dumpPython(None) == 'cms.Path(process.d)\n')
2216  #print process.path3
2217  #print process.dumpPython()
2218 
2219  process.path200 = EndPath(Sequence(process.c,Task(process.e)))
2220  process.path200.replace(process.c,process.b)
2221  process.path200.replace(process.e,process.f)
2222  self.assertEqual(process.path200.dumpPython(None), "cms.EndPath(process.b, cms.Task(process.f))\n")
2223  process.path200.replace(process.b,process.c)
2224  process.path200.replace(process.f,process.e)
2225  self.assertEqual(process.path200.dumpPython(None), "cms.EndPath(process.c, cms.Task(process.e))\n")
2226  process.path200.replace(process.c,process.a)
2227  process.path200.replace(process.e,process.g)
2228  self.assertEqual(process.path200.dumpPython(None), "cms.EndPath(process.a, cms.Task(process.g))\n")
2229  process.path200.replace(process.a,process.c)
2230  process.path200.replace(process.g,process.e)
2231  self.assertEqual(process.path200.dumpPython(None), "cms.EndPath(process.c, cms.Task(process.e))\n")
2232 
2233 
2234  def testPath(self):
2235  p = Process("test")
2236  p.a = EDAnalyzer("MyAnalyzer")
2237  p.b = EDAnalyzer("YourAnalyzer")
2238  p.c = EDAnalyzer("OurAnalyzer")
2239  path = Path(p.a)
2240  path *= p.b
2241  path += p.c
2242  self.assertEqual(str(path),'a+b+c')
2243  path = Path(p.a*p.b+p.c)
2244  self.assertEqual(str(path),'a+b+c')
2245 # path = Path(p.a)*p.b+p.c #This leads to problems with sequences
2246 # self.assertEqual(str(path),'((a*b)+c)')
2247  path = Path(p.a+ p.b*p.c)
2248  self.assertEqual(str(path),'a+b+c')
2249  path = Path(p.a*(p.b+p.c))
2250  self.assertEqual(str(path),'a+b+c')
2251  path = Path(p.a*(p.b+~p.c))
2252  pathx = Path(p.a*(p.b+ignore(p.c)))
2253  self.assertEqual(str(path),'a+b+~c')
2254  p.es = ESProducer("AnESProducer")
2255  self.assertRaises(TypeError,Path,p.es)
2256 
2257  t = Path()
2258  self.assertTrue(t.dumpPython(PrintOptions()) == 'cms.Path()\n')
2259 
2260  t = Path(p.a)
2261  self.assertTrue(t.dumpPython(PrintOptions()) == 'cms.Path(process.a)\n')
2262 
2263  t = Path(Task())
2264  self.assertTrue(t.dumpPython(PrintOptions()) == 'cms.Path(cms.Task())\n')
2265 
2266  t = Path(p.a, Task())
2267  self.assertTrue(t.dumpPython(PrintOptions()) == 'cms.Path(process.a, cms.Task())\n')
2268 
2269  p.prod = EDProducer("prodName")
2270  p.t1 = Task(p.prod)
2271  t = Path(p.a, p.t1, Task(), p.t1)
2272  self.assertTrue(t.dumpPython(PrintOptions()) == 'cms.Path(process.a, cms.Task(), process.t1)\n')
2273 
2275  p = Process("test")
2276  a = EDAnalyzer("MyAnalyzer")
2277  p.a = a
2278  a.setLabel("a")
2279  b = EDAnalyzer("YOurAnalyzer")
2280  p.b = b
2281  b.setLabel("b")
2282  path = Path(a * b)
2283  p.path = Path(p.a*p.b)
2284  lookuptable = {id(a): p.a, id(b): p.b}
2285  #self.assertEqual(str(path),str(path._postProcessFixup(lookuptable)))
2286  #lookuptable = p._cloneToObjectDict
2287  #self.assertEqual(str(path),str(path._postProcessFixup(lookuptable)))
2288  self.assertEqual(str(path),str(p.path))
2289 
2290  def testContains(self):
2291 
2292  a = EDProducer("a")
2293  b = EDProducer("b")
2294  c = EDProducer("c")
2295  d = EDProducer("d")
2296  e = EDProducer("e")
2297  f = EDProducer("f")
2298  g = EDProducer("g")
2299  h = EDProducer("h")
2300  i = EDProducer("i")
2301  j = EDProducer("j")
2302  k = EDProducer("k")
2303  l = EDProducer("l")
2304  m = EDProducer("m")
2305  n = EDProducer("n")
2306 
2307  seq1 = Sequence(e)
2308  task1 = Task(g)
2309  path = Path(a * c * seq1, task1)
2310 
2311  self.assertTrue(path.contains(a))
2312  self.assertFalse(path.contains(b))
2313  self.assertTrue(path.contains(c))
2314  self.assertFalse(path.contains(d))
2315  self.assertTrue(path.contains(e))
2316  self.assertFalse(path.contains(f))
2317  self.assertTrue(path.contains(g))
2318 
2319  endpath = EndPath(h * i)
2320  self.assertFalse(endpath.contains(b))
2321  self.assertTrue(endpath.contains(i))
2322 
2323  seq = Sequence(a * c)
2324  self.assertFalse(seq.contains(b))
2325  self.assertTrue(seq.contains(c))
2326 
2327  task2 = Task(l)
2328  task = Task(j, k, task2)
2329  self.assertFalse(task.contains(b))
2330  self.assertTrue(task.contains(j))
2331  self.assertTrue(task.contains(k))
2332  self.assertTrue(task.contains(l))
2333 
2334  task3 = Task(m)
2335  path2 = Path(n)
2336  sch = Schedule(path, path2, tasks=[task,task3])
2337  self.assertFalse(sch.contains(b))
2338  self.assertTrue(sch.contains(a))
2339  self.assertTrue(sch.contains(c))
2340  self.assertTrue(sch.contains(e))
2341  self.assertTrue(sch.contains(g))
2342  self.assertTrue(sch.contains(n))
2343  self.assertTrue(sch.contains(j))
2344  self.assertTrue(sch.contains(k))
2345  self.assertTrue(sch.contains(l))
2346  self.assertTrue(sch.contains(m))
2347 
2348  def testSchedule(self):
2349  p = Process("test")
2350  p.a = EDAnalyzer("MyAnalyzer")
2351  p.b = EDAnalyzer("YourAnalyzer")
2352  p.c = EDAnalyzer("OurAnalyzer")
2353  p.d = EDAnalyzer("OurAnalyzer")
2354  p.path1 = Path(p.a)
2355  p.path2 = Path(p.b)
2356  p.path3 = Path(p.d)
2357 
2358  s = Schedule(p.path1,p.path2)
2359  self.assertEqual(s[0],p.path1)
2360  self.assertEqual(s[1],p.path2)
2361  p.schedule = s
2362  self.assert_('b' in p.schedule.moduleNames())
2363  self.assert_(hasattr(p, 'b'))
2364  self.assert_(hasattr(p, 'c'))
2365  self.assert_(hasattr(p, 'd'))
2366  self.assert_(hasattr(p, 'path1'))
2367  self.assert_(hasattr(p, 'path2'))
2368  self.assert_(hasattr(p, 'path3'))
2369  p.prune()
2370  self.assert_('b' in p.schedule.moduleNames())
2371  self.assert_(hasattr(p, 'b'))
2372  self.assert_(not hasattr(p, 'c'))
2373  self.assert_(not hasattr(p, 'd'))
2374  self.assert_(hasattr(p, 'path1'))
2375  self.assert_(hasattr(p, 'path2'))
2376  self.assert_(not hasattr(p, 'path3'))
2377 
2378  self.assertTrue(len(p.schedule._tasks) == 0)
2379 
2380  p = Process("test")
2381  p.a = EDAnalyzer("MyAnalyzer")
2382  p.b = EDAnalyzer("YourAnalyzer")
2383  p.c = EDAnalyzer("OurAnalyzer")
2384  p.d = EDAnalyzer("dAnalyzer")
2385  p.e = EDProducer("eProducer")
2386  p.f = EDProducer("fProducer")
2387  p.Tracer = Service("Tracer")
2388  p.path1 = Path(p.a)
2389  p.path2 = Path(p.b)
2390  p.path3 = Path(p.d)
2391  p.task1 = Task(p.e)
2392  p.task2 = Task(p.f, p.Tracer)
2393  s = Schedule(p.path1,p.path2,tasks=[p.task1,p.task2,p.task1])
2394  self.assertEqual(s[0],p.path1)
2395  self.assertEqual(s[1],p.path2)
2396  self.assertTrue(len(s._tasks) == 2)
2397  self.assertTrue(p.task1 in s._tasks)
2398  self.assertTrue(p.task2 in s._tasks)
2399  listOfTasks = list(s._tasks)
2400  self.assertTrue(len(listOfTasks) == 2)
2401  self.assertTrue(p.task1 == listOfTasks[0])
2402  self.assertTrue(p.task2 == listOfTasks[1])
2403  p.schedule = s
2404  self.assert_('b' in p.schedule.moduleNames())
2405 
2406  process2 = Process("test")
2407  process2.a = EDAnalyzer("MyAnalyzer")
2408  process2.e = EDProducer("eProducer")
2409  process2.path1 = Path(process2.a)
2410  process2.task1 = Task(process2.e)
2411  process2.schedule = Schedule(process2.path1,tasks=process2.task1)
2412  listOfTasks = list(process2.schedule._tasks)
2413  self.assertTrue(listOfTasks[0] == process2.task1)
2414 
2415  # test Schedule copy
2416  s2 = s.copy()
2417  self.assertEqual(s2[0],p.path1)
2418  self.assertEqual(s2[1],p.path2)
2419  self.assertTrue(len(s2._tasks) == 2)
2420  self.assertTrue(p.task1 in s2._tasks)
2421  self.assertTrue(p.task2 in s2._tasks)
2422  listOfTasks = list(s2._tasks)
2423  self.assertTrue(len(listOfTasks) == 2)
2424  self.assertTrue(p.task1 == listOfTasks[0])
2425  self.assertTrue(p.task2 == listOfTasks[1])
2426 
2427  names = s.moduleNames()
2428  self.assertTrue(names == set(['a', 'b', 'e', 'Tracer', 'f']))
2429  #adding a path not attached to the Process should cause an exception
2430  p = Process("test")
2431  p.a = EDAnalyzer("MyAnalyzer")
2432  path1 = Path(p.a)
2433  s = Schedule(path1)
2434  self.assertRaises(RuntimeError, lambda : p.setSchedule_(s) )
2435 
2436  #make sure anonymous sequences work
2437  p = Process("test")
2438  p.a = EDAnalyzer("MyAnalyzer")
2439  p.b = EDAnalyzer("MyOtherAnalyzer")
2440  p.c = EDProducer("MyProd")
2441  path1 = Path(p.c*Sequence(p.a+p.b))
2442  s = Schedule(path1)
2443  self.assert_('a' in s.moduleNames())
2444  self.assert_('b' in s.moduleNames())
2445  self.assert_('c' in s.moduleNames())
2446  p.path1 = path1
2447  p.schedule = s
2448  p.prune()
2449  self.assert_('a' in s.moduleNames())
2450  self.assert_('b' in s.moduleNames())
2451  self.assert_('c' in s.moduleNames())
2452 
2454  p = Process("test")
2455  p.a = EDAnalyzer("MyAnalyzer")
2456  p.b = EDAnalyzer("YourAnalyzer")
2457  p.c = EDAnalyzer("OurAnalyzer")
2458  p.path1 = Path(p.a)
2459  p.path2 = Path(p.b)
2460  self.assert_(p.schedule is None)
2461  pths = p.paths
2462  keys = pths.keys()
2463  self.assertEqual(pths[keys[0]],p.path1)
2464  self.assertEqual(pths[keys[1]],p.path2)
2465  p.prune()
2466  self.assert_(hasattr(p, 'a'))
2467  self.assert_(hasattr(p, 'b'))
2468  self.assert_(not hasattr(p, 'c'))
2469  self.assert_(hasattr(p, 'path1'))
2470  self.assert_(hasattr(p, 'path2'))
2471 
2472 
2473  p = Process("test")
2474  p.a = EDAnalyzer("MyAnalyzer")
2475  p.b = EDAnalyzer("YourAnalyzer")
2476  p.c = EDAnalyzer("OurAnalyzer")
2477  p.path2 = Path(p.b)
2478  p.path1 = Path(p.a)
2479  self.assert_(p.schedule is None)
2480  pths = p.paths
2481  keys = pths.keys()
2482  self.assertEqual(pths[keys[1]],p.path1)
2483  self.assertEqual(pths[keys[0]],p.path2)
2484 
2485 
2486  def testUsing(self):
2487  p = Process('test')
2488  p.block = PSet(a = int32(1))
2489  p.modu = EDAnalyzer('Analyzer', p.block, b = int32(2))
2490  self.assertEqual(p.modu.a.value(),1)
2491  self.assertEqual(p.modu.b.value(),2)
2492 
2493  def testOverride(self):
2494  p = Process('test')
2495  a = EDProducer("A", a1=int32(0))
2496  self.assert_(not a.isModified())
2497  a.a1 = 1
2498  self.assert_(a.isModified())
2499  p.a = a
2500  self.assertEqual(p.a.a1.value(), 1)
2501  # try adding an unmodified module.
2502  # should accept it
2503  p.a = EDProducer("A", a1=int32(2))
2504  self.assertEqual(p.a.a1.value(), 2)
2505  # try adding a modified module. Should throw
2506  # no longer, since the same (modified) say, geometry
2507  # could come from more than one cff
2508  b = EDProducer("A", a1=int32(3))
2509  b.a1 = 4
2510  #self.assertRaises(RuntimeError, setattr, *(p,'a',b))
2511  ps1 = PSet(a = int32(1))
2512  ps2 = PSet(a = int32(2))
2513  self.assertRaises(ValueError, EDProducer, 'C', ps1, ps2)
2514  self.assertRaises(ValueError, EDProducer, 'C', ps1, a=int32(3))
2515 
2516  def testExamples(self):
2517  p = Process("Test")
2518  p.source = Source("PoolSource",fileNames = untracked(string("file:reco.root")))
2519  p.foos = EDProducer("FooProducer")
2520  p.bars = EDProducer("BarProducer", foos=InputTag("foos"))
2521  p.out = OutputModule("PoolOutputModule",fileName=untracked(string("file:foos.root")))
2522  p.bars.foos = 'Foosball'
2523  self.assertEqual(p.bars.foos, InputTag('Foosball'))
2524  p.p = Path(p.foos*p.bars)
2525  p.e = EndPath(p.out)
2526  p.add_(Service("MessageLogger"))
2527 
2528  def testPrefers(self):
2529  p = Process("Test")
2530  p.add_(ESSource("ForceSource"))
2531  p.juicer = ESProducer("JuicerProducer")
2532  p.prefer("ForceSource")
2533  p.prefer("juicer")
2534  self.assertEqual(p.dumpConfig(),
2535 """process Test = {
2536  es_module juicer = JuicerProducer {
2537  }
2538  es_source = ForceSource {
2539  }
2540  es_prefer = ForceSource {
2541  }
2542  es_prefer juicer = JuicerProducer {
2543  }
2544 }
2545 """)
2546  p.prefer("juicer",fooRcd=vstring("Foo"))
2547  self.assertEqual(p.dumpConfig(),
2548 """process Test = {
2549  es_module juicer = JuicerProducer {
2550  }
2551  es_source = ForceSource {
2552  }
2553  es_prefer = ForceSource {
2554  }
2555  es_prefer juicer = JuicerProducer {
2556  vstring fooRcd = {
2557  'Foo'
2558  }
2559 
2560  }
2561 }
2562 """)
2563  self.assertEqual(p.dumpPython(),
2564 """import FWCore.ParameterSet.Config as cms
2565 
2566 process = cms.Process("Test")
2567 
2568 process.juicer = cms.ESProducer("JuicerProducer")
2569 
2570 
2571 process.ForceSource = cms.ESSource("ForceSource")
2572 
2573 
2574 process.prefer("ForceSource")
2575 
2576 process.prefer("juicer",
2577  fooRcd = cms.vstring('Foo')
2578 )
2579 
2580 """)
2581 
2582  def testFreeze(self):
2583  process = Process("Freeze")
2584  m = EDProducer("M", p=PSet(i = int32(1)))
2585  m.p.i = 2
2586  process.m = m
2587  # should be frozen
2588  #self.assertRaises(ValueError, setattr, m.p, 'i', 3)
2589  #self.assertRaises(ValueError, setattr, m, 'p', PSet(i=int32(1)))
2590  #self.assertRaises(ValueError, setattr, m.p, 'j', 1)
2591  #self.assertRaises(ValueError, setattr, m, 'j', 1)
2592  # But OK to change through the process
2593  process.m.p.i = 4
2594  self.assertEqual(process.m.p.i.value(), 4)
2595  process.m.p = PSet(j=int32(1))
2596  # should work to clone it, though
2597  m2 = m.clone(p = PSet(i = int32(5)), j = int32(8))
2598  m2.p.i = 6
2599  m2.j = 8
2600  def testSubProcess(self):
2601  process = Process("Parent")
2602  subProcess = Process("Child")
2603  subProcess.a = EDProducer("A")
2604  subProcess.p = Path(subProcess.a)
2605  subProcess.add_(Service("Foo"))
2606  process.addSubProcess(SubProcess(subProcess))
2607  d = process.dumpPython()
2608  equalD ="""import FWCore.ParameterSet.Config as cms
2609 
2610 process = cms.Process("Parent")
2611 
2612 parentProcess = process
2613 import FWCore.ParameterSet.Config as cms
2614 
2615 process = cms.Process("Child")
2616 
2617 process.a = cms.EDProducer("A")
2618 
2619 
2620 process.Foo = cms.Service("Foo")
2621 
2622 
2623 process.p = cms.Path(process.a)
2624 
2625 
2626 childProcess = process
2627 process = parentProcess
2628 process.addSubProcess(cms.SubProcess(process = childProcess, SelectEvents = cms.untracked.PSet(
2629 
2630 ), outputCommands = cms.untracked.vstring()))
2631 
2632 """
2633  equalD = equalD.replace("parentProcess","parentProcess"+str(hash(process.subProcesses_()[0])))
2634  self.assertEqual(d,equalD)
2635  p = TestMakePSet()
2636  process.fillProcessDesc(p)
2637  self.assertEqual((True,['a']),p.values["subProcesses"][1][0].values["process"][1].values['@all_modules'])
2638  self.assertEqual((True,['p']),p.values["subProcesses"][1][0].values["process"][1].values['@paths'])
2639  self.assertEqual({'@service_type':(True,'Foo')}, p.values["subProcesses"][1][0].values["process"][1].values["services"][1][0].values)
2640  def testRefToPSet(self):
2641  proc = Process("test")
2642  proc.top = PSet(a = int32(1))
2643  proc.ref = PSet(refToPSet_ = string("top"))
2644  proc.ref2 = PSet( a = int32(1), b = PSet( refToPSet_ = string("top")))
2645  proc.ref3 = PSet(refToPSet_ = string("ref"))
2646  proc.ref4 = VPSet(PSet(refToPSet_ = string("top")),
2647  PSet(refToPSet_ = string("ref2")))
2648  p = TestMakePSet()
2649  proc.fillProcessDesc(p)
2650  self.assertEqual((True,1),p.values["ref"][1].values["a"])
2651  self.assertEqual((True,1),p.values["ref3"][1].values["a"])
2652  self.assertEqual((True,1),p.values["ref2"][1].values["a"])
2653  self.assertEqual((True,1),p.values["ref2"][1].values["b"][1].values["a"])
2654  self.assertEqual((True,1),p.values["ref4"][1][0].values["a"])
2655  self.assertEqual((True,1),p.values["ref4"][1][1].values["a"])
2656  def testPrune(self):
2657  p = Process("test")
2658  p.a = EDAnalyzer("MyAnalyzer")
2659  p.b = EDAnalyzer("YourAnalyzer")
2660  p.c = EDAnalyzer("OurAnalyzer")
2661  p.d = EDAnalyzer("OurAnalyzer")
2662  p.s = Sequence(p.d)
2663  p.path1 = Path(p.a)
2664  p.path2 = Path(p.b)
2665  self.assert_(p.schedule is None)
2666  pths = p.paths
2667  keys = pths.keys()
2668  self.assertEqual(pths[keys[0]],p.path1)
2669  self.assertEqual(pths[keys[1]],p.path2)
2670  p.pset1 = PSet(parA = string("pset1"))
2671  p.pset2 = untracked.PSet(parA = string("pset2"))
2672  p.vpset1 = VPSet()
2673  p.vpset2 = untracked.VPSet()
2674  p.prune()
2675  self.assert_(hasattr(p, 'a'))
2676  self.assert_(hasattr(p, 'b'))
2677  self.assert_(not hasattr(p, 'c'))
2678  self.assert_(not hasattr(p, 'd'))
2679  self.assert_(not hasattr(p, 's'))
2680  self.assert_(hasattr(p, 'path1'))
2681  self.assert_(hasattr(p, 'path2'))
2682 # self.assert_(not hasattr(p, 'pset1'))
2683 # self.assert_(hasattr(p, 'pset2'))
2684 # self.assert_(not hasattr(p, 'vpset1'))
2685 # self.assert_(not hasattr(p, 'vpset2'))
2686 
2687  p = Process("test")
2688  p.a = EDAnalyzer("MyAnalyzer")
2689  p.b = EDAnalyzer("YourAnalyzer")
2690  p.c = EDAnalyzer("OurAnalyzer")
2691  p.d = EDAnalyzer("OurAnalyzer")
2692  p.e = EDAnalyzer("OurAnalyzer")
2693  p.s = Sequence(p.d)
2694  p.s2 = Sequence(p.b)
2695  p.s3 = Sequence(p.e)
2696  p.path1 = Path(p.a)
2697  p.path2 = Path(p.b)
2698  p.path3 = Path(p.b+p.s2)
2699  p.path4 = Path(p.b+p.s3)
2700  p.schedule = Schedule(p.path1,p.path2,p.path3)
2701  pths = p.paths
2702  keys = pths.keys()
2703  self.assertEqual(pths[keys[0]],p.path1)
2704  self.assertEqual(pths[keys[1]],p.path2)
2705  p.prune()
2706  self.assert_(hasattr(p, 'a'))
2707  self.assert_(hasattr(p, 'b'))
2708  self.assert_(not hasattr(p, 'c'))
2709  self.assert_(not hasattr(p, 'd'))
2710  self.assert_(not hasattr(p, 'e'))
2711  self.assert_(not hasattr(p, 's'))
2712  self.assert_(hasattr(p, 's2'))
2713  self.assert_(not hasattr(p, 's3'))
2714  self.assert_(hasattr(p, 'path1'))
2715  self.assert_(hasattr(p, 'path2'))
2716  self.assert_(hasattr(p, 'path3'))
2717  self.assert_(not hasattr(p, 'path4'))
2718  #test SequencePlaceholder
2719  p = Process("test")
2720  p.a = EDAnalyzer("MyAnalyzer")
2721  p.b = EDAnalyzer("YourAnalyzer")
2722  p.s = Sequence(SequencePlaceholder("a")+p.b)
2723  p.pth = Path(p.s)
2724  p.prune()
2725  self.assert_(hasattr(p, 'a'))
2726  self.assert_(hasattr(p, 'b'))
2727  self.assert_(hasattr(p, 's'))
2728  self.assert_(hasattr(p, 'pth'))
2729  #test unresolved SequencePlaceholder
2730  p = Process("test")
2731  p.b = EDAnalyzer("YourAnalyzer")
2732  p.s = Sequence(SequencePlaceholder("a")+p.b)
2733  p.pth = Path(p.s)
2734  p.prune(keepUnresolvedSequencePlaceholders=True)
2735  self.assert_(hasattr(p, 'b'))
2736  self.assert_(hasattr(p, 's'))
2737  self.assert_(hasattr(p, 'pth'))
2738  self.assertEqual(p.s.dumpPython(''),'cms.Sequence(cms.SequencePlaceholder("a")+process.b)\n')
2740  p = Process("test")
2741  p.a = EDProducer("ma")
2742  p.b = EDAnalyzer("mb")
2743  p.t1 = Task(TaskPlaceholder("c"))
2744  p.t2 = Task(p.a, TaskPlaceholder("d"), p.t1)
2745  p.t3 = Task(TaskPlaceholder("e"))
2746  p.path1 = Path(p.b, p.t2, p.t3)
2747  p.t5 = Task(p.a, TaskPlaceholder("g"), TaskPlaceholder("t4"))
2748  p.t4 = Task(TaskPlaceholder("f"))
2749  p.endpath1 = EndPath(p.b, p.t5)
2750  p.t6 = Task(TaskPlaceholder("h"))
2751  p.t7 = Task(p.a, TaskPlaceholder("i"), p.t6)
2752  p.t8 = Task(TaskPlaceholder("j"))
2753  p.schedule = Schedule(p.path1, p.endpath1,tasks=[p.t7,p.t8])
2754  p.c = EDProducer("mc")
2755  p.d = EDProducer("md")
2756  p.e = EDProducer("me")
2757  p.f = EDProducer("mf")
2758  p.g = EDProducer("mg")
2759  p.h = EDProducer("mh")
2760  p.i = EDProducer("mi")
2761  p.j = EDProducer("mj")
2762  self.assertEqual(p.dumpPython(),
2763 """import FWCore.ParameterSet.Config as cms
2764 
2765 process = cms.Process("test")
2766 
2767 process.a = cms.EDProducer("ma")
2768 
2769 
2770 process.c = cms.EDProducer("mc")
2771 
2772 
2773 process.d = cms.EDProducer("md")
2774 
2775 
2776 process.e = cms.EDProducer("me")
2777 
2778 
2779 process.f = cms.EDProducer("mf")
2780 
2781 
2782 process.g = cms.EDProducer("mg")
2783 
2784 
2785 process.h = cms.EDProducer("mh")
2786 
2787 
2788 process.i = cms.EDProducer("mi")
2789 
2790 
2791 process.j = cms.EDProducer("mj")
2792 
2793 
2794 process.b = cms.EDAnalyzer("mb")
2795 
2796 
2797 process.t8 = cms.Task(cms.TaskPlaceholder("j"))
2798 
2799 
2800 process.t6 = cms.Task(cms.TaskPlaceholder("h"))
2801 
2802 
2803 process.t7 = cms.Task(cms.TaskPlaceholder("i"), process.a, process.t6)
2804 
2805 
2806 process.t4 = cms.Task(cms.TaskPlaceholder("f"))
2807 
2808 
2809 process.t5 = cms.Task(cms.TaskPlaceholder("g"), cms.TaskPlaceholder("t4"), process.a)
2810 
2811 
2812 process.t3 = cms.Task(cms.TaskPlaceholder("e"))
2813 
2814 
2815 process.t1 = cms.Task(cms.TaskPlaceholder("c"))
2816 
2817 
2818 process.t2 = cms.Task(cms.TaskPlaceholder("d"), process.a, process.t1)
2819 
2820 
2821 process.path1 = cms.Path(process.b, process.t2, process.t3)
2822 
2823 
2824 process.endpath1 = cms.EndPath(process.b, process.t5)
2825 
2826 
2827 process.schedule = cms.Schedule(*[ process.path1, process.endpath1 ], tasks=[process.t7, process.t8])
2828 """)
2829  p.resolve()
2830  self.assertEqual(p.dumpPython(),
2831 """import FWCore.ParameterSet.Config as cms
2832 
2833 process = cms.Process("test")
2834 
2835 process.a = cms.EDProducer("ma")
2836 
2837 
2838 process.c = cms.EDProducer("mc")
2839 
2840 
2841 process.d = cms.EDProducer("md")
2842 
2843 
2844 process.e = cms.EDProducer("me")
2845 
2846 
2847 process.f = cms.EDProducer("mf")
2848 
2849 
2850 process.g = cms.EDProducer("mg")
2851 
2852 
2853 process.h = cms.EDProducer("mh")
2854 
2855 
2856 process.i = cms.EDProducer("mi")
2857 
2858 
2859 process.j = cms.EDProducer("mj")
2860 
2861 
2862 process.b = cms.EDAnalyzer("mb")
2863 
2864 
2865 process.t8 = cms.Task(process.j)
2866 
2867 
2868 process.t6 = cms.Task(process.h)
2869 
2870 
2871 process.t7 = cms.Task(process.a, process.i, process.t6)
2872 
2873 
2874 process.t4 = cms.Task(process.f)
2875 
2876 
2877 process.t5 = cms.Task(process.a, process.g, process.t4)
2878 
2879 
2880 process.t3 = cms.Task(process.e)
2881 
2882 
2883 process.t1 = cms.Task(process.c)
2884 
2885 
2886 process.t2 = cms.Task(process.a, process.d, process.t1)
2887 
2888 
2889 process.path1 = cms.Path(process.b, process.t2, process.t3)
2890 
2891 
2892 process.endpath1 = cms.EndPath(process.b, process.t5)
2893 
2894 
2895 process.schedule = cms.Schedule(*[ process.path1, process.endpath1 ], tasks=[process.t7, process.t8])
2896 """)
2897 
2898  def testDelete(self):
2899  p = Process("test")
2900  p.a = EDAnalyzer("MyAnalyzer")
2901  p.b = EDAnalyzer("YourAnalyzer")
2902  p.c = EDAnalyzer("OurAnalyzer")
2903  p.d = EDAnalyzer("OurAnalyzer")
2904  p.e = EDAnalyzer("OurAnalyzer")
2905  p.f = EDAnalyzer("OurAnalyzer")
2906  p.g = EDProducer("OurProducer")
2907  p.h = EDProducer("YourProducer")
2908  p.t1 = Task(p.g, p.h)
2909  t2 = Task(p.g, p.h)
2910  t3 = Task(p.g, p.h)
2911  p.s = Sequence(p.d+p.e)
2912  p.path1 = Path(p.a+p.f+p.s,t2)
2913  p.endpath1 = EndPath(p.b+p.f)
2914  p.schedule = Schedule(tasks=[t3])
2915  self.assertTrue(hasattr(p, 'f'))
2916  self.assertTrue(hasattr(p, 'g'))
2917  del p.e
2918  del p.f
2919  del p.g
2920  self.assertFalse(hasattr(p, 'f'))
2921  self.assertFalse(hasattr(p, 'g'))
2922  self.assertTrue(p.t1.dumpPython(None) == 'cms.Task(process.h)\n')
2923  self.assertTrue(p.s.dumpPython(None) == 'cms.Sequence(process.d)\n')
2924  self.assertTrue(p.path1.dumpPython(None) == 'cms.Path(process.a+process.s, cms.Task(process.h))\n')
2925  self.assertTrue(p.endpath1.dumpPython(None) == 'cms.EndPath(process.b)\n')
2926  del p.s
2927  self.assertTrue(p.path1.dumpPython(None) == 'cms.Path(process.a+(process.d), cms.Task(process.h))\n')
2928  self.assertTrue(p.schedule_().dumpPython(None) == 'cms.Schedule(tasks=[cms.Task(process.h)])\n')
2929  def testModifier(self):
2930  m1 = Modifier()
2931  p = Process("test",m1)
2932  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1))
2933  def _mod_fred(obj):
2934  obj.fred = 2
2935  m1.toModify(p.a,_mod_fred)
2936  self.assertEqual(p.a.fred.value(),2)
2937  p.b = EDAnalyzer("YourAnalyzer", wilma = int32(1))
2938  m1.toModify(p.b, wilma = 2)
2939  self.assertEqual(p.b.wilma.value(),2)
2940  self.assert_(p.isUsingModifier(m1))
2941  #check that Modifier not attached to a process doesn't run
2942  m1 = Modifier()
2943  p = Process("test")
2944  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1))
2945  m1.toModify(p.a,_mod_fred)
2946  p.b = EDAnalyzer("YourAnalyzer", wilma = int32(1))
2947  m1.toModify(p.b, wilma = 2)
2948  self.assertEqual(p.a.fred.value(),1)
2949  self.assertEqual(p.b.wilma.value(),1)
2950  self.assertEqual(p.isUsingModifier(m1),False)
2951  #make sure clones get the changes
2952  m1 = Modifier()
2953  p = Process("test",m1)
2954  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
2955  m1.toModify(p.a, fred = int32(2))
2956  p.b = p.a.clone(wilma = int32(3))
2957  self.assertEqual(p.a.fred.value(),2)
2958  self.assertEqual(p.a.wilma.value(),1)
2959  self.assertEqual(p.b.fred.value(),2)
2960  self.assertEqual(p.b.wilma.value(),3)
2961  #test removal of parameter
2962  m1 = Modifier()
2963  p = Process("test",m1)
2964  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1), fintstones = PSet(fred = int32(1)))
2965  m1.toModify(p.a, fred = None, fintstones = dict(fred = None))
2966  self.assertEqual(hasattr(p.a, "fred"), False)
2967  self.assertEqual(hasattr(p.a.fintstones, "fred"), False)
2968  self.assertEqual(p.a.wilma.value(),1)
2969  #test adding a parameter
2970  m1 = Modifier()
2971  p = Process("test",m1)
2972  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1))
2973  m1.toModify(p.a, wilma = int32(2))
2974  self.assertEqual(p.a.fred.value(), 1)
2975  self.assertEqual(p.a.wilma.value(),2)
2976  #test setting of value in PSet
2977  m1 = Modifier()
2978  p = Process("test",m1)
2979  p.a = EDAnalyzer("MyAnalyzer", flintstones = PSet(fred = int32(1), wilma = int32(1)))
2980  m1.toModify(p.a, flintstones = dict(fred = int32(2)))
2981  self.assertEqual(p.a.flintstones.fred.value(),2)
2982  self.assertEqual(p.a.flintstones.wilma.value(),1)
2983  #test proper exception from nonexisting parameter name
2984  m1 = Modifier()
2985  p = Process("test",m1)
2986  p.a = EDAnalyzer("MyAnalyzer", flintstones = PSet(fred = PSet(wilma = int32(1))))
2987  self.assertRaises(KeyError, lambda: m1.toModify(p.a, flintstones = dict(imnothere = dict(wilma=2))))
2988  self.assertRaises(KeyError, lambda: m1.toModify(p.a, foo = 1))
2989  #test setting a value in a VPSet
2990  m1 = Modifier()
2991  p = Process("test",m1)
2992  p.a = EDAnalyzer("MyAnalyzer", flintstones = VPSet(PSet(fred = int32(1)), PSet(wilma = int32(1))))
2993  m1.toModify(p.a, flintstones = {1:dict(wilma = int32(2))})
2994  self.assertEqual(p.a.flintstones[0].fred.value(),1)
2995  self.assertEqual(p.a.flintstones[1].wilma.value(),2)
2996  #test setting a value in a list of values
2997  m1 = Modifier()
2998  p = Process("test",m1)
2999  p.a = EDAnalyzer("MyAnalyzer", fred = vuint32(1,2,3))
3000  m1.toModify(p.a, fred = {1:7})
3001  self.assertEqual(p.a.fred[0],1)
3002  self.assertEqual(p.a.fred[1],7)
3003  self.assertEqual(p.a.fred[2],3)
3004  #test IndexError setting a value in a list to an item key not in the list
3005  m1 = Modifier()
3006  p = Process("test",m1)
3007  p.a = EDAnalyzer("MyAnalyzer", fred = vuint32(1,2,3))
3008  raised = False
3009  try: m1.toModify(p.a, fred = {5:7})
3010  except IndexError as e: raised = True
3011  self.assertEqual(raised, True)
3012  #test TypeError setting a value in a list using a key that is not an int
3013  m1 = Modifier()
3014  p = Process("test",m1)
3015  p.a = EDAnalyzer("MyAnalyzer", flintstones = VPSet(PSet(fred = int32(1)), PSet(wilma = int32(1))))
3016  raised = False
3017  try: m1.toModify(p.a, flintstones = dict(bogus = int32(37)))
3018  except TypeError as e: raised = True
3019  self.assertEqual(raised, True)
3020  #test that load causes process wide methods to run
3021  def _rem_a(proc):
3022  del proc.a
3023  class ProcModifierMod(object):
3024  def __init__(self,modifier,func):
3025  self.proc_mod_ = modifier.makeProcessModifier(func)
3026  class DummyMod(object):
3027  def __init__(self):
3028  self.a = EDAnalyzer("Dummy")
3029  testMod = DummyMod()
3030  p.extend(testMod)
3031  self.assert_(hasattr(p,"a"))
3032  m1 = Modifier()
3033  p = Process("test",m1)
3034  testProcMod = ProcModifierMod(m1,_rem_a)
3035  p.extend(testMod)
3036  p.extend(testProcMod)
3037  self.assert_(not hasattr(p,"a"))
3038  #test ModifierChain
3039  m1 = Modifier()
3040  mc = ModifierChain(m1)
3041  p = Process("test",mc)
3042  self.assert_(p.isUsingModifier(m1))
3043  self.assert_(p.isUsingModifier(mc))
3044  testMod = DummyMod()
3045  p.b = EDAnalyzer("Dummy2", fred = int32(1))
3046  m1.toModify(p.b, fred = int32(3))
3047  p.extend(testMod)
3048  testProcMod = ProcModifierMod(m1,_rem_a)
3049  p.extend(testProcMod)
3050  self.assert_(not hasattr(p,"a"))
3051  self.assertEqual(p.b.fred.value(),3)
3052  #check cloneAndExclude
3053  m1 = Modifier()
3054  m2 = Modifier()
3055  mc = ModifierChain(m1,m2)
3056  mclone = mc.copyAndExclude([m2])
3057  self.assert_(not mclone._isOrContains(m2))
3058  self.assert_(mclone._isOrContains(m1))
3059  m3 = Modifier()
3060  mc2 = ModifierChain(mc,m3)
3061  mclone = mc2.copyAndExclude([m2])
3062  self.assert_(not mclone._isOrContains(m2))
3063  self.assert_(mclone._isOrContains(m1))
3064  self.assert_(mclone._isOrContains(m3))
3065  #check combining
3066  m1 = Modifier()
3067  m2 = Modifier()
3068  p = Process("test",m1)
3069  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
3070  (m1 & m2).toModify(p.a, fred = int32(2))
3071  self.assertRaises(TypeError, lambda: (m1 & m2).toModify(p.a, 1, wilma=2))
3072  self.assertEqual(p.a.fred, 1)
3073  m1 = Modifier()
3074  m2 = Modifier()
3075  p = Process("test",m1,m2)
3076  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
3077  (m1 & m2).toModify(p.a, fred = int32(2))
3078  self.assertEqual(p.a.fred, 2)
3079  m1 = Modifier()
3080  m2 = Modifier()
3081  m3 = Modifier()
3082  p = Process("test",m1,m2,m3)
3083  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
3084  (m1 & m2 & m3).toModify(p.a, fred = int32(2))
3085  self.assertEqual(p.a.fred, 2)
3086  (m1 & (m2 & m3)).toModify(p.a, fred = int32(3))
3087  self.assertEqual(p.a.fred, 3)
3088  ((m1 & m2) & m3).toModify(p.a, fred = int32(4))
3089  self.assertEqual(p.a.fred, 4)
3090  #check inverse
3091  m1 = Modifier()
3092  m2 = Modifier()
3093  p = Process("test", m1)
3094  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
3095  (~m1).toModify(p.a, fred=2)
3096  self.assertEqual(p.a.fred, 1)
3097  (~m2).toModify(p.a, wilma=2)
3098  self.assertEqual(p.a.wilma, 2)
3099  self.assertRaises(TypeError, lambda: (~m1).toModify(p.a, 1, wilma=2))
3100  self.assertRaises(TypeError, lambda: (~m2).toModify(p.a, 1, wilma=2))
3101  # check or
3102  m1 = Modifier()
3103  m2 = Modifier()
3104  m3 = Modifier()
3105  p = Process("test", m1)
3106  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
3107  (m1 | m2).toModify(p.a, fred=2)
3108  self.assertEqual(p.a.fred, 2)
3109  (m1 | m2 | m3).toModify(p.a, fred=3)
3110  self.assertEqual(p.a.fred, 3)
3111  (m3 | m2 | m1).toModify(p.a, fred=4)
3112  self.assertEqual(p.a.fred, 4)
3113  ((m1 | m2) | m3).toModify(p.a, fred=5)
3114  self.assertEqual(p.a.fred, 5)
3115  (m1 | (m2 | m3)).toModify(p.a, fred=6)
3116  self.assertEqual(p.a.fred, 6)
3117  (m2 | m3).toModify(p.a, fred=7)
3118  self.assertEqual(p.a.fred, 6)
3119  self.assertRaises(TypeError, lambda: (m1 | m2).toModify(p.a, 1, wilma=2))
3120  self.assertRaises(TypeError, lambda: (m2 | m3).toModify(p.a, 1, wilma=2))
3121  # check combinations
3122  m1 = Modifier()
3123  m2 = Modifier()
3124  m3 = Modifier()
3125  m4 = Modifier()
3126  p = Process("test", m1, m2)
3127  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
3128  (m1 & ~m2).toModify(p.a, fred=2)
3129  self.assertEqual(p.a.fred, 1)
3130  (m1 & ~m3).toModify(p.a, fred=2)
3131  self.assertEqual(p.a.fred, 2)
3132  (m1 | ~m2).toModify(p.a, fred=3)
3133  self.assertEqual(p.a.fred, 3)
3134  (~m1 | ~m2).toModify(p.a, fred=4)
3135  self.assertEqual(p.a.fred, 3)
3136  (~m3 & ~m4).toModify(p.a, fred=4)
3137  self.assertEqual(p.a.fred, 4)
3138  ((m1 & m3) | ~m4).toModify(p.a, fred=5)
3139  self.assertEqual(p.a.fred, 5)
3140  #check toReplaceWith
3141  m1 = Modifier()
3142  p = Process("test",m1)
3143  p.a =EDAnalyzer("MyAnalyzer", fred = int32(1))
3144  m1.toReplaceWith(p.a, EDAnalyzer("YourAnalyzer", wilma = int32(3)))
3145  self.assertRaises(TypeError, lambda: m1.toReplaceWith(p.a, EDProducer("YourProducer")))
3146  p.b =EDAnalyzer("BAn")
3147  p.c =EDProducer("c")
3148  p.d =EDProducer("d")
3149  p.tc = Task(p.c)
3150  p.td = Task(p.d)
3151  p.s = Sequence(p.a, p.tc)
3152  m1.toReplaceWith(p.s, Sequence(p.a+p.b, p.td))
3153  self.assertEqual(p.a.wilma.value(),3)
3154  self.assertEqual(p.a.type_(),"YourAnalyzer")
3155  self.assertEqual(hasattr(p,"fred"),False)
3156  self.assertTrue(p.s.dumpPython("") == "cms.Sequence(process.a+process.b, process.td)\n")
3157  p.e =EDProducer("e")
3158  m1.toReplaceWith(p.td, Task(p.e))
3159  self.assertTrue(p.td._collection == OrderedSet([p.e]))
3160  #check toReplaceWith doesn't activate not chosen
3161  m1 = Modifier()
3162  p = Process("test")
3163  p.a =EDAnalyzer("MyAnalyzer", fred = int32(1))
3164  m1.toReplaceWith(p.a, EDAnalyzer("YourAnalyzer", wilma = int32(3)))
3165  self.assertEqual(p.a.type_(),"MyAnalyzer")
3166  #check toReplaceWith and and/not/or combinations
3167  m1 = Modifier()
3168  m2 = Modifier()
3169  m3 = Modifier()
3170  m4 = Modifier()
3171  p = Process("test", m1, m2)
3172  p.a = EDAnalyzer("MyAnalyzer", fred = int32(1), wilma = int32(1))
3173  self.assertRaises(TypeError, lambda: (m1 & m2).toReplaceWith(p.a, EDProducer("YourProducer")))
3174  self.assertRaises(TypeError, lambda: (m3 & m4).toReplaceWith(p.a, EDProducer("YourProducer")))
3175  self.assertRaises(TypeError, lambda: (~m3).toReplaceWith(p.a, EDProducer("YourProducer")))
3176  self.assertRaises(TypeError, lambda: (~m1).toReplaceWith(p.a, EDProducer("YourProducer")))
3177  self.assertRaises(TypeError, lambda: (m1 | m3).toReplaceWith(p.a, EDProducer("YourProducer")))
3178  self.assertRaises(TypeError, lambda: (m3 | m4).toReplaceWith(p.a, EDProducer("YourProducer")))
3179  (m1 & m2).toReplaceWith(p.a, EDAnalyzer("YourAnalyzer1"))
3180  self.assertEqual(p.a.type_(), "YourAnalyzer1")
3181  (m1 & m3).toReplaceWith(p.a, EDAnalyzer("YourAnalyzer2"))
3182  self.assertEqual(p.a.type_(), "YourAnalyzer1")
3183  (~m1).toReplaceWith(p.a, EDAnalyzer("YourAnalyzer2"))
3184  self.assertEqual(p.a.type_(), "YourAnalyzer1")
3185  (~m3).toReplaceWith(p.a, EDAnalyzer("YourAnalyzer2"))
3186  self.assertEqual(p.a.type_(), "YourAnalyzer2")
3187  (m1 | m3).toReplaceWith(p.a, EDAnalyzer("YourAnalyzer3"))
3188  self.assertEqual(p.a.type_(), "YourAnalyzer3")
3189  (m3 | m4).toReplaceWith(p.a, EDAnalyzer("YourAnalyzer4"))
3190  self.assertEqual(p.a.type_(), "YourAnalyzer3")
3191  unittest.main()
def __setstate__(self, pkldict)
Definition: Config.py:155
def addVString(self, tracked, label, value)
Definition: Config.py:1522
def _dumpConfigOptionallyNamedList(self, items, typeName, options)
Definition: Config.py:653
def addEventRange(self, tracked, label, value)
Definition: Config.py:1540
def __init__(self, lhs, rhs)
Definition: Config.py:1325
def testExamples(self)
Definition: Config.py:2516
def __getattribute__(self, name)
Definition: Config.py:1166
def _place(self, label, process)
Definition: Config.py:1250
def getProcessName(self)
Definition: Config.py:1238
def testServiceInProcess(self)
Definition: Config.py:2022
def __or__(self, other)
Definition: Config.py:1416
def outputCommands(self)
Definition: Config.py:1244
def _setChosen(self)
Definition: Config.py:1433
def producerNames(self)
Definition: Config.py:142
def _dumpConfigUnnamedList(self, items, typeName, options)
Definition: Config.py:648
def newPSet(self)
Definition: Config.py:1550
def _placeAnalyzer(self, name, mod)
Definition: Config.py:524
def addString(self, tracked, label, value)
Definition: Config.py:1520
def __findFirstUsingModule(self, seqsOrTasks, mod)
Definition: Config.py:410
def subProcesses_(self)
Definition: Config.py:199
def __repr__(self)
Definition: Config.py:1209
def _pruneModules(self, d, scheduledNames)
Definition: Config.py:1016
def _modifyParametersFromDict(params, newParams, errorRaiser, keyDepth="")
Definition: Mixins.py:629
def vpsets_(self)
Definition: Config.py:270
def setName_(self, name)
Definition: Config.py:178
def copy(args, dbName)
def _placeESPrefer(self, name, mod)
Definition: Config.py:545
def testSequence2(self)
Definition: Config.py:2012
def _insertPaths(self, processPSet, nodeVisitor)
Definition: Config.py:901
def es_producers_(self)
Definition: Config.py:250
def _placeESProducer(self, name, mod)
Definition: Config.py:543
def __invert__(self)
Definition: Config.py:1414
def pathNames(self)
Definition: Config.py:151
def addVESInputTag(self, tracked, label, value)
Definition: Config.py:1530
def __and__(self, other)
Definition: Config.py:1412
def _placeSequence(self, name, mod)
Definition: Config.py:540
def __call__(self, obj)
Definition: Config.py:1265
def _setChosen(self)
Definition: Config.py:1407
def _validateSequence(self, sequence, label)
Definition: Config.py:741
def __getattr__(self, attr)
Definition: Config.py:1211
def tasks_(self)
Definition: Config.py:223
def setStrict(self, value)
Definition: Config.py:137
def addDouble(self, tracked, label, value)
Definition: Config.py:1514
def isChosen(self)
Definition: Config.py:1438
def producers_(self)
Definition: Config.py:183
def _findPreferred(self, esname, d, args, kargs)
Definition: Config.py:1135
def replace(string, replacements)
def testModifier(self)
Definition: Config.py:2929
def _insertOneInto(self, parameterSet, label, item, tracked)
Definition: Config.py:872
def filterNames(self)
Definition: Config.py:148
def __delattr__(self, name)
Definition: Config.py:440
def _placePath(self, name, mod)
Definition: Config.py:526
def addVUInt64(self, tracked, label, value)
Definition: Config.py:1512
def isChosen(self)
Definition: Config.py:1327
def _placeEndPath(self, name, mod)
Definition: Config.py:533
def es_sources_(self)
Definition: Config.py:254
def __init__(self, name, Mods)
Definition: Config.py:101
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:20
def testTypedParameterizable(self)
Definition: Config.py:1590
def addUInt64(self, tracked, label, value)
Definition: Config.py:1510
def _itemsInDependencyOrder(self, processDictionaryOfItems)
Definition: Config.py:757
def source_(self)
Definition: Config.py:187
def addVPSet(self, tracked, label, value)
Definition: Config.py:1546
def nameInProcessDesc_(self, label)
Definition: Config.py:1248
def psets_(self)
Definition: Config.py:266
def testSecSource(self)
Definition: Config.py:1947
def __init__(self, args)
Definition: Config.py:1263
def format_outerframe(number)
def __init__(self, args, kw)
Definition: Config.py:1207
def load(self, moduleName)
Definition: Config.py:581
def _insertSubProcessesInto(self, parameterSet, label, itemList, tracked)
Definition: Config.py:888
def addUInt32(self, tracked, label, value)
Definition: Config.py:1502
def _dumpConfigESPrefers(self, options)
Definition: Config.py:722
def __setattr__(self, name, value)
Definition: Config.py:1171
def setLooper_(self, lpr)
Definition: Config.py:196
def setSource_(self, src)
Definition: Config.py:190
def __init__(self, process)
Definition: Config.py:1157
def extend(self, other, items=())
Definition: Config.py:585
def _okToPlace(self, name, mod, d)
Definition: Config.py:489
def __or__(self, other)
Definition: Config.py:1306
def visit(visitdir)
Retrieve data from a perf suite output (sub) directory, only examines TimeSize at the moment...
def _replaceInTasks(self, label, new)
Definition: Config.py:854
def addVInt32(self, tracked, label, value)
Definition: Config.py:1500
def _placeFilter(self, name, mod)
Definition: Config.py:522
def schedule_(self)
Definition: Config.py:227
def validate(self)
Definition: Config.py:1099
def addVInputTag(self, tracked, label, value)
Definition: Config.py:1526
def _applyNewProcessModifiers(self, process)
Definition: Config.py:1428
def analyzerNames(self)
Definition: Config.py:145
def testSchedule(self)
Definition: Config.py:2348
def addLuminosityBlockID(self, tracked, label, value)
Definition: Config.py:1536
def addESInputTag(self, tracked, label, value)
Definition: Config.py:1528
def __init__(self, lhs)
Definition: Config.py:1318
def __new__(cls, args, kw)
Definition: Config.py:1190
def testContains(self)
Definition: Config.py:2290
def endpaths_(self)
Definition: Config.py:215
def toModify(self, obj, func=None, kw)
Definition: Config.py:1287
def SelectEvents(self)
Definition: Config.py:1242
def __setattr__(self, name, value)
Definition: Config.py:310
def _placeESSource(self, name, mod)
Definition: Config.py:547
def addVInt64(self, tracked, label, value)
Definition: Config.py:1508
def addVEventID(self, tracked, label, value)
Definition: Config.py:1534
def toModify(self, obj, func=None, kw)
Definition: Config.py:1353
def testGlobalReplace(self)
Definition: Config.py:1952
def toReplaceWith(self, toObj, fromObj)
Definition: Config.py:1292
def isChosen(self)
Definition: Config.py:1320
def _placeOutputModule(self, name, mod)
Definition: Config.py:518
def addFileInPath(self, tracked, label, value)
Definition: Config.py:1548
def testRefToPSet(self)
Definition: Config.py:2640
def testOverride(self)
Definition: Config.py:2493
def _placeSource(self, name, mod)
Definition: Config.py:558
def __init__(self)
Definition: Config.py:1340
def __init__(self, lhs, rhs=None)
Definition: Config.py:1283
def _dumpPythonSubProcesses(self, l, options)
Definition: Config.py:727
def checkImportPermission(minLevel=2, allowedPatterns=[])
Definition: Config.py:27
def ignore(seq)
def _toModify(obj, func, kw)
Definition: Config.py:1371
def __init__(self, modifier, func)
Definition: Config.py:1477
def _toReplaceWith(toObj, fromObj)
Definition: Config.py:1389
def _toModifyCheck(obj, func, kw)
Definition: Config.py:1350
def isUsingModifier(self, mod)
Definition: Config.py:275
def dumpPython(self, options=PrintOptions())
Definition: Config.py:1231
def __copyIfExclude(self, toExclude)
Definition: Config.py:1454
def sequences_(self)
Definition: Config.py:219
def _validateTask(self, task, label)
Definition: Config.py:749
def testParameterizable(self)
Definition: Config.py:1557
def testSubProcess(self)
Definition: Config.py:2600
def _placeSubProcess(self, name, mod)
Definition: Config.py:571
def setPartialSchedule_(self, sch, label)
Definition: Config.py:230
def addPSet(self, tracked, label, value)
Definition: Config.py:1544
def testProcessDumpPython(self)
Definition: Config.py:1692
def _placeService(self, typeName, mod)
Definition: Config.py:576
def resolve(self, keepUnresolvedSequencePlaceholders=False)
Definition: Config.py:955
def looper_(self)
Definition: Config.py:193
def es_prefers_(self)
Definition: Config.py:258
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def _isOrContains(self, other)
Definition: Config.py:1418
def getSubProcessPSet(self, parameterSet)
Definition: Config.py:1252
def copyAndExclude(self, toExclude)
Definition: Config.py:1440
def addVUInt32(self, tracked, label, value)
Definition: Config.py:1504
def addVEventRange(self, tracked, label, value)
Definition: Config.py:1542
def __init__(self, lhs, rhs)
Definition: Config.py:1311
def filters_(self)
Definition: Config.py:172
def dumpPython(process, name)
def __setObjectLabel(self, object, newLabel)
Definition: Config.py:283
def _delHelper(self, name)
Definition: Config.py:423
def _placeAlias(self, name, mod)
Definition: Config.py:552
def dumpPython(self, options=PrintOptions())
Definition: Config.py:818
def _replaceInSequences(self, label, new)
Definition: Config.py:845
def setSchedule_(self, sch)
Definition: Config.py:235
def analyzers_(self)
Definition: Config.py:203
def _toReplaceWithCheck(toObj, fromObj)
Definition: Config.py:1378
def testSequence(self)
Definition: Config.py:1997
def toReplaceWith(self, toObj, fromObj)
Definition: Config.py:1381
def _placeProducer(self, name, mod)
Definition: Config.py:520
def prefer(self, esmodule, args, kargs)
Definition: Config.py:1106
def __delattr__(self, name)
Definition: Config.py:1176
def _dumpConfigNamedList(self, items, typeName, options)
Definition: Config.py:643
def addInputTag(self, tracked, label, value)
Definition: Config.py:1524
def add_(self, value)
Definition: Config.py:474
def _insertManyInto(self, parameterSet, label, itemDict, tracked)
Definition: Config.py:879
def dumpConfig(self, options=PrintOptions())
Definition: Config.py:660
def apply(self, process)
Definition: Config.py:1481
def testCloneSequence(self)
Definition: Config.py:2274
def process(self)
Definition: Config.py:1240
def _placeTask(self, name, task)
Definition: Config.py:549
def makeProcessModifier(self, func)
Definition: Config.py:1297
def isChosen(self)
Definition: Config.py:1313
def addSubProcess(self, mod)
Definition: Config.py:574
def _placePSet(self, name, mod)
Definition: Config.py:554
def _isOrContains(self, other)
Definition: Config.py:1463
def addInt64(self, tracked, label, value)
Definition: Config.py:1506
def name_(self)
Definition: Config.py:176
def _place(self, name, mod, d)
Definition: Config.py:510
def testProcessExtend(self)
Definition: Config.py:1622
def _dumpPythonList(self, d, options)
Definition: Config.py:732
dbl *** dir
Definition: mlp_gen.cc:35
def __insertValue(self, tracked, label, value)
Definition: Config.py:1496
def _placeVPSet(self, name, mod)
Definition: Config.py:556
def __and__(self, other)
Definition: Config.py:1302
def globalReplace(self, label, new)
Definition: Config.py:864
#define str(s)
def addBool(self, tracked, label, value)
Definition: Config.py:1518
def paths_(self)
Definition: Config.py:211
def addEventID(self, tracked, label, value)
Definition: Config.py:1532
def outputModules_(self)
Definition: Config.py:207
def _placeLooper(self, name, mod)
Definition: Config.py:566
def testImplicitSchedule(self)
Definition: Config.py:2453
def prune(self, verbose=False, keepUnresolvedSequencePlaceholders=False)
Definition: Config.py:964
def addVDouble(self, tracked, label, value)
Definition: Config.py:1516
def _insertInto(self, parameterSet, itemDict)
Definition: Config.py:869
def _delattrFromSetattr(self, name)
Definition: Config.py:465
def makeProcessModifier(self, func)
Definition: Config.py:1343
def __init__(self, process, SelectEvents=untracked.PSet(), outputCommands=untracked.vstring())
Definition: Config.py:1219
def type_(self)
Definition: Config.py:1246
def __init__(self, chainedModifiers)
Definition: Config.py:1425
def testTaskPlaceholder(self)
Definition: Config.py:2739
def services_(self)
Definition: Config.py:246
def _replaceInSchedule(self, label, new)
Definition: Config.py:858
def _dumpPython(self, d, options)
Definition: Config.py:813
def addInt32(self, tracked, label, value)
Definition: Config.py:1498
How EventSelector::AcceptEvent() decides whether to accept an event for output otherwise it is excluding the probing of A single or multiple positive and the trigger will pass if any such matching triggers are PASS or EXCEPTION[A criterion thatmatches no triggers at all is detected and causes a throw.] A single negative with an expectation of appropriate bit checking in the decision and the trigger will pass if any such matching triggers are FAIL or EXCEPTION A wildcarded negative criterion that matches more than one trigger in the trigger list("!*","!HLTx*"if it matches 2 triggers or more) will accept the event if all the matching triggers are FAIL.It will reject the event if any of the triggers are PASS or EXCEPTION(this matches the behavior of"!*"before the partial wildcard feature was incorporated).Triggers which are in the READY state are completely ignored.(READY should never be returned since the trigger paths have been run
def fillProcessDesc(self, processPSet)
Definition: Config.py:1023
def findProcess(module)
Definition: Config.py:80
def isChosen(self)
Definition: Config.py:1410
def testProcessInsertion(self)
Definition: Config.py:1597
def __init__(self)
Definition: Config.py:1494
def aliases_(self)
Definition: Config.py:262