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