CMS 3D CMS Logo

Modules.py
Go to the documentation of this file.
1 from __future__ import absolute_import
2 from .Mixins import _ConfigureComponent, saveOrigin
3 from .Mixins import _Unlabelable, _Labelable
4 from .Mixins import _TypedParameterizable, _Parameterizable, PrintOptions, specialImportRegistry
5 from .SequenceTypes import _SequenceLeaf
6 from .Types import vstring, EDAlias
7 
8 
9 import six
10 import copy
11 from .ExceptionHandling import *
13  def __init__(self,type_,*arg,**kargs):
14  super(Service,self).__init__(type_,*arg,**kargs)
15  self._inProcess = False
16  def _placeImpl(self,name,proc):
17  self._inProcess = True
18  proc._placeService(self.type_(),self)
19  def insertInto(self, processDesc):
20  newpset = processDesc.newPSet()
21  newpset.addString(True, "@service_type", self.type_())
22  self.insertContentsInto(newpset)
23  processDesc.addService(newpset)
24  def dumpSequencePython(self, options=PrintOptions()):
25  return "process." + self.type_()
26  def _isTaskComponent(self):
27  return True
28  def isLeaf(self):
29  return True
30  def __str__(self):
31  return str(self.type_())
32 
34  def __init__(self,type_,*arg,**kargs):
35  super(ESSource,self).__init__(type_,*arg,**kargs)
36  saveOrigin(self, 1)
37  def _placeImpl(self,name,proc):
38  if name == '':
39  name=self.type_()
40  proc._placeESSource(name,self)
41  def moduleLabel_(self,myname):
42  result = myname
43  if self.type_() == myname:
44  result = ""
45  return result
46  def nameInProcessDesc_(self, myname):
47  result = self.type_() + "@" + self.moduleLabel_(myname)
48  return result
49  def _isTaskComponent(self):
50  return True
51  def isLeaf(self):
52  return True
53 
55  def __init__(self,type_,*arg,**kargs):
56  super(ESProducer,self).__init__(type_,*arg,**kargs)
57  def _placeImpl(self,name,proc):
58  if name == '':
59  name=self.type_()
60  proc._placeESProducer(name,self)
61  def moduleLabel_(self,myname):
62  result = myname
63  if self.type_() == myname:
64  result = ''
65  return result
66  def nameInProcessDesc_(self, myname):
67  result = self.type_() + "@" + self.moduleLabel_(myname)
68  return result
69  def _isTaskComponent(self):
70  return True
71  def isLeaf(self):
72  return True
73 
75  """Used to set which EventSetup provider should provide a particular data item
76  in the case where multiple providers are capable of delivering the data.
77  The first argument specifies the C++ class type of the prodiver.
78  If the provider has been given a label, you must specify that label as the second argument.
79  Additional 'vstring' arguments maybe used to specify exactly which EventSetup Records
80  are being preferred and optionally which data items within that Record.
81  E.g.,
82  #prefer all data in record 'OrangeRecord' from 'juicer'
83  ESPrefer("ESJuicerProd", OrangeRecord=cms.vstring())
84  or
85  #prefer only "Orange" data in "OrangeRecord" from "juicer"
86  ESPrefer("ESJuicerProd", OrangeRecord=cms.vstring("ExtraPulp"))
87  or
88  #prefer only "Orange" data with label "ExtraPulp" in "OrangeRecord" from "juicer"
89  ESPrefer("ESJuicerProd", OrangeRecord=cms.vstring("Orange/ExtraPulp"))
90  """
91  def __init__(self,type_,targetLabel='',*arg,**kargs):
92  super(ESPrefer,self).__init__(type_,*arg,**kargs)
93  self._targetLabel = targetLabel
94  if targetLabel is None:
95  self._targetLabel = str('')
96  if kargs:
97  for k,v in six.iteritems(kargs):
98  if not isinstance(v,vstring):
99  raise RuntimeError('ESPrefer only allows vstring attributes. "'+k+'" is a '+str(type(v)))
100  def _placeImpl(self,name,proc):
101  proc._placeESPrefer(name,self)
102  def nameInProcessDesc_(self, myname):
103  # the C++ parser can give it a name like "label@prefer". Get rid of that.
104  return "esprefer_" + self.type_() + "@" + self._targetLabel
105  def copy(self):
106  returnValue = ESPrefer.__new__(type(self))
107  returnValue.__init__(self.type_(), self._targetLabel)
108  return returnValue
109  def moduleLabel_(self, myname):
110  return self._targetLabel
111  def targetLabel_(self):
112  return self._targetLabel
113  def dumpPythonAs(self, label, options=PrintOptions()):
114  result = options.indentation()
115  basename = self._targetLabel
116  if basename == '':
117  basename = self.type_()
118  if options.isCfg:
119  # do either type or label
120  result += 'process.prefer("'+basename+'"'
121  if self.parameterNames_():
122  result += ",\n"+_Parameterizable.dumpPython(self,options)+options.indentation()
123  result +=')\n'
124  else:
125  # use the base class Module
126  result += 'es_prefer_'+basename+' = cms.ESPrefer("'+self.type_()+'"'
127  if self._targetLabel != '':
128  result += ',"'+self._targetLabel+'"'
129  if self.parameterNames_():
130  result += ",\n"+_Parameterizable.dumpPython(self,options)+options.indentation()
131  result += ')\n'
132  return result
133 
135  """base class for classes which denote framework event based 'modules'"""
136  __isStrict__ = False
137  def __init__(self,type_,*arg,**kargs):
138  super(_Module,self).__init__(type_,*arg,**kargs)
139  if _Module.__isStrict__:
140  self.setIsFrozen()
141  saveOrigin(self, 2)
142  def _clonesequence(self, lookuptable):
143  try:
144  return lookuptable[id(self)]
145  except:
146  raise ModuleCloneError(self._errorstr())
147  def _errorstr(self):
148  # return something like "EDAnalyzer("foo", ...)"
149  typename = format_typename(self)
150  return "%s('%s', ...)" %(typename, self.type_())
151 
152  def setPrerequisites(self, *libs):
153  self.__dict__["libraries_"] = libs
154 
155  def insertInto(self, parameterSet, myname):
156  if "libraries_" in self.__dict__:
157  from ctypes import LibraryLoader, CDLL
158  import platform
159  loader = LibraryLoader(CDLL)
160  ext = platform.uname()[0] == "Darwin" and "dylib" or "so"
161  [loader.LoadLibrary("lib%s.%s" % (l, ext)) for l in self.libraries_]
162  super(_Module,self).insertInto(parameterSet,myname)
163 
165  def __init__(self,type_,*arg,**kargs):
166  super(EDProducer,self).__init__(type_,*arg,**kargs)
167  def _placeImpl(self,name,proc):
168  proc._placeProducer(name,self)
169  def _isTaskComponent(self):
170  return True
171 
173  def __init__(self,type_,*arg,**kargs):
174  super(EDFilter,self).__init__(type_,*arg,**kargs)
175  def _placeImpl(self,name,proc):
176  proc._placeFilter(name,self)
177  def _isTaskComponent(self):
178  return True
179 
181  def __init__(self,type_,*arg,**kargs):
182  super(EDAnalyzer,self).__init__(type_,*arg,**kargs)
183  def _placeImpl(self,name,proc):
184  proc._placeAnalyzer(name,self)
185 
186 
188  def __init__(self,type_,*arg,**kargs):
189  super(OutputModule,self).__init__(type_,*arg,**kargs)
190  def _placeImpl(self,name,proc):
191  proc._placeOutputModule(name,self)
192 
193 
195  def __init__(self,type_,*arg,**kargs):
196  super(Source,self).__init__(type_,*arg,**kargs)
197  def _placeImpl(self,name,proc):
198  proc._placeSource(name,self)
199  def moduleLabel_(self,myname):
200  return "@main_input"
201  def nameInProcessDesc_(self,myname):
202  return "@main_input"
203 
204 
206  def __init__(self,type_,*arg,**kargs):
207  super(Looper,self).__init__(type_,*arg,**kargs)
208  def _placeImpl(self,name,proc):
209  proc._placeLooper(name,self)
210  def moduleLabel_(self,myname):
211  return "@main_looper"
212  def nameInProcessDesc_(self, myname):
213  return "@main_looper"
214 
215 
216 # Need to be a module-level function for the configuration with a
217 # SwitchProducer to be pickleable.
219  return (True, 1)
220 
222  """This purpose class is to provide a switch of EDProducers for a single module/product label.
223 
224  The decision is done at the time when the python configuration is
225  translated to C++. This class is generic, and intended to be
226  inherited for concrete switches. Example:
227 
228  class SwitchProducerFoo(SwitchProducer):
229  def __init__(self, **kargs):
230  super(SwitchProducerFoo,self).__init__(
231  dict(case1 = case1Func, case2 = case2Func),
232  **kargs
233  )
234 
235  foo = SwitchProducerFoo(
236  case1 = EDProducer("Producer1"),
237  case2 = EDProducer("Producer2")
238  )
239 
240  Here case1Func and case2Func are functions that return a (bool,
241  int) tuple, where the bool tells whether that case is enabled or
242  not, and the int tells the priority of that case. The case with
243  the highest priority among those that are enabled will get chosen.
244 
245  The end result is that the product(s) labeled as "foo" will be
246  produced with one of the producers. It would be good if their
247  output product types and instance names would be the same (or very
248  close).
249  """
250  def __init__(self, caseFunctionDict, **kargs):
251  super(SwitchProducer,self).__init__(None)
252  self._caseFunctionDict = copy.copy(caseFunctionDict)
253  self.__setParameters(kargs)
254  self._isModified = False
255 
256  @staticmethod
257  def getCpu():
258  """Returns a function that returns the priority for a CPU "computing device". Intended to be used by deriving classes."""
259  return _switch_cpu
260 
261  def _chooseCase(self):
262  """Returns the name of the chosen case."""
263  cases = self.parameterNames_()
264  bestCase = None
265  for case in cases:
266  (enabled, priority) = self._caseFunctionDict[case]()
267  if enabled and (bestCase is None or bestCase[0] < priority):
268  bestCase = (priority, case)
269  if bestCase is None:
270  raise RuntimeError("All cases '%s' were disabled" % (str(cases)))
271  return bestCase[1]
272 
273  def _getProducer(self):
274  """Returns the EDroducer of the chosen case"""
275  return self.__dict__[self._chooseCase()]
276 
277  @staticmethod
278  def __typeIsValid(typ):
279  return (isinstance(typ, EDProducer) and not isinstance(typ, SwitchProducer)) or isinstance(typ, EDAlias)
280 
281  def __addParameter(self, name, value):
282  if not self.__typeIsValid(value):
283  raise TypeError(name+" does not already exist, so it can only be set to a cms.EDProducer or cms.EDAlias")
284  if name not in self._caseFunctionDict:
285  raise ValueError("Case '%s' is not allowed (allowed ones are %s)" % (name, ",".join(six.iterkeys(self._caseFunctionDict))))
286  if name in self.__dict__:
287  message = "Duplicate insert of member " + name
288  message += "\nThe original parameters are:\n"
289  message += self.dumpPython() + '\n'
290  raise ValueError(message)
291  self.__dict__[name]=value
292  self._Parameterizable__parameterNames.append(name)
293  self._isModified = True
294 
295  def __setParameters(self, parameters):
296  for name, value in six.iteritems(parameters):
297  self.__addParameter(name, value)
298 
299  def __setattr__(self, name, value):
300  # Following snippet copied and customized from
301  # _Parameterizable in order to support Modifier.toModify
302  #
303  #since labels are not supposed to have underscores at the beginning
304  # I will assume that if we have such then we are setting an internal variable
305  if self.isFrozen() and not (name in ["_Labelable__label","_isFrozen"] or name.startswith('_')):
306  message = "Object already added to a process. It is read only now\n"
307  message += " %s = %s" %(name, value)
308  message += "\nThe original parameters are:\n"
309  message += self.dumpPython() + '\n'
310  raise ValueError(message)
311  # underscored names bypass checking for _ParameterTypeBase
312  if name[0]=='_':
313  super(SwitchProducer, self).__setattr__(name,value)
314  elif not name in self.__dict__:
315  self.__addParameter(name, value)
316  self._isModified = True
317  else:
318  if not self.__typeIsValid(value):
319  raise TypeError(name+" can only be set to a cms.EDProducer or cms.EDAlias")
320  # We should always receive an cms.EDProducer
321  self.__dict__[name] = value
322  self._isModified = True
323 
324  def clone(self, **params):
325  returnValue = SwitchProducer.__new__(type(self))
326 
327  # Need special treatment as cms.EDProducer is not a valid parameter type (except in this case)
328  myparams = dict()
329  for name, value in six.iteritems(params):
330  if value is None:
331  continue
332  elif isinstance(value, dict):
333  myparams[name] = self.__dict__[name].clone(**value)
334  else: # value is an EDProducer
335  myparams[name] = value.clone()
336 
337  # Add the ones that were not customized
338  for name in self.parameterNames_():
339  if name not in params:
340  myparams[name] = self.__dict__[name].clone()
341  returnValue.__init__(**myparams)
342  returnValue._isModified = False
343  returnValue._isFrozen = False
344  saveOrigin(returnValue, 1)
345  return returnValue
346 
347  def dumpPython(self, options=PrintOptions()):
348  # Note that if anyone uses the generic SwitchProducer instead
349  # of a derived-one, the information on the functions for the
350  # producer decision is lost
351  specialImportRegistry.registerUse(self)
352  result = "%s(" % self.__class__.__name__ # not including cms. since the deriving classes are not in cms "namespace"
353  options.indent()
354  for resource in sorted(self.parameterNames_()):
355  result += "\n" + options.indentation() + resource + " = " + getattr(self, resource).dumpPython(options).rstrip() + ","
356  if result[-1] == ",":
357  result = result.rstrip(",")
358  options.unindent()
359  result += "\n)\n"
360  return result
361 
362  def nameInProcessDesc_(self, myname):
363  return myname
364  def moduleLabel_(self, myname):
365  return myname
366  def caseLabel_(self, name, case):
367  return name+"@"+case
368  def appendToProcessDescLists_(self, modules, aliases, myname):
369  # This way we can insert the chosen EDProducer to @all_modules
370  # so that we get easily a worker for it
371  modules.append(myname)
372  for case in self.parameterNames_():
373  if isinstance(self.__dict__[case], EDAlias):
374  aliases.append(self.caseLabel_(myname, case))
375  else:
376  modules.append(self.caseLabel_(myname, case))
377 
378  def insertInto(self, parameterSet, myname):
379  for case in self.parameterNames_():
380  producer = self.__dict__[case]
381  producer.insertInto(parameterSet, self.caseLabel_(myname, case))
382  newpset = parameterSet.newPSet()
383  newpset.addString(True, "@module_label", self.moduleLabel_(myname))
384  newpset.addString(True, "@module_type", "SwitchProducer")
385  newpset.addString(True, "@module_edm_type", "EDProducer")
386  newpset.addVString(True, "@all_cases", [myname+"@"+p for p in self.parameterNames_()])
387  newpset.addString(False, "@chosen_case", myname+"@"+self._chooseCase())
388  parameterSet.addPSet(True, self.nameInProcessDesc_(myname), newpset)
389 
390  def _placeImpl(self,name,proc):
391  proc._placeSwitchProducer(name,self)
392 # for case in self.parameterNames_():
393 # caseLabel = self.caseLabel_(name, case)
394 # caseObj = self.__dict__[case]
395 #
396 # if isinstance(caseObj, EDAlias):
397 # # EDAliases end up in @all_aliases automatically
398 # proc._placeAlias(caseLabel, caseObj)
399 # else:
400 # # Note that these don't end up in @all_modules
401 # # automatically because they're not part of any
402 # # Task/Sequence/Path
403 # proc._placeProducer(caseLabel, caseObj)
404 
405  def _clonesequence(self, lookuptable):
406  try:
407  return lookuptable[id(self)]
408  except:
409  raise ModuleCloneError(self._errorstr())
410  def _errorstr(self):
411  return "SwitchProducer"
412 
413 
414 if __name__ == "__main__":
415  import unittest
416  from .Types import *
417  from .SequenceTypes import *
418 
420  def __init__(self, **kargs):
421  super(SwitchProducerTest,self).__init__(
422  dict(
423  test1 = lambda: (True, -10),
424  test2 = lambda: (True, -9),
425  test3 = lambda: (True, -8)
426  ), **kargs)
428  def __init__(self, **kargs):
429  super(SwitchProducerTest1Dis,self).__init__(
430  dict(
431  test1 = lambda: (False, -10),
432  test2 = lambda: (True, -9)
433  ), **kargs)
435  def __init__(self, **kargs):
436  super(SwitchProducerTest2Dis,self).__init__(
437  dict(
438  test1 = lambda: (True, -10),
439  test2 = lambda: (False, -9)
440  ), **kargs)
442  def __init__(self, **kargs):
443  super(SwitchProducerPickleable,self).__init__(
444  dict(cpu = SwitchProducer.getCpu()), **kargs)
445 
446  class TestModules(unittest.TestCase):
447  def testEDAnalyzer(self):
448  empty = EDAnalyzer("Empty")
449  withParam = EDAnalyzer("Parameterized",foo=untracked(int32(1)), bar = untracked(string("it")))
450  self.assertEqual(withParam.foo.value(), 1)
451  self.assertEqual(withParam.bar.value(), "it")
452  aCopy = withParam.copy()
453  self.assertEqual(aCopy.foo.value(), 1)
454  self.assertEqual(aCopy.bar.value(), "it")
455  withType = EDAnalyzer("Test",type = int32(1))
456  self.assertEqual(withType.type.value(),1)
457  block = PSet(i = int32(9))
458  m = EDProducer("DumbProducer", block, j = int32(10))
459  self.assertEqual(9, m.i.value())
460  self.assertEqual(10, m.j.value())
461  def testESPrefer(self):
462  juicer = ESPrefer("JuiceProducer")
463  options = PrintOptions()
464  options.isCfg = True
465  self.assertEqual(juicer.dumpPythonAs("juicer", options), "process.prefer(\"JuiceProducer\")\n")
466  options.isCfg = False
467  self.assertEqual(juicer.dumpPythonAs("juicer", options), "es_prefer_JuiceProducer = cms.ESPrefer(\"JuiceProducer\")\n")
468 
469  juicer = ESPrefer("JuiceProducer","juicer")
470  options = PrintOptions()
471  options.isCfg = True
472  self.assertEqual(juicer.dumpPythonAs("juicer", options), 'process.prefer("juicer")\n')
473  options.isCfg = False
474  self.assertEqual(juicer.dumpPythonAs("juicer", options), 'es_prefer_juicer = cms.ESPrefer("JuiceProducer","juicer")\n')
475  juicer = ESPrefer("JuiceProducer",fooRcd=vstring())
476  self.assertEqual(juicer.dumpConfig(options),
477 """JuiceProducer {
478  vstring fooRcd = {
479  }
480 
481 }
482 """)
483  options = PrintOptions()
484  options.isCfg = True
485  self.assertEqual(juicer.dumpPythonAs("juicer"),
486 """process.prefer("JuiceProducer",
487  fooRcd = cms.vstring()
488 )
489 """)
490  options.isCfg = False
491  self.assertEqual(juicer.dumpPythonAs("juicer", options),
492 """es_prefer_JuiceProducer = cms.ESPrefer("JuiceProducer",
493  fooRcd = cms.vstring()
494 )
495 """)
496 
497  def testService(self):
498  empty = Service("Empty")
499  withParam = Service("Parameterized",foo=untracked(int32(1)), bar = untracked(string("it")))
500  self.assertEqual(withParam.foo.value(), 1)
501  self.assertEqual(withParam.bar.value(), "it")
502  self.assertEqual(empty.dumpPython(), "cms.Service(\"Empty\")\n")
503  self.assertEqual(withParam.dumpPython(), "cms.Service(\"Parameterized\",\n bar = cms.untracked.string(\'it\'),\n foo = cms.untracked.int32(1)\n)\n")
504  def testSequences(self):
505  m = EDProducer("MProducer")
506  n = EDProducer("NProducer")
507  m.setLabel("m")
508  n.setLabel("n")
509  s1 = Sequence(m*n)
510  options = PrintOptions()
511 
513  m = EDProducer("x")
514  self.assertTrue(m._isTaskComponent())
515  self.assertTrue(m.isLeaf())
516  m = SwitchProducerTest(test1=EDProducer("x"))
517  self.assertTrue(m._isTaskComponent())
518  self.assertTrue(m.isLeaf())
519  m = EDFilter("x")
520  self.assertTrue(m._isTaskComponent())
521  self.assertTrue(m.isLeaf())
522  m = OutputModule("x")
523  self.assertFalse(m._isTaskComponent())
524  self.assertTrue(m.isLeaf())
525  m = EDAnalyzer("x")
526  self.assertFalse(m._isTaskComponent())
527  self.assertTrue(m.isLeaf())
528  m = Service("x")
529  self.assertTrue(m._isTaskComponent())
530  self.assertTrue(m.isLeaf())
531  m = ESProducer("x")
532  self.assertTrue(m._isTaskComponent())
533  self.assertTrue(m.isLeaf())
534  m = ESSource("x")
535  self.assertTrue(m._isTaskComponent())
536  self.assertTrue(m.isLeaf())
537  m = Sequence()
538  self.assertFalse(m._isTaskComponent())
539  self.assertFalse(m.isLeaf())
540  m = Path()
541  self.assertFalse(m._isTaskComponent())
542  m = EndPath()
543  self.assertFalse(m._isTaskComponent())
544  m = Task()
545  self.assertTrue(m._isTaskComponent())
546  self.assertFalse(m.isLeaf())
547 
549  # Constructor
550  sp = SwitchProducerTest(test1 = EDProducer("Foo"), test2 = EDProducer("Bar"))
551  self.assertEqual(sp.test1.type_(), "Foo")
552  self.assertEqual(sp.test2.type_(), "Bar")
553  self.assertRaises(ValueError, lambda: SwitchProducerTest(nonexistent = EDProducer("Foo")))
554  self.assertRaises(TypeError, lambda: SwitchProducerTest(test1 = EDAnalyzer("Foo")))
555  self.assertRaises(TypeError, lambda: SwitchProducerTest(test1 = EDFilter("Foo")))
556  self.assertRaises(TypeError, lambda: SwitchProducerTest(test1 = Source("Foo")))
557  self.assertRaises(TypeError, lambda: SwitchProducerTest(test1 = OutputModule("Foo")))
558  self.assertRaises(TypeError, lambda: SwitchProducerTest(test1 = Looper("Foo")))
559  self.assertRaises(TypeError, lambda: SwitchProducerTest(test1 = Service("Foo")))
560  self.assertRaises(TypeError, lambda: SwitchProducerTest(test1 = ESSource("Foo")))
561  self.assertRaises(TypeError, lambda: SwitchProducerTest(test1 = ESProducer("Foo")))
562  self.assertRaises(TypeError, lambda: SwitchProducerTest(test1 = ESPrefer("Foo")))
563  self.assertRaises(TypeError, lambda: SwitchProducerTest(test1 = SwitchProducerTest(test1 = EDProducer("Foo"))))
564 
565  # Case decision
566  sp = SwitchProducerTest(test1 = EDProducer("Foo"), test2 = EDProducer("Bar"))
567  self.assertEqual(sp._getProducer().type_(), "Bar")
568  sp = SwitchProducerTest1Dis(test1 = EDProducer("Foo"), test2 = EDProducer("Bar"))
569  self.assertEqual(sp._getProducer().type_(), "Bar")
570  sp = SwitchProducerTest2Dis(test1 = EDProducer("Foo"), test2 = EDProducer("Bar"))
571  self.assertEqual(sp._getProducer().type_(), "Foo")
572  sp = SwitchProducerTest(test1 = EDProducer("Bar"))
573  self.assertEqual(sp._getProducer().type_(), "Bar")
574  sp = SwitchProducerTest1Dis(test1 = EDProducer("Bar"))
575  self.assertRaises(RuntimeError, sp._getProducer)
576 
577  # Mofications
578  from .Types import int32, string, PSet
579  sp = SwitchProducerTest(test1 = EDProducer("Foo",
580  a = int32(1),
581  b = PSet(c = int32(2))),
582  test2 = EDProducer("Bar",
583  aa = int32(11),
584  bb = PSet(cc = int32(12))))
585  # Simple clone
586  cl = sp.clone()
587  self.assertEqual(cl.test1.type_(), "Foo")
588  self.assertEqual(cl.test1.a.value(), 1)
589  self.assertEqual(cl.test1.b.c.value(), 2)
590  self.assertEqual(cl.test2.type_(), "Bar")
591  self.assertEqual(cl.test2.aa.value(), 11)
592  self.assertEqual(cl.test2.bb.cc.value(), 12)
593  self.assertEqual(sp._getProducer().type_(), "Bar")
594  # Modify clone
595  cl.test1.a = 3
596  self.assertEqual(cl.test1.a.value(), 3)
597  cl.test1 = EDProducer("Fred")
598  self.assertEqual(cl.test1.type_(), "Fred")
599  def _assignEDAnalyzer():
600  cl.test1 = EDAnalyzer("Foo")
601  self.assertRaises(TypeError, _assignEDAnalyzer)
602  def _assignSwitchProducer():
603  cl.test1 = SwitchProducerTest(test1 = SwitchProducerTest(test1 = EDProducer("Foo")))
604  self.assertRaises(TypeError, _assignSwitchProducer)
605  # Modify values with a dict
606  cl = sp.clone(test1 = dict(a = 4, b = dict(c = None)),
607  test2 = dict(aa = 15, bb = dict(cc = 45, dd = string("foo"))))
608  self.assertEqual(cl.test1.a.value(), 4)
609  self.assertEqual(cl.test1.b.hasParameter("c"), False)
610  self.assertEqual(cl.test2.aa.value(), 15)
611  self.assertEqual(cl.test2.bb.cc.value(), 45)
612  self.assertEqual(cl.test2.bb.dd.value(), "foo")
613  # Replace/add/remove EDProducers
614  cl = sp.clone(test1 = EDProducer("Fred", x = int32(42)),
615  test3 = EDProducer("Wilma", y = int32(24)),
616  test2 = None)
617  self.assertEqual(cl.test1.type_(), "Fred")
618  self.assertEqual(cl.test1.x.value(), 42)
619  self.assertEqual(cl.test3.type_(), "Wilma")
620  self.assertEqual(cl.test3.y.value(), 24)
621  self.assertEqual(hasattr(cl, "test2"), False)
622  self.assertRaises(TypeError, lambda: sp.clone(test1 = EDAnalyzer("Foo")))
623  self.assertRaises(TypeError, lambda: sp.clone(test1 = SwitchProducerTest(test1 = SwitchProducerTest(test1 = EDProducer("Foo")))))
624 
625  # Dump
626  sp = SwitchProducerTest(test2 = EDProducer("Foo",
627  a = int32(1),
628  b = PSet(c = int32(2))),
629  test1 = EDProducer("Bar",
630  aa = int32(11),
631  bb = PSet(cc = int32(12))))
632  self.assertEqual(sp.dumpPython(),
633 """SwitchProducerTest(
634  test1 = cms.EDProducer("Bar",
635  aa = cms.int32(11),
636  bb = cms.PSet(
637  cc = cms.int32(12)
638  )
639  ),
640  test2 = cms.EDProducer("Foo",
641  a = cms.int32(1),
642  b = cms.PSet(
643  c = cms.int32(2)
644  )
645  )
646 )
647 """)
648  # Pickle
649  import pickle
650  sp = SwitchProducerPickleable(cpu = EDProducer("Foo"))
651  pkl = pickle.dumps(sp)
652  unpkl = pickle.loads(pkl)
653  self.assertEqual(unpkl.cpu.type_(), "Foo")
654 
656  # Constructor
657  sp = SwitchProducerTest(test1 = EDProducer("Foo"), test2 = EDAlias())
658  self.assertEqual(sp.test1.type_(), "Foo")
659  self.assertTrue(isinstance(sp.test2, EDAlias))
660 
661  # Modifications
662  from .Types import int32, string, PSet, VPSet
663  sp = SwitchProducerTest(test1 = EDProducer("Foo"),
664  test2 = EDAlias(foo = VPSet(PSet(type = string("Foo2")))))
665 
666  # Simple clone
667  cl = sp.clone()
668  self.assertTrue(hasattr(cl.test2, "foo"))
669  # Modify clone
670  cl.test2.foo[0].type = "Foo3"
671  self.assertEqual(cl.test2.foo[0].type, "Foo3")
672  # Modify values with a dict
673  cl = sp.clone(test2 = dict(foo = {0: dict(type = "Foo4")}))
674  self.assertEqual(cl.test2.foo[0].type, "Foo4")
675  # Replace or add EDAlias
676  cl = sp.clone(test1 = EDAlias(foo = VPSet(PSet(type = string("Foo5")))),
677  test3 = EDAlias(foo = VPSet(PSet(type = string("Foo6")))))
678  self.assertEqual(cl.test1.foo[0].type, "Foo5")
679  self.assertEqual(cl.test3.foo[0].type, "Foo6")
680  # Modify clone
681  cl.test1 = EDProducer("Xyzzy")
682  self.assertEqual(cl.test1.type_(), "Xyzzy")
683  cl.test1 = EDAlias(foo = VPSet(PSet(type = string("Foo7"))))
684  self.assertEqual(cl.test1.foo[0].type, "Foo7")
685 
686 
687  # Dump
688  from .Types import int32, string, PSet, VPSet
689  sp = SwitchProducerTest(test1 = EDProducer("Foo"),
690  test2 = EDAlias(foo = VPSet(PSet(type = string("Foo2")))))
691 
692  self.assertEqual(sp.dumpPython(),
693 """SwitchProducerTest(
694  test1 = cms.EDProducer("Foo"),
695  test2 = cms.EDAlias(
696  foo = cms.VPSet(cms.PSet(
697  type = cms.string('Foo2')
698  ))
699 )
700 )
701 """)
702 
703  # Pickle
704  import pickle
705  sp = SwitchProducerPickleable(cpu = EDAlias(foo = VPSet(PSet(type = string("Foo2")))))
706  pkl = pickle.dumps(sp)
707  unpkl = pickle.loads(pkl)
708  self.assertEqual(sp.cpu.foo[0].type, "Foo2")
709  unittest.main()
def _placeImpl(self, name, proc)
Definition: Modules.py:208
def moduleLabel_(self, myname)
Definition: Mixins.py:473
def __typeIsValid(typ)
Definition: Modules.py:278
def nameInProcessDesc_(self, myname)
Definition: Modules.py:212
def moduleLabel_(self, myname)
Definition: Modules.py:61
def _isTaskComponent(self)
Definition: Modules.py:49
def _placeImpl(self, name, proc)
Definition: Modules.py:197
def testSwitchProducer(self)
Definition: Modules.py:548
def _isTaskComponent(self)
Definition: Modules.py:26
def testEDAnalyzer(self)
Definition: Modules.py:447
def isLeaf(self)
Definition: Modules.py:51
def _placeImpl(self, name, proc)
Definition: Modules.py:100
def __setParameters(self, parameters)
Definition: Mixins.py:242
def appendToProcessDescLists_(self, modules, aliases, myname)
Definition: Modules.py:368
def _errorstr(self)
Definition: Modules.py:147
def __addParameter(self, name, value)
Definition: Modules.py:281
def nameInProcessDesc_(self, myname)
Definition: Modules.py:102
def _isTaskComponent(self)
Definition: Modules.py:169
def nameInProcessDesc_(self, myname)
Definition: Modules.py:201
def __setParameters(self, parameters)
Definition: Modules.py:295
def setPrerequisites(self, libs)
Definition: Modules.py:152
def __init__(self, type_, arg, kargs)
Definition: Modules.py:188
def __init__(self, kargs)
Definition: Modules.py:435
def dumpPython(self, options=PrintOptions())
Definition: Modules.py:347
def testIsTaskComponent(self)
Definition: Modules.py:512
def moduleLabel_(self, myname)
Definition: Modules.py:109
def __init__(self, type_, targetLabel='', arg, kargs)
Definition: Modules.py:91
def __init__(self, kargs)
Definition: Modules.py:420
def nameInProcessDesc_(self, myname)
Definition: Mixins.py:471
def _placeImpl(self, name, proc)
Definition: Modules.py:390
def format_typename(object)
def __init__(self, type_, arg, kargs)
Definition: Modules.py:181
def _clonesequence(self, lookuptable)
Definition: Modules.py:142
def insertInto(self, processDesc)
Definition: Modules.py:19
def dumpPython(self, options=PrintOptions())
Definition: Mixins.py:283
def __init__(self, type_, arg, kargs)
Definition: Modules.py:195
def __init__(self, type_, arg, kargs)
Definition: Modules.py:137
def _placeImpl(self, name, proc)
Definition: Modules.py:175
def _errorstr(self)
Definition: Modules.py:410
def setIsFrozen(self)
Definition: Mixins.py:271
def __init__(self, type_, arg, kargs)
Definition: Modules.py:34
def moduleLabel_(self, myname)
Definition: Modules.py:199
def targetLabel_(self)
Definition: Modules.py:111
def _placeImpl(self, name, proc)
Definition: Modules.py:57
def __init__(self, kargs)
Definition: Modules.py:442
def _isTaskComponent(self)
Definition: Modules.py:69
def nameInProcessDesc_(self, myname)
Definition: Modules.py:362
def _placeImpl(self, name, proc)
Definition: Modules.py:183
def isLeaf(self)
Definition: Modules.py:28
def nameInProcessDesc_(self, myname)
Definition: Modules.py:46
def _getProducer(self)
Definition: Modules.py:273
def __addParameter(self, name, value)
Definition: Mixins.py:230
def saveOrigin(obj, level)
Definition: Mixins.py:659
def insertInto(self, parameterSet, myname)
Definition: Modules.py:378
def moduleLabel_(self, myname)
Definition: Modules.py:210
def __init__(self, type_, arg, kargs)
Definition: Modules.py:55
def _placeImpl(self, name, proc)
Definition: Modules.py:16
def clone(self, params)
Definition: Modules.py:324
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def _isTaskComponent(self)
Definition: Modules.py:177
def __str__(self)
Definition: Modules.py:30
def _placeImpl(self, name, proc)
Definition: Modules.py:37
def testSequences(self)
Definition: Modules.py:504
def _placeImpl(self, name, proc)
Definition: Modules.py:167
def parameterNames_(self)
Definition: Mixins.py:175
def dumpPythonAs(self, label, options=PrintOptions())
Definition: Modules.py:113
def insertInto(self, parameterSet, myname)
Definition: Modules.py:155
def __init__(self, type_, arg, kargs)
Definition: Modules.py:173
def testService(self)
Definition: Modules.py:497
def __init__(self, caseFunctionDict, kargs)
Definition: Modules.py:250
def caseLabel_(self, name, case)
Definition: Modules.py:366
def __setattr__(self, name, value)
Definition: Modules.py:299
def _placeImpl(self, name, proc)
Definition: Modules.py:190
def moduleLabel_(self, myname)
Definition: Modules.py:364
def isFrozen(self)
Definition: Mixins.py:269
def moduleLabel_(self, myname)
Definition: Modules.py:41
def __init__(self, type_, arg, kargs)
Definition: Modules.py:13
def testESPrefer(self)
Definition: Modules.py:461
def _chooseCase(self)
Definition: Modules.py:261
def _clonesequence(self, lookuptable)
Definition: Modules.py:405
def copy(self)
Definition: Modules.py:105
def nameInProcessDesc_(self, myname)
Definition: Modules.py:66
def testSwithProducerWithAlias(self)
Definition: Modules.py:655
def isLeaf(self)
Definition: Modules.py:71
#define str(s)
def dumpSequencePython(self, options=PrintOptions())
Definition: Modules.py:24
def __init__(self, type_, arg, kargs)
Definition: Modules.py:206
def insertContentsInto(self, parameterSet)
Definition: Mixins.py:353
def __init__(self, type_, arg, kargs)
Definition: Modules.py:165
def __init__(self, kargs)
Definition: Modules.py:428
def _switch_cpu()
Definition: Modules.py:218