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"]:
180 raise ValueError(
"Only PSets can be passed as unnamed argument blocks. This is a "+type(block).__name__)
186 """Returns the name of the parameters""" 187 return self.__parameterNames[:]
192 param = self.__dict__[name]
193 if isinstance(param, _Parameterizable)
and param.isModified():
202 check that pset provided has the attribute chain 205 Eg, if params is [ 'attr1', 'attr2', 'attr3' ] 206 check for pset.attr1.attr2.attr3 208 returns True if parameter exists, False if not 216 Retrieve the specified parameter from the PSet Provided 217 given the attribute chain 219 returns None if not found 223 if type(params).__name__ ==
'str':
224 return getattr(self, params,
None)
226 lastParam = getattr(lastParam, param,
None)
227 if lastParam ==
None:
232 """Returns a dictionary of copies of the user-set parameters""" 236 result[name]=copy.deepcopy(self.__dict__[name])
240 if name ==
'allowAnyLabel_':
244 if not isinstance(value,_ParameterTypeBase):
249 if name
in self.__dict__:
250 message =
"Duplicate insert of member " + name
251 message +=
"\nThe original parameters are:\n" 253 raise ValueError(message)
254 self.__dict__[name]=value
255 self.__parameterNames.
append(name)
260 for name,value
in parameters.items():
261 if name ==
'allowAnyLabel_':
270 if self.
isFrozen()
and not (name
in [
"_Labelable__label",
"_isFrozen"]
or name.startswith(
'_')):
271 message =
"Object already added to a process. It is read only now\n" 272 message +=
" %s = %s" %(name, value)
273 message +=
"\nThe original parameters are:\n" 275 raise ValueError(message)
278 super(_Parameterizable,self).
__setattr__(name,value)
279 elif not name
in self.__dict__:
284 if isinstance(value,_ParameterTypeBase):
285 self.__dict__[name] = self.__dict__[name]._checkAndReturnValueWithType(value)
298 raise ValueError(
"Object already added to a process. It is read only now")
300 self.__parameterNames.
remove(name)
303 raise TypeError(name+
" does not already exist, so it can only be set to a CMS python configuration type")
305 specialImportRegistry.registerUse(self)
307 if len(sortedNames) > 200:
316 for name
in sortedNames:
317 param = self.__dict__[name]
319 name2 = name.replace(
'-',
'_')
322 if name.startswith(
"using_"):
323 usings.append(options.indentation()+param.dumpPython(options))
325 others.append((name2, param.dumpPython(options)))
328 resultList =
',\n'.
join(usings)
329 longOthers = options.indentation()+
"**dict(\n" 331 longOthers += options.indentation()+
"[\n" 336 if entriesInList > 200:
339 longOthers += options.indentation()+
"] +\n"+options.indentation()+
"[\n" 342 longOthers += options.indentation()+
'("'+n+
'" , '+v+
' ),\n' 344 longOthers += options.indentation()+
"]\n" 346 longOthers +=options.indentation()+
")\n" 350 ret.append(resultList)
352 ret.append(longOthers)
353 return ",\n".
join(ret)
357 for name
in sortedNames:
358 param = self.__dict__[name]
360 name2 = name.replace(
'-',
'_')
363 if name.startswith(
"using_"):
364 usings.append(options.indentation()+param.dumpPython(options))
366 others.append(options.indentation()+name2+
' = '+param.dumpPython(options))
370 resultList.extend(others)
375 return ',\n'.
join(resultList)+
'\n' 380 param = getattr(self,name)
381 param.insertInto(parameterSet, name)
385 """Base class for classes which are Parameterizable and have a 'type' assigned""" 387 self.__dict__[
'_TypedParameterizable__type'] = type_
393 super(_TypedParameterizable,self).
__init__(*arg,**kargs)
396 self._placeImpl(name,proc)
398 """returns the type of the object, e.g. 'FooProducer'""" 401 returnValue =_TypedParameterizable.__new__(type(self))
403 returnValue.__init__(self.__type,**params)
407 """Copies the object and allows one to modify the parameters of the clone. 408 New parameters may be added by specify the exact type 409 Modifying existing parameters can be done by just specifying the new 410 value without having to specify the type. 411 A parameter may be removed from the clone using the value None. 412 #remove the parameter foo.fred 413 mod.toModify(foo, fred = None) 414 A parameter embedded within a PSet may be changed via a dictionary 415 #change foo.fred.pebbles to 3 and foo.fred.friend to "barney" 416 mod.toModify(foo, fred = dict(pebbles = 3, friend = "barney)) ) 418 returnValue =_TypedParameterizable.__new__(type(self))
424 if type(block).__name__
not in [
"PSet",
"__PSet"]:
425 raise ValueError(
"Only PSets can be passed as unnamed argument blocks. This is a "+type(block).__name__)
426 for name
in block.parameterNames_():
433 if self._Parameterizable__validator
is not None:
434 myparams[
"allowAnyLabel_"] = self._Parameterizable__validator
436 returnValue.__init__(self.__type,*args,
438 returnValue._isModified =
False 439 returnValue._isFrozen =
False 450 choices.extend(glob.glob(d+
'/*/*/'+label+
'.py'))
460 mod = __import__(name)
461 components = name.split(
'.')
462 for comp
in components[1:]:
463 mod = getattr(mod,comp)
464 if hasattr(mod,label):
465 default = getattr(mod,label)
466 if isinstance(default,_TypedParameterizable):
467 if(default.type_() == type):
469 for name
in default.parameterNames_():
470 params[name] = getattr(default,name)
478 config = self.__type +
' { \n' 480 param = self.__dict__[name]
482 config+=options.indentation()+param.configTypeName()+
' '+name+
' = '+param.configValue(options)+
'\n' 484 config += options.indentation()+
'}\n' 488 specialImportRegistry.registerUse(self)
489 result =
"cms."+
str(type(self).__name__)+
'("'+self.
type_()+
'"' 494 result +=
",\n"+_Parameterizable.dumpPython(self,options)+options.indentation() +
")\n" 498 """ dumps the object with all attributes declared after the constructor""" 501 param = self.__dict__[name]
502 result += options.indentation() + myname +
"." + name +
" = " + param.dumpPython(options) +
"\n" 512 newpset = parameterSet.newPSet()
513 newpset.addString(
True,
"@module_label", self.
moduleLabel_(myname))
514 newpset.addString(
True,
"@module_type", self.
type_())
515 newpset.addString(
True,
"@module_edm_type", type(self).__name__)
522 """A 'mixin' used to denote that the class can be paired with a label (e.g. an EDProducer)""" 524 if not hasattr(self,
"_Labelable__label"):
525 raise RuntimeError(
"module has no label. Perhaps it wasn't inserted into the process?")
528 return hasattr(self,
"_Labelable__label")
and self.
__label is not None 531 if self.
label_() != label
and label
is not None :
532 msg100 =
"Attempting to change the label of a Labelable object, possibly an attribute of the Process\n" 533 msg101 =
"Old label = "+self.
label_()+
" New label = "+label+
"\n" 534 msg102 =
"Type = "+
str(type(self))+
"\n" 535 msg103 =
"Some possible solutions:\n" 536 msg104 =
" 1. Clone modules instead of using simple assignment. Cloning is\n" 537 msg105 =
" also preferred for other types when possible.\n" 538 msg106 =
" 2. Declare new names starting with an underscore if they are\n" 539 msg107 =
" for temporaries you do not want propagated into the Process. The\n" 540 msg108 =
" underscore tells \"from x import *\" and process.load not to import\n" 541 msg109 =
" the name.\n" 542 msg110 =
" 3. Reorganize so the assigment is not necessary. Giving a second\n" 543 msg111 =
" name to the same object usually causes confusion and problems.\n" 544 msg112 =
" 4. Compose Sequences: newName = cms.Sequence(oldName)\n" 545 raise ValueError(msg100+msg101+msg102+msg103+msg104+msg105+msg106+msg107+msg108+msg109+msg110+msg111+msg112)
564 myDeps=knownDeps.get(self.
label_(),
None)
566 if presentDeps != myDeps:
567 raise RuntimeError(
"the module "+self.
label_()+
" has two dependencies \n" 568 +
str(presentDeps)+
"\n" 570 +
"Please modify sequences to rectify this inconsistency")
572 myDeps=set(presentDeps)
573 knownDeps[self.
label_()]=myDeps
574 presentDeps.add(self.
label_())
578 """A 'mixin' used to denote that the class can be used without a label (e.g. a Service)""" 581 class _ValidatingListBase(list):
582 """Base class for a list which enforces that its entries pass a 'validity' test""" 584 super(_ValidatingListBase,self).
__init__(arg)
586 raise SyntaxError(
"named arguments ("+
','.
join([x
for x
in args])+
") passsed to "+
str(type(self)))
587 if not type(self).
_isValid(iter(self)):
588 raise TypeError(
"wrong types ("+
','.
join([
str(type(value))
for value
in iter(self)])+
589 ") added to "+
str(type(self)))
591 if isinstance(key,slice):
593 raise TypeError(
"wrong type being inserted into this container "+self.
_labelIfAny())
595 if not self._itemIsValid(value):
596 raise TypeError(
"can not insert the type "+
str(type(value))+
" in container "+self.
_labelIfAny())
597 super(_ValidatingListBase,self).
__setitem__(key,value)
601 if isinstance(seq, str):
604 if not cls._itemIsValid(item):
610 if isinstance(seq, str):
615 if not self._itemIsValid(x):
616 raise TypeError(
"wrong type being appended to container "+self.
_labelIfAny())
620 raise TypeError(
"wrong type being extended to container "+self.
_labelIfAny())
624 raise TypeError(
"wrong type being added to container "+self.
_labelIfAny())
626 value = copy.copy(self)
630 if not self._itemIsValid(x):
631 raise TypeError(
"wrong type being inserted to container "+self.
_labelIfAny())
634 result = type(self).__name__
635 if hasattr(self,
'__label'):
636 result +=
' ' + self.__label
641 _ParameterTypeBase.__init__(self)
642 if len (arg) == 1
and not isinstance(arg[0],str):
647 super(_ValidatingParameterListBase,self).
__init__(*arg,**args)
657 for value
in iter(self):
659 config += options.indentation()
665 config += options.indentation()+
'}\n' 674 specialImportRegistry.registerUse(self)
677 if hasattr(self,
"_nPerLine"):
678 nPerLine = self._nPerLine
681 if n>nPerLine: options.indent()
685 for i, v
in enumerate(self):
687 if n>nPerLine: result +=
'\n'+options.indentation()
689 if i % nPerLine == 0:
690 result +=
',\n'+options.indentation()
696 result +=
'\n'+options.indentation()
709 fInfo = inspect.getframeinfo(sys._getframe(level+1))
710 obj._filename = fInfo.filename
711 obj._lineNumber =fInfo.lineno
716 for key,value
in newParams.items():
720 elif isinstance(value, dict):
721 if isinstance(params[key],_Parameterizable):
723 p =pset.parameters_()
724 oldkeys = set(p.keys())
727 (
"%s.%s" if isinstance(key, str)
else "%s[%s]")%(keyDepth,key))
728 for k,v
in p.items():
733 elif isinstance(params[key],_ValidatingParameterListBase):
734 if any(
not isinstance(k, int)
for k
in value.keys()):
735 raise TypeError(
"Attempted to change a list using a dict whose keys are not integers")
737 if any((k < 0
or k >= len(plist))
for k
in value.keys()):
738 raise IndexError(
"Attempted to set an index which is not in the list")
739 p = dict(enumerate(plist))
742 (
"%s.%s" if isinstance(key, str)
else "%s[%s]")%(keyDepth,key))
743 for k,v
in p.items():
746 raise ValueError(
"Attempted to change non PSet value "+keyDepth+
" using a dictionary")
747 elif isinstance(value,_ParameterTypeBase)
or (isinstance(key, int))
or isinstance(value, _Parameterizable):
752 if isinstance(value,_ParameterTypeBase)
or isinstance(value, _Parameterizable):
758 if __name__ ==
"__main__":
768 self.assertEqual(t,[1])
770 self.assertEqual(t,[1])
772 self.assertEqual(t,[
"one"])
774 self.assertEqual(t,[1])
776 self.assertEqual(t,[1])
779 self.assertEqual(t,[1,2])
781 self.assertEqual(t,[1,2])
783 self.assertEqual(t,[
"one",
"two"])
785 self.assertEqual(t,[
"one",
"two"])
787 self.assertEqual(t,[1,2])
789 self.assertEqual(t,[1,2])
791 self.assertEqual(t,[1,2])
797 args = [i
for i
in range(0,300)]
800 pdump= t.dumpPython()
804 pythonized = eval( pdump, globals(),{
'cms':
cms()} )
805 self.assertEqual(t,pythonized)
808 self.assertTrue(isinstance(a, _ParameterTypeBase))
813 def _isValid(self,value):
818 _ParameterTypeBase.__init__(self)
819 _Parameterizable.__init__(self,*arg,**args)
821 a = __Test(
"MyType", __PSet(a=__TestType(1)))
822 self.assertEqual(a.a.value(), 1)
823 b = __Test(
"MyType", __PSet(a=__TestType(1)), __PSet(b=__TestType(2)))
824 self.assertEqual(b.a.value(), 1)
825 self.assertEqual(b.b.value(), 2)
826 self.assertRaises(ValueError,
lambda: __Test(
"MyType", __PSet(a=__TestType(1)), __PSet(a=__TestType(2))))
832 def _isValid(self,value):
834 a = __Test(
"MyType",t=__TestType(1), u=__TestType(2))
836 self.assertEqual(b.t.value(),1)
837 self.assertEqual(b.u.value(),2)
840 self.assertEqual(len(c.parameterNames_()), 0)
842 self.assertEqual(len(d.parameterNames_()), 0)
847 def _isValid(self,value):
852 _ParameterTypeBase.__init__(self)
853 _Parameterizable.__init__(self,*arg,**args)
855 return "__PSet(\n"+_Parameterizable.dumpPython(self, options)+options.indentation()+
")" 861 x = __PSet(a = __TestType(4),
863 c = __PSet(gamma = __TestType(5))))
870 c = a.clone(x = dict(a=
None, c=
None))
871 self.assertEqual(a.t.value(),1)
872 self.assertEqual(a.u.value(),2)
873 self.assertEqual(b.t.value(),3)
874 self.assertEqual(b.u.value(),2)
875 self.assertEqual(b.v.value(),4)
876 self.assertEqual(b.x.a.value(),7)
877 self.assertEqual(b.x.b.value(),6)
878 self.assertEqual(b.x.c.gamma.value(),8)
879 self.assertEqual(b.x.d.value(),9)
880 self.assertEqual(hasattr(b,
"w"),
False)
881 self.assertEqual(hasattr(c.x,
"a"),
False)
882 self.assertEqual(hasattr(c.x,
"c"),
False)
883 self.assertRaises(TypeError,a.clone,**{
"v":1})
884 d = a.clone(__PSet(k=__TestType(42)))
885 self.assertEqual(d.t.value(), 1)
886 self.assertEqual(d.k.value(), 42)
887 d2 = a.clone(__PSet(t=__TestType(42)))
888 self.assertEqual(d2.t.value(), 42)
889 d3 = a.clone(__PSet(t=__TestType(42)),
890 __PSet(u=__TestType(56)))
891 self.assertEqual(d3.t.value(), 42)
892 self.assertEqual(d3.u.value(), 56)
893 self.assertRaises(ValueError,a.clone,
894 __PSet(t=__TestType(42)),
895 __PSet(t=__TestType(56)))
896 d4 = a.clone(__PSet(t=__TestType(43)), u = 57)
897 self.assertEqual(d4.t.value(), 43)
898 self.assertEqual(d4.u.value(), 57)
899 self.assertRaises(TypeError,a.clone,t=__TestType(43),**{
"doesNotExist":57})
902 self.assertEqual(len(e.parameterNames_()), 0)
903 f = e.clone(__PSet(a = __TestType(1)), b = __TestType(2))
904 self.assertEqual(f.a.value(), 1)
905 self.assertEqual(f.b.value(), 2)
907 self.assertEqual(len(g.parameterNames_()), 0)
911 def _isValid(self,value):
914 self.assertEqual(a.isModified(),
False)
916 self.assertEqual(a.isModified(),
False)
918 self.assertEqual(a.isModified(),
True)
920 self.assertEqual(a.isModified(),
False)
925 def _isValid(self,value):
927 class __DummyModule(
object):
933 self.assertEqual(p.dumpPython(), eval(p.dumpPython(),{
"cms": __DummyModule()}).
dumpPython())
936 reg.registerSpecialImportForType(int,
"import foo")
937 self.assertRaises(RuntimeError,
lambda: reg.registerSpecialImportForType(int,
"import bar"))
938 reg.registerSpecialImportForType(str,
"import bar")
939 self.assertEqual(reg.getSpecialImports(), [])
941 self.assertEqual(reg.getSpecialImports(), [])
943 self.assertEqual(reg.getSpecialImports(), [
"import foo"])
945 self.assertEqual(reg.getSpecialImports(), [
"import foo"])
947 self.assertEqual(reg.getSpecialImports(), [
"import bar",
"import foo"])
952 def _isValid(self,value):
955 def _isValid(self,value):
960 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)