CMS 3D CMS Logo

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