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""" 180 if type(block).__name__
not in [
"PSet",
"__PSet",
"dict"]:
181 raise ValueError(
"Only PSets can be passed as unnamed argument blocks. This is a "+type(block).__name__)
182 if isinstance(block,dict):
190 """Returns the name of the parameters""" 191 return self.__parameterNames[:]
196 param = self.__dict__[name]
197 if isinstance(param, _Parameterizable)
and param.isModified():
206 check that pset provided has the attribute chain 209 Eg, if params is [ 'attr1', 'attr2', 'attr3' ] 210 check for pset.attr1.attr2.attr3 212 returns True if parameter exists, False if not 220 Retrieve the specified parameter from the PSet Provided 221 given the attribute chain 223 returns None if not found 227 if type(params).__name__ ==
'str':
228 return getattr(self, params,
None)
230 lastParam = getattr(lastParam, param,
None)
231 if lastParam ==
None:
236 """Returns a dictionary of copies of the user-set parameters""" 240 result[name]=copy.deepcopy(self.__dict__[name])
244 if name ==
'allowAnyLabel_':
248 if not isinstance(value,_ParameterTypeBase):
253 if name
in self.__dict__:
254 message =
"Duplicate insert of member " + name
255 message +=
"\nThe original parameters are:\n" 257 raise ValueError(message)
258 self.__dict__[name]=value
259 self.__parameterNames.
append(name)
264 for name,value
in parameters.items():
265 if name ==
'allowAnyLabel_':
274 if self.
isFrozen()
and not (name
in [
"_Labelable__label",
"_isFrozen"]
or name.startswith(
'_')):
275 message =
"Object already added to a process. It is read only now\n" 276 message +=
" %s = %s" %(name, value)
277 message +=
"\nThe original parameters are:\n" 279 raise ValueError(message)
282 super(_Parameterizable,self).
__setattr__(name,value)
283 elif not name
in self.__dict__:
288 if isinstance(value,_ParameterTypeBase):
289 self.__dict__[name] = self.__dict__[name]._checkAndReturnValueWithType(value)
302 raise ValueError(
"Object already added to a process. It is read only now")
304 self.__parameterNames.
remove(name)
307 raise TypeError(name+
" does not already exist, so it can only be set to a CMS python configuration type")
309 specialImportRegistry.registerUse(self)
311 if len(sortedNames) > 200:
320 for name
in sortedNames:
321 param = self.__dict__[name]
323 name2 = name.replace(
'-',
'_')
326 if name.startswith(
"using_"):
327 usings.append(options.indentation()+param.dumpPython(options))
329 others.append((name2, param.dumpPython(options)))
332 resultList =
',\n'.
join(usings)
333 longOthers = options.indentation()+
"**dict(\n" 335 longOthers += options.indentation()+
"[\n" 340 if entriesInList > 200:
343 longOthers += options.indentation()+
"] +\n"+options.indentation()+
"[\n" 346 longOthers += options.indentation()+
'("'+n+
'" , '+v+
' ),\n' 348 longOthers += options.indentation()+
"]\n" 350 longOthers +=options.indentation()+
")\n" 354 ret.append(resultList)
356 ret.append(longOthers)
357 return ",\n".
join(ret)
361 for name
in sortedNames:
362 param = self.__dict__[name]
364 name2 = name.replace(
'-',
'_')
367 if name.startswith(
"using_"):
368 usings.append(options.indentation()+param.dumpPython(options))
370 others.append(options.indentation()+name2+
' = '+param.dumpPython(options))
374 resultList.extend(others)
379 return ',\n'.
join(resultList)+
'\n' 384 param = getattr(self,name)
385 param.insertInto(parameterSet, name)
389 """Base class for classes which are Parameterizable and have a 'type' assigned""" 391 self.__dict__[
'_TypedParameterizable__type'] = type_
397 super(_TypedParameterizable,self).
__init__(*arg,**kargs)
400 self._placeImpl(name,proc)
402 """returns the type of the object, e.g. 'FooProducer'""" 405 returnValue =_TypedParameterizable.__new__(type(self))
407 returnValue.__init__(self.__type,**params)
411 """Copies the object and allows one to modify the parameters of the clone. 412 New parameters may be added by specify the exact type 413 Modifying existing parameters can be done by just specifying the new 414 value without having to specify the type. 415 A parameter may be removed from the clone using the value None. 416 #remove the parameter foo.fred 417 mod.toModify(foo, fred = None) 418 A parameter embedded within a PSet may be changed via a dictionary 419 #change foo.fred.pebbles to 3 and foo.fred.friend to "barney" 420 mod.toModify(foo, fred = dict(pebbles = 3, friend = "barney)) ) 422 returnValue =_TypedParameterizable.__new__(type(self))
428 if type(block).__name__
not in [
"PSet",
"__PSet"]:
429 raise ValueError(
"Only PSets can be passed as unnamed argument blocks. This is a "+type(block).__name__)
430 for name
in block.parameterNames_():
437 if self._Parameterizable__validator
is not None:
438 myparams[
"allowAnyLabel_"] = self._Parameterizable__validator
440 returnValue.__init__(self.__type,*args,
442 returnValue._isModified =
False 443 returnValue._isFrozen =
False 454 choices.extend(glob.glob(d+
'/*/*/'+label+
'.py'))
464 mod = __import__(name)
465 components = name.split(
'.')
466 for comp
in components[1:]:
467 mod = getattr(mod,comp)
468 if hasattr(mod,label):
469 default = getattr(mod,label)
470 if isinstance(default,_TypedParameterizable):
471 if(default.type_() == type):
473 for name
in default.parameterNames_():
474 params[name] = getattr(default,name)
482 config = self.__type +
' { \n' 484 param = self.__dict__[name]
486 config+=options.indentation()+param.configTypeName()+
' '+name+
' = '+param.configValue(options)+
'\n' 488 config += options.indentation()+
'}\n' 492 specialImportRegistry.registerUse(self)
493 result =
"cms."+
str(type(self).__name__)+
'("'+self.
type_()+
'"' 498 result +=
",\n"+_Parameterizable.dumpPython(self,options)+options.indentation() +
")\n" 502 """ dumps the object with all attributes declared after the constructor""" 505 param = self.__dict__[name]
506 result += options.indentation() + myname +
"." + name +
" = " + param.dumpPython(options) +
"\n" 516 newpset = parameterSet.newPSet()
517 newpset.addString(
True,
"@module_label", self.
moduleLabel_(myname))
518 newpset.addString(
True,
"@module_type", self.
type_())
519 newpset.addString(
True,
"@module_edm_type", type(self).__name__)
526 """A 'mixin' used to denote that the class can be paired with a label (e.g. an EDProducer)""" 528 if not hasattr(self,
"_Labelable__label"):
529 raise RuntimeError(
"module has no label. Perhaps it wasn't inserted into the process?")
532 return hasattr(self,
"_Labelable__label")
and self.
__label is not None 535 if self.
label_() != label
and label
is not None :
536 msg100 =
"Attempting to change the label of a Labelable object, possibly an attribute of the Process\n" 537 msg101 =
"Old label = "+self.
label_()+
" New label = "+label+
"\n" 538 msg102 =
"Type = "+
str(type(self))+
"\n" 539 msg103 =
"Some possible solutions:\n" 540 msg104 =
" 1. Clone modules instead of using simple assignment. Cloning is\n" 541 msg105 =
" also preferred for other types when possible.\n" 542 msg106 =
" 2. Declare new names starting with an underscore if they are\n" 543 msg107 =
" for temporaries you do not want propagated into the Process. The\n" 544 msg108 =
" underscore tells \"from x import *\" and process.load not to import\n" 545 msg109 =
" the name.\n" 546 msg110 =
" 3. Reorganize so the assigment is not necessary. Giving a second\n" 547 msg111 =
" name to the same object usually causes confusion and problems.\n" 548 msg112 =
" 4. Compose Sequences: newName = cms.Sequence(oldName)\n" 549 raise ValueError(msg100+msg101+msg102+msg103+msg104+msg105+msg106+msg107+msg108+msg109+msg110+msg111+msg112)
568 myDeps=knownDeps.get(self.
label_(),
None)
570 if presentDeps != myDeps:
571 raise RuntimeError(
"the module "+self.
label_()+
" has two dependencies \n" 572 +
str(presentDeps)+
"\n" 574 +
"Please modify sequences to rectify this inconsistency")
576 myDeps=set(presentDeps)
577 knownDeps[self.
label_()]=myDeps
578 presentDeps.add(self.
label_())
582 """A 'mixin' used to denote that the class can be used without a label (e.g. a Service)""" 585 class _ValidatingListBase(list):
586 """Base class for a list which enforces that its entries pass a 'validity' test""" 588 super(_ValidatingListBase,self).
__init__(arg)
590 raise SyntaxError(
"named arguments ("+
','.
join([x
for x
in args])+
") passsed to "+
str(type(self)))
591 if not type(self).
_isValid(iter(self)):
592 raise TypeError(
"wrong types ("+
','.
join([
str(type(value))
for value
in iter(self)])+
593 ") added to "+
str(type(self)))
595 if isinstance(key,slice):
597 raise TypeError(
"wrong type being inserted into this container "+self.
_labelIfAny())
599 if not self._itemIsValid(value):
600 raise TypeError(
"can not insert the type "+
str(type(value))+
" in container "+self.
_labelIfAny())
601 super(_ValidatingListBase,self).
__setitem__(key,value)
605 if isinstance(seq, str):
608 if not cls._itemIsValid(item):
614 if isinstance(seq, str):
619 if not self._itemIsValid(x):
620 raise TypeError(
"wrong type being appended to container "+self.
_labelIfAny())
624 raise TypeError(
"wrong type being extended to container "+self.
_labelIfAny())
628 raise TypeError(
"wrong type being added to container "+self.
_labelIfAny())
630 value = copy.copy(self)
634 if not self._itemIsValid(x):
635 raise TypeError(
"wrong type being inserted to container "+self.
_labelIfAny())
638 result = type(self).__name__
639 if hasattr(self,
'__label'):
640 result +=
' ' + self.__label
645 _ParameterTypeBase.__init__(self)
646 if len (arg) == 1
and not isinstance(arg[0],str):
651 super(_ValidatingParameterListBase,self).
__init__(*arg,**args)
661 for value
in iter(self):
663 config += options.indentation()
669 config += options.indentation()+
'}\n' 678 specialImportRegistry.registerUse(self)
681 if hasattr(self,
"_nPerLine"):
682 nPerLine = self._nPerLine
685 if n>nPerLine: options.indent()
689 for i, v
in enumerate(self):
691 if n>nPerLine: result +=
'\n'+options.indentation()
693 if i % nPerLine == 0:
694 result +=
',\n'+options.indentation()
700 result +=
'\n'+options.indentation()
713 fInfo = inspect.getframeinfo(sys._getframe(level+1))
714 obj._filename = fInfo.filename
715 obj._lineNumber =fInfo.lineno
720 for key,value
in newParams.items():
724 elif isinstance(value, dict):
725 if isinstance(params[key],_Parameterizable):
727 p =pset.parameters_()
728 oldkeys = set(p.keys())
731 (
"%s.%s" if isinstance(key, str)
else "%s[%s]")%(keyDepth,key))
732 for k,v
in p.items():
737 elif isinstance(params[key],_ValidatingParameterListBase):
738 if any(
not isinstance(k, int)
for k
in value.keys()):
739 raise TypeError(
"Attempted to change a list using a dict whose keys are not integers")
741 if any((k < 0
or k >= len(plist))
for k
in value.keys()):
742 raise IndexError(
"Attempted to set an index which is not in the list")
743 p = dict(enumerate(plist))
746 (
"%s.%s" if isinstance(key, str)
else "%s[%s]")%(keyDepth,key))
747 for k,v
in p.items():
750 raise ValueError(
"Attempted to change non PSet value "+keyDepth+
" using a dictionary")
751 elif isinstance(value,_ParameterTypeBase)
or (isinstance(key, int))
or isinstance(value, _Parameterizable):
756 if isinstance(value,_ParameterTypeBase)
or isinstance(value, _Parameterizable):
762 if __name__ ==
"__main__":
772 self.assertEqual(t,[1])
774 self.assertEqual(t,[1])
776 self.assertEqual(t,[
"one"])
778 self.assertEqual(t,[1])
780 self.assertEqual(t,[1])
783 self.assertEqual(t,[1,2])
785 self.assertEqual(t,[1,2])
787 self.assertEqual(t,[
"one",
"two"])
789 self.assertEqual(t,[
"one",
"two"])
791 self.assertEqual(t,[1,2])
793 self.assertEqual(t,[1,2])
795 self.assertEqual(t,[1,2])
801 args = [i
for i
in range(0,300)]
804 pdump= t.dumpPython()
808 pythonized = eval( pdump, globals(),{
'cms':
cms()} )
809 self.assertEqual(t,pythonized)
812 self.assertTrue(isinstance(a, _ParameterTypeBase))
817 def _isValid(self,value):
822 _ParameterTypeBase.__init__(self)
823 _Parameterizable.__init__(self,*arg,**args)
825 a = __Test(
"MyType", __PSet(a=__TestType(1)))
826 self.assertEqual(a.a.value(), 1)
827 b = __Test(
"MyType", __PSet(a=__TestType(1)), __PSet(b=__TestType(2)))
828 self.assertEqual(b.a.value(), 1)
829 self.assertEqual(b.b.value(), 2)
830 self.assertRaises(ValueError,
lambda: __Test(
"MyType", __PSet(a=__TestType(1)), __PSet(a=__TestType(2))))
836 def _isValid(self,value):
838 a = __Test(
"MyType",t=__TestType(1), u=__TestType(2))
840 self.assertEqual(b.t.value(),1)
841 self.assertEqual(b.u.value(),2)
844 self.assertEqual(len(c.parameterNames_()), 0)
846 self.assertEqual(len(d.parameterNames_()), 0)
851 def _isValid(self,value):
856 _ParameterTypeBase.__init__(self)
857 _Parameterizable.__init__(self,*arg,**args)
859 return "__PSet(\n"+_Parameterizable.dumpPython(self, options)+options.indentation()+
")" 865 x = __PSet(a = __TestType(4),
867 c = __PSet(gamma = __TestType(5))))
874 c = a.clone(x = dict(a=
None, c=
None))
875 self.assertEqual(a.t.value(),1)
876 self.assertEqual(a.u.value(),2)
877 self.assertEqual(b.t.value(),3)
878 self.assertEqual(b.u.value(),2)
879 self.assertEqual(b.v.value(),4)
880 self.assertEqual(b.x.a.value(),7)
881 self.assertEqual(b.x.b.value(),6)
882 self.assertEqual(b.x.c.gamma.value(),8)
883 self.assertEqual(b.x.d.value(),9)
884 self.assertEqual(hasattr(b,
"w"),
False)
885 self.assertEqual(hasattr(c.x,
"a"),
False)
886 self.assertEqual(hasattr(c.x,
"c"),
False)
887 self.assertRaises(TypeError,a.clone,**{
"v":1})
888 d = a.clone(__PSet(k=__TestType(42)))
889 self.assertEqual(d.t.value(), 1)
890 self.assertEqual(d.k.value(), 42)
891 d2 = a.clone(__PSet(t=__TestType(42)))
892 self.assertEqual(d2.t.value(), 42)
893 d3 = a.clone(__PSet(t=__TestType(42)),
894 __PSet(u=__TestType(56)))
895 self.assertEqual(d3.t.value(), 42)
896 self.assertEqual(d3.u.value(), 56)
897 self.assertRaises(ValueError,a.clone,
898 __PSet(t=__TestType(42)),
899 __PSet(t=__TestType(56)))
900 d4 = a.clone(__PSet(t=__TestType(43)), u = 57)
901 self.assertEqual(d4.t.value(), 43)
902 self.assertEqual(d4.u.value(), 57)
903 self.assertRaises(TypeError,a.clone,t=__TestType(43),**{
"doesNotExist":57})
906 self.assertEqual(len(e.parameterNames_()), 0)
907 f = e.clone(__PSet(a = __TestType(1)), b = __TestType(2))
908 self.assertEqual(f.a.value(), 1)
909 self.assertEqual(f.b.value(), 2)
911 self.assertEqual(len(g.parameterNames_()), 0)
915 def _isValid(self,value):
918 self.assertEqual(a.isModified(),
False)
920 self.assertEqual(a.isModified(),
False)
922 self.assertEqual(a.isModified(),
True)
924 self.assertEqual(a.isModified(),
False)
929 def _isValid(self,value):
931 class __DummyModule(
object):
937 self.assertEqual(p.dumpPython(), eval(p.dumpPython(),{
"cms": __DummyModule()}).
dumpPython())
940 reg.registerSpecialImportForType(int,
"import foo")
941 self.assertRaises(RuntimeError,
lambda: reg.registerSpecialImportForType(int,
"import bar"))
942 reg.registerSpecialImportForType(str,
"import bar")
943 self.assertEqual(reg.getSpecialImports(), [])
945 self.assertEqual(reg.getSpecialImports(), [])
947 self.assertEqual(reg.getSpecialImports(), [
"import foo"])
949 self.assertEqual(reg.getSpecialImports(), [
"import foo"])
951 self.assertEqual(reg.getSpecialImports(), [
"import bar",
"import foo"])
956 def _isValid(self,value):
959 def _isValid(self,value):
964 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 __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)