1 from __future__
import print_function
2 from builtins
import range, object
6 """Denotes a class that can be used by the Processes class""" 11 def __init__(self, indent = 0, deltaIndent = 4, process = True, targetDirectory = None, useSubdirectories = False):
25 """This class collects special import statements of configuration types""" 34 className = cls.__name__
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]
40 className = obj.__class__.__name__
56 """base class for classes which are used as the 'parameters' for a ParameterSet""" 58 self.__dict__[
"_isFrozen"] =
False 67 return type(self).__name__
68 return 'untracked '+type(self).__name__
71 return 'cms.'+type(self).__name__
72 return 'cms.untracked.'+type(self).__name__
74 specialImportRegistry.registerUse(self)
87 return isinstance(self,aType)
90 """base class for parameter classes which only hold a single value""" 92 super(_SimpleParameterTypeBase,self).
__init__()
94 if not self._isValid(value):
95 raise ValueError(
str(value)+
" is not a valid "+
str(type(self)))
99 if not self._isValid(value):
100 raise ValueError(
str(value)+
" is not a valid "+
str(type(self)))
109 if isinstance(other,_SimpleParameterTypeBase):
110 return self.
_value == other._value
111 return self.
_value == other
113 if isinstance(other,_SimpleParameterTypeBase):
114 return self.
_value != other._value
115 return self.
_value != other
117 if isinstance(other,_SimpleParameterTypeBase):
118 return self.
_value < other._value
119 return self.
_value < other
121 if isinstance(other,_SimpleParameterTypeBase):
122 return self.
_value <= other._value
123 return self.
_value <= other
125 if isinstance(other,_SimpleParameterTypeBase):
126 return self.
_value > other._value
127 return self.
_value > other
129 if isinstance(other,_SimpleParameterTypeBase):
130 return self.
_value >= other._value
131 return self.
_value >= other
135 """For injection purposes, pretend this is a new parameter type 136 then have a post process step which strips these out 139 super(UsingBlock,self).
__init__(value)
146 return isinstance(value,str)
148 """only used for cfg-parsing""" 155 parameterSet.addString(self.
isTracked(), myname, value)
158 return "process."+self.
value()
164 """Base class for classes which allow addition of _ParameterTypeBase data""" 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""" 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__)
181 """Returns the name of the parameters""" 182 return self.__parameterNames[:]
187 param = self.__dict__[name]
188 if isinstance(param, _Parameterizable)
and param.isModified():
197 check that pset provided has the attribute chain 200 Eg, if params is [ 'attr1', 'attr2', 'attr3' ] 201 check for pset.attr1.attr2.attr3 203 returns True if parameter exists, False if not 211 Retrieve the specified parameter from the PSet Provided 212 given the attribute chain 214 returns None if not found 218 if type(params).__name__ ==
'str':
219 return getattr(self, params,
None)
221 lastParam = getattr(lastParam, param,
None)
222 if lastParam ==
None:
227 """Returns a dictionary of copies of the user-set parameters""" 231 result[name]=copy.deepcopy(self.__dict__[name])
235 if name ==
'allowAnyLabel_':
239 if not isinstance(value,_ParameterTypeBase):
244 if name
in self.__dict__:
245 message =
"Duplicate insert of member " + name
246 message +=
"\nThe original parameters are:\n" 248 raise ValueError(message)
249 self.__dict__[name]=value
250 self.__parameterNames.
append(name)
255 for name,value
in parameters.items():
256 if name ==
'allowAnyLabel_':
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" 270 raise ValueError(message)
273 super(_Parameterizable,self).
__setattr__(name,value)
274 elif not name
in self.__dict__:
279 if isinstance(value,_ParameterTypeBase):
280 self.__dict__[name] = value
293 raise ValueError(
"Object already added to a process. It is read only now")
295 self.__parameterNames.
remove(name)
298 raise TypeError(name+
" does not already exist, so it can only be set to a CMS python configuration type")
300 specialImportRegistry.registerUse(self)
302 if len(sortedNames) > 200:
311 for name
in sortedNames:
312 param = self.__dict__[name]
314 name2 = name.replace(
'-',
'_')
317 if name.startswith(
"using_"):
318 usings.append(options.indentation()+param.dumpPython(options))
320 others.append((name2, param.dumpPython(options)))
323 resultList =
',\n'.
join(usings)
324 longOthers = options.indentation()+
"**dict(\n" 326 longOthers += options.indentation()+
"[\n" 331 if entriesInList > 200:
334 longOthers += options.indentation()+
"] +\n"+options.indentation()+
"[\n" 337 longOthers += options.indentation()+
'("'+n+
'" , '+v+
' ),\n' 339 longOthers += options.indentation()+
"]\n" 341 longOthers +=options.indentation()+
")\n" 345 ret.append(resultList)
347 ret.append(longOthers)
348 return ",\n".
join(ret)
352 for name
in sortedNames:
353 param = self.__dict__[name]
355 name2 = name.replace(
'-',
'_')
358 if name.startswith(
"using_"):
359 usings.append(options.indentation()+param.dumpPython(options))
361 others.append(options.indentation()+name2+
' = '+param.dumpPython(options))
365 resultList.extend(others)
370 return ',\n'.
join(resultList)+
'\n' 375 param = getattr(self,name)
376 param.insertInto(parameterSet, name)
380 """Base class for classes which are Parameterizable and have a 'type' assigned""" 382 self.__dict__[
'_TypedParameterizable__type'] = type_
388 super(_TypedParameterizable,self).
__init__(*arg,**kargs)
391 self._placeImpl(name,proc)
393 """returns the type of the object, e.g. 'FooProducer'""" 396 returnValue =_TypedParameterizable.__new__(type(self))
398 returnValue.__init__(self.__type,**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)) ) 413 returnValue =_TypedParameterizable.__new__(type(self))
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_():
428 if self._Parameterizable__validator
is not None:
429 myparams[
"allowAnyLabel_"] = self._Parameterizable__validator
431 returnValue.__init__(self.__type,*args,
433 returnValue._isModified =
False 434 returnValue._isFrozen =
False 445 choices.extend(glob.glob(d+
'/*/*/'+label+
'.py'))
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):
464 for name
in default.parameterNames_():
465 params[name] = getattr(default,name)
473 config = self.__type +
' { \n' 475 param = self.__dict__[name]
477 config+=options.indentation()+param.configTypeName()+
' '+name+
' = '+param.configValue(options)+
'\n' 479 config += options.indentation()+
'}\n' 483 specialImportRegistry.registerUse(self)
484 result =
"cms."+
str(type(self).__name__)+
'("'+self.
type_()+
'"' 489 result +=
",\n"+_Parameterizable.dumpPython(self,options)+options.indentation() +
")\n" 493 """ dumps the object with all attributes declared after the constructor""" 496 param = self.__dict__[name]
497 result += options.indentation() + myname +
"." + name +
" = " + param.dumpPython(options) +
"\n" 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__)
517 """A 'mixin' used to denote that the class can be paired with a label (e.g. an EDProducer)""" 519 if not hasattr(self,
"_Labelable__label"):
520 raise RuntimeError(
"module has no label. Perhaps it wasn't inserted into the process?")
523 return hasattr(self,
"_Labelable__label")
and self.
__label is not None 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)
559 myDeps=knownDeps.get(self.
label_(),
None)
561 if presentDeps != myDeps:
562 raise RuntimeError(
"the module "+self.
label_()+
" has two dependencies \n" 563 +
str(presentDeps)+
"\n" 565 +
"Please modify sequences to rectify this inconsistency")
567 myDeps=set(presentDeps)
568 knownDeps[self.
label_()]=myDeps
569 presentDeps.add(self.
label_())
573 """A 'mixin' used to denote that the class can be used without a label (e.g. a Service)""" 576 class _ValidatingListBase(list):
577 """Base class for a list which enforces that its entries pass a 'validity' test""" 579 super(_ValidatingListBase,self).
__init__(arg)
581 raise SyntaxError(
"named arguments ("+
','.
join([x
for x
in args])+
") passsed to "+
str(type(self)))
583 raise TypeError(
"wrong types ("+
','.
join([
str(type(value))
for value
in iter(self)])+
584 ") added to "+
str(type(self)))
586 if isinstance(key,slice):
588 raise TypeError(
"wrong type being inserted into this container "+self.
_labelIfAny())
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)
595 if isinstance(seq, str):
598 if not self._itemIsValid(item):
604 if isinstance(seq, str):
609 if not self._itemIsValid(x):
610 raise TypeError(
"wrong type being appended to container "+self.
_labelIfAny())
614 raise TypeError(
"wrong type being extended to container "+self.
_labelIfAny())
618 raise TypeError(
"wrong type being added to container "+self.
_labelIfAny())
620 value = copy.copy(self)
624 if not self._itemIsValid(x):
625 raise TypeError(
"wrong type being inserted to container "+self.
_labelIfAny())
628 result = type(self).__name__
629 if hasattr(self,
'__label'):
630 result +=
' ' + self.__label
635 _ParameterTypeBase.__init__(self)
636 if len (arg) == 1
and not isinstance(arg[0],str):
641 super(_ValidatingParameterListBase,self).
__init__(*arg,**args)
651 for value
in iter(self):
653 config += options.indentation()
659 config += options.indentation()+
'}\n' 668 specialImportRegistry.registerUse(self)
671 if hasattr(self,
"_nPerLine"):
672 nPerLine = self._nPerLine
675 if n>nPerLine: options.indent()
679 for i, v
in enumerate(self):
681 if n>nPerLine: result +=
'\n'+options.indentation()
683 if i % nPerLine == 0:
684 result +=
',\n'+options.indentation()
690 result +=
'\n'+options.indentation()
703 fInfo = inspect.getframeinfo(sys._getframe(level+1))
704 obj._filename = fInfo.filename
705 obj._lineNumber =fInfo.lineno
710 for key,value
in newParams.items():
714 elif isinstance(value, dict):
715 if isinstance(params[key],_Parameterizable):
717 p =pset.parameters_()
718 oldkeys = set(p.keys())
721 (
"%s.%s" if isinstance(key, str)
else "%s[%s]")%(keyDepth,key))
722 for k,v
in p.items():
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")
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))
736 (
"%s.%s" if isinstance(key, str)
else "%s[%s]")%(keyDepth,key))
737 for k,v
in p.items():
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):
746 if isinstance(value,_ParameterTypeBase)
or isinstance(value, _Parameterizable):
752 if __name__ ==
"__main__":
761 self.assertEqual(t,[1])
763 self.assertEqual(t,[1])
765 self.assertEqual(t,[
"one"])
767 self.assertEqual(t,[1])
769 self.assertEqual(t,[1])
772 self.assertEqual(t,[1,2])
774 self.assertEqual(t,[1,2])
776 self.assertEqual(t,[
"one",
"two"])
778 self.assertEqual(t,[
"one",
"two"])
780 self.assertEqual(t,[1,2])
782 self.assertEqual(t,[1,2])
784 self.assertEqual(t,[1,2])
790 args = [i
for i
in range(0,300)]
793 pdump= t.dumpPython()
797 pythonized = eval( pdump, globals(),{
'cms':
cms()} )
798 self.assertEqual(t,pythonized)
801 self.assertTrue(isinstance(a, _ParameterTypeBase))
806 def _isValid(self,value):
811 _ParameterTypeBase.__init__(self)
812 _Parameterizable.__init__(self,*arg,**args)
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))))
825 def _isValid(self,value):
827 a = __Test(
"MyType",t=__TestType(1), u=__TestType(2))
829 self.assertEqual(b.t.value(),1)
830 self.assertEqual(b.u.value(),2)
833 self.assertEqual(len(c.parameterNames_()), 0)
835 self.assertEqual(len(d.parameterNames_()), 0)
840 def _isValid(self,value):
845 _ParameterTypeBase.__init__(self)
846 _Parameterizable.__init__(self,*arg,**args)
848 return "__PSet(\n"+_Parameterizable.dumpPython(self, options)+options.indentation()+
")" 854 x = __PSet(a = __TestType(4),
856 c = __PSet(gamma = __TestType(5))))
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})
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)
900 self.assertEqual(len(g.parameterNames_()), 0)
904 def _isValid(self,value):
907 self.assertEqual(a.isModified(),
False)
909 self.assertEqual(a.isModified(),
False)
911 self.assertEqual(a.isModified(),
True)
913 self.assertEqual(a.isModified(),
False)
918 def _isValid(self,value):
920 class __DummyModule(
object):
926 self.assertEqual(p.dumpPython(), eval(p.dumpPython(),{
"cms": __DummyModule()}).
dumpPython())
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(), [])
934 self.assertEqual(reg.getSpecialImports(), [])
936 self.assertEqual(reg.getSpecialImports(), [
"import foo"])
938 self.assertEqual(reg.getSpecialImports(), [
"import foo"])
940 self.assertEqual(reg.getSpecialImports(), [
"import bar",
"import foo"])
def __init__(self, arg, args)
def testSpecialImportRegistry(self)
def getSpecialImports(self)
def moduleLabel_(self, myname)
def dumpPython(self, options=PrintOptions())
def dumpConfig(self, options=PrintOptions())
def insertInto(self, parameterSet, myname)
def _modifyParametersFromDict(params, newParams, errorRaiser, keyDepth="")
def __setParameters(self, parameters)
def _findDependencies(self, knownDeps, presentDeps)
def dumpPython(self, options=PrintOptions())
bool any(const std::vector< T > &v, const T &what)
def _itemFromArgument(self, x)
def dumpPython(self, options=PrintOptions())
def __init__(self, arg, kargs)
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 dumpPythonAttributes(self, myname, options)
def _valueFromString(value)
def testConstruction(self)
def setLabel(self, label)
def registerUse(self, obj)
def nameInProcessDesc_(self, myname)
bool setValue(Container &, const reco::JetBaseRef &, const JetExtendedData &)
associate jet with value. Returns false and associate nothing if jet is already associated ...
def isCompatibleCMSType(self, aType)
def dumpPython(self, options=PrintOptions())
def testListConstruction(self)
def insertInto(self, parameterSet, myname)
def _convertArguments(self, seq)
def dumpPython(self, options=PrintOptions())
def __delattr__(self, name)
def _itemsFromStrings(strings, converter)
def clone(self, args, params)
def directDependencies(self)
def dumpSequenceConfig(self)
def directDependencies(self)
def __init__(self, type_, arg, kargs)
def testLargeParameterizable(self)
def __init__(self, value, s='', loc=0, file='')
def __init__(self, indent=0, deltaIndent=4, process=True, targetDirectory=None, useSubdirectories=False)
def __addParameter(self, name, value)
def _place(self, name, proc)
def __findDefaultsFor(label, type)
def __setattr__(self, name, value)
def saveOrigin(obj, level)
def __raiseBadSetAttr(name)
def registerSpecialImportForType(self, cls, impStatement)
Namespace of DDCMS conversion namespace.
def configValue(self, options=PrintOptions())
def _itemIsValid(self, item)
def split(sequence, size)
def configValue(self, options=PrintOptions())
def setIsTracked(self, trackness)
static std::string join(char **cmd)
def hasParameter(self, params)
def setValue(self, value)
def parameterNames_(self)
def dumpPython(process, name)
def remove(d, key, TELL=False)
def pythonValueForItem(self, item, options)
def __setitem__(self, key, value)
def pythonValue(self, options=PrintOptions())
def configValueForItem(self, item, options)
def __init__(self, value)
def getParameter(self, params)
def appendToProcessDescList_(self, lst, myname)
def insertContentsInto(self, parameterSet)
def dumpSequencePython(self, options=PrintOptions())
def __init__(self, arg, args)