CMS 3D CMS Logo

List of all members | Public Member Functions | Static Public Member Functions | Private Member Functions | Static Private Member Functions | Private Attributes
Modules.SwitchProducer Class Reference
Inheritance diagram for Modules.SwitchProducer:
Modules.EDProducer Modules._Module Mixins._ConfigureComponent Mixins._TypedParameterizable Mixins._Labelable SequenceTypes._SequenceLeaf Mixins._Parameterizable SequenceTypes._Sequenceable Config.SwitchProducerTest Modules.SwitchProducerPickleable Modules.SwitchProducerTest Modules.SwitchProducerTest1Dis Modules.SwitchProducerTest2Dis

Public Member Functions

def __init__ (self, caseFunctionDict, **kargs)
 
def __setattr__ (self, name, value)
 
def appendToProcessDescLists_ (self, modules, aliases, myname)
 
def caseLabel_ (self, name, case)
 
def clone (self, **params)
 
def directDependencies (self)
 
def dumpPython (self, options=PrintOptions())
 
def insertInto (self, parameterSet, myname)
 
def moduleLabel_ (self, myname)
 
def nameInProcessDesc_ (self, myname)
 
- Public Member Functions inherited from Modules.EDProducer
def __init__ (self, type_, *arg, **kargs)
 
- Public Member Functions inherited from Modules._Module
def setPrerequisites (self, *libs)
 
- Public Member Functions inherited from Mixins._TypedParameterizable
def appendToProcessDescList_ (self, lst, myname)
 
def clone (self, *args, **params)
 
def copy (self)
 
def dumpConfig (self, options=PrintOptions())
 
def dumpPythonAttributes (self, myname, options)
 
def type_ (self)
 
- Public Member Functions inherited from Mixins._Parameterizable
def __delattr__ (self, name)
 
def __init__ (self, *arg, **kargs)
 
def __repr__ (self)
 
def getParameter (self, params)
 
def hasParameter (self, params)
 
def insertContentsInto (self, parameterSet)
 
def isFrozen (self)
 
def isModified (self)
 
def parameterNames_ (self)
 
def parameters_ (self)
 
def setIsFrozen (self)
 
- Public Member Functions inherited from Mixins._Labelable
def __str__ (self)
 
def dumpSequenceConfig (self)
 
def dumpSequencePython (self, options=PrintOptions())
 
def hasLabel_ (self)
 
def label (self)
 
def label_ (self)
 
def setLabel (self, label)
 
- Public Member Functions inherited from SequenceTypes._SequenceLeaf
def __init__ (self)
 
def isLeaf (self)
 
- Public Member Functions inherited from SequenceTypes._Sequenceable
def __add__ (self, rhs)
 
def __invert__ (self)
 
def __mul__ (self, rhs)
 
def isOperation (self)
 
def resolve (self, processDict, keepIfCannotResolve=False)
 
def visitNode (self, visitor)
 

Static Public Member Functions

def getCpu ()
 

Private Member Functions

def __addParameter (self, name, value)
 
def __setParameters (self, parameters)
 
def _chooseCase (self)
 
def _clonesequence (self, lookuptable)
 
def _errorstr (self)
 
def _getProducer (self)
 
def _placeImpl (self, name, proc)
 

Static Private Member Functions

def __typeIsValid (typ)
 

Private Attributes

 _caseFunctionDict
 
 _isModified
 

Detailed Description

This purpose class is to provide a switch of EDProducers for a single module/product label.

The decision is done at the time when the python configuration is
translated to C++. This class is generic, and intended to be
inherited for concrete switches. Example:

class SwitchProducerFoo(SwitchProducer):
    def __init__(self, **kargs):
        super(SwitchProducerFoo,self).__init__(
            dict(case1 = case1Func, case2 = case2Func),
            **kargs
        )

foo = SwitchProducerFoo(
    case1 = EDProducer("Producer1"),
    case2 = EDProducer("Producer2")
)

Here case1Func and case2Func are functions that return a (bool,
int) tuple, where the bool tells whether that case is enabled or
not, and the int tells the priority of that case. The case with
the highest priority among those that are enabled will get chosen.

The end result is that the product(s) labeled as "foo" will be
produced with one of the producers. It would be good if their
output product types and instance names would be the same (or very
close).

Definition at line 220 of file Modules.py.

Constructor & Destructor Documentation

◆ __init__()

def Modules.SwitchProducer.__init__ (   self,
  caseFunctionDict,
**  kargs 
)

