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)
89 if isinstance(valueWithType, type(self)):
91 raise TypeError(
"Attempted to assign type {from_} to type {to}".
format(from_ =
str(type(valueWithType)), to =
str(type(self))) )
95 """base class for parameter classes which only hold a single value""" 97 super(_SimpleParameterTypeBase,self).
__init__()
99 if not self._isValid(value):
100 raise ValueError(
str(value)+
" is not a valid "+
str(type(self)))
104 if not self._isValid(value):
105 raise ValueError(
str(value)+
" is not a valid "+
str(type(self)))
114 if isinstance(other,_SimpleParameterTypeBase):
115 return self.
_value == other._value
116 return self.
_value == other
118 if isinstance(other,_SimpleParameterTypeBase):
119 return self.
_value != other._value
120 return self.
_value != other
122 if isinstance(other,_SimpleParameterTypeBase):
123 return self.
_value < other._value
124 return self.
_value < other
126 if isinstance(other,_SimpleParameterTypeBase):
127 return self.
_value <= other._value
128 return self.
_value <= other
130 if isinstance(other,_SimpleParameterTypeBase):
131 return self.
_value > other._value
132 return self.
_value > other
134 if isinstance(other,_SimpleParameterTypeBase):
135 return self.
_value >= other._value
136 return self.
_value >= other
140 """For injection purposes, pretend this is a new parameter type 141 then have a post process step which strips these out 144 super(UsingBlock,self).
__init__(value)
151 return isinstance(value,str)
153 """only used for cfg-parsing""" 160 parameterSet.addString(self.
isTracked(), myname, value)
163 return "process."+self.
value()
169 """Base class for classes which allow addition of _ParameterTypeBase data""" 171 self.__dict__[
'_Parameterizable__parameterNames'] = []
172 self.__dict__[
"_isFrozen"] =
False 173 self.__dict__[
'_Parameterizable__validator'] =
None 174 """The named arguments are the 'parameters' which are added as 'python attributes' to the object""" 179 if type(block).__name__
not in [
"PSet",
"__PSet",
"dict"]:
180 raise ValueError(
"Only PSets can be passed as unnamed argument blocks. This is a "+type(block).__name__)
181 if isinstance(block,dict):
189 """Returns the name of the parameters""" 190 return self.__parameterNames[:]
195 param = self.__dict__[name]
196 if isinstance(param, _Parameterizable)
and param.isModified():
205 check that pset provided has the attribute chain 208 Eg, if params is [ 'attr1', 'attr2', 'attr3' ] 209 check for pset.attr1.attr2.attr3 211 returns True if parameter exists, False if not 219 Retrieve the specified parameter from the PSet Provided 220 given the attribute chain 222 returns None if not found 226 if type(params).__name__ ==
'str':
227 return getattr(self, params,
None)
229 lastParam = getattr(lastParam, param,
None)
230 if lastParam ==
None:
235 """Returns a dictionary of copies of the user-set parameters""" 239 result[name]=copy.deepcopy(self.__dict__[name])
243 if name ==
'allowAnyLabel_':
247 if not isinstance(value,_ParameterTypeBase):
252 if name
in self.__dict__:
253 message =
"Duplicate insert of member " + name
254 message +=
"\nThe original parameters are:\n" 256 raise ValueError(message)
257 self.__dict__[name]=value
258 self.__parameterNames.
append(name)
263 for name,value
in parameters.items():
264 if name ==
'allowAnyLabel_':
273 if self.
isFrozen()
and not (name
in [
"_Labelable__label",
"_isFrozen"]
or name.startswith(
'_')):
274 message =
"Object already added to a process. It is read only now\n" 275 message +=
" %s = %s" %(name, value)
276 message +=
"\nThe original parameters are:\n" 278 raise ValueError(message)
281 super(_Parameterizable,self).
__setattr__(name,value)
282 elif not name
in self.__dict__:
287 if isinstance(value,_ParameterTypeBase):
288 self.__dict__[name] = self.__dict__[name]._checkAndReturnValueWithType(value)
301 raise ValueError(
"Object already added to a process. It is read only now")
303 self.__parameterNames.
remove(name)
306 raise TypeError(name+
" does not already exist, so it can only be set to a CMS python configuration type")
308 specialImportRegistry.registerUse(self)
310 if len(sortedNames) > 200:
319 for name
in sortedNames:
320 param = self.__dict__[name]
322 name2 = name.replace(
'-',
'_')
325 if name.startswith(
"using_"):
326 usings.append(options.indentation()+param.dumpPython(options))
328 others.append((name2, param.dumpPython(options)))
331 resultList =
',\n'.
join(usings)
332 longOthers = options.indentation()+
"**dict(\n" 334 longOthers += options.indentation()+
"[\n" 339 if entriesInList > 200:
342 longOthers += options.indentation()+
"] +\n"+options.indentation()+
"[\n" 345 longOthers += options.indentation()+
'("'+n+
'" , '+v+
' ),\n' 347 longOthers += options.indentation()+
"]\n" 349 longOthers +=options.indentation()+
")\n" 353 ret.append(resultList)
355 ret.append(longOthers)
356 return ",\n".
join(ret)
360 for name
in sortedNames:
361 param = self.__dict__[name]
363 name2 = name.replace(
'-',
'_')
366 if name.startswith(
"using_"):
367 usings.append(options.indentation()+param.dumpPython(options))
369 others.append(options.indentation()+name2+
' = '+param.dumpPython(options))
373 resultList.extend(others)
378 return ',\n'.
join(resultList)+
'\n' 383 param = getattr(self,name)
384 param.insertInto(parameterSet, name)
388 """Base class for classes which are Parameterizable and have a 'type' assigned""" 390 self.__dict__[
'_TypedParameterizable__type'] = type_
396 super(_TypedParameterizable,self).
__init__(*arg,**kargs)
399 self._placeImpl(name,proc)
401 """returns the type of the object, e.g. 'FooProducer'""" 404 returnValue =_TypedParameterizable.__new__(type(self))
406 returnValue.__init__(self.__type,**params)
410 """Copies the object and allows one to modify the parameters of the clone. 411 New parameters may be added by specify the exact type 412 Modifying existing parameters can be done by just specifying the new 413 value without having to specify the type. 414 A parameter may be removed from the clone using the value None. 415 #remove the parameter foo.fred 416 mod.toModify(foo, fred = None) 417 A parameter embedded within a PSet may be changed via a dictionary 418 #change foo.fred.pebbles to 3 and foo.fred.friend to "barney" 419 mod.toModify(foo, fred = dict(pebbles = 3, friend = "barney)) ) 421 returnValue =_TypedParameterizable.__new__(type(self))
427 if type(block).__name__
not in [
"PSet",
"__PSet"]:
428 raise ValueError(
"Only PSets can be passed as unnamed argument blocks. This is a "+type(block).__name__)
429 for name
in block.parameterNames_():
436 if self._Parameterizable__validator
is not None:
437 myparams[
"allowAnyLabel_"] = self._Parameterizable__validator
439 returnValue.__init__(self.__type,*args,
441 returnValue._isModified =
False 442 returnValue._isFrozen =
False 453 choices.extend(glob.glob(d+
'/*/*/'+label+
'.py'))
463 mod = __import__(name)
464 components = name.split(
'.')
465 for comp
in components[1:]:
466 mod = getattr(mod,comp)
467 if hasattr(mod,label):
468 default = getattr(mod,label)
469 if isinstance(default,_TypedParameterizable):
470 if(default.type_() == type):
472 for name
in default.parameterNames_():
473 params[name] = getattr(default,name)
481 config = self.__type +
' { \n' 483 param = self.__dict__[name]
485 config+=options.indentation()+param.configTypeName()+
' '+name+
' = '+param.configValue(options)+
'\n' 487 config += options.indentation()+
'}\n' 491 specialImportRegistry.registerUse(self)
492 result =
"cms."+
str(type(self).__name__)+
'("'+self.
type_()+
'"' 497 result +=
",\n"+_Parameterizable.dumpPython(self,options)+options.indentation() +
")\n" 501 """ dumps the object with all attributes declared after the constructor""" 504 param = self.__dict__[name]
505 result += options.indentation() + myname +
"." + name +
" = " + param.dumpPython(options) +
"\n" 515 newpset = parameterSet.newPSet()
516 newpset.addString(
True,
"@module_label", self.
moduleLabel_(myname))
517 newpset.addString(
True,
"@module_type", self.
type_())
518 newpset.addString(
True,
"@module_edm_type", type(self).__name__)
525 """A 'mixin' used to denote that the class can be paired with a label (e.g. an EDProducer)""" 527 if not hasattr(self,
"_Labelable__label"):
528 raise RuntimeError(
"module has no label. Perhaps it wasn't inserted into the process?")
531 return hasattr(self,
"_Labelable__label")
and self.
__label is not None 534 if self.
label_() != label
and label
is not None :
535 msg100 =
"Attempting to change the label of a Labelable object, possibly an attribute of the Process\n" 536 msg101 =
"Old label = "+self.
label_()+
" New label = "+label+
"\n" 537 msg102 =
"Type = "+
str(type(self))+
"\n" 538 msg103 =
"Some possible solutions:\n" 539 msg104 =
" 1. Clone modules instead of using simple assignment. Cloning is\n" 540 msg105 =
" also preferred for other types when possible.\n" 541 msg106 =
" 2. Declare new names starting with an underscore if they are\n" 542 msg107 =
" for temporaries you do not want propagated into the Process. The\n" 543 msg108 =
" underscore tells \"from x import *\" and process.load not to import\n" 544 msg109 =
" the name.\n" 545 msg110 =
" 3. Reorganize so the assigment is not necessary. Giving a second\n" 546 msg111 =
" name to the same object usually causes confusion and problems.\n" 547 msg112 =
" 4. Compose Sequences: newName = cms.Sequence(oldName)\n" 548 raise ValueError(msg100+msg101+msg102+msg103+msg104+msg105+msg106+msg107+msg108+msg109+msg110+msg111+msg112)
567 myDeps=knownDeps.get(self.
label_(),
None)
569 if presentDeps != myDeps:
570 raise RuntimeError(
"the module "+self.
label_()+
" has two dependencies \n" 571 +
str(presentDeps)+
"\n" 573 +
"Please modify sequences to rectify this inconsistency")
575 myDeps=set(presentDeps)
576 knownDeps[self.
label_()]=myDeps
577 presentDeps.add(self.
label_())
581 """A 'mixin' used to denote that the class can be used without a label (e.g. a Service)""" 584 class _ValidatingListBase(list):
585 """Base class for a list which enforces that its entries pass a 'validity' test""" 587 super(_ValidatingListBase,self).
__init__(arg)
589 raise SyntaxError(
"named arguments ("+
','.
join([x
for x
in args])+
") passsed to "+
str(type(self)))
590 if not type(self).
_isValid(iter(self)):
591 raise TypeError(
"wrong types ("+
','.
join([
str(type(value))
for value
in iter(self)])+
592 ") added to "+
str(type(self)))
594 if isinstance(key,slice):
596 raise TypeError(
"wrong type being inserted into this container "+self.
_labelIfAny())
598 if not self._itemIsValid(value):
599 raise TypeError(
"can not insert the type "+
str(type(value))+
" in container "+self.
_labelIfAny())
600 super(_ValidatingListBase,self).
__setitem__(key,value)
604 if isinstance(seq, str):
607 if not cls._itemIsValid(item):
613 if isinstance(seq, str):
618 if not self._itemIsValid(x):
619 raise TypeError(
"wrong type being appended to container "+self.
_labelIfAny())
623 raise TypeError(
"wrong type being extended to container "+self.
_labelIfAny())
627 raise TypeError(
"wrong type being added to container "+self.
_labelIfAny())
629 value = copy.copy(self)
633 if not self._itemIsValid(x):
634 raise TypeError(
"wrong type being inserted to container "+self.
_labelIfAny())
637 result = type(self).__name__
638 if hasattr(self,
'__label'):
639 result +=
' ' + self.__label
644 _ParameterTypeBase.__init__(self)
645 if len (arg) == 1
and not isinstance(arg[0],str):
650 super(_ValidatingParameterListBase,self).
__init__(*arg,**args)
660 for value
in iter(self):
662 config += options.indentation()
668 config += options.indentation()+
'}\n' 677 specialImportRegistry.registerUse(self)
680 if hasattr(self,
"_nPerLine"):
681 nPerLine = self._nPerLine
684 if n>nPerLine: options.indent()
688 for i, v
in enumerate(self):
690 if n>nPerLine: result +=
'\n'+options.indentation()
692 if i % nPerLine == 0:
693 result +=
',\n'+options.indentation()
699 result +=
'\n'+options.indentation()
712 fInfo = inspect.getframeinfo(sys._getframe(level+1))
713 obj._filename = fInfo.filename
714 obj._lineNumber =fInfo.lineno
719 for key,value
in newParams.items():
723 elif isinstance(value, dict):
724 if isinstance(params[key],_Parameterizable):
726 p =pset.parameters_()
727 oldkeys = set(p.keys())
730 (
"%s.%s" if isinstance(key, str)
else "%s[%s]")%(keyDepth,key))
731 for k,v
in p.items():
736 elif isinstance(params[key],_ValidatingParameterListBase):
737 if any(
not isinstance(k, int)
for k
in value.keys()):
738 raise TypeError(
"Attempted to change a list using a dict whose keys are not integers")
740 if any((k < 0
or k >= len(plist))
for k
in value.keys()):
741 raise IndexError(
"Attempted to set an index which is not in the list")
742 p = dict(enumerate(plist))
745 (
"%s.%s" if isinstance(key, str)
else "%s[%s]")%(keyDepth,key))
746 for k,v
in p.items():
749 raise ValueError(
"Attempted to change non PSet value "+keyDepth+
" using a dictionary")
750 elif isinstance(value,_ParameterTypeBase)
or (isinstance(key, int))
or isinstance(value, _Parameterizable):
755 if isinstance(value,_ParameterTypeBase)
or isinstance(value, _Parameterizable):
761 if __name__ ==
"__main__":
771 self.assertEqual(t,[1])
773 self.assertEqual(t,[1])
775 self.assertEqual(t,[
"one"])
777 self.assertEqual(t,[1])
779 self.assertEqual(t,[1])
782 self.assertEqual(t,[1,2])
784 self.assertEqual(t,[1,2])
786 self.assertEqual(t,[
"one",
"two"])
788 self.assertEqual(t,[
"one",
"two"])
790 self.assertEqual(t,[1,2])
792 self.assertEqual(t,[1,2])
794 self.assertEqual(t,[1,2])
800 args = [i
for i
in range(0,300)]
803 pdump= t.dumpPython()
807 pythonized = eval( pdump, globals(),{
'cms':
cms()} )
808 self.assertEqual(t,pythonized)
811 self.assertTrue(isinstance(a, _ParameterTypeBase))
816 def _isValid(self,value):
821 _ParameterTypeBase.__init__(self)
822 _Parameterizable.__init__(self,*arg,**args)
824 a = __Test(
"MyType", __PSet(a=__TestType(1)))
825 self.assertEqual(a.a.value(), 1)
826 b = __Test(
"MyType", __PSet(a=__TestType(1)), __PSet(b=__TestType(2)))
827 self.assertEqual(b.a.value(), 1)
828 self.assertEqual(b.b.value(), 2)
829 self.assertRaises(ValueError,
lambda: __Test(
"MyType", __PSet(a=__TestType(1)), __PSet(a=__TestType(2))))
835 def _isValid(self,value):
837 a = __Test(
"MyType",t=__TestType(1), u=__TestType(2))
839 self.assertEqual(b.t.value(),1)
840 self.assertEqual(b.u.value(),2)
843 self.assertEqual(len(c.parameterNames_()), 0)
845 self.assertEqual(len(d.parameterNames_()), 0)
850 def _isValid(self,value):
855 _ParameterTypeBase.__init__(self)
856 _Parameterizable.__init__(self,*arg,**args)
858 return "__PSet(\n"+_Parameterizable.dumpPython(self, options)+options.indentation()+
")" 864 x = __PSet(a = __TestType(4),
866 c = __PSet(gamma = __TestType(5))))
873 c = a.clone(x = dict(a=
None, c=
None))
874 self.assertEqual(a.t.value(),1)
875 self.assertEqual(a.u.value(),2)
876 self.assertEqual(b.t.value(),3)
877 self.assertEqual(b.u.value(),2)
878 self.assertEqual(b.v.value(),4)
879 self.assertEqual(b.x.a.value(),7)
880 self.assertEqual(b.x.b.value(),6)
881 self.assertEqual(b.x.c.gamma.value(),8)
882 self.assertEqual(b.x.d.value(),9)
883 self.assertEqual(hasattr(b,
"w"),
False)
884 self.assertEqual(hasattr(c.x,
"a"),
False)
885 self.assertEqual(hasattr(c.x,
"c"),
False)
886 self.assertRaises(TypeError,a.clone,**{
"v":1})
887 d = a.clone(__PSet(k=__TestType(42)))
888 self.assertEqual(d.t.value(), 1)
889 self.assertEqual(d.k.value(), 42)
890 d2 = a.clone(__PSet(t=__TestType(42)))
891 self.assertEqual(d2.t.value(), 42)
892 d3 = a.clone(__PSet(t=__TestType(42)),
893 __PSet(u=__TestType(56)))
894 self.assertEqual(d3.t.value(), 42)
895 self.assertEqual(d3.u.value(), 56)
896 self.assertRaises(ValueError,a.clone,
897 __PSet(t=__TestType(42)),
898 __PSet(t=__TestType(56)))
899 d4 = a.clone(__PSet(t=__TestType(43)), u = 57)
900 self.assertEqual(d4.t.value(), 43)
901 self.assertEqual(d4.u.value(), 57)
902 self.assertRaises(TypeError,a.clone,t=__TestType(43),**{
"doesNotExist":57})
905 self.assertEqual(len(e.parameterNames_()), 0)
906 f = e.clone(__PSet(a = __TestType(1)), b = __TestType(2))
907 self.assertEqual(f.a.value(), 1)
908 self.assertEqual(f.b.value(), 2)
910 self.assertEqual(len(g.parameterNames_()), 0)
914 def _isValid(self,value):
917 self.assertEqual(a.isModified(),
False)
919 self.assertEqual(a.isModified(),
False)
921 self.assertEqual(a.isModified(),
True)
923 self.assertEqual(a.isModified(),
False)
928 def _isValid(self,value):
930 class __DummyModule(
object):
936 self.assertEqual(p.dumpPython(), eval(p.dumpPython(),{
"cms": __DummyModule()}).
dumpPython())
939 reg.registerSpecialImportForType(int,
"import foo")
940 self.assertRaises(RuntimeError,
lambda: reg.registerSpecialImportForType(int,
"import bar"))
941 reg.registerSpecialImportForType(str,
"import bar")
942 self.assertEqual(reg.getSpecialImports(), [])
944 self.assertEqual(reg.getSpecialImports(), [])
946 self.assertEqual(reg.getSpecialImports(), [
"import foo"])
948 self.assertEqual(reg.getSpecialImports(), [
"import foo"])
950 self.assertEqual(reg.getSpecialImports(), [
"import bar",
"import foo"])
955 def _isValid(self,value):
958 def _isValid(self,value):
963 self.assertRaises(TypeError,
lambda : setattr(a,
't',__TestTypeB(2)))
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 _checkAndReturnValueWithType(self, valueWithType)
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 _itemIsValid(cls, item)
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 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 testInvalidTypeChange(self)
if(threadIdxLocalY==0 &&threadIdxLocalX==0)
def getParameter(self, params)
def appendToProcessDescList_(self, lst, myname)
def insertContentsInto(self, parameterSet)
def dumpSequencePython(self, options=PrintOptions())
def __init__(self, arg, args)