CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
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 
5 class _ConfigureComponent(object):
6  """Denotes a class that can be used by the Processes class"""
7  def _isTaskComponent(self):
8  return False
9 
10 class PrintOptions(object):
11  def __init__(self, indent = 0, deltaIndent = 4, process = True, targetDirectory = None, useSubdirectories = False):
12  self.indent_= indent
13  self.deltaIndent_ = deltaIndent
14  self.isCfg = process
15  self.targetDirectory = targetDirectory
16  self.useSubdirectories = useSubdirectories
17  def indentation(self):
18  return ' '*self.indent_
19  def indent(self):
20  self.indent_ += self.deltaIndent_
21  def unindent(self):
22  self.indent_ -= self.deltaIndent_
23 
24 class _SpecialImportRegistry(object):
25  """This class collects special import statements of configuration types"""
26  def __init__(self):
27  self._registry = {}
28 
29  def _reset(self):
30  for lst in self._registry.values():
31  lst[1] = False
32 
33  def registerSpecialImportForType(self, cls, impStatement):
34  className = cls.__name__
35  if className in self._registry:
36  raise RuntimeError("Error: the configuration type '%s' already has an import statement registered '%s'" % (className, self._registry[className][0]))
37  self._registry[className] = [impStatement, False]
38 
39  def registerUse(self, obj):
40  className = obj.__class__.__name__
41  try:
42  self._registry[className][1] = True
43  except KeyError:
44  pass
45 
46  def getSpecialImports(self):
47  coll = set()
48  for (imp, used) in self._registry.values():
49  if used:
50  coll.add(imp)
51  return sorted(coll)
52 
53 specialImportRegistry = _SpecialImportRegistry()
54 
55 class _ParameterTypeBase(object):
56  """base class for classes which are used as the 'parameters' for a ParameterSet"""
57  def __init__(self):
58  self.__dict__["_isFrozen"] = False
59  self.__isTracked = True
60  self._isModified = False
61  def isModified(self):
62  return self._isModified
63  def resetModified(self):
64  self._isModified=False
65  def configTypeName(self):
66  if self.isTracked():
67  return type(self).__name__
68  return 'untracked '+type(self).__name__
69  def pythonTypeName(self):
70  if self.isTracked():
71  return 'cms.'+type(self).__name__
72  return 'cms.untracked.'+type(self).__name__
73  def dumpPython(self, options=PrintOptions()):
74  specialImportRegistry.registerUse(self)
75  return self.pythonTypeName()+"("+self.pythonValue(options)+")"
76  def __repr__(self):
77  return self.dumpPython()
78  def isTracked(self):
79  return self.__isTracked
80  def setIsTracked(self,trackness):
81  self.__isTracked = trackness
82  def isFrozen(self):
83  return self._isFrozen
84  def setIsFrozen(self):
85  self._isFrozen = True
86  def isCompatibleCMSType(self,aType):
87  return isinstance(self,aType)
88 
90  """base class for parameter classes which only hold a single value"""
91  def __init__(self,value):
92  super(_SimpleParameterTypeBase,self).__init__()
93  self._value = value
94  if not self._isValid(value):
95  raise ValueError(str(value)+" is not a valid "+str(type(self)))
96  def value(self):
97  return self._value
98  def setValue(self,value):
99  if not self._isValid(value):
100  raise ValueError(str(value)+" is not a valid "+str(type(self)))
101  if value!=self._value:
102  self._isModified=True
103  self._value=value
104  def configValue(self, options=PrintOptions()):
105  return str(self._value)
106  def pythonValue(self, options=PrintOptions()):
107  return self.configValue(options)
108  def __eq__(self,other):
109  if isinstance(other,_SimpleParameterTypeBase):
110  return self._value == other._value
111  return self._value == other
112  def __ne__(self,other):
113  if isinstance(other,_SimpleParameterTypeBase):
114  return self._value != other._value
115  return self._value != other
116  def __lt__(self,other):
117  if isinstance(other,_SimpleParameterTypeBase):
118  return self._value < other._value
119  return self._value < other
120  def __le__(self,other):
121  if isinstance(other,_SimpleParameterTypeBase):
122  return self._value <= other._value
123  return self._value <= other
124  def __gt__(self,other):
125  if isinstance(other,_SimpleParameterTypeBase):
126  return self._value > other._value
127  return self._value > other
128  def __ge__(self,other):
129  if isinstance(other,_SimpleParameterTypeBase):
130  return self._value >= other._value
131  return self._value >= other
132 
133 
135  """For injection purposes, pretend this is a new parameter type
136  then have a post process step which strips these out
137  """
138  def __init__(self,value, s='', loc=0, file=''):
139  super(UsingBlock,self).__init__(value)
140  self.s = s
141  self.loc = loc
142  self.file = file
143  self.isResolved = False
144  @staticmethod
145  def _isValid(value):
146  return isinstance(value,str)
147  def _valueFromString(value):
148  """only used for cfg-parsing"""
149  return string(value)
150  def insertInto(self, parameterSet, myname):
151  value = self.value()
152  # doesn't seem to handle \0 correctly
153  #if value == '\0':
154  # value = ''
155  parameterSet.addString(self.isTracked(), myname, value)
156  def dumpPython(self, options=PrintOptions()):
157  if options.isCfg:
158  return "process."+self.value()
159  else:
160  return self.value()
161 
162 
163 class _Parameterizable(object):
164  """Base class for classes which allow addition of _ParameterTypeBase data"""
165  def __init__(self,*arg,**kargs):
166  self.__dict__['_Parameterizable__parameterNames'] = []
167  self.__dict__["_isFrozen"] = False
168  self.__dict__['_Parameterizable__validator'] = None
169  """The named arguments are the 'parameters' which are added as 'python attributes' to the object"""
170  if len(arg) != 0:
171  #raise ValueError("unnamed arguments are not allowed. Please use the syntax 'name = value' when assigning arguments.")
172  for block in arg:
173  # Allow __PSet for testing
174  if type(block).__name__ not in ["PSet", "__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 parameters.items():
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  super(_TypedParameterizable,self).__init__(*arg,**kargs)
390  saveOrigin(self, 1)
391  def _place(self,name,proc):
392  self._placeImpl(name,proc)
393  def type_(self):
394  """returns the type of the object, e.g. 'FooProducer'"""
395  return self.__type
396  def copy(self):
397  returnValue =_TypedParameterizable.__new__(type(self))
398  params = self.parameters_()
399  returnValue.__init__(self.__type,**params)
400  returnValue._isModified = self._isModified
401  return returnValue
402  def clone(self, *args, **params):
403  """Copies the object and allows one to modify the parameters of the clone.
404  New parameters may be added by specify the exact type
405  Modifying existing parameters can be done by just specifying the new
406  value without having to specify the type.
407  A parameter may be removed from the clone using the value None.
408  #remove the parameter foo.fred
409  mod.toModify(foo, fred = None)
410  A parameter embedded within a PSet may be changed via a dictionary
411  #change foo.fred.pebbles to 3 and foo.fred.friend to "barney"
412  mod.toModify(foo, fred = dict(pebbles = 3, friend = "barney)) )
413  """
414  returnValue =_TypedParameterizable.__new__(type(self))
415  myparams = self.parameters_()
416 
417  # Prefer parameters given in PSet blocks over those in clone-from module
418  for block in args:
419  # Allow __PSet for testing
420  if type(block).__name__ not in ["PSet", "__PSet"]:
421  raise ValueError("Only PSets can be passed as unnamed argument blocks. This is a "+type(block).__name__)
422  for name in block.parameterNames_():
423  try:
424  del myparams[name]
425  except KeyError:
426  pass
427 
428  _modifyParametersFromDict(myparams, params, self._Parameterizable__raiseBadSetAttr)
429  if self._Parameterizable__validator is not None:
430  myparams["allowAnyLabel_"] = self._Parameterizable__validator
431 
432  returnValue.__init__(self.__type,*args,
433  **myparams)
434  returnValue._isModified = False
435  returnValue._isFrozen = False
436  saveOrigin(returnValue, 1)
437  return returnValue
438 
439  @staticmethod
440  def __findDefaultsFor(label,type):
441  #This routine is no longer used, but I might revive it in the future
442  import sys
443  import glob
444  choices = list()
445  for d in sys.path:
446  choices.extend(glob.glob(d+'/*/*/'+label+'.py'))
447  if not choices:
448  return None
449  #now see if any of them have what we want
450  #the use of __import__ is taken from an example
451  # from the www.python.org documentation on __import__
452  for c in choices:
453  #print " found file "+c
454  name='.'.join(c[:-3].split('/')[-3:])
455  #name = c[:-3].replace('/','.')
456  mod = __import__(name)
457  components = name.split('.')
458  for comp in components[1:]:
459  mod = getattr(mod,comp)
460  if hasattr(mod,label):
461  default = getattr(mod,label)
462  if isinstance(default,_TypedParameterizable):
463  if(default.type_() == type):
464  params = dict()
465  for name in default.parameterNames_():
466  params[name] = getattr(default,name)
467  return params
468  return None
469 
471  return []
472 
473  def dumpConfig(self, options=PrintOptions()):
474  config = self.__type +' { \n'
475  for name in self.parameterNames_():
476  param = self.__dict__[name]
477  options.indent()
478  config+=options.indentation()+param.configTypeName()+' '+name+' = '+param.configValue(options)+'\n'
479  options.unindent()
480  config += options.indentation()+'}\n'
481  return config
482 
483  def dumpPython(self, options=PrintOptions()):
484  specialImportRegistry.registerUse(self)
485  result = "cms."+str(type(self).__name__)+'("'+self.type_()+'"'
486  nparam = len(self.parameterNames_())
487  if nparam == 0:
488  result += ")\n"
489  else:
490  result += ",\n"+_Parameterizable.dumpPython(self,options)+options.indentation() + ")\n"
491  return result
492 
493  def dumpPythonAttributes(self, myname, options):
494  """ dumps the object with all attributes declared after the constructor"""
495  result = ""
496  for name in sorted(self.parameterNames_()):
497  param = self.__dict__[name]
498  result += options.indentation() + myname + "." + name + " = " + param.dumpPython(options) + "\n"
499  return result
500 
501  def nameInProcessDesc_(self, myname):
502  return myname;
503  def moduleLabel_(self, myname):
504  return myname
505  def appendToProcessDescList_(self, lst, myname):
506  lst.append(self.nameInProcessDesc_(myname))
507  def insertInto(self, parameterSet, myname):
508  newpset = parameterSet.newPSet()
509  newpset.addString(True, "@module_label", self.moduleLabel_(myname))
510  newpset.addString(True, "@module_type", self.type_())
511  newpset.addString(True, "@module_edm_type", type(self).__name__)
512  self.insertContentsInto(newpset)
513  parameterSet.addPSet(True, self.nameInProcessDesc_(myname), newpset)
514 
515 
516 
517 class _Labelable(object):
518  """A 'mixin' used to denote that the class can be paired with a label (e.g. an EDProducer)"""
519  def label_(self):
520  if not hasattr(self, "_Labelable__label"):
521  raise RuntimeError("module has no label. Perhaps it wasn't inserted into the process?")
522  return self.__label
523  def hasLabel_(self):
524  return hasattr(self, "_Labelable__label") and self.__label is not None
525  def setLabel(self,label):
526  if self.hasLabel_() :
527  if self.label_() != label and label is not None :
528  msg100 = "Attempting to change the label of a Labelable object, possibly an attribute of the Process\n"
529  msg101 = "Old label = "+self.label_()+" New label = "+label+"\n"
530  msg102 = "Type = "+str(type(self))+"\n"
531  msg103 = "Some possible solutions:\n"
532  msg104 = " 1. Clone modules instead of using simple assignment. Cloning is\n"
533  msg105 = " also preferred for other types when possible.\n"
534  msg106 = " 2. Declare new names starting with an underscore if they are\n"
535  msg107 = " for temporaries you do not want propagated into the Process. The\n"
536  msg108 = " underscore tells \"from x import *\" and process.load not to import\n"
537  msg109 = " the name.\n"
538  msg110 = " 3. Reorganize so the assigment is not necessary. Giving a second\n"
539  msg111 = " name to the same object usually causes confusion and problems.\n"
540  msg112 = " 4. Compose Sequences: newName = cms.Sequence(oldName)\n"
541  raise ValueError(msg100+msg101+msg102+msg103+msg104+msg105+msg106+msg107+msg108+msg109+msg110+msg111+msg112)
542  self.__label = label
543  def label(self):
544  #print "WARNING: _Labelable::label() needs to be changed to label_()"
545  return self.__label
546  def __str__(self):
547  #this is probably a bad idea
548  # I added this so that when we ask a path to print
549  # we will see the label that has been assigned
550  return str(self.__label)
552  return str(self.__label)
553  def dumpSequencePython(self, options=PrintOptions()):
554  if options.isCfg:
555  return 'process.'+str(self.__label)
556  else:
557  return str(self.__label)
558  def _findDependencies(self,knownDeps,presentDeps):
559  #print 'in labelled'
560  myDeps=knownDeps.get(self.label_(),None)
561  if myDeps!=None:
562  if presentDeps != myDeps:
563  raise RuntimeError("the module "+self.label_()+" has two dependencies \n"
564  +str(presentDeps)+"\n"
565  +str(myDeps)+"\n"
566  +"Please modify sequences to rectify this inconsistency")
567  else:
568  myDeps=set(presentDeps)
569  knownDeps[self.label_()]=myDeps
570  presentDeps.add(self.label_())
571 
572 
573 class _Unlabelable(object):
574  """A 'mixin' used to denote that the class can be used without a label (e.g. a Service)"""
575  pass
576 
577 class _ValidatingListBase(list):
578  """Base class for a list which enforces that its entries pass a 'validity' test"""
579  def __init__(self,*arg,**args):
580  super(_ValidatingListBase,self).__init__(arg)
581  if 0 != len(args):
582  raise SyntaxError("named arguments ("+','.join([x for x in args])+") passsed to "+str(type(self)))
583  if not self._isValid(iter(self)):
584  raise TypeError("wrong types ("+','.join([str(type(value)) for value in iter(self)])+
585  ") added to "+str(type(self)))
586  def __setitem__(self,key,value):
587  if isinstance(key,slice):
588  if not self._isValid(value):
589  raise TypeError("wrong type being inserted into this container "+self._labelIfAny())
590  else:
591  if not self._itemIsValid(value):
592  raise TypeError("can not insert the type "+str(type(value))+" in container "+self._labelIfAny())
593  super(_ValidatingListBase,self).__setitem__(key,value)
594  def _isValid(self,seq):
595  # see if strings get reinterpreted as lists
596  if isinstance(seq, str):
597  return False
598  for item in seq:
599  if not self._itemIsValid(item):
600  return False
601  return True
602  def _itemFromArgument(self, x):
603  return x
604  def _convertArguments(self, seq):
605  if isinstance(seq, str):
606  yield seq
607  for x in seq:
608  yield self._itemFromArgument(x)
609  def append(self,x):
610  if not self._itemIsValid(x):
611  raise TypeError("wrong type being appended to container "+self._labelIfAny())
612  super(_ValidatingListBase,self).append(self._itemFromArgument(x))
613  def extend(self,x):
614  if not self._isValid(x):
615  raise TypeError("wrong type being extended to container "+self._labelIfAny())
616  super(_ValidatingListBase,self).extend(self._convertArguments(x))
617  def __add__(self,rhs):
618  if not self._isValid(rhs):
619  raise TypeError("wrong type being added to container "+self._labelIfAny())
620  import copy
621  value = copy.copy(self)
622  value.extend(rhs)
623  return value
624  def insert(self,i,x):
625  if not self._itemIsValid(x):
626  raise TypeError("wrong type being inserted to container "+self._labelIfAny())
627  super(_ValidatingListBase,self).insert(i,self._itemFromArgument(x))
628  def _labelIfAny(self):
629  result = type(self).__name__
630  if hasattr(self, '__label'):
631  result += ' ' + self.__label
632  return result
633 
635  def __init__(self,*arg,**args):
636  _ParameterTypeBase.__init__(self)
637  if len (arg) == 1 and not isinstance(arg[0],str):
638  try:
639  arg = iter(arg[0])
640  except TypeError:
641  pass
642  super(_ValidatingParameterListBase,self).__init__(*arg,**args)
643  def value(self):
644  return list(self)
645  def setValue(self,v):
646  self[:] = []
647  self.extend(v)
648  self._isModified=True
649  def configValue(self, options=PrintOptions()):
650  config = '{\n'
651  first = True
652  for value in iter(self):
653  options.indent()
654  config += options.indentation()
655  if not first:
656  config+=', '
657  config+= self.configValueForItem(value, options)+'\n'
658  first = False
659  options.unindent()
660  config += options.indentation()+'}\n'
661  return config
662  def configValueForItem(self,item, options):
663  return str(item)
664  def pythonValueForItem(self,item, options):
665  return self.configValueForItem(item, options)
666  def __repr__(self):
667  return self.dumpPython()
668  def dumpPython(self, options=PrintOptions()):
669  specialImportRegistry.registerUse(self)
670  result = self.pythonTypeName()+"("
671  n = len(self)
672  if hasattr(self, "_nPerLine"):
673  nPerLine = self._nPerLine
674  else:
675  nPerLine = 5
676  if n>nPerLine: options.indent()
677  if n>=256:
678  #wrap in a tuple since they don't have a size constraint
679  result+=" ("
680  for i, v in enumerate(self):
681  if i == 0:
682  if n>nPerLine: result += '\n'+options.indentation()
683  else:
684  if i % nPerLine == 0:
685  result += ',\n'+options.indentation()
686  else:
687  result += ', '
688  result += self.pythonValueForItem(v,options)
689  if n>nPerLine:
690  options.unindent()
691  result += '\n'+options.indentation()
692  if n>=256:
693  result +=' ) '
694  result += ')'
695  return result
697  return []
698  @staticmethod
699  def _itemsFromStrings(strings,converter):
700  return (converter(x).value() for x in strings)
701 
702 def saveOrigin(obj, level):
703  import sys
704  fInfo = inspect.getframeinfo(sys._getframe(level+1))
705  obj._filename = fInfo.filename
706  obj._lineNumber =fInfo.lineno
707 
708 def _modifyParametersFromDict(params, newParams, errorRaiser, keyDepth=""):
709  if len(newParams):
710  #need to treat items both in params and myparams specially
711  for key,value in newParams.items():
712  if key in params:
713  if value is None:
714  del params[key]
715  elif isinstance(value, dict):
716  if isinstance(params[key],_Parameterizable):
717  pset = params[key]
718  p =pset.parameters_()
719  oldkeys = set(p.keys())
721  value,errorRaiser,
722  ("%s.%s" if isinstance(key, str) else "%s[%s]")%(keyDepth,key))
723  for k,v in p.items():
724  setattr(pset,k,v)
725  oldkeys.discard(k)
726  for k in oldkeys:
727  delattr(pset,k)
728  elif isinstance(params[key],_ValidatingParameterListBase):
729  if any(not isinstance(k, int) for k in value.keys()):
730  raise TypeError("Attempted to change a list using a dict whose keys are not integers")
731  plist = params[key]
732  if any((k < 0 or k >= len(plist)) for k in value.keys()):
733  raise IndexError("Attempted to set an index which is not in the list")
734  p = dict(enumerate(plist))
736  value,errorRaiser,
737  ("%s.%s" if isinstance(key, str) else "%s[%s]")%(keyDepth,key))
738  for k,v in p.items():
739  plist[k] = v
740  else:
741  raise ValueError("Attempted to change non PSet value "+keyDepth+" using a dictionary")
742  elif isinstance(value,_ParameterTypeBase) or (isinstance(key, int)) or isinstance(value, _Parameterizable):
743  params[key] = value
744  else:
745  params[key].setValue(value)
746  else:
747  if isinstance(value,_ParameterTypeBase) or isinstance(value, _Parameterizable):
748  params[key]=value
749  else:
750  errorRaiser(key)
751 
752 
753 if __name__ == "__main__":
754 
755  import unittest
757  def _itemIsValid(self,item):
758  return True
759  class testMixins(unittest.TestCase):
761  t = TestList(1)
762  self.assertEqual(t,[1])
763  t = TestList((1,))
764  self.assertEqual(t,[1])
765  t = TestList("one")
766  self.assertEqual(t,["one"])
767  t = TestList( [1,])
768  self.assertEqual(t,[1])
769  t = TestList( (x for x in [1]) )
770  self.assertEqual(t,[1])
771 
772  t = TestList(1,2)
773  self.assertEqual(t,[1,2])
774  t = TestList((1,2))
775  self.assertEqual(t,[1,2])
776  t = TestList("one","two")
777  self.assertEqual(t,["one","two"])
778  t = TestList(("one","two"))
779  self.assertEqual(t,["one","two"])
780  t = TestList( [1,2])
781  self.assertEqual(t,[1,2])
782  t = TestList( (x for x in [1,2]) )
783  self.assertEqual(t,[1,2])
784  t = TestList( iter((1,2)) )
785  self.assertEqual(t,[1,2])
786 
787 
788  def testLargeList(self):
789  #lists larger than 255 entries can not be initialized
790  #using the constructor
791  args = [i for i in range(0,300)]
792 
793  t = TestList(*args)
794  pdump= t.dumpPython()
795  class cms(object):
796  def __init__(self):
797  self.TestList = TestList
798  pythonized = eval( pdump, globals(),{'cms':cms()} )
799  self.assertEqual(t,pythonized)
800  def testUsingBlock(self):
801  a = UsingBlock("a")
802  self.assertTrue(isinstance(a, _ParameterTypeBase))
803  def testConstruction(self):
804  class __Test(_TypedParameterizable):
805  pass
806  class __TestType(_SimpleParameterTypeBase):
807  def _isValid(self,value):
808  return True
809  class __PSet(_ParameterTypeBase,_Parameterizable):
810  def __init__(self,*arg,**args):
811  #need to call the inits separately
812  _ParameterTypeBase.__init__(self)
813  _Parameterizable.__init__(self,*arg,**args)
814 
815  a = __Test("MyType", __PSet(a=__TestType(1)))
816  self.assertEqual(a.a.value(), 1)
817  b = __Test("MyType", __PSet(a=__TestType(1)), __PSet(b=__TestType(2)))
818  self.assertEqual(b.a.value(), 1)
819  self.assertEqual(b.b.value(), 2)
820  self.assertRaises(ValueError, lambda: __Test("MyType", __PSet(a=__TestType(1)), __PSet(a=__TestType(2))))
821 
822  def testCopy(self):
823  class __Test(_TypedParameterizable):
824  pass
825  class __TestType(_SimpleParameterTypeBase):
826  def _isValid(self,value):
827  return True
828  a = __Test("MyType",t=__TestType(1), u=__TestType(2))
829  b = a.copy()
830  self.assertEqual(b.t.value(),1)
831  self.assertEqual(b.u.value(),2)
832 
833  c = __Test("MyType")
834  self.assertEqual(len(c.parameterNames_()), 0)
835  d = c.copy()
836  self.assertEqual(len(d.parameterNames_()), 0)
837  def testClone(self):
838  class __Test(_TypedParameterizable):
839  pass
840  class __TestType(_SimpleParameterTypeBase):
841  def _isValid(self,value):
842  return True
843  class __PSet(_ParameterTypeBase,_Parameterizable):
844  def __init__(self,*arg,**args):
845  #need to call the inits separately
846  _ParameterTypeBase.__init__(self)
847  _Parameterizable.__init__(self,*arg,**args)
848  def dumpPython(self,options=PrintOptions()):
849  return "__PSet(\n"+_Parameterizable.dumpPython(self, options)+options.indentation()+")"
850 
851  a = __Test("MyType",
852  t=__TestType(1),
853  u=__TestType(2),
854  w = __TestType(3),
855  x = __PSet(a = __TestType(4),
856  b = __TestType(6),
857  c = __PSet(gamma = __TestType(5))))
858  b = a.clone(t=3,
859  v=__TestType(4),
860  w= None,
861  x = dict(a = 7,
862  c = dict(gamma = 8),
863  d = __TestType(9)))
864  c = a.clone(x = dict(a=None, c=None))
865  self.assertEqual(a.t.value(),1)
866  self.assertEqual(a.u.value(),2)
867  self.assertEqual(b.t.value(),3)
868  self.assertEqual(b.u.value(),2)
869  self.assertEqual(b.v.value(),4)
870  self.assertEqual(b.x.a.value(),7)
871  self.assertEqual(b.x.b.value(),6)
872  self.assertEqual(b.x.c.gamma.value(),8)
873  self.assertEqual(b.x.d.value(),9)
874  self.assertEqual(hasattr(b,"w"), False)
875  self.assertEqual(hasattr(c.x,"a"), False)
876  self.assertEqual(hasattr(c.x,"c"), False)
877  self.assertRaises(TypeError,a.clone,**{"v":1})
878  d = a.clone(__PSet(k=__TestType(42)))
879  self.assertEqual(d.t.value(), 1)
880  self.assertEqual(d.k.value(), 42)
881  d2 = a.clone(__PSet(t=__TestType(42)))
882  self.assertEqual(d2.t.value(), 42)
883  d3 = a.clone(__PSet(t=__TestType(42)),
884  __PSet(u=__TestType(56)))
885  self.assertEqual(d3.t.value(), 42)
886  self.assertEqual(d3.u.value(), 56)
887  self.assertRaises(ValueError,a.clone,
888  __PSet(t=__TestType(42)),
889  __PSet(t=__TestType(56)))
890  d4 = a.clone(__PSet(t=__TestType(43)), u = 57)
891  self.assertEqual(d4.t.value(), 43)
892  self.assertEqual(d4.u.value(), 57)
893  self.assertRaises(TypeError,a.clone,t=__TestType(43),**{"doesNotExist":57})
894 
895  e = __Test("MyType")
896  self.assertEqual(len(e.parameterNames_()), 0)
897  f = e.clone(__PSet(a = __TestType(1)), b = __TestType(2))
898  self.assertEqual(f.a.value(), 1)
899  self.assertEqual(f.b.value(), 2)
900  g = e.clone()
901  self.assertEqual(len(g.parameterNames_()), 0)
902 
903  def testModified(self):
904  class __TestType(_SimpleParameterTypeBase):
905  def _isValid(self,value):
906  return True
907  a = __TestType(1)
908  self.assertEqual(a.isModified(),False)
909  a.setValue(1)
910  self.assertEqual(a.isModified(),False)
911  a.setValue(2)
912  self.assertEqual(a.isModified(),True)
913  a.resetModified()
914  self.assertEqual(a.isModified(),False)
917  pass
919  def _isValid(self,value):
920  return True
921  class __DummyModule(object):
922  def __init__(self):
923  self.tLPTest = tLPTest
924  self.tLPTestType = tLPTestType
925  p = tLPTest("MyType",** dict( [ ("a"+str(x), tLPTestType(x)) for x in range(0,300) ] ) )
926  #check they are the same
927  self.assertEqual(p.dumpPython(), eval(p.dumpPython(),{"cms": __DummyModule()}).dumpPython())
929  reg = _SpecialImportRegistry()
930  reg.registerSpecialImportForType(int, "import foo")
931  self.assertRaises(RuntimeError, lambda: reg.registerSpecialImportForType(int, "import bar"))
932  reg.registerSpecialImportForType(str, "import bar")
933  self.assertEqual(reg.getSpecialImports(), [])
934  reg.registerUse([1])
935  self.assertEqual(reg.getSpecialImports(), [])
936  reg.registerUse(1)
937  self.assertEqual(reg.getSpecialImports(), ["import foo"])
938  reg.registerUse(1)
939  self.assertEqual(reg.getSpecialImports(), ["import foo"])
940  reg.registerUse("a")
941  self.assertEqual(reg.getSpecialImports(), ["import bar", "import foo"])
942 
943  unittest.main()
bool any(const std::vector< T > &v, const T &what)
Definition: ECalSD.cc:37
def _valueFromString
Definition: Mixins.py:147
def testUsingBlock
Definition: Mixins.py:800
bool setValue(Container &, const reco::JetBaseRef &, const JetExtendedData &)
associate jet with value. Returns false and associate nothing if jet is already associated ...
def dumpSequenceConfig
Definition: Mixins.py:551
const uint16_t range(const Frame &aFrame)
def saveOrigin
Definition: Mixins.py:702
if(conf_.getParameter< bool >("UseStripCablingDB"))
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def testListConstruction
Definition: Mixins.py:760
Definition: value.py:1
Namespace of DDCMS conversion namespace.
def dumpSequencePython
Definition: Mixins.py:553
static std::string join(char **cmd)
Definition: RemoteFile.cc:19
def _itemIsValid
Definition: Mixins.py:757
def _modifyParametersFromDict
Definition: Mixins.py:708
def testConstruction
Definition: Mixins.py:803
def _findDependencies
Definition: Mixins.py:558
def testSpecialImportRegistry
Definition: Mixins.py:928
def testLargeParameterizable
Definition: Mixins.py:915
#define str(s)