Definition at line 249 of file Modules.py.

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 

Member Function Documentation

◆ __addParameter()

def Modules.SwitchProducer.__addParameter (   self,
  name,
  value 
)
private

Reimplemented from Mixins._Parameterizable.

Definition at line 280 of file Modules.py.

280  def __addParameter(self, name, value):
281  if not self.__typeIsValid(value):
282  raise TypeError(name+" does not already exist, so it can only be set to a cms.EDProducer or cms.EDAlias")
283  if name not in self._caseFunctionDict:
284  raise ValueError("Case '%s' is not allowed (allowed ones are %s)" % (name, ",".join(self._caseFunctionDict.keys())))
285  if name in self.__dict__:
286  message = "Duplicate insert of member " + name
287  message += "\nThe original parameters are:\n"
288  message += self.dumpPython() + '\n'
289  raise ValueError(message)
290  self.__dict__[name]=value
291  self._Parameterizable__parameterNames.append(name)
292  self._isModified = True
293 

References Modules.SwitchProducer.__typeIsValid(), Modules.SwitchProducer._caseFunctionDict, Mixins._ParameterTypeBase._isModified, Mixins._SimpleParameterTypeBase._isModified, Mixins._Parameterizable._isModified, mps_setup.append, Mixins._ParameterTypeBase.dumpPython(), Mixins.UsingBlock.dumpPython(), Mixins._Parameterizable.dumpPython(), Config.Process.dumpPython(), Config.SubProcess.dumpPython(), join(), and relativeConstraints.keys.

◆ __setattr__()

def Modules.SwitchProducer.__setattr__ (   self,
  name,
  value 
)

Reimplemented from Mixins._Parameterizable.

Definition at line 298 of file Modules.py.

298  def __setattr__(self, name, value):
299  # Following snippet copied and customized from
300  # _Parameterizable in order to support Modifier.toModify
301  #
302  #since labels are not supposed to have underscores at the beginning
303  # I will assume that if we have such then we are setting an internal variable
304  if self.isFrozen() and not (name in ["_Labelable__label","_isFrozen"] or name.startswith('_')):
305  message = "Object already added to a process. It is read only now\n"
306  message += " %s = %s" %(name, value)
307  message += "\nThe original parameters are:\n"
308  message += self.dumpPython() + '\n'
309  raise ValueError(message)
310  # underscored names bypass checking for _ParameterTypeBase
311  if name[0]=='_':
312  super(SwitchProducer, self).__setattr__(name,value)
313  elif not name in self.__dict__:
314  self.__addParameter(name, value)
315  self._isModified = True
316  else:
317  if not self.__typeIsValid(value):
318  raise TypeError(name+" can only be set to a cms.EDProducer or cms.EDAlias")
319  # We should always receive an cms.EDProducer
320  self.__dict__[name] = value
321  self._isModified = True
322 

References Mixins._Parameterizable.__addParameter(), Modules.SwitchProducer.__typeIsValid(), Mixins._ParameterTypeBase._isModified, Mixins._SimpleParameterTypeBase._isModified, Mixins._Parameterizable._isModified, Mixins._ParameterTypeBase.dumpPython(), Mixins.UsingBlock.dumpPython(), Mixins._Parameterizable.dumpPython(), Config.Process.dumpPython(), Config.SubProcess.dumpPython(), Mixins._ParameterTypeBase.isFrozen(), and Mixins._Parameterizable.isFrozen().

Referenced by GenObject.GenObject.setValue().

◆ __setParameters()

def Modules.SwitchProducer.__setParameters (   self,
  parameters 
)
private

Reimplemented from Mixins._Parameterizable.

Definition at line 294 of file Modules.py.

294  def __setParameters(self, parameters):
295  for name, value in parameters.items():
296  self.__addParameter(name, value)
297 

References Mixins._Parameterizable.__addParameter().

◆ __typeIsValid()

def Modules.SwitchProducer.__typeIsValid (   typ)
staticprivate

Definition at line 277 of file Modules.py.

277  def __typeIsValid(typ):
278  return (isinstance(typ, EDProducer) and not isinstance(typ, SwitchProducer)) or isinstance(typ, EDAlias)
279 

Referenced by Modules.SwitchProducer.__addParameter(), and Modules.SwitchProducer.__setattr__().

◆ _chooseCase()

def Modules.SwitchProducer._chooseCase (   self)
private
Returns the name of the chosen case.

Definition at line 260 of file Modules.py.

