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"""
30 for lst
in self._registry.values():
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__
48 for (imp, used)
in self._registry.values():
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)
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):
242 value = self.__validator.convert_(value)
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 for name,value
in parameters.items():
257 if name ==
'allowAnyLabel_':
266 if self.
isFrozen()
and not (name
in [
"_Labelable__label",
"_isFrozen"]
or name.startswith(
'_')):
267 message =
"Object already added to a process. It is read only now\n"
268 message +=
" %s = %s" %(name, value)
269 message +=
"\nThe original parameters are:\n"
271 raise ValueError(message)
274 super(_Parameterizable,self).
__setattr__(name,value)
275 elif not name
in self.__dict__:
280 if isinstance(value,_ParameterTypeBase):
281 self.__dict__[name] = value
294 raise ValueError(
"Object already added to a process. It is read only now")
296 self.__parameterNames.remove(name)
299 raise TypeError(name+
" does not already exist, so it can only be set to a CMS python configuration type")
301 specialImportRegistry.registerUse(self)
303 if len(sortedNames) > 200:
312 for name
in sortedNames:
313 param = self.__dict__[name]
315 name2 = name.replace(
'-',
'_')
318 if name.startswith(
"using_"):
319 usings.append(options.indentation()+param.dumpPython(options))
321 others.append((name2, param.dumpPython(options)))
324 resultList =
',\n'.
join(usings)
325 longOthers = options.indentation()+
"**dict(\n"
327 longOthers += options.indentation()+
"[\n"
332 if entriesInList > 200:
335 longOthers += options.indentation()+
"] +\n"+options.indentation()+
"[\n"
338 longOthers += options.indentation()+
'("'+n+
'" , '+v+
' ),\n'
340 longOthers += options.indentation()+
"]\n"
342 longOthers +=options.indentation()+
")\n"
346 ret.append(resultList)
348 ret.append(longOthers)
349 return ",\n".
join(ret)
353 for name
in sortedNames:
354 param = self.__dict__[name]
356 name2 = name.replace(
'-',
'_')
359 if name.startswith(
"using_"):
360 usings.append(options.indentation()+param.dumpPython(options))
362 others.append(options.indentation()+name2+
' = '+param.dumpPython(options))
366 resultList.extend(others)
369 resultList.append(options.indentation()+
"allowAnyLabel_="+self.__validator.dumpPython(options))
371 return ',\n'.
join(resultList)+
'\n'
376 param = getattr(self,name)
377 param.insertInto(parameterSet, name)
381 """Base class for classes which are Parameterizable and have a 'type' assigned"""
383 self.__dict__[
'_TypedParameterizable__type'] = type_
389 super(_TypedParameterizable,self).
__init__(*arg,**kargs)
392 self._placeImpl(name,proc)
394 """returns the type of the object, e.g. 'FooProducer'"""
397 returnValue =_TypedParameterizable.__new__(type(self))
399 returnValue.__init__(self.__type,**params)
403 """Copies the object and allows one to modify the parameters of the clone.
404 New parameters may be added by specify the exact type
405 Modifying existing parameters can be done by just specifying the new
406 value without having to specify the type.
407 A parameter may be removed from the clone using the value None.
408 #remove the parameter foo.fred
409 mod.toModify(foo, fred = None)
410 A parameter embedded within a PSet may be changed via a dictionary
411 #change foo.fred.pebbles to 3 and foo.fred.friend to "barney"
412 mod.toModify(foo, fred = dict(pebbles = 3, friend = "barney)) )
414 returnValue =_TypedParameterizable.__new__(type(self))
420 if type(block).__name__
not in [
"PSet",
"__PSet"]:
421 raise ValueError(
"Only PSets can be passed as unnamed argument blocks. This is a "+type(block).__name__)
422 for name
in block.parameterNames_():
429 if self._Parameterizable__validator
is not None:
430 myparams[
"allowAnyLabel_"] = self._Parameterizable__validator
432 returnValue.__init__(self.__type,*args,
434 returnValue._isModified =
False
435 returnValue._isFrozen =
False
446 choices.extend(glob.glob(d+
'/*/*/'+label+
'.py'))
456 mod = __import__(name)
457 components = name.split(
'.')
458 for comp
in components[1:]:
459 mod = getattr(mod,comp)
460 if hasattr(mod,label):
461 default = getattr(mod,label)
462 if isinstance(default,_TypedParameterizable):
463 if(default.type_() == type):
465 for name
in default.parameterNames_():
466 params[name] = getattr(default,name)
474 config = self.__type +
' { \n'
476 param = self.__dict__[name]
478 config+=options.indentation()+param.configTypeName()+
' '+name+
' = '+param.configValue(options)+
'\n'
480 config += options.indentation()+
'}\n'
484 specialImportRegistry.registerUse(self)
485 result =
"cms."+
str(type(self).__name__)+
'("'+self.
type_()+
'"'
490 result +=
",\n"+_Parameterizable.dumpPython(self,options)+options.indentation() +
")\n"
494 """ dumps the object with all attributes declared after the constructor"""
497 param = self.__dict__[name]
498 result += options.indentation() + myname +
"." + name +
" = " + param.dumpPython(options) +
"\n"
508 newpset = parameterSet.newPSet()
509 newpset.addString(
True,
"@module_label", self.
moduleLabel_(myname))
510 newpset.addString(
True,
"@module_type", self.
type_())
511 newpset.addString(
True,
"@module_edm_type", type(self).__name__)
518 """A 'mixin' used to denote that the class can be paired with a label (e.g. an EDProducer)"""
520 if not hasattr(self,
"_Labelable__label"):
521 raise RuntimeError(
"module has no label. Perhaps it wasn't inserted into the process?")
524 return hasattr(self,
"_Labelable__label")
and self.
__label is not None
527 if self.
label_() != label
and label
is not None :
528 msg100 =
"Attempting to change the label of a Labelable object, possibly an attribute of the Process\n"
529 msg101 =
"Old label = "+self.
label_()+
" New label = "+label+
"\n"
530 msg102 =
"Type = "+
str(type(self))+
"\n"
531 msg103 =
"Some possible solutions:\n"
532 msg104 =
" 1. Clone modules instead of using simple assignment. Cloning is\n"
533 msg105 =
" also preferred for other types when possible.\n"
534 msg106 =
" 2. Declare new names starting with an underscore if they are\n"
535 msg107 =
" for temporaries you do not want propagated into the Process. The\n"
536 msg108 =
" underscore tells \"from x import *\" and process.load not to import\n"
537 msg109 =
" the name.\n"
538 msg110 =
" 3. Reorganize so the assigment is not necessary. Giving a second\n"
539 msg111 =
" name to the same object usually causes confusion and problems.\n"
540 msg112 =
" 4. Compose Sequences: newName = cms.Sequence(oldName)\n"
541 raise ValueError(msg100+msg101+msg102+msg103+msg104+msg105+msg106+msg107+msg108+msg109+msg110+msg111+msg112)
560 myDeps=knownDeps.get(self.
label_(),
None)
562 if presentDeps != myDeps:
563 raise RuntimeError(
"the module "+self.
label_()+
" has two dependencies \n"
564 +
str(presentDeps)+
"\n"
566 +
"Please modify sequences to rectify this inconsistency")
568 myDeps=set(presentDeps)
569 knownDeps[self.
label_()]=myDeps
570 presentDeps.add(self.
label_())
574 """A 'mixin' used to denote that the class can be used without a label (e.g. a Service)"""
577 class _ValidatingListBase(list):
578 """Base class for a list which enforces that its entries pass a 'validity' test"""
580 super(_ValidatingListBase,self).
__init__(arg)
582 raise SyntaxError(
"named arguments ("+
','.
join([x
for x
in args])+
") passsed to "+
str(type(self)))
584 raise TypeError(
"wrong types ("+
','.
join([
str(type(value))
for value
in iter(self)])+
585 ") added to "+
str(type(self)))
587 if isinstance(key,slice):
589 raise TypeError(
"wrong type being inserted into this container "+self.
_labelIfAny())
591 if not self._itemIsValid(value):
592 raise TypeError(
"can not insert the type "+
str(type(value))+
" in container "+self.
_labelIfAny())
593 super(_ValidatingListBase,self).
__setitem__(key,value)
596 if isinstance(seq, str):
599 if not self._itemIsValid(item):
605 if isinstance(seq, str):
610 if not self._itemIsValid(x):
611 raise TypeError(
"wrong type being appended to container "+self.
_labelIfAny())
615 raise TypeError(
"wrong type being extended to container "+self.
_labelIfAny())
619 raise TypeError(
"wrong type being added to container "+self.
_labelIfAny())
621 value = copy.copy(self)
625 if not self._itemIsValid(x):
626 raise TypeError(
"wrong type being inserted to container "+self.
_labelIfAny())
629 result = type(self).__name__
630 if hasattr(self,
'__label'):
631 result +=
' ' + self.__label
636 _ParameterTypeBase.__init__(self)
637 if len (arg) == 1
and not isinstance(arg[0],str):
642 super(_ValidatingParameterListBase,self).
__init__(*arg,**args)
652 for value
in iter(self):
654 config += options.indentation()
660 config += options.indentation()+
'}\n'
669 specialImportRegistry.registerUse(self)
672 if hasattr(self,
"_nPerLine"):
673 nPerLine = self._nPerLine
676 if n>nPerLine: options.indent()
680 for i, v
in enumerate(self):
682 if n>nPerLine: result +=
'\n'+options.indentation()
684 if i % nPerLine == 0:
685 result +=
',\n'+options.indentation()
691 result +=
'\n'+options.indentation()
704 fInfo = inspect.getframeinfo(sys._getframe(level+1))
705 obj._filename = fInfo.filename
706 obj._lineNumber =fInfo.lineno
711 for key,value
in newParams.items():
715 elif isinstance(value, dict):
716 if isinstance(params[key],_Parameterizable):
718 p =pset.parameters_()
719 oldkeys = set(p.keys())
722 (
"%s.%s" if isinstance(key, str)
else "%s[%s]")%(keyDepth,key))
723 for k,v
in p.items():
728 elif isinstance(params[key],_ValidatingParameterListBase):
729 if any(
not isinstance(k, int)
for k
in value.keys()):
730 raise TypeError(
"Attempted to change a list using a dict whose keys are not integers")
732 if any((k < 0
or k >= len(plist))
for k
in value.keys()):
733 raise IndexError(
"Attempted to set an index which is not in the list")
734 p = dict(enumerate(plist))
737 (
"%s.%s" if isinstance(key, str)
else "%s[%s]")%(keyDepth,key))
738 for k,v
in p.items():
741 raise ValueError(
"Attempted to change non PSet value "+keyDepth+
" using a dictionary")
742 elif isinstance(value,_ParameterTypeBase)
or (isinstance(key, int))
or isinstance(value, _Parameterizable):
747 if isinstance(value,_ParameterTypeBase)
or isinstance(value, _Parameterizable):
753 if __name__ ==
"__main__":
762 self.assertEqual(t,[1])
764 self.assertEqual(t,[1])
766 self.assertEqual(t,[
"one"])
768 self.assertEqual(t,[1])
770 self.assertEqual(t,[1])
773 self.assertEqual(t,[1,2])
775 self.assertEqual(t,[1,2])
777 self.assertEqual(t,[
"one",
"two"])
779 self.assertEqual(t,[
"one",
"two"])
781 self.assertEqual(t,[1,2])
783 self.assertEqual(t,[1,2])
785 self.assertEqual(t,[1,2])
791 args = [i
for i
in range(0,300)]
794 pdump= t.dumpPython()
798 pythonized = eval( pdump, globals(),{
'cms':
cms()} )
799 self.assertEqual(t,pythonized)
802 self.assertTrue(isinstance(a, _ParameterTypeBase))
807 def _isValid(self,value):
812 _ParameterTypeBase.__init__(self)
813 _Parameterizable.__init__(self,*arg,**args)
815 a = __Test(
"MyType", __PSet(a=__TestType(1)))
816 self.assertEqual(a.a.value(), 1)
817 b = __Test(
"MyType", __PSet(a=__TestType(1)), __PSet(b=__TestType(2)))
818 self.assertEqual(b.a.value(), 1)
819 self.assertEqual(b.b.value(), 2)
820 self.assertRaises(ValueError,
lambda: __Test(
"MyType", __PSet(a=__TestType(1)), __PSet(a=__TestType(2))))
826 def _isValid(self,value):
828 a = __Test(
"MyType",t=__TestType(1), u=__TestType(2))
830 self.assertEqual(b.t.value(),1)
831 self.assertEqual(b.u.value(),2)
834 self.assertEqual(len(c.parameterNames_()), 0)
836 self.assertEqual(len(d.parameterNames_()), 0)
841 def _isValid(self,value):
846 _ParameterTypeBase.__init__(self)
847 _Parameterizable.__init__(self,*arg,**args)
849 return "__PSet(\n"+_Parameterizable.dumpPython(self, options)+options.indentation()+
")"
855 x = __PSet(a = __TestType(4),
857 c = __PSet(gamma = __TestType(5))))
864 c = a.clone(x = dict(a=
None, c=
None))
865 self.assertEqual(a.t.value(),1)
866 self.assertEqual(a.u.value(),2)
867 self.assertEqual(b.t.value(),3)
868 self.assertEqual(b.u.value(),2)
869 self.assertEqual(b.v.value(),4)
870 self.assertEqual(b.x.a.value(),7)
871 self.assertEqual(b.x.b.value(),6)
872 self.assertEqual(b.x.c.gamma.value(),8)
873 self.assertEqual(b.x.d.value(),9)
874 self.assertEqual(hasattr(b,
"w"),
False)
875 self.assertEqual(hasattr(c.x,
"a"),
False)
876 self.assertEqual(hasattr(c.x,
"c"),
False)
877 self.assertRaises(TypeError,a.clone,**{
"v":1})
878 d = a.clone(__PSet(k=__TestType(42)))
879 self.assertEqual(d.t.value(), 1)
880 self.assertEqual(d.k.value(), 42)
881 d2 = a.clone(__PSet(t=__TestType(42)))
882 self.assertEqual(d2.t.value(), 42)
883 d3 = a.clone(__PSet(t=__TestType(42)),
884 __PSet(u=__TestType(56)))
885 self.assertEqual(d3.t.value(), 42)
886 self.assertEqual(d3.u.value(), 56)
887 self.assertRaises(ValueError,a.clone,
888 __PSet(t=__TestType(42)),
889 __PSet(t=__TestType(56)))
890 d4 = a.clone(__PSet(t=__TestType(43)), u = 57)
891 self.assertEqual(d4.t.value(), 43)
892 self.assertEqual(d4.u.value(), 57)
893 self.assertRaises(TypeError,a.clone,t=__TestType(43),**{
"doesNotExist":57})
896 self.assertEqual(len(e.parameterNames_()), 0)
897 f = e.clone(__PSet(a = __TestType(1)), b = __TestType(2))
898 self.assertEqual(f.a.value(), 1)
899 self.assertEqual(f.b.value(), 2)
901 self.assertEqual(len(g.parameterNames_()), 0)
905 def _isValid(self,value):
908 self.assertEqual(a.isModified(),
False)
910 self.assertEqual(a.isModified(),
False)
912 self.assertEqual(a.isModified(),
True)
914 self.assertEqual(a.isModified(),
False)
919 def _isValid(self,value):
921 class __DummyModule(object):
927 self.assertEqual(p.dumpPython(), eval(p.dumpPython(),{
"cms": __DummyModule()}).
dumpPython())
930 reg.registerSpecialImportForType(int,
"import foo")
931 self.assertRaises(RuntimeError,
lambda: reg.registerSpecialImportForType(int,
"import bar"))
932 reg.registerSpecialImportForType(str,
"import bar")
933 self.assertEqual(reg.getSpecialImports(), [])
935 self.assertEqual(reg.getSpecialImports(), [])
937 self.assertEqual(reg.getSpecialImports(), [
"import foo"])
939 self.assertEqual(reg.getSpecialImports(), [
"import foo"])
941 self.assertEqual(reg.getSpecialImports(), [
"import bar",
"import foo"])
def appendToProcessDescList_
bool any(const std::vector< T > &v, const T &what)
bool setValue(Container &, const reco::JetBaseRef &, const JetExtendedData &)
associate jet with value. Returns false and associate nothing if jet is already associated ...
const uint16_t range(const Frame &aFrame)
if(conf_.getParameter< bool >("UseStripCablingDB"))
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Namespace of DDCMS conversion namespace.
static std::string join(char **cmd)
def _modifyParametersFromDict
def testSpecialImportRegistry
def registerSpecialImportForType
def testLargeParameterizable