1 from __future__
import print_function
2 from builtins
import range, object
4 from typing
import Union
7 """Denotes a class that can be used by the Processes class""" 12 def __init__(self, indent:int = 0, deltaIndent:int = 4, process:bool =
True, targetDirectory: Union[str,
None] =
None, useSubdirectories:bool =
False):
26 """This class collects special import statements of configuration types""" 35 className = cls.__name__
37 raise RuntimeError(
"Error: the configuration type '%s' already has an import statement registered '%s'" % (className, self.
_registry[className][0]))
38 self.
_registry[className] = [impStatement,
False]
41 className = obj.__class__.__name__
57 """base class for classes which are used as the 'parameters' for a ParameterSet""" 59 self.__dict__[
"_isFrozen"] =
False 68 return type(self).__name__
69 return 'untracked '+type(self).__name__
72 return 'cms.'+type(self).__name__
73 return 'cms.untracked.'+type(self).__name__
75 specialImportRegistry.registerUse(self)
88 return isinstance(self,aType)
90 if isinstance(valueWithType, type(self)):
92 raise TypeError(
"Attempted to assign type {from_} to type {to}".
format(from_ =
str(type(valueWithType)), to =
str(type(self))) )
96 """base class for parameter classes which only hold a single value""" 98 super(_SimpleParameterTypeBase,self).
__init__()
100 if not self._isValid(value):
101 raise ValueError(
str(value)+
" is not a valid "+
str(type(self)))
105 if not self._isValid(value):
106 raise ValueError(
str(value)+
" is not a valid "+
str(type(self)))
115 if isinstance(other,_SimpleParameterTypeBase):
116 return self.
_value == other._value
117 return self.
_value == other
119 if isinstance(other,_SimpleParameterTypeBase):
120 return self.
_value != other._value
121 return self.
_value != other
123 if isinstance(other,_SimpleParameterTypeBase):
124 return self.
_value < other._value
125 return self.
_value < other
127 if isinstance(other,_SimpleParameterTypeBase):
128 return self.
_value <= other._value
129 return self.
_value <= other
131 if isinstance(other,_SimpleParameterTypeBase):
132 return self.
_value > other._value
133 return self.
_value > other
135 if isinstance(other,_SimpleParameterTypeBase):
136 return self.
_value >= other._value
137 return self.
_value >= other
141 """For injection purposes, pretend this is a new parameter type 142 then have a post process step which strips these out 144 def __init__(self,value, s:str=
'', loc:int=0, file:str=
''):
145 super(UsingBlock,self).
__init__(value)
152 return isinstance(value,str)
154 """only used for cfg-parsing""" 161 parameterSet.addString(self.
isTracked(), myname, value)
164 return "process."+self.
value()
170 """Base class for classes which allow addition of _ParameterTypeBase data""" 172 self.__dict__[
'_Parameterizable__parameterNames'] = []
173 self.__dict__[
"_isFrozen"] =
False 174 self.__dict__[
'_Parameterizable__validator'] =
None 175 """The named arguments are the 'parameters' which are added as 'python attributes' to the object""" 182 """Returns the name of the parameters""" 183 return self.__parameterNames[:]
188 param = self.__dict__[name]
189 if isinstance(param, _Parameterizable)
and param.isModified():
198 check that pset provided has the attribute chain 201 Eg, if params is [ 'attr1', 'attr2', 'attr3' ] 202 check for pset.attr1.attr2.attr3 204 returns True if parameter exists, False if not 212 Retrieve the specified parameter from the PSet Provided 213 given the attribute chain 215 returns None if not found 219 if type(params).__name__ ==
'str':
220 return getattr(self, params,
None)
222 lastParam = getattr(lastParam, param,
None)
223 if lastParam ==
None:
228 """Returns a dictionary of copies of the user-set parameters""" 232 result[name]=copy.deepcopy(self.__dict__[name])
236 if name ==
'allowAnyLabel_':
240 if not isinstance(value,_ParameterTypeBase):
245 if name
in self.__dict__:
246 message =
"Duplicate insert of member " + name
247 message +=
"\nThe original parameters are:\n" 249 raise ValueError(message)
250 self.__dict__[name]=value
251 self.__parameterNames.
append(name)
256 if type(block).__name__
not in [
"PSet",
"__PSet",
"dict"]:
257 raise ValueError(
"Only PSets can be passed as unnamed argument blocks. This is a "+type(block).__name__)
258 if isinstance(block,dict):
265 for name,value
in parameters.items():
266 if name ==
'allowAnyLabel_':
275 if self.
isFrozen()
and not (name
in [
"_Labelable__label",
"_isFrozen"]
or name.startswith(
'_')):
276 message =
"Object already added to a process. It is read only now\n" 277 message +=
" %s = %s" %(name, value)
278 message +=
"\nThe original parameters are:\n" 280 raise ValueError(message)
283 super(_Parameterizable,self).
__setattr__(name,value)
284 elif not name
in self.__dict__:
289 if isinstance(value,_ParameterTypeBase):
290 self.__dict__[name] = self.__dict__[name]._checkAndReturnValueWithType(value)
295 """"Takes a PSet or dict and adds the entries as parameters. Already existing parameters will be overwritten. 297 if type(d).__name__
not in [
"PSet",
"__PSet",
"dict"]:
298 raise ValueError(
"Only PSets or dicts can be passed to update_. This is a "+type(d).__name__)
300 items = d.items()
if isinstance(d, dict)
else d.parameters_().
items()
314 raise ValueError(
"Object already added to a process. It is read only now")
316 self.__parameterNames.
remove(name)
319 raise TypeError(name+
" does not already exist, so it can only be set to a CMS python configuration type")
321 specialImportRegistry.registerUse(self)
323 if len(sortedNames) > 200:
332 for name
in sortedNames:
333 param = self.__dict__[name]
335 name2 = name.replace(
'-',
'_')
338 if name.startswith(
"using_"):
339 usings.append(options.indentation()+param.dumpPython(options))
341 others.append((name2, param.dumpPython(options)))
344 resultList =
',\n'.
join(usings)
345 longOthers = options.indentation()+
"**dict(\n" 347 longOthers += options.indentation()+
"[\n" 352 if entriesInList > 200:
355 longOthers += options.indentation()+
"] +\n"+options.indentation()+
"[\n" 358 longOthers += options.indentation()+
'("'+n+
'" , '+v+
' ),\n' 360 longOthers += options.indentation()+
"]\n" 362 longOthers +=options.indentation()+
")\n" 366 ret.append(resultList)
368 ret.append(longOthers)
369 return ",\n".
join(ret)
373 for name
in sortedNames:
374 param = self.__dict__[name]
376 name2 = name.replace(
'-',
'_')
379 if name.startswith(
"using_"):
380 usings.append(options.indentation()+param.dumpPython(options))
382 others.append(options.indentation()+name2+
' = '+param.dumpPython(options))
386 resultList.extend(others)
391 return ',\n'.
join(resultList)+
'\n' 396 param = getattr(self,name)
397 param.insertInto(parameterSet, name)
401 """Base class for classes which are Parameterizable and have a 'type' assigned""" 403 self.__dict__[
'_TypedParameterizable__type'] = type_
409 super(_TypedParameterizable,self).
__init__(*arg,**kargs)
412 self._placeImpl(name,proc)
414 """returns the type of the object, e.g. 'FooProducer'""" 417 returnValue =_TypedParameterizable.__new__(type(self))
419 returnValue.__init__(self.__type,**params)
423 """Copies the object and allows one to modify the parameters of the clone. 424 New parameters may be added by specify the exact type 425 Modifying existing parameters can be done by just specifying the new 426 value without having to specify the type. 427 A parameter may be removed from the clone using the value None. 428 #remove the parameter foo.fred 429 mod.toModify(foo, fred = None) 430 A parameter embedded within a PSet may be changed via a dictionary 431 #change foo.fred.pebbles to 3 and foo.fred.friend to "barney" 432 mod.toModify(foo, fred = dict(pebbles = 3, friend = "barney)) ) 434 returnValue =_TypedParameterizable.__new__(type(self))
440 if type(block).__name__
not in [
"PSet",
"__PSet"]:
441 raise ValueError(
"Only PSets can be passed as unnamed argument blocks. This is a "+type(block).__name__)
442 for name
in block.parameterNames_():
449 if self._Parameterizable__validator
is not None:
450 myparams[
"allowAnyLabel_"] = self._Parameterizable__validator
452 returnValue.__init__(self.__type,*args,
454 returnValue._isModified =
False 455 returnValue._isFrozen =
False 466 choices.extend(glob.glob(d+
'/*/*/'+label+
'.py'))
476 mod = __import__(name)
477 components = name.split(
'.')
478 for comp
in components[1:]:
479 mod = getattr(mod,comp)
480 if hasattr(mod,label):
481 default = getattr(mod,label)
482 if isinstance(default,_TypedParameterizable):
483 if(default.type_() == type):
485 for name
in default.parameterNames_():
486 params[name] = getattr(default,name)
494 config = self.__type +
' { \n' 496 param = self.__dict__[name]
498 config+=options.indentation()+param.configTypeName()+
' '+name+
' = '+param.configValue(options)+
'\n' 500 config += options.indentation()+
'}\n' 504 specialImportRegistry.registerUse(self)
505 result =
"cms."+
str(type(self).__name__)+
'("'+self.
type_()+
'"' 510 result +=
",\n"+_Parameterizable.dumpPython(self,options)+options.indentation() +
")\n" 514 """ dumps the object with all attributes declared after the constructor""" 517 param = self.__dict__[name]
518 result += options.indentation() + myname +
"." + name +
" = " + param.dumpPython(options) +
"\n" 528 newpset = parameterSet.newPSet()
529 newpset.addString(
True,
"@module_label", self.
moduleLabel_(myname))
530 newpset.addString(
True,
"@module_type", self.
type_())
531 newpset.addString(
True,
"@module_edm_type", type(self).__name__)
538 """A 'mixin' used to denote that the class can be paired with a label (e.g. an EDProducer)""" 540 if not hasattr(self,
"_Labelable__label"):
541 raise RuntimeError(
"module has no label. Perhaps it wasn't inserted into the process?")
544 return hasattr(self,
"_Labelable__label")
and self.
__label is not None 547 if self.
label_() != label
and label
is not None :
548 msg100 =
"Attempting to change the label of a Labelable object, possibly an attribute of the Process\n" 549 msg101 =
"Old label = "+self.
label_()+
" New label = "+label+
"\n" 550 msg102 =
"Type = "+
str(type(self))+
"\n" 551 msg103 =
"Some possible solutions:\n" 552 msg104 =
" 1. Clone modules instead of using simple assignment. Cloning is\n" 553 msg105 =
" also preferred for other types when possible.\n" 554 msg106 =
" 2. Declare new names starting with an underscore if they are\n" 555 msg107 =
" for temporaries you do not want propagated into the Process. The\n" 556 msg108 =
" underscore tells \"from x import *\" and process.load not to import\n" 557 msg109 =
" the name.\n" 558 msg110 =
" 3. Reorganize so the assigment is not necessary. Giving a second\n" 559 msg111 =
" name to the same object usually causes confusion and problems.\n" 560 msg112 =
" 4. Compose Sequences: newName = cms.Sequence(oldName)\n" 561 raise ValueError(msg100+msg101+msg102+msg103+msg104+msg105+msg106+msg107+msg108+msg109+msg110+msg111+msg112)
580 myDeps=knownDeps.get(self.
label_(),
None)
582 if presentDeps != myDeps:
583 raise RuntimeError(
"the module "+self.
label_()+
" has two dependencies \n" 584 +
str(presentDeps)+
"\n" 586 +
"Please modify sequences to rectify this inconsistency")
588 myDeps=set(presentDeps)
589 knownDeps[self.
label_()]=myDeps
590 presentDeps.add(self.
label_())
594 """A 'mixin' used to denote that the class can be used without a label (e.g. a Service)""" 597 class _ValidatingListBase(list):
598 """Base class for a list which enforces that its entries pass a 'validity' test""" 600 super(_ValidatingListBase,self).
__init__(arg)
602 raise SyntaxError(
"named arguments ("+
','.
join([x
for x
in args])+
") passsed to "+
str(type(self)))
603 if not type(self).
_isValid(iter(self)):
604 raise TypeError(
"wrong types ("+
','.
join([
str(type(value))
for value
in iter(self)])+
605 ") added to "+
str(type(self)))
607 if isinstance(key,slice):
609 raise TypeError(
"wrong type being inserted into this container "+self.
_labelIfAny())
611 if not self._itemIsValid(value):
612 raise TypeError(
"can not insert the type "+
str(type(value))+
" in container "+self.
_labelIfAny())
613 super(_ValidatingListBase,self).
__setitem__(key,value)
617 if isinstance(seq, str):
620 if not cls._itemIsValid(item):
626 if isinstance(seq, str):
631 if not self._itemIsValid(x):
632 raise TypeError(
"wrong type being appended to container "+self.
_labelIfAny())
636 raise TypeError(
"wrong type being extended to container "+self.
_labelIfAny())
640 raise TypeError(
"wrong type being added to container "+self.
_labelIfAny())
642 value = copy.copy(self)
646 if not self._itemIsValid(x):
647 raise TypeError(
"wrong type being inserted to container "+self.
_labelIfAny())
650 result = type(self).__name__
651 if hasattr(self,
'__label'):
652 result +=
' ' + self.__label
657 _ParameterTypeBase.__init__(self)
658 if len (arg) == 1
and not isinstance(arg[0],str):
663 super(_ValidatingParameterListBase,self).
__init__(*arg,**args)
673 for value
in iter(self):
675 config += options.indentation()
681 config += options.indentation()+
'}\n' 690 specialImportRegistry.registerUse(self)
693 if hasattr(self,
"_nPerLine"):
694 nPerLine = self._nPerLine
697 if n>nPerLine: options.indent()
701 for i, v
in enumerate(self):
703 if n>nPerLine: result +=
'\n'+options.indentation()
705 if i % nPerLine == 0:
706 result +=
',\n'+options.indentation()
712 result +=
'\n'+options.indentation()
725 fInfo = inspect.getframeinfo(sys._getframe(level+1))
726 obj._filename = fInfo.filename
727 obj._lineNumber =fInfo.lineno
732 for key,value
in newParams.items():
736 elif isinstance(value, dict):
737 if isinstance(params[key],_Parameterizable):
739 p =pset.parameters_()
740 oldkeys = set(p.keys())
743 (
"%s.%s" if isinstance(key, str)
else "%s[%s]")%(keyDepth,key))
744 for k,v
in p.items():
749 elif isinstance(params[key],_ValidatingParameterListBase):
750 if any(
not isinstance(k, int)
for k
in value.keys()):
751 raise TypeError(
"Attempted to change a list using a dict whose keys are not integers")
753 if any((k < 0
or k >= len(plist))
for k
in value.keys()):
754 raise IndexError(
"Attempted to set an index which is not in the list")
755 p = dict(enumerate(plist))
758 (
"%s.%s" if isinstance(key, str)
else "%s[%s]")%(keyDepth,key))
759 for k,v
in p.items():
762 raise ValueError(
"Attempted to change non PSet value "+keyDepth+
" using a dictionary")
763 elif isinstance(value,_ParameterTypeBase)
or (isinstance(key, int))
or isinstance(value, _Parameterizable):
768 if isinstance(value,_ParameterTypeBase)
or isinstance(value, _Parameterizable):
774 if __name__ ==
"__main__":
784 self.assertEqual(t,[1])
786 self.assertEqual(t,[1])
788 self.assertEqual(t,[
"one"])
790 self.assertEqual(t,[1])
792 self.assertEqual(t,[1])
795 self.assertEqual(t,[1,2])
797 self.assertEqual(t,[1,2])
799 self.assertEqual(t,[
"one",
"two"])
801 self.assertEqual(t,[
"one",
"two"])
803 self.assertEqual(t,[1,2])
805 self.assertEqual(t,[1,2])
807 self.assertEqual(t,[1,2])
813 args = [i
for i
in range(0,300)]
816 pdump= t.dumpPython()
820 pythonized = eval( pdump, globals(),{
'cms':
cms()} )
821 self.assertEqual(t,pythonized)
824 self.assertTrue(isinstance(a, _ParameterTypeBase))
829 def _isValid(self,value):
834 _ParameterTypeBase.__init__(self)
835 _Parameterizable.__init__(self,*arg,**args)
837 a = __Test(
"MyType", __PSet(a=__TestType(1)))
838 self.assertEqual(a.a.value(), 1)
839 b = __Test(
"MyType", __PSet(a=__TestType(1)), __PSet(b=__TestType(2)))
840 self.assertEqual(b.a.value(), 1)
841 self.assertEqual(b.b.value(), 2)
842 self.assertRaises(ValueError,
lambda: __Test(
"MyType", __PSet(a=__TestType(1)), __PSet(a=__TestType(2))))
843 c = __Test(
"MyType", dict(a=__TestType(1)), dict(b=__TestType(2)))
844 self.assertEqual(c.a.value(), 1)
845 self.assertEqual(c.b.value(), 2)
846 self.assertRaises(ValueError,
lambda: __Test(
"MyType", dict(a=__TestType(1)), dict(a=__TestType(2))))
851 def _isValid(self,value):
856 _ParameterTypeBase.__init__(self)
857 _Parameterizable.__init__(self,*arg,**args)
858 a = __Test(
"MyType", a = __TestType(1))
859 a.update_(dict(b=__TestType(2)))
860 self.assertEqual(a.a.value(), 1)
861 self.assertEqual(a.b.value(), 2)
863 self.assertEqual(a.a.value(), 3)
864 a.update_(__PSet(a=__TestType(5)))
865 self.assertEqual(a.a.value(), 5)
866 self.assertRaises(TypeError,
lambda: a.update_(dict(c=6)))
872 def _isValid(self,value):
874 a = __Test(
"MyType",t=__TestType(1), u=__TestType(2))
876 self.assertEqual(b.t.value(),1)
877 self.assertEqual(b.u.value(),2)
880 self.assertEqual(len(c.parameterNames_()), 0)
882 self.assertEqual(len(d.parameterNames_()), 0)
887 def _isValid(self,value):
892 _ParameterTypeBase.__init__(self)
893 _Parameterizable.__init__(self,*arg,**args)
895 return "__PSet(\n"+_Parameterizable.dumpPython(self, options)+options.indentation()+
")" 901 x = __PSet(a = __TestType(4),
903 c = __PSet(gamma = __TestType(5))))
910 c = a.clone(x = dict(a=
None, c=
None))
911 self.assertEqual(a.t.value(),1)
912 self.assertEqual(a.u.value(),2)
913 self.assertEqual(b.t.value(),3)
914 self.assertEqual(b.u.value(),2)
915 self.assertEqual(b.v.value(),4)
916 self.assertEqual(b.x.a.value(),7)
917 self.assertEqual(b.x.b.value(),6)
918 self.assertEqual(b.x.c.gamma.value(),8)
919 self.assertEqual(b.x.d.value(),9)
920 self.assertEqual(hasattr(b,
"w"),
False)
921 self.assertEqual(hasattr(c.x,
"a"),
False)
922 self.assertEqual(hasattr(c.x,
"c"),
False)
923 self.assertRaises(TypeError,a.clone,**{
"v":1})
924 d = a.clone(__PSet(k=__TestType(42)))
925 self.assertEqual(d.t.value(), 1)
926 self.assertEqual(d.k.value(), 42)
927 d2 = a.clone(__PSet(t=__TestType(42)))
928 self.assertEqual(d2.t.value(), 42)
929 d3 = a.clone(__PSet(t=__TestType(42)),
930 __PSet(u=__TestType(56)))
931 self.assertEqual(d3.t.value(), 42)
932 self.assertEqual(d3.u.value(), 56)
933 self.assertRaises(ValueError,a.clone,
934 __PSet(t=__TestType(42)),
935 __PSet(t=__TestType(56)))
936 d4 = a.clone(__PSet(t=__TestType(43)), u = 57)
937 self.assertEqual(d4.t.value(), 43)
938 self.assertEqual(d4.u.value(), 57)
939 self.assertRaises(TypeError,a.clone,t=__TestType(43),**{
"doesNotExist":57})
942 self.assertEqual(len(e.parameterNames_()), 0)
943 f = e.clone(__PSet(a = __TestType(1)), b = __TestType(2))
944 self.assertEqual(f.a.value(), 1)
945 self.assertEqual(f.b.value(), 2)
947 self.assertEqual(len(g.parameterNames_()), 0)
951 def _isValid(self,value):
954 self.assertEqual(a.isModified(),
False)
956 self.assertEqual(a.isModified(),
False)
958 self.assertEqual(a.isModified(),
True)
960 self.assertEqual(a.isModified(),
False)
965 def _isValid(self,value):
967 class __DummyModule(
object):
973 self.assertEqual(p.dumpPython(), eval(p.dumpPython(),{
"cms": __DummyModule()}).
dumpPython())
976 reg.registerSpecialImportForType(int,
"import foo")
977 self.assertRaises(RuntimeError,
lambda: reg.registerSpecialImportForType(int,
"import bar"))
978 reg.registerSpecialImportForType(str,
"import bar")
979 self.assertEqual(reg.getSpecialImports(), [])
981 self.assertEqual(reg.getSpecialImports(), [])
983 self.assertEqual(reg.getSpecialImports(), [
"import foo"])
985 self.assertEqual(reg.getSpecialImports(), [
"import foo"])
987 self.assertEqual(reg.getSpecialImports(), [
"import bar",
"import foo"])
992 def _isValid(self,value):
995 def _isValid(self,value):
1000 self.assertRaises(TypeError,
lambda : setattr(a,
't',__TestTypeB(2)))
def __init__(self, arg, args)
def testSpecialImportRegistry(self)
def getSpecialImports(self)
def appendToProcessDescList_
def _modifyParametersFromDict(params, newParams, errorRaiser, keyDepth="")
def __setParameters(self, parameters)
def _findDependencies(self, knownDeps, presentDeps)
bool any(const std::vector< T > &v, const T &what)
def _itemFromArgument(self, x)
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 _valueFromString(value)
def testConstruction(self)
def registerUse(self, obj)
def _checkAndReturnValueWithType(self, valueWithType)
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 testListConstruction(self)
def _itemIsValid(cls, item)
def _convertArguments(self, seq)
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 saveOrigin(obj, level)
def registerSpecialImportForType(self, cls, impStatement)
Namespace of DDCMS conversion namespace.
def split(sequence, size)
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 __setParametersFromArg(self, arg)
def __setitem__(self, key, value)
def __init__(self, value)
def testInvalidTypeChange(self)
if(threadIdxLocalY==0 &&threadIdxLocalX==0)
def getParameter(self, params)
def insertContentsInto(self, parameterSet)
def __init__(self, arg, args)