260  def _chooseCase(self):
261  """Returns the name of the chosen case."""
262  cases = self.parameterNames_()
263  bestCase = None
264  for case in cases:
265  (enabled, priority) = self._caseFunctionDict[case]()
266  if enabled and (bestCase is None or bestCase[0] < priority):
267  bestCase = (priority, case)
268  if bestCase is None:
269  raise RuntimeError("All cases '%s' were disabled" % (str(cases)))
270  return bestCase[1]
271 

References Modules.SwitchProducer._caseFunctionDict, Mixins._Parameterizable.parameterNames_(), and str.

Referenced by Modules.SwitchProducer._getProducer(), and Modules.SwitchProducer.insertInto().

◆ _clonesequence()

def Modules.SwitchProducer._clonesequence (   self,
  lookuptable 
)
private

Reimplemented from Modules._Module.

Definition at line 408 of file Modules.py.

408  def _clonesequence(self, lookuptable):
409  try:
410  return lookuptable[id(self)]
411  except:
412  raise ModuleCloneError(self._errorstr())

References Modules._Module._errorstr(), and triggerObjects_cff.id.

◆ _errorstr()

def Modules.SwitchProducer._errorstr (   self)
private

Reimplemented from Modules._Module.

Definition at line 413 of file Modules.py.

413  def _errorstr(self):
414  return "SwitchProducer"
415 
416 

◆ _getProducer()

def Modules.SwitchProducer._getProducer (   self)
private
Returns the EDroducer of the chosen case

Definition at line 272 of file Modules.py.

272  def _getProducer(self):
273  """Returns the EDroducer of the chosen case"""
274  return self.__dict__[self._chooseCase()]
275 

References Modules.SwitchProducer._chooseCase().

◆ _placeImpl()

def Modules.SwitchProducer._placeImpl (   self,
  name,
  proc 
)
private

Reimplemented from Modules.EDProducer.

Definition at line 393 of file Modules.py.

393  def _placeImpl(self,name,proc):
394  proc._placeSwitchProducer(name,self)
395 # for case in self.parameterNames_():
396 # caseLabel = self.caseLabel_(name, case)
397 # caseObj = self.__dict__[case]
398 #
399 # if isinstance(caseObj, EDAlias):
400 # # EDAliases end up in @all_aliases automatically
401 # proc._placeAlias(caseLabel, caseObj)
402 # else:
403 # # Note that these don't end up in @all_modules
404 # # automatically because they're not part of any
405 # # Task/Sequence/Path
406 # proc._placeProducer(caseLabel, caseObj)
407 

Referenced by SequenceTypes._ModuleSequenceType._place(), and Mixins._TypedParameterizable._place().

◆ appendToProcessDescLists_()

def Modules.SwitchProducer.appendToProcessDescLists_ (   self,
  modules,
  aliases,
  myname 
)

Definition at line 371 of file Modules.py.

371  def appendToProcessDescLists_(self, modules, aliases, myname):
372  # This way we can insert the chosen EDProducer to @all_modules
373  # so that we get easily a worker for it
374  modules.append(myname)
375  for case in self.parameterNames_():
376  if isinstance(self.__dict__[case], EDAlias):
377  aliases.append(self.caseLabel_(myname, case))
378  else:
379  modules.append(self.caseLabel_(myname, case))
380 

References Modules.SwitchProducer.caseLabel_(), and Mixins._Parameterizable.parameterNames_().

◆ caseLabel_()

def Modules.SwitchProducer.caseLabel_ (   self,
  name,
  case 
)

Definition at line 369 of file Modules.py.

369  def caseLabel_(self, name, case):
370  return name+"@"+case

Referenced by Modules.SwitchProducer.appendToProcessDescLists_(), and Modules.SwitchProducer.insertInto().

◆ clone()

def Modules.SwitchProducer.clone (   self,
**  params 
)

Definition at line 323 of file Modules.py.

323  def clone(self, **params):
324  returnValue = SwitchProducer.__new__(type(self))
325 
326  # Need special treatment as cms.EDProducer is not a valid parameter type (except in this case)
327  myparams = dict()
328  for name, value in params.items():
329  if value is None:
330  continue
331  elif isinstance(value, dict):
332  myparams[name] = self.__dict__[name].clone(**value)
333  else: # value is an EDProducer
334  myparams[name] = value.clone()
335 
336  # Add the ones that were not customized
337  for name in self.parameterNames_():
338  if name not in params:
339  myparams[name] = self.__dict__[name].clone()
340  returnValue.__init__(**myparams)
341  returnValue._isModified = False
342  returnValue._isFrozen = False
343  saveOrigin(returnValue, 1)
344  return returnValue
345 

