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  if self._Parameterizable__validator is not None:
426  myparams["allowAnyLabel_"] = self._Parameterizable__validator
427 
428  returnValue.__init__(self.__type,*args,
429  **myparams)
430  returnValue._isModified = False
431  returnValue._isFrozen = False
432  saveOrigin(returnValue, 1)
433  return returnValue
434 
435  @staticmethod
436  def __findDefaultsFor(label,type):
437  #This routine is no longer used, but I might revive it in the future
438  import sys
439  import glob
440  choices = list()
441  for d in sys.path:
442  choices.extend(glob.glob(d+'/*/*/'+label+'.py'))
443  if not choices:
444  return None
445  #now see if any of them have what we want
446  #the use of __import__ is taken from an example
447  # from the www.python.org documentation on __import__
448  for c in choices:
449  #print " found file "+c
450  name='.'.join(c[:-3].split('/')[-3:])
451  #name = c[:-3].replace('/','.')
452  mod = __import__(name)
453  components = name.split('.')
454  for comp in components[1:]:
455  mod = getattr(mod,comp)
456  if hasattr(mod,label):
457  default = getattr(mod,label)
458  if isinstance(default,_TypedParameterizable):
459  if(default.type_() == type):
460  params = dict()
461  for name in default.parameterNames_():
462  params[name] = getattr(default,name)
463  return params
464  return None
465 
467  return []
468 
469  def dumpConfig(self, options=PrintOptions()):
470  config = self.__type +' { \n'
471  for name in self.parameterNames_():
472  param = self.__dict__[name]
473  options.indent()
474  config+=options.indentation()+param.configTypeName()+' '+name+' = '+param.configValue(options)+'\n'
475  options.unindent()
476  config += options.indentation()+'}\n'
477  return config
478 
479  def dumpPython(self, options=PrintOptions()):
480  specialImportRegistry.registerUse(self)
481  result = "cms."+str(type(self).__name__)+'("'+self.type_()+'"'
482  nparam = len(self.parameterNames_())
483  if nparam == 0:
484  result += ")\n"
485  else:
486  result += ",\n"+_Parameterizable.dumpPython(self,options)+options.indentation() + ")\n"
487  return result
488 
489  def dumpPythonAttributes(self, myname, options):
490  """ dumps the object with all attributes declared after the constructor"""
491  result = ""
492  for name in sorted(self.parameterNames_()):
493  param = self.__dict__[name]
494  result += options.indentation() + myname + "." + name + " = " + param.dumpPython(options) + "\n"
495  return result
496 
497  def nameInProcessDesc_(self, myname):
498  return myname;
499  def moduleLabel_(self, myname):
500  return myname
501  def appendToProcessDescList_(self, lst, myname):
502  lst.append(self.nameInProcessDesc_(myname))
503  def insertInto(self, parameterSet, myname):
504  newpset = parameterSet.newPSet()
505  newpset.addString(True, "@module_label", self.moduleLabel_(myname))
506  newpset.addString(True, "@module_type", self.type_())
507  newpset.addString(True, "@module_edm_type", type(self).__name__)
508  self.insertContentsInto(newpset)
509  parameterSet.addPSet(True, self.nameInProcessDesc_(myname), newpset)
510 
511 
512 
514  """A 'mixin' used to denote that the class can be paired with a label (e.g. an EDProducer)"""
515  def label_(self):
516  if not hasattr(self, "_Labelable__label"):
517  raise RuntimeError("module has no label. Perhaps it wasn't inserted into the process?")
518  return self.__label
519  def hasLabel_(self):
520  return hasattr(self, "_Labelable__label") and self.__label is not None
521  def setLabel(self,label):
522  if self.hasLabel_() :
523  if self.label_() != label and label is not None :
524  msg100 = "Attempting to change the label of a Labelable object, possibly an attribute of the Process\n"
525  msg101 = "Old label = "+self.label_()+" New label = "+label+"\n"
526  msg102 = "Type = "+str(type(self))+"\n"
527  msg103 = "Some possible solutions:\n"
528  msg104 = " 1. Clone modules instead of using simple assignment. Cloning is\n"
529  msg105 = " also preferred for other types when possible.\n"
530  msg106 = " 2. Declare new names starting with an underscore if they are\n"
531  msg107 = " for temporaries you do not want propagated into the Process. The\n"
532  msg108 = " underscore tells \"from x import *\" and process.load not to import\n"
533  msg109 = " the name.\n"
534  msg110 = " 3. Reorganize so the assigment is not necessary. Giving a second\n"
535  msg111 = " name to the same object usually causes confusion and problems.\n"
536  msg112 = " 4. Compose Sequences: newName = cms.Sequence(oldName)\n"
537  raise ValueError(msg100+msg101+msg102+msg103+msg104+msg105+msg106+msg107+msg108+msg109+msg110+msg111+msg112)
538  self.__label = label
539  def label(self):
540  #print "WARNING: _Labelable::label() needs to be changed to label_()"
541  return self.__label
542  def __str__(self):
543  #this is probably a bad idea
544  # I added this so that when we ask a path to print
545  # we will see the label that has been assigned
546  return str(self.__label)
548  return str(self.__label)
549  def dumpSequencePython(self, options=PrintOptions()):
550  if options.isCfg:
551  return 'process.'+str(self.__label)
552  else:
553  return str(self.__label)
554  def _findDependencies(self,knownDeps,presentDeps):
555  #print 'in labelled'
556  myDeps=knownDeps.get(self.label_(),None)
557  if myDeps!=None:
558  if presentDeps != myDeps:
559  raise RuntimeError("the module "+self.label_()+" has two dependencies \n"
560  +str(presentDeps)+"\n"
561  +str(myDeps)+"\n"
562  +"Please modify sequences to rectify this inconsistency")
563  else:
564  myDeps=set(presentDeps)
565  knownDeps[self.label_()]=myDeps
566  presentDeps.add(self.label_())
567 
568 
570  """A 'mixin' used to denote that the class can be used without a label (e.g. a Service)"""
571  pass
572 
573 class _ValidatingListBase(list):
574  """Base class for a list which enforces that its entries pass a 'validity' test"""
575  def __init__(self,*arg,**args):
576  super(_ValidatingListBase,self).__init__(arg)
577  if 0 != len(args):
578  raise SyntaxError("named arguments ("+','.join([x for x in args])+") passsed to "+str(type(self)))
579  if not self._isValid(iter(self)):
580  raise TypeError("wrong types ("+','.join([str(type(value)) for value in iter(self)])+
581  ") added to "+str(type(self)))
582  def __setitem__(self,key,value):
583  if isinstance(key,slice):
584  if not self._isValid(value):
585  raise TypeError("wrong type being inserted into this container "+self._labelIfAny())
586  else:
587  if not self._itemIsValid(value):
588  raise TypeError("can not insert the type "+str(type(value))+" in container "+self._labelIfAny())
589  super(_ValidatingListBase,self).__setitem__(key,value)
590  def _isValid(self,seq):
591  # see if strings get reinterpreted as lists
592  if isinstance(seq, str):
593  return False
594  for item in seq:
595  if not self._itemIsValid(item):
596  return False
597  return True
598  def _itemFromArgument(self, x):
599  return x
600  def _convertArguments(self, seq):
601  if isinstance(seq, str):
602  yield seq
603  for x in seq:
604  yield self._itemFromArgument(x)
605  def append(self,x):
606  if not self._itemIsValid(x):
607  raise TypeError("wrong type being appended to container "+self._labelIfAny())
608  super(_ValidatingListBase,self).append(self._itemFromArgument(x))
609  def extend(self,x):
610  if not self._isValid(x):
611  raise TypeError("wrong type being extended to container "+self._labelIfAny())
612  super(_ValidatingListBase,self).extend(self._convertArguments(x))
613  def __add__(self,rhs):
614  if not self._isValid(rhs):
615  raise TypeError("wrong type being added to container "+self._labelIfAny())
616  import copy
617  value = copy.copy(self)
618  value.extend(rhs)
619  return value
620  def insert(self,i,x):
621  if not self._itemIsValid(x):
622  raise TypeError("wrong type being inserted to container "+self._labelIfAny())
623  super(_ValidatingListBase,self).insert(i,self._itemFromArgument(x))
624  def _labelIfAny(self):
625  result = type(self).__name__
626  if hasattr(self, '__label'):
627  result += ' ' + self.__label
628  return result
629 
631  def __init__(self,*arg,**args):
632  _ParameterTypeBase.__init__(self)
633  if len (arg) == 1 and not isinstance(arg[0],str):
634  try:
635  arg = iter(arg[0])
636  except TypeError:
637  pass
638  super(_ValidatingParameterListBase,self).__init__(*arg,**args)
639  def value(self):
640  return list(self)
641  def setValue(self,v):
642  self[:] = []
643  self.extend(v)
644  self._isModified=True
645  def configValue(self, options=PrintOptions()):
646  config = '{\n'
647  first = True
648  for value in iter(self):
649  options.indent()
650  config += options.indentation()
651  if not first:
652  config+=', '
653  config+= self.configValueForItem(value, options)+'\n'
654  first = False
655  options.unindent()
656  config += options.indentation()+'}\n'
657  return config
658  def configValueForItem(self,item, options):
659  return str(item)
660  def pythonValueForItem(self,item, options):
661  return self.configValueForItem(item, options)
662  def __repr__(self):
663  return self.dumpPython()
664  def dumpPython(self, options=PrintOptions()):
665  specialImportRegistry.registerUse(self)
666  result = self.pythonTypeName()+"("
667  n = len(self)
668  if hasattr(self, "_nPerLine"):
669  nPerLine = self._nPerLine
670  else:
671  nPerLine = 5
672  if n>nPerLine: options.indent()
673  if n>=256:
674  #wrap in a tuple since they don't have a size constraint
675  result+=" ("
676  for i, v in enumerate(self):
677  if i == 0:
678  if n>nPerLine: result += '\n'+options.indentation()
679  else:
680  result += ', '
681  if i % nPerLine == 0:
682  result += '\n'+options.indentation()
683  result += self.pythonValueForItem(v,options)
684  if n>nPerLine:
685  options.unindent()
686  result += '\n'+options.indentation()
687  if n>=256:
688  result +=' ) '
689  result += ')'
690  return result
692  return []
693  @staticmethod
694  def _itemsFromStrings(strings,converter):
695  return (converter(x).value() for x in strings)
696 
697 def saveOrigin(obj, level):
698  import sys
699  fInfo = inspect.getframeinfo(sys._getframe(level+1))
700  obj._filename = fInfo.filename
701  obj._lineNumber =fInfo.lineno
702 
703 def _modifyParametersFromDict(params, newParams, errorRaiser, keyDepth=""):
704  if len(newParams):
705  #need to treat items both in params and myparams specially
706  for key,value in six.iteritems(newParams):
707  if key in params:
708  if value is None:
709  del params[key]
710  elif isinstance(value, dict):
711  if isinstance(params[key],_Parameterizable):
712  pset = params[key]
713  p =pset.parameters_()
714  oldkeys = set(p.keys())
716  value,errorRaiser,
717  ("%s.%s" if isinstance(key, str) else "%s[%s]")%(keyDepth,key))
718  for k,v in six.iteritems(p):
719  setattr(pset,k,v)
720  oldkeys.discard(k)
721  for k in oldkeys:
722  delattr(pset,k)
723  elif isinstance(params[key],_ValidatingParameterListBase):
724  if any(not isinstance(k, int) for k in value.keys()):
725  raise TypeError("Attempted to change a list using a dict whose keys are not integers")
726  plist = params[key]
727  if any((k < 0 or k >= len(plist)) for k in value.keys()):
728  raise IndexError("Attempted to set an index which is not in the list")
729  p = dict(enumerate(plist))
731  value,errorRaiser,
732  ("%s.%s" if isinstance(key, str) else "%s[%s]")%(keyDepth,key))
733  for k,v in six.iteritems(p):
734  plist[k] = v
735  else:
736  raise ValueError("Attempted to change non PSet value "+keyDepth+" using a dictionary")
737  elif isinstance(value,_ParameterTypeBase) or (isinstance(key, int)) or isinstance(value, _Parameterizable):
738  params[key] = value
739  else:
740  params[key].setValue(value)
741  else:
742  if isinstance(value,_ParameterTypeBase) or isinstance(value, _Parameterizable):
743  params[key]=value
744  else:
745  errorRaiser(key)
746 
747 
748 if __name__ == "__main__":
749 
750  import unittest
752  def _itemIsValid(self,item):
753  return True
754  class testMixins(unittest.TestCase):
756  t = TestList(1)
757  self.assertEqual(t,[1])
758  t = TestList((1,))
759  self.assertEqual(t,[1])
760  t = TestList("one")
761  self.assertEqual(t,["one"])
762  t = TestList( [1,])
763  self.assertEqual(t,[1])
764  t = TestList( (x for x in [1]) )
765  self.assertEqual(t,[1])
766 
767  t = TestList(1,2)
768  self.assertEqual(t,[1,2])
769  t = TestList((1,2))
770  self.assertEqual(t,[1,2])
771  t = TestList("one","two")
772  self.assertEqual(t,["one","two"])
773  t = TestList(("one","two"))
774  self.assertEqual(t,["one","two"])
775  t = TestList( [1,2])
776  self.assertEqual(t,[1,2])
777  t = TestList( (x for x in [1,2]) )
778  self.assertEqual(t,[1,2])
779  t = TestList( iter((1,2)) )
780  self.assertEqual(t,[1,2])
781 
782 
783  def testLargeList(self):
784  #lists larger than 255 entries can not be initialized
785  #using the constructor
786  args = [i for i in range(0,300)]
787 
788  t = TestList(*args)
789  pdump= t.dumpPython()
790  class cms(object):
791  def __init__(self):
792  self.TestList = TestList
793  pythonized = eval( pdump, globals(),{'cms':cms()} )
794  self.assertEqual(t,pythonized)
795  def testUsingBlock(self):
796  a = UsingBlock("a")
797  self.assert_(isinstance(a, _ParameterTypeBase))
798  def testCopy(self):
799  class __Test(_TypedParameterizable):
800  pass
801  class __TestType(_SimpleParameterTypeBase):
802  def _isValid(self,value):
803  return True
804  a = __Test("MyType",t=__TestType(1), u=__TestType(2))
805  b = a.copy()
806  self.assertEqual(b.t.value(),1)
807  self.assertEqual(b.u.value(),2)
808  def testClone(self):
809  class __Test(_TypedParameterizable):
810  pass
811  class __TestType(_SimpleParameterTypeBase):
812  def _isValid(self,value):
813  return True
814  class __PSet(_ParameterTypeBase,_Parameterizable):
815  def __init__(self,*arg,**args):
816  #need to call the inits separately
817  _ParameterTypeBase.__init__(self)
818  _Parameterizable.__init__(self,*arg,**args)
819  a = __Test("MyType",
820  t=__TestType(1),
821  u=__TestType(2),
822  w = __TestType(3),
823  x = __PSet(a = __TestType(4),
824  b = __TestType(6),
825  c = __PSet(gamma = __TestType(5))))
826  b = a.clone(t=3,
827  v=__TestType(4),
828  w= None,
829  x = dict(a = 7,
830  c = dict(gamma = 8),
831  d = __TestType(9)))
832  c = a.clone(x = dict(a=None, c=None))
833  self.assertEqual(a.t.value(),1)
834  self.assertEqual(a.u.value(),2)
835  self.assertEqual(b.t.value(),3)
836  self.assertEqual(b.u.value(),2)
837  self.assertEqual(b.v.value(),4)
838  self.assertEqual(b.x.a.value(),7)
839  self.assertEqual(b.x.b.value(),6)
840  self.assertEqual(b.x.c.gamma.value(),8)
841  self.assertEqual(b.x.d.value(),9)
842  self.assertEqual(hasattr(b,"w"), False)
843  self.assertEqual(hasattr(c.x,"a"), False)
844  self.assertEqual(hasattr(c.x,"c"), False)
845  self.assertRaises(TypeError,a.clone,None,**{"v":1})
846  def testModified(self):
847  class __TestType(_SimpleParameterTypeBase):
848  def _isValid(self,value):
849  return True
850  a = __TestType(1)
851  self.assertEqual(a.isModified(),False)
852  a.setValue(1)
853  self.assertEqual(a.isModified(),False)
854  a.setValue(2)
855  self.assertEqual(a.isModified(),True)
856  a.resetModified()
857  self.assertEqual(a.isModified(),False)
860  pass
862  def _isValid(self,value):
863  return True
864  class __DummyModule(object):
865  def __init__(self):
866  self.tLPTest = tLPTest
867  self.tLPTestType = tLPTestType
868  p = tLPTest("MyType",** dict( [ ("a"+str(x), tLPTestType(x)) for x in range(0,300) ] ) )
869  #check they are the same
870  self.assertEqual(p.dumpPython(), eval(p.dumpPython(),{"cms": __DummyModule()}).dumpPython())
872  reg = _SpecialImportRegistry()
873  reg.registerSpecialImportForType(int, "import foo")
874  self.assertRaises(lambda x: reg.registerSpecialImportForType(int, "import bar"))
875  reg.registerSpecialImportForType(str, "import bar")
876  self.assertEqual(reg.getSpecialImports(), [])
877  reg.registerUse([1])
878  self.assertEqual(reg.getSpecialImports(), [])
879  reg.registerUse(1)
880  self.assertEqual(reg.getSpecialImports(), ["import foo"])
881  reg.registerUse(1)
882  self.assertEqual(reg.getSpecialImports(), ["import foo"])
883  reg.registerUse("a")
884  self.assertEqual(reg.getSpecialImports(), ["import bar", "import foo"])
885 
886  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:620
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:554
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:867
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:694
Mixins._Parameterizable.parameterNames_
def parameterNames_(self)
Definition: Mixins.py:180
Mixins._ParameterTypeBase.__isTracked
__isTracked
Definition: Mixins.py:60
Mixins._Labelable
Definition: Mixins.py:513
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:613
Mixins._Parameterizable.isFrozen
def isFrozen(self)
Definition: Mixins.py:286
Mixins.testMixins.testSpecialImportRegistry
def testSpecialImportRegistry(self)
Definition: Mixins.py:871
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
if
if(0==first)
Definition: CAHitNtupletGeneratorKernelsImpl.h:48
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:658
Mixins._ParameterTypeBase._isFrozen
_isFrozen
Definition: Mixins.py:86
Mixins._TypedParameterizable.dumpPythonAttributes
def dumpPythonAttributes(self, myname, options)
Definition: Mixins.py:489
Mixins._ParameterTypeBase.dumpPython
def dumpPython(self, options=PrintOptions())
Definition: Mixins.py:74
Mixins.testMixins.tLPTest
tLPTest
Definition: Mixins.py:866
Mixins.UsingBlock._isValid
def _isValid(value)
Definition: Mixins.py:146
Mixins._ValidatingListBase.__init__
def __init__(self, *arg, **args)
Definition: Mixins.py:575
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:751
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:609
Mixins._Labelable.setLabel
def setLabel(self, label)
Definition: Mixins.py:521
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:515
Mixins._Parameterizable.__setattr__
def __setattr__(self, name, value)
Definition: Mixins.py:263
Mixins.testMixins.testUsingBlock
def testUsingBlock(self)
Definition: Mixins.py:795
Mixins._TypedParameterizable.directDependencies
def directDependencies(self)
Definition: Mixins.py:466
Mixins._ValidatingParameterListBase
Definition: Mixins.py:630
Mixins._ValidatingListBase
Definition: Mixins.py:573
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:582
Mixins._TypedParameterizable.nameInProcessDesc_
def nameInProcessDesc_(self, myname)
Definition: Mixins.py:497
Mixins._ValidatingParameterListBase.setValue
def setValue(self, v)
Definition: Mixins.py:641
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:754
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:639
Mixins.testMixins.testCopy
def testCopy(self)
Definition: Mixins.py:798
Mixins._SpecialImportRegistry.registerSpecialImportForType
def registerSpecialImportForType(self, cls, impStatement)
Definition: Mixins.py:34
str
#define str(s)
Definition: TestProcessor.cc:52
Mixins._ValidatingParameterListBase.pythonValueForItem
def pythonValueForItem(self, item, options)
Definition: Mixins.py:660
Mixins.testMixins.testClone
def testClone(self)
Definition: Mixins.py:808
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:569
Mixins._Labelable.dumpSequencePython
def dumpSequencePython(self, options=PrintOptions())
Definition: Mixins.py:549
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:662
AlCaHLTBitMon_QueryRunRegistry.string
string
Definition: AlCaHLTBitMon_QueryRunRegistry.py:256
Mixins.TestList._itemIsValid
def _itemIsValid(self, item)
Definition: Mixins.py:752
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:664
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:792
Mixins._SpecialImportRegistry
Definition: Mixins.py:25
Mixins._Labelable.label
def label(self)
Definition: Mixins.py:539
Mixins._Labelable.hasLabel_
def hasLabel_(self)
Definition: Mixins.py:519
Mixins.UsingBlock._valueFromString
def _valueFromString(value)
Definition: Mixins.py:148
Mixins.testMixins.testListConstruction
def testListConstruction(self)
Definition: Mixins.py:755
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:697
Mixins._Labelable.__label
__label
Definition: Mixins.py:538
Mixins._ParameterTypeBase.setIsFrozen
def setIsFrozen(self)
Definition: Mixins.py:85
Mixins._TypedParameterizable.moduleLabel_
def moduleLabel_(self, myname)
Definition: Mixins.py:499
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:645
Mixins._ValidatingListBase._isValid
def _isValid(self, seq)
Definition: Mixins.py:590
Mixins._TypedParameterizable.__findDefaultsFor
def __findDefaultsFor(label, type)
Definition: Mixins.py:436
Mixins._ParameterTypeBase._isModified
_isModified
Definition: Mixins.py:61
ConfigBuilder.dumpPython
def dumpPython(process, name)
Definition: ConfigBuilder.py:93
Mixins._ParameterTypeBase.isFrozen
def isFrozen(self)
Definition: Mixins.py:83
Mixins.testMixins.testLargeParameterizable
def testLargeParameterizable(self)
Definition: Mixins.py:858
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:503
Mixins._ValidatingParameterListBase.directDependencies
def directDependencies(self)
Definition: Mixins.py:691
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:542
Mixins._ValidatingListBase._labelIfAny
def _labelIfAny(self)
Definition: Mixins.py:624
Mixins._TypedParameterizable.appendToProcessDescList_
def appendToProcessDescList_(self, lst, myname)
Definition: Mixins.py:501
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:605
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:469
Mixins._ValidatingParameterListBase.__init__
def __init__(self, *arg, **args)
Definition: Mixins.py:631
Mixins._ValidatingListBase._convertArguments
def _convertArguments(self, seq)
Definition: Mixins.py:600
Mixins._ValidatingListBase._itemFromArgument
def _itemFromArgument(self, x)
Definition: Mixins.py:598
Mixins._Parameterizable.dumpPython
def dumpPython(self, options=PrintOptions())
Definition: Mixins.py:300
Mixins._TypedParameterizable.dumpPython
def dumpPython(self, options=PrintOptions())
Definition: Mixins.py:479
Mixins.UsingBlock
Definition: Mixins.py:135
Mixins.testMixins.testModified
def testModified(self)
Definition: Mixins.py:846
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:547
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:703
Mixins.testMixins.testLargeList
def testLargeList(self)
Definition: Mixins.py:783
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