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