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