References Mixins._Parameterizable.parameterNames_(), and Mixins.saveOrigin().

◆ directDependencies()

def Modules.SwitchProducer.directDependencies (   self)

Reimplemented from Mixins._TypedParameterizable.

Definition at line 361 of file Modules.py.

361  def directDependencies(self):
362  # XXX FIXME handle SwitchProducer dependencies
363  return []
364 

◆ dumpPython()

def Modules.SwitchProducer.dumpPython (   self,
  options = PrintOptions() 
)

Reimplemented from Mixins._TypedParameterizable.

Definition at line 346 of file Modules.py.

346  def dumpPython(self, options=PrintOptions()):
347  # Note that if anyone uses the generic SwitchProducer instead
348  # of a derived-one, the information on the functions for the
349  # producer decision is lost
350  specialImportRegistry.registerUse(self)
351  result = "%s(" % self.__class__.__name__ # not including cms. since the deriving classes are not in cms "namespace"
352  options.indent()
353  for resource in sorted(self.parameterNames_()):
354  result += "\n" + options.indentation() + resource + " = " + getattr(self, resource).dumpPython(options).rstrip() + ","
355  if result[-1] == ",":
356  result = result.rstrip(",")
357  options.unindent()
358  result += "\n)\n"
359  return result
360 

References __class__< T >.__class__(), and Mixins._Parameterizable.parameterNames_().

Referenced by Types._AllowedParameterTypes.__init__().

◆ getCpu()

def Modules.SwitchProducer.getCpu ( )
static
Returns a function that returns the priority for a CPU "computing device". Intended to be used by deriving classes.

Definition at line 256 of file Modules.py.

256  def getCpu():
257  """Returns a function that returns the priority for a CPU "computing device". Intended to be used by deriving classes."""
258  return _switch_cpu
259 

◆ insertInto()

def Modules.SwitchProducer.insertInto (   self,
  parameterSet,
  myname 
)

Reimplemented from Modules._Module.

Definition at line 381 of file Modules.py.

381  def insertInto(self, parameterSet, myname):
382  for case in self.parameterNames_():
383  producer = self.__dict__[case]
384  producer.insertInto(parameterSet, self.caseLabel_(myname, case))
385  newpset = parameterSet.newPSet()
386  newpset.addString(True, "@module_label", self.moduleLabel_(myname))
387  newpset.addString(True, "@module_type", "SwitchProducer")
388  newpset.addString(True, "@module_edm_type", "EDProducer")
389  newpset.addVString(True, "@all_cases", [myname+"@"+p for p in self.parameterNames_()])
390  newpset.addString(False, "@chosen_case", myname+"@"+self._chooseCase())
391  parameterSet.addPSet(True, self.nameInProcessDesc_(myname), newpset)
392 

