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