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