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