References Modules.SwitchProducer._chooseCase(), Modules.SwitchProducer.caseLabel_(), edm::ModuleProcessName.moduleLabel_, FWJobMetadataManager::Data.moduleLabel_, PFMatchedCandidateRefExtractor.moduleLabel_, edm::ModuleLabelMatch.moduleLabel_, GBRForestWriter.moduleLabel_, HPSPFTauProducer.moduleLabel_, edm::BranchKey.moduleLabel_, MuonMETcorrInputProducer.moduleLabel_, SysShiftMETcorrInputProducer.moduleLabel_, ShiftedJetProducerByMatchedObjectT< T >.moduleLabel_, Type0PFMETcorrInputProducer.moduleLabel_, NoPileUpPFMEtProducer.moduleLabel_, PFCandMETcorrInputProducer.moduleLabel_, ShiftedPFCandidateProducerForPFMVAMEt.moduleLabel_, PFchsMETcorrInputProducer.moduleLabel_, ShiftedParticleProducer.moduleLabel_, MultShiftMETcorrInputProducer.moduleLabel_, edm::ESTagGetter::Info.moduleLabel_, ShiftedPFCandidateProducerForPFNoPUMEt.moduleLabel_, MultShiftMETcorrDBInputProducer.moduleLabel_, NoPileUpPFMEtDataProducer.moduleLabel_, TauDiscriminantCutMultiplexerT< TauType, TauTypeRef, ParentClass >.moduleLabel_, RecoTauGenericJetRegionProducer< JetType, CandType >.moduleLabel_, BoostedTauSeedsProducer.moduleLabel_, edm::ESConsumesInfoEntry.moduleLabel_, TauDiscriminationAgainstElectronDeadECAL< TauType, TauDiscriminator >.moduleLabel_, SubjetFilterAlgorithm.moduleLabel_, pat::TauJetCorrFactorsProducer.moduleLabel_, TauDiscriminationAgainstElectronMVA6< TauType, TauDiscriminator, ElectronType >.moduleLabel_, JetIdSelector< T >.moduleLabel_, edm::ModuleDescription.moduleLabel_, PFRecoTauChargedHadronProducer.moduleLabel_, edm::ProductSelectorRules::Rule.moduleLabel_, ObjectViewMatcher< T1, T2 >.moduleLabel_, MinMETProducerT< T >.moduleLabel_, PFRecoTauDiscriminationAgainstMuon2.moduleLabel_, TauTagValidation.moduleLabel_, ObjectViewCleaner< T >.moduleLabel_, PFRecoTauDiscriminationAgainstMuon2Container.moduleLabel_, PFRecoTauDiscriminationAgainstMuonSimple.moduleLabel_, ShiftedParticleProducerT< T >.moduleLabel_, PFRecoTauDiscriminationAgainstMuonMVA.moduleLabel_, CorrectedMETProducerT< T >.moduleLabel_, TauDiscriminationProducerBase< TauType, TauDiscriminator, TauDiscriminatorDataType, ConsumeType >.moduleLabel_, HLTMuonMatchAndPlot.moduleLabel_, PFRecoTauDiscriminationByIsolationMVA2.moduleLabel_, edm::test::TestProcessorConfig::ProduceEntry.moduleLabel_, reco::tau::PFRecoTauDiscriminationByMVAIsolationRun2.moduleLabel_, VirtualJetProducer.moduleLabel_, reco::tau::PATTauDiscriminationByMVAIsolationRun2.moduleLabel_, ShiftedJetProducerT< T, Textractor >.moduleLabel_, CaloJetMETcorrInputProducerT< T, Textractor >.moduleLabel_, PFRecoTauDiscriminationByIsolation.moduleLabel_, JetCleanerForType1METT< T, Textractor >.moduleLabel_, edm::PoolOutputModule.moduleLabel_, edm::BranchDescription.moduleLabel_, PFRecoTauDiscriminationByIsolationContainer.moduleLabel_, PFJetMETcorrInputProducerT< T, Textractor >.moduleLabel_, edm::ProductResolverIndexHelper::Item.moduleLabel_, Mixins._TypedParameterizable.moduleLabel_(), Mixins._TypedParameterizable.nameInProcessDesc_(), Config.SubProcess.nameInProcessDesc_(), and Mixins._Parameterizable.parameterNames_().

◆ moduleLabel_()

def Modules.SwitchProducer.moduleLabel_ (   self,
  myname 
)

Reimplemented from Mixins._TypedParameterizable.

Definition at line 367 of file Modules.py.

367  def moduleLabel_(self, myname):
368  return myname

Referenced by ExternalGeneratorFilter.ExternalGeneratorFilter.insertInto().

◆ nameInProcessDesc_()

def Modules.SwitchProducer.nameInProcessDesc_ (   self,
  myname 
)

Reimplemented from Mixins._TypedParameterizable.

Definition at line 365 of file Modules.py.

365  def nameInProcessDesc_(self, myname):
366  return myname

Referenced by Types.EDAlias.appendToProcessDescList_(), ExternalGeneratorFilter.ExternalGeneratorFilter.insertInto(), and Types.EDAlias.insertInto().

Member Data Documentation

◆ _caseFunctionDict

Modules.SwitchProducer._caseFunctionDict
private

◆ _isModified

Modules.SwitchProducer._isModified
private

Definition at line 253 of file Modules.py.

join
static std::string join(char **cmd)
Definition: RemoteFile.cc:17
relativeConstraints.keys
keys
Definition: relativeConstraints.py:89
clone
TEveGeoShape * clone(const TEveElement *element, TEveElement *parent)
Definition: eve_macros.cc:135
str
#define str(s)
Definition: TestProcessor.cc:53
mps_setup.append
append
Definition: mps_setup.py:85
Mixins.saveOrigin
def saveOrigin(obj, level)
Definition: Mixins.py:702
triggerObjects_cff.id
id
Definition: triggerObjects_cff.py:29
ConfigBuilder.dumpPython
def dumpPython(process, name)
Definition: ConfigBuilder.py:94