CMS 3D CMS Logo

Mixins.py
Go to the documentation of this file.
1 from __future__ import print_function
2 from builtins import range
3 import inspect
4 import six
5 
7  """Denotes a class that can be used by the Processes class"""
8  def _isTaskComponent(self):
9  return False
10 
12  def __init__(self):
13  self.indent_= 0
14  self.deltaIndent_ = 4
15  self.isCfg = True
16  def indentation(self):
17  return ' '*self.indent_
18  def indent(self):
19  self.indent_ += self.deltaIndent_
20  def unindent(self):
21  self.indent_ -= self.deltaIndent_
22 
24  """This class collects special import statements of configuration types"""
25  def __init__(self):
26  self._registry = {}
27 
28  def _reset(self):
29  for lst in six.itervalues(self._registry):
30  lst[1] = False
31 
32  def registerSpecialImportForType(self, cls, impStatement):
33  className = cls.__name__
34  if className in self._registry:
35  raise RuntimeError("Error: the configuration type '%s' already has an import statement registered '%s'" % (className, self._registry[className][0]))
36  self._registry[className] = [impStatement, False]
37 
38  def registerUse(self, obj):
39  className = obj.__class__.__name__
40  try:
41  self._registry[className][1] = True
42  except KeyError:
43  pass
44 
45  def getSpecialImports(self):
46  coll = set()
47  for (imp, used) in six.itervalues(self._registry):
48  if used:
49  coll.add(imp)
50  return sorted(coll)
51 
52 specialImportRegistry = _SpecialImportRegistry()
53 
55  """base class for classes which are used as the 'parameters' for a ParameterSet"""
56  def __init__(self):
57  self.__dict__["_isFrozen"] = False
58  self.__isTracked = True
59  self._isModified = False
60  def isModified(self):
61  return self._isModified
62  def resetModified(self):
63  self._isModified=False
64  def configTypeName(self):
65  if self.isTracked():
66  return type(self).__name__
67  return 'untracked '+type(self).__name__
68  def pythonTypeName(self):
69  if self.isTracked():
70  return 'cms.'+type(self).__name__
71  return 'cms.untracked.'+type(self).__name__
72  def dumpPython(self, options=PrintOptions()):
73  specialImportRegistry.registerUse(self)
74  return self.pythonTypeName()+"("+self.pythonValue(options)+")"
75  def __repr__(self):
76  return self.dumpPython()
77  def isTracked(self):
78  return self.__isTracked
79  def setIsTracked(self,trackness):
80  self.__isTracked = trackness
81  def isFrozen(self):
82  return self._isFrozen
83  def setIsFrozen(self):
84  self._isFrozen = True
85 
87  """base class for parameter classes which only hold a single value"""
88  def __init__(self,value):
89  super(_SimpleParameterTypeBase,self).__init__()
90  self._value = value
91  if not self._isValid(value):
92  raise ValueError(str(value)+" is not a valid "+str(type(self)))
93  def value(self):
94  return self._value
95  def setValue(self,value):
96  if not self._isValid(value):
97  raise ValueError(str(value)+" is not a valid "+str(type(self)))
98  if value!=self._value:
99  self._isModified=True
100  self._value=value
101  def configValue(self, options=PrintOptions()):
102  return str(self._value)
103  def pythonValue(self, options=PrintOptions()):
104  return self.configValue(options)
105  def __eq__(self,other):
106  if isinstance(other,_SimpleParameterTypeBase):
107  return self._value == other._value
108  return self._value == other
109  def __ne__(self,other):
110  if isinstance(other,_SimpleParameterTypeBase):
111  return self._value != other._value
112  return self._value != other
113  def __lt__(self,other):
114  if isinstance(other,_SimpleParameterTypeBase):
115  return self._value < other._value
116  return self._value < other
117  def __le__(self,other):
118  if isinstance(other,_SimpleParameterTypeBase):
119  return self._value <= other._value
120  return self._value <= other
121  def __gt__(self,other):
122  if isinstance(other,_SimpleParameterTypeBase):
123  return self._value > other._value
124  return self._value > other
125  def __ge__(self,other):
126  if isinstance(other,_SimpleParameterTypeBase):
127  return self._value >= other._value
128  return self._value >= other
129 
130 
132  """For injection purposes, pretend this is a new parameter type
133  then have a post process step which strips these out
134  """
135  def __init__(self,value, s='', loc=0, file=''):
136  super(UsingBlock,self).__init__(value)
137  self.s = s
138  self.loc = loc
139  self.file = file
140  self.isResolved = False
141  @staticmethod
142  def _isValid(value):
143  return isinstance(value,str)
144  def _valueFromString(value):
145  """only used for cfg-parsing"""
146  return string(value)
147  def insertInto(self, parameterSet, myname):
148  value = self.value()
149  # doesn't seem to handle \0 correctly
150  #if value == '\0':
151  # value = ''
152  parameterSet.addString(self.isTracked(), myname, value)
153  def dumpPython(self, options=PrintOptions()):
154  if options.isCfg:
155  return "process."+self.value()
156  else:
157  return self.value()
158 
159 
161  """Base class for classes which allow addition of _ParameterTypeBase data"""
162  def __init__(self,*arg,**kargs):
163  self.__dict__['_Parameterizable__parameterNames'] = []
164  self.__dict__["_isFrozen"] = False
165  """The named arguments are the 'parameters' which are added as 'python attributes' to the object"""
166  if len(arg) != 0:
167  #raise ValueError("unnamed arguments are not allowed. Please use the syntax 'name = value' when assigning arguments.")
168  for block in arg:
169  if type(block).__name__ != "PSet":
170  raise ValueError("Only PSets can be passed as unnamed argument blocks. This is a "+type(block).__name__)
171  self.__setParameters(block.parameters_())
172  self.__setParameters(kargs)
173  self._isModified = False
174 
175  def parameterNames_(self):
176  """Returns the name of the parameters"""
177  return self.__parameterNames[:]
178  def isModified(self):
179  if self._isModified:
180  return True
181  for name in self.parameterNames_():
182  param = self.__dict__[name]
183  if isinstance(param, _Parameterizable) and param.isModified():
184  self._isModified = True
185  return True
186  return False
187 
188  def hasParameter(self, params):
189  """
190  _hasParameter_
191 
192  check that pset provided has the attribute chain
193  specified.
194 
195  Eg, if params is [ 'attr1', 'attr2', 'attr3' ]
196  check for pset.attr1.attr2.attr3
197 
198  returns True if parameter exists, False if not
199  """
200  return (self.getParameter(params) != None)
201 
202  def getParameter(self, params):
203  """
204  _getParameter_
205 
206  Retrieve the specified parameter from the PSet Provided
207  given the attribute chain
208 
209  returns None if not found
210  """
211  lastParam = self
212  # Don't accidentally iterate over letters in a string
213  if type(params).__name__ == 'str':
214  return getattr(self, params, None)
215  for param in params:
216  lastParam = getattr(lastParam, param, None)
217  print(str(lastParam))
218  if lastParam == None:
219  return None
220  return lastParam
221 
222  def parameters_(self):
223  """Returns a dictionary of copies of the user-set parameters"""
224  import copy
225  result = dict()
226  for name in self.parameterNames_():
227  result[name]=copy.deepcopy(self.__dict__[name])
228  return result
229 
230  def __addParameter(self, name, value):
231  if not isinstance(value,_ParameterTypeBase):
232  self.__raiseBadSetAttr(name)
233  if name in self.__dict__:
234  message = "Duplicate insert of member " + name
235  message += "\nThe original parameters are:\n"
236  message += self.dumpPython() + '\n'
237  raise ValueError(message)
238  self.__dict__[name]=value
239  self.__parameterNames.append(name)
240  self._isModified = True
241 
242  def __setParameters(self,parameters):
243  for name,value in six.iteritems(parameters):
244  self.__addParameter(name, value)
245 
246  def __setattr__(self,name,value):
247  #since labels are not supposed to have underscores at the beginning
248  # I will assume that if we have such then we are setting an internal variable
249  if self.isFrozen() and not (name in ["_Labelable__label","_isFrozen"] or name.startswith('_')):
250  message = "Object already added to a process. It is read only now\n"
251  message += " %s = %s" %(name, value)
252  message += "\nThe original parameters are:\n"
253  message += self.dumpPython() + '\n'
254  raise ValueError(message)
255  # underscored names bypass checking for _ParameterTypeBase
256  if name[0]=='_':
257  super(_Parameterizable,self).__setattr__(name,value)
258  elif not name in self.__dict__:
259  self.__addParameter(name, value)
260  self._isModified = True
261  else:
262  # handle the case where users just replace with a value, a = 12, rather than a = cms.int32(12)
263  if isinstance(value,_ParameterTypeBase):
264  self.__dict__[name] = value
265  else:
266  self.__dict__[name].setValue(value)
267  self._isModified = True
268 
269  def isFrozen(self):
270  return self._isFrozen
271  def setIsFrozen(self):
272  self._isFrozen = True
273  for name in self.parameterNames_():
274  self.__dict__[name].setIsFrozen()
275  def __delattr__(self,name):
276  if self.isFrozen():
277  raise ValueError("Object already added to a process. It is read only now")
278  super(_Parameterizable,self).__delattr__(name)
279  self.__parameterNames.remove(name)
280  @staticmethod
281  def __raiseBadSetAttr(name):
282  raise TypeError(name+" does not already exist, so it can only be set to a CMS python configuration type")
283  def dumpPython(self, options=PrintOptions()):
284  specialImportRegistry.registerUse(self)
285  sortedNames = sorted(self.parameterNames_())
286  if len(sortedNames) > 200:
287  #Too many parameters for a python function call
288  # The solution is to create a temporary dictionary which
289  # is constructed by concatenating long lists (with maximum
290  # 200 entries each) together.
291  # This looks like
292  # **dict( [(...,...), ...] + [...] + ... )
293  others = []
294  usings = []
295  for name in sortedNames:
296  param = self.__dict__[name]
297  # we don't want minuses in names
298  name2 = name.replace('-','_')
299  options.indent()
300  #_UsingNodes don't get assigned variables
301  if name.startswith("using_"):
302  usings.append(options.indentation()+param.dumpPython(options))
303  else:
304  others.append((name2, param.dumpPython(options)))
305  options.unindent()
306 
307  resultList = ',\n'.join(usings)
308  longOthers = options.indentation()+"**dict(\n"
309  options.indent()
310  longOthers += options.indentation()+"[\n"
311  entriesInList = 0
312  options.indent()
313  for n,v in others:
314  entriesInList +=1
315  if entriesInList > 200:
316  #need to start a new list
317  options.unindent()
318  longOthers += options.indentation()+"] +\n"+options.indentation()+"[\n"
319  entriesInList = 0
320  options.indent()
321  longOthers += options.indentation()+'("'+n+'" , '+v+' ),\n'
322 
323  longOthers += options.indentation()+"]\n"
324  options.unindent()
325  longOthers +=options.indentation()+")\n"
326  options.unindent()
327  ret = []
328  if resultList:
329  ret.append(resultList)
330  if longOthers:
331  ret.append(longOthers)
332  return ",\n".join(ret)
333  #Standard case, small number of parameters
334  others = []
335  usings = []
336  for name in sortedNames:
337  param = self.__dict__[name]
338  # we don't want minuses in names
339  name2 = name.replace('-','_')
340  options.indent()
341  #_UsingNodes don't get assigned variables
342  if name.startswith("using_"):
343  usings.append(options.indentation()+param.dumpPython(options))
344  else:
345  others.append(options.indentation()+name2+' = '+param.dumpPython(options))
346  options.unindent()
347  # usings need to go first
348  resultList = usings
349  resultList.extend(others)
350  return ',\n'.join(resultList)+'\n'
351  def __repr__(self):
352  return self.dumpPython()
353  def insertContentsInto(self, parameterSet):
354  for name in self.parameterNames_():
355  param = getattr(self,name)
356  param.insertInto(parameterSet, name)
357 
358 
360  """Base class for classes which are Parameterizable and have a 'type' assigned"""
361  def __init__(self,type_,*arg,**kargs):
362  self.__dict__['_TypedParameterizable__type'] = type_
363  #the 'type' is also placed in the 'arg' list and we need to remove it
364  #if 'type_' not in kargs:
365  # arg = arg[1:]
366  #else:
367  # del args['type_']
368  arg = tuple([x for x in arg if x != None])
369  super(_TypedParameterizable,self).__init__(*arg,**kargs)
370  saveOrigin(self, 1)
371  def _place(self,name,proc):
372  self._placeImpl(name,proc)
373  def type_(self):
374  """returns the type of the object, e.g. 'FooProducer'"""
375  return self.__type
376  def copy(self):
377  returnValue =_TypedParameterizable.__new__(type(self))
378  params = self.parameters_()
379  args = list()
380  if len(params) == 0:
381  args.append(None)
382  returnValue.__init__(self.__type,*args,
383  **params)
384  returnValue._isModified = self._isModified
385  return returnValue
386  def clone(self, *args, **params):
387  """Copies the object and allows one to modify the parameters of the clone.
388  New parameters may be added by specify the exact type
389  Modifying existing parameters can be done by just specifying the new
390  value without having to specify the type.
391  A parameter may be removed from the clone using the value None.
392  #remove the parameter foo.fred
393  mod.toModify(foo, fred = None)
394  A parameter embedded within a PSet may be changed via a dictionary
395  #change foo.fred.pebbles to 3 and foo.fred.friend to "barney"
396  mod.toModify(foo, fred = dict(pebbles = 3, friend = "barney)) )
397  """
398  returnValue =_TypedParameterizable.__new__(type(self))
399  myparams = self.parameters_()
400  if len(myparams) == 0 and len(params) and len(args):
401  args.append(None)
402 
403  _modifyParametersFromDict(myparams, params, self._Parameterizable__raiseBadSetAttr)
404 
405  returnValue.__init__(self.__type,*args,
406  **myparams)
407  returnValue._isModified = False
408  returnValue._isFrozen = False
409  saveOrigin(returnValue, 1)
410  return returnValue
411 
412  @staticmethod
413  def __findDefaultsFor(label,type):
414  #This routine is no longer used, but I might revive it in the future
415  import sys
416  import glob
417  choices = list()
418  for d in sys.path:
419  choices.extend(glob.glob(d+'/*/*/'+label+'.py'))
420  if not choices:
421  return None
422  #now see if any of them have what we want
423  #the use of __import__ is taken from an example
424  # from the www.python.org documentation on __import__
425  for c in choices:
426  #print " found file "+c
427  name='.'.join(c[:-3].split('/')[-3:])
428  #name = c[:-3].replace('/','.')
429  mod = __import__(name)
430  components = name.split('.')
431  for comp in components[1:]:
432  mod = getattr(mod,comp)
433  if hasattr(mod,label):
434  default = getattr(mod,label)
435  if isinstance(default,_TypedParameterizable):
436  if(default.type_() == type):
437  params = dict()
438  for name in default.parameterNames_():
439  params[name] = getattr(default,name)
440  return params
441  return None
442 
443  def dumpConfig(self, options=PrintOptions()):
444  config = self.__type +' { \n'
445  for name in self.parameterNames_():
446  param = self.__dict__[name]
447  options.indent()
448  config+=options.indentation()+param.configTypeName()+' '+name+' = '+param.configValue(options)+'\n'
449  options.unindent()
450  config += options.indentation()+'}\n'
451  return config
452 
453  def dumpPython(self, options=PrintOptions()):
454  specialImportRegistry.registerUse(self)
455  result = "cms."+str(type(self).__name__)+'("'+self.type_()+'"'
456  nparam = len(self.parameterNames_())
457  if nparam == 0:
458  result += ")\n"
459  else:
460  result += ",\n"+_Parameterizable.dumpPython(self,options)+options.indentation() + ")\n"
461  return result
462 
463  def dumpPythonAttributes(self, myname, options):
464  """ dumps the object with all attributes declared after the constructor"""
465  result = ""
466  for name in sorted(self.parameterNames_()):
467  param = self.__dict__[name]
468  result += options.indentation() + myname + "." + name + " = " + param.dumpPython(options) + "\n"
469  return result
470 
471  def nameInProcessDesc_(self, myname):
472  return myname;
473  def moduleLabel_(self, myname):
474  return myname
475  def appendToProcessDescList_(self, lst, myname):
476  lst.append(self.nameInProcessDesc_(myname))
477  def insertInto(self, parameterSet, myname):
478  newpset = parameterSet.newPSet()
479  newpset.addString(True, "@module_label", self.moduleLabel_(myname))
480  newpset.addString(True, "@module_type", self.type_())
481  newpset.addString(True, "@module_edm_type", type(self).__name__)
482  self.insertContentsInto(newpset)
483  parameterSet.addPSet(True, self.nameInProcessDesc_(myname), newpset)
484 
485 
486 
488  """A 'mixin' used to denote that the class can be paired with a label (e.g. an EDProducer)"""
489  def label_(self):
490  if not hasattr(self, "_Labelable__label"):
491  raise RuntimeError("module has no label. Perhaps it wasn't inserted into the process?")
492  return self.__label
493  def hasLabel_(self):
494  return hasattr(self, "_Labelable__label") and self.__label is not None
495  def setLabel(self,label):
496  if self.hasLabel_() :
497  if self.label_() != label and label is not None :
498  msg100 = "Attempting to change the label of a Labelable object, possibly an attribute of the Process\n"
499  msg101 = "Old label = "+self.label_()+" New label = "+label+"\n"
500  msg102 = "Type = "+str(type(self))+"\n"
501  msg103 = "Some possible solutions:\n"
502  msg104 = " 1. Clone modules instead of using simple assignment. Cloning is\n"
503  msg105 = " also preferred for other types when possible.\n"
504  msg106 = " 2. Declare new names starting with an underscore if they are\n"
505  msg107 = " for temporaries you do not want propagated into the Process. The\n"
506  msg108 = " underscore tells \"from x import *\" and process.load not to import\n"
507  msg109 = " the name.\n"
508  msg110 = " 3. Reorganize so the assigment is not necessary. Giving a second\n"
509  msg111 = " name to the same object usually causes confusion and problems.\n"
510  msg112 = " 4. Compose Sequences: newName = cms.Sequence(oldName)\n"
511  raise ValueError(msg100+msg101+msg102+msg103+msg104+msg105+msg106+msg107+msg108+msg109+msg110+msg111+msg112)
512  self.__label = label
513  def label(self):
514  #print "WARNING: _Labelable::label() needs to be changed to label_()"
515  return self.__label
516  def __str__(self):
517  #this is probably a bad idea
518  # I added this so that when we ask a path to print
519  # we will see the label that has been assigned
520  return str(self.__label)
522  return str(self.__label)
523  def dumpSequencePython(self, options=PrintOptions()):
524  return 'process.'+str(self.__label)
525  def _findDependencies(self,knownDeps,presentDeps):
526  #print 'in labelled'
527  myDeps=knownDeps.get(self.label_(),None)
528  if myDeps!=None:
529  if presentDeps != myDeps:
530  raise RuntimeError("the module "+self.label_()+" has two dependencies \n"
531  +str(presentDeps)+"\n"
532  +str(myDeps)+"\n"
533  +"Please modify sequences to rectify this inconsistency")
534  else:
535  myDeps=set(presentDeps)
536  knownDeps[self.label_()]=myDeps
537  presentDeps.add(self.label_())
538 
539 
541  """A 'mixin' used to denote that the class can be used without a label (e.g. a Service)"""
542  pass
543 
544 class _ValidatingListBase(list):
545  """Base class for a list which enforces that its entries pass a 'validity' test"""
546  def __init__(self,*arg,**args):
547  super(_ValidatingListBase,self).__init__(arg)
548  if 0 != len(args):
549  raise SyntaxError("named arguments ("+','.join([x for x in args])+") passsed to "+str(type(self)))
550  if not self._isValid(iter(self)):
551  raise TypeError("wrong types ("+','.join([str(type(value)) for value in iter(self)])+
552  ") added to "+str(type(self)))
553  def __setitem__(self,key,value):
554  if isinstance(key,slice):
555  if not self._isValid(value):
556  raise TypeError("wrong type being inserted into this container "+self._labelIfAny())
557  else:
558  if not self._itemIsValid(value):
559  raise TypeError("can not insert the type "+str(type(value))+" in container "+self._labelIfAny())
560  super(_ValidatingListBase,self).__setitem__(key,value)
561  def _isValid(self,seq):
562  # see if strings get reinterpreted as lists
563  if isinstance(seq, str):
564  return False
565  for item in seq:
566  if not self._itemIsValid(item):
567  return False
568  return True
569  def append(self,x):
570  if not self._itemIsValid(x):
571  raise TypeError("wrong type being appended to container "+self._labelIfAny())
572  super(_ValidatingListBase,self).append(x)
573  def extend(self,x):
574  if not self._isValid(x):
575  raise TypeError("wrong type being extended to container "+self._labelIfAny())
576  super(_ValidatingListBase,self).extend(x)
577  def __add__(self,rhs):
578  if not self._isValid(rhs):
579  raise TypeError("wrong type being added to container "+self._labelIfAny())
580  import copy
581  value = copy.copy(self)
582  value.extend(rhs)
583  return value
584  def insert(self,i,x):
585  if not self._itemIsValid(x):
586  raise TypeError("wrong type being inserted to container "+self._labelIfAny())
587  super(_ValidatingListBase,self).insert(i,x)
588  def _labelIfAny(self):
589  result = type(self).__name__
590  if hasattr(self, '__label'):
591  result += ' ' + self.__label
592  return result
593 
595  def __init__(self,*arg,**args):
596  _ParameterTypeBase.__init__(self)
597  if len (arg) == 1 and not isinstance(arg[0],str):
598  try:
599  arg = iter(arg[0])
600  except TypeError:
601  pass
602  super(_ValidatingParameterListBase,self).__init__(*arg,**args)
603  def value(self):
604  return list(self)
605  def setValue(self,v):
606  self[:] = []
607  self.extend(v)
608  self._isModified=True
609  def configValue(self, options=PrintOptions()):
610  config = '{\n'
611  first = True
612  for value in iter(self):
613  options.indent()
614  config += options.indentation()
615  if not first:
616  config+=', '
617  config+= self.configValueForItem(value, options)+'\n'
618  first = False
619  options.unindent()
620  config += options.indentation()+'}\n'
621  return config
622  def configValueForItem(self,item, options):
623  return str(item)
624  def pythonValueForItem(self,item, options):
625  return self.configValueForItem(item, options)
626  def __repr__(self):
627  return self.dumpPython()
628  def dumpPython(self, options=PrintOptions()):
629  specialImportRegistry.registerUse(self)
630  result = self.pythonTypeName()+"("
631  n = len(self)
632  if hasattr(self, "_nPerLine"):
633  nPerLine = self._nPerLine
634  else:
635  nPerLine = 5
636  if n>nPerLine: options.indent()
637  if n>=256:
638  #wrap in a tuple since they don't have a size constraint
639  result+=" ("
640  for i, v in enumerate(self):
641  if i == 0:
642  if n>nPerLine: result += '\n'+options.indentation()
643  else:
644  result += ', '
645  if i % nPerLine == 0:
646  result += '\n'+options.indentation()
647  result += self.pythonValueForItem(v,options)
648  if n>nPerLine:
649  options.unindent()
650  result += '\n'+options.indentation()
651  if n>=256:
652  result +=' ) '
653  result += ')'
654  return result
655  @staticmethod
656  def _itemsFromStrings(strings,converter):
657  return (converter(x).value() for x in strings)
658 
659 def saveOrigin(obj, level):
660  import sys
661  fInfo = inspect.getframeinfo(sys._getframe(level+1))
662  obj._filename = fInfo.filename
663  obj._lineNumber =fInfo.lineno
664 
665 def _modifyParametersFromDict(params, newParams, errorRaiser, keyDepth=""):
666  if len(newParams):
667  #need to treat items both in params and myparams specially
668  for key,value in six.iteritems(newParams):
669  if key in params:
670  if value is None:
671  del params[key]
672  elif isinstance(value, dict):
673  if isinstance(params[key],_Parameterizable):
674  pset = params[key]
675  p =pset.parameters_()
676  oldkeys = set(p.keys())
678  value,errorRaiser,
679  ("%s.%s" if isinstance(key, str) else "%s[%s]")%(keyDepth,key))
680  for k,v in six.iteritems(p):
681  setattr(pset,k,v)
682  oldkeys.discard(k)
683  for k in oldkeys:
684  delattr(pset,k)
685  elif isinstance(params[key],_ValidatingParameterListBase):
686  if any(not isinstance(k, int) for k in value.keys()):
687  raise TypeError("Attempted to change a list using a dict whose keys are not integers")
688  plist = params[key]
689  if any((k < 0 or k >= len(plist)) for k in value.keys()):
690  raise IndexError("Attempted to set an index which is not in the list")
691  p = dict(enumerate(plist))
693  value,errorRaiser,
694  ("%s.%s" if isinstance(key, str) else "%s[%s]")%(keyDepth,key))
695  for k,v in six.iteritems(p):
696  plist[k] = v
697  else:
698  raise ValueError("Attempted to change non PSet value "+keyDepth+" using a dictionary")
699  elif isinstance(value,_ParameterTypeBase) or (isinstance(key, int)) or isinstance(value, _Parameterizable):
700  params[key] = value
701  else:
702  params[key].setValue(value)
703  else:
704  if isinstance(value,_ParameterTypeBase) or isinstance(value, _Parameterizable):
705  params[key]=value
706  else:
707  errorRaiser(key)
708 
709 
710 if __name__ == "__main__":
711 
712  import unittest
714  def _itemIsValid(self,item):
715  return True
716  class testMixins(unittest.TestCase):
718  t = TestList(1)
719  self.assertEqual(t,[1])
720  t = TestList((1,))
721  self.assertEqual(t,[1])
722  t = TestList("one")
723  self.assertEqual(t,["one"])
724  t = TestList( [1,])
725  self.assertEqual(t,[1])
726  t = TestList( (x for x in [1]) )
727  self.assertEqual(t,[1])
728 
729  t = TestList(1,2)
730  self.assertEqual(t,[1,2])
731  t = TestList((1,2))
732  self.assertEqual(t,[1,2])
733  t = TestList("one","two")
734  self.assertEqual(t,["one","two"])
735  t = TestList(("one","two"))
736  self.assertEqual(t,["one","two"])
737  t = TestList( [1,2])
738  self.assertEqual(t,[1,2])
739  t = TestList( (x for x in [1,2]) )
740  self.assertEqual(t,[1,2])
741  t = TestList( iter((1,2)) )
742  self.assertEqual(t,[1,2])
743 
744 
745  def testLargeList(self):
746  #lists larger than 255 entries can not be initialized
747  #using the constructor
748  args = [i for i in range(0,300)]
749 
750  t = TestList(*args)
751  pdump= t.dumpPython()
752  class cms(object):
753  def __init__(self):
754  self.TestList = TestList
755  pythonized = eval( pdump, globals(),{'cms':cms()} )
756  self.assertEqual(t,pythonized)
757  def testUsingBlock(self):
758  a = UsingBlock("a")
759  self.assert_(isinstance(a, _ParameterTypeBase))
760  def testCopy(self):
761  class __Test(_TypedParameterizable):
762  pass
763  class __TestType(_SimpleParameterTypeBase):
764  def _isValid(self,value):
765  return True
766  a = __Test("MyType",t=__TestType(1), u=__TestType(2))
767  b = a.copy()
768  self.assertEqual(b.t.value(),1)
769  self.assertEqual(b.u.value(),2)
770  def testClone(self):
771  class __Test(_TypedParameterizable):
772  pass
773  class __TestType(_SimpleParameterTypeBase):
774  def _isValid(self,value):
775  return True
776  class __PSet(_ParameterTypeBase,_Parameterizable):
777  def __init__(self,*arg,**args):
778  #need to call the inits separately
779  _ParameterTypeBase.__init__(self)
780  _Parameterizable.__init__(self,*arg,**args)
781  a = __Test("MyType",
782  t=__TestType(1),
783  u=__TestType(2),
784  w = __TestType(3),
785  x = __PSet(a = __TestType(4),
786  b = __TestType(6),
787  c = __PSet(gamma = __TestType(5))))
788  b = a.clone(t=3,
789  v=__TestType(4),
790  w= None,
791  x = dict(a = 7,
792  c = dict(gamma = 8),
793  d = __TestType(9)))
794  c = a.clone(x = dict(a=None, c=None))
795  self.assertEqual(a.t.value(),1)
796  self.assertEqual(a.u.value(),2)
797  self.assertEqual(b.t.value(),3)
798  self.assertEqual(b.u.value(),2)
799  self.assertEqual(b.v.value(),4)
800  self.assertEqual(b.x.a.value(),7)
801  self.assertEqual(b.x.b.value(),6)
802  self.assertEqual(b.x.c.gamma.value(),8)
803  self.assertEqual(b.x.d.value(),9)
804  self.assertEqual(hasattr(b,"w"), False)
805  self.assertEqual(hasattr(c.x,"a"), False)
806  self.assertEqual(hasattr(c.x,"c"), False)
807  self.assertRaises(TypeError,a.clone,None,**{"v":1})
808  def testModified(self):
809  class __TestType(_SimpleParameterTypeBase):
810  def _isValid(self,value):
811  return True
812  a = __TestType(1)
813  self.assertEqual(a.isModified(),False)
814  a.setValue(1)
815  self.assertEqual(a.isModified(),False)
816  a.setValue(2)
817  self.assertEqual(a.isModified(),True)
818  a.resetModified()
819  self.assertEqual(a.isModified(),False)
822  pass
824  def _isValid(self,value):
825  return True
826  class __DummyModule(object):
827  def __init__(self):
828  self.tLPTest = tLPTest
829  self.tLPTestType = tLPTestType
830  p = tLPTest("MyType",** dict( [ ("a"+str(x), tLPTestType(x)) for x in range(0,300) ] ) )
831  #check they are the same
832  self.assertEqual(p.dumpPython(), eval(p.dumpPython(),{"cms": __DummyModule()}).dumpPython())
834  reg = _SpecialImportRegistry()
835  reg.registerSpecialImportForType(int, "import foo")
836  self.assertRaises(lambda x: reg.registerSpecialImportForType(int, "import bar"))
837  reg.registerSpecialImportForType(str, "import bar")
838  self.assertEqual(reg.getSpecialImports(), [])
839  reg.registerUse([1])
840  self.assertEqual(reg.getSpecialImports(), [])
841  reg.registerUse(1)
842  self.assertEqual(reg.getSpecialImports(), ["import foo"])
843  reg.registerUse(1)
844  self.assertEqual(reg.getSpecialImports(), ["import foo"])
845  reg.registerUse("a")
846  self.assertEqual(reg.getSpecialImports(), ["import bar", "import foo"])
847 
848  unittest.main()
def __init__(self, arg, args)
Definition: Mixins.py:546
def indent(self)
Definition: Mixins.py:18
def testSpecialImportRegistry(self)
Definition: Mixins.py:833
def __gt__(self, other)
Definition: Mixins.py:121
def moduleLabel_(self, myname)
Definition: Mixins.py:473
def testModified(self)
Definition: Mixins.py:808
def label_(self)
Definition: Mixins.py:489
def pythonTypeName(self)
Definition: Mixins.py:68
def dumpPython(self, options=PrintOptions())
Definition: Mixins.py:72
def dumpConfig(self, options=PrintOptions())
Definition: Mixins.py:443
def insertInto(self, parameterSet, myname)
Definition: Mixins.py:147
def __eq__(self, other)
Definition: Mixins.py:105
def _modifyParametersFromDict(params, newParams, errorRaiser, keyDepth="")
Definition: Mixins.py:665
def __setParameters(self, parameters)
Definition: Mixins.py:242
def _findDependencies(self, knownDeps, presentDeps)
Definition: Mixins.py:525
def testClone(self)
Definition: Mixins.py:770
def dumpPython(self, options=PrintOptions())
Definition: Mixins.py:628
bool any(const std::vector< T > &v, const T &what)
Definition: ECalSD.cc:37
def testCopy(self)
Definition: Mixins.py:760
def dumpPython(self, options=PrintOptions())
Definition: Mixins.py:153
def __init__(self, arg, kargs)
Definition: Mixins.py:162
def unindent(self)
Definition: Mixins.py:20
def dumpPythonAttributes(self, myname, options)
Definition: Mixins.py:463
def _valueFromString(value)
Definition: Mixins.py:144
def __ne__(self, other)
Definition: Mixins.py:109
def append(self, x)
Definition: Mixins.py:569
def setLabel(self, label)
Definition: Mixins.py:495
def registerUse(self, obj)
Definition: Mixins.py:38
def nameInProcessDesc_(self, myname)
Definition: Mixins.py:471
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def insert(self, i, x)
Definition: Mixins.py:584
bool setValue(Container &, const reco::JetBaseRef &, const JetExtendedData &)
associate jet with value. Returns false and associate nothing if jet is already associated ...
def __le__(self, other)
Definition: Mixins.py:117
def dumpPython(self, options=PrintOptions())
Definition: Mixins.py:283
def isModified(self)
Definition: Mixins.py:60
def testListConstruction(self)
Definition: Mixins.py:717
def __init__(self)
Definition: Mixins.py:12
def insertInto(self, parameterSet, myname)
Definition: Mixins.py:477
def setIsFrozen(self)
Definition: Mixins.py:271
def dumpPython(self, options=PrintOptions())
Definition: Mixins.py:453
def isModified(self)
Definition: Mixins.py:178
def __delattr__(self, name)
Definition: Mixins.py:275
def _itemsFromStrings(strings, converter)
Definition: Mixins.py:656
def configTypeName(self)
Definition: Mixins.py:64
def clone(self, args, params)
Definition: Mixins.py:386
def setIsFrozen(self)
Definition: Mixins.py:83
def dumpSequenceConfig(self)
Definition: Mixins.py:521
def __init__(self, type_, arg, kargs)
Definition: Mixins.py:361
def testLargeParameterizable(self)
Definition: Mixins.py:820
def indentation(self)
Definition: Mixins.py:16
def __repr__(self)
Definition: Mixins.py:351
def resetModified(self)
Definition: Mixins.py:62
def __init__(self, value, s='', loc=0, file='')
Definition: Mixins.py:135
def __addParameter(self, name, value)
Definition: Mixins.py:230
def _place(self, name, proc)
Definition: Mixins.py:371
Definition: value.py:1
def __findDefaultsFor(label, type)
Definition: Mixins.py:413
def __setattr__(self, name, value)
Definition: Mixins.py:246
def saveOrigin(obj, level)
Definition: Mixins.py:659
def __raiseBadSetAttr(name)
Definition: Mixins.py:281
def testUsingBlock(self)
Definition: Mixins.py:757
def registerSpecialImportForType(self, cls, impStatement)
Definition: Mixins.py:32
Namespace of DDCMS conversion namespace.
def configValue(self, options=PrintOptions())
Definition: Mixins.py:101
def _itemIsValid(self, item)
Definition: Mixins.py:714
def _isTaskComponent(self)
Definition: Mixins.py:8
def configValue(self, options=PrintOptions())
Definition: Mixins.py:609
def _isValid(self, seq)
Definition: Mixins.py:561
def setIsTracked(self, trackness)
Definition: Mixins.py:79
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def hasParameter(self, params)
Definition: Mixins.py:188
def setValue(self, value)
Definition: Mixins.py:95
def __ge__(self, other)
Definition: Mixins.py:125
def extend(self, x)
Definition: Mixins.py:573
def _isValid(value)
Definition: Mixins.py:142
def parameterNames_(self)
Definition: Mixins.py:175
def dumpPython(process, name)
def __str__(self)
Definition: Mixins.py:516
def __add__(self, rhs)
Definition: Mixins.py:577
def pythonValueForItem(self, item, options)
Definition: Mixins.py:624
def label(self)
Definition: Mixins.py:513
def testLargeList(self)
Definition: Mixins.py:745
def isFrozen(self)
Definition: Mixins.py:269
def hasLabel_(self)
Definition: Mixins.py:493
def __setitem__(self, key, value)
Definition: Mixins.py:553
def pythonValue(self, options=PrintOptions())
Definition: Mixins.py:103
def configValueForItem(self, item, options)
Definition: Mixins.py:622
def __init__(self, value)
Definition: Mixins.py:88
def parameters_(self)
Definition: Mixins.py:222
#define str(s)
def getParameter(self, params)
Definition: Mixins.py:202
double split
Definition: MVATrainer.cc:139
def appendToProcessDescList_(self, lst, myname)
Definition: Mixins.py:475
def insertContentsInto(self, parameterSet)
Definition: Mixins.py:353
def dumpSequencePython(self, options=PrintOptions())
Definition: Mixins.py:523
def __init__(self, arg, args)
Definition: Mixins.py:595
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 __lt__(self, other)
Definition: Mixins.py:113