1 from __future__
import print_function
2 from builtins
import range
7 """Denotes a class that can be used by the Processes class""" 24 """This class collects special import statements of configuration types""" 29 for lst
in six.itervalues(self.
_registry):
33 className = cls.__name__
35 raise RuntimeError(
"Error: the configuration type '%s' already has an import statement registered '%s'" % (className, self.
_registry[className][0]))
36 self.
_registry[className] = [impStatement,
False]
39 className = obj.__class__.__name__
47 for (imp, used)
in six.itervalues(self.
_registry):
55 """base class for classes which are used as the 'parameters' for a ParameterSet""" 57 self.__dict__[
"_isFrozen"] =
False 66 return type(self).__name__
67 return 'untracked '+type(self).__name__
70 return 'cms.'+type(self).__name__
71 return 'cms.untracked.'+type(self).__name__
73 specialImportRegistry.registerUse(self)
87 """base class for parameter classes which only hold a single value""" 89 super(_SimpleParameterTypeBase,self).
__init__()
91 if not self._isValid(value):
92 raise ValueError(
str(value)+
" is not a valid "+
str(type(self)))
96 if not self._isValid(value):
97 raise ValueError(
str(value)+
" is not a valid "+
str(type(self)))
106 if isinstance(other,_SimpleParameterTypeBase):
107 return self.
_value == other._value
108 return self.
_value == other
110 if isinstance(other,_SimpleParameterTypeBase):
111 return self.
_value != other._value
112 return self.
_value != other
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
132 """For injection purposes, pretend this is a new parameter type 133 then have a post process step which strips these out 136 super(UsingBlock,self).
__init__(value)
143 return isinstance(value,str)
145 """only used for cfg-parsing""" 152 parameterSet.addString(self.
isTracked(), myname, value)
155 return "process."+self.
value()
161 """Base class for classes which allow addition of _ParameterTypeBase data""" 163 self.__dict__[
'_Parameterizable__parameterNames'] = []
164 self.__dict__[
"_isFrozen"] =
False 165 """The named arguments are the 'parameters' which are added as 'python attributes' to the object""" 169 if type(block).__name__ !=
"PSet":
170 raise ValueError(
"Only PSets can be passed as unnamed argument blocks. This is a "+type(block).__name__)
176 """Returns the name of the parameters""" 177 return self.__parameterNames[:]
182 param = self.__dict__[name]
183 if isinstance(param, _Parameterizable)
and param.isModified():
192 check that pset provided has the attribute chain 195 Eg, if params is [ 'attr1', 'attr2', 'attr3' ] 196 check for pset.attr1.attr2.attr3 198 returns True if parameter exists, False if not 206 Retrieve the specified parameter from the PSet Provided 207 given the attribute chain 209 returns None if not found 213 if type(params).__name__ ==
'str':
214 return getattr(self, params,
None)
216 lastParam = getattr(lastParam, param,
None)
218 if lastParam ==
None:
223 """Returns a dictionary of copies of the user-set parameters""" 227 result[name]=copy.deepcopy(self.__dict__[name])
231 if not isinstance(value,_ParameterTypeBase):
233 if name
in self.__dict__:
234 message =
"Duplicate insert of member " + name
235 message +=
"\nThe original parameters are:\n" 237 raise ValueError(message)
238 self.__dict__[name]=value
239 self.__parameterNames.append(name)
243 for name,value
in six.iteritems(parameters):
249 if self.
isFrozen()
and not (name
in [
"_Labelable__label",
"_isFrozen"]
or name.startswith(
'_')):
250 message =
"Object already added to a process. It is read only now\n" 251 message +=
" %s = %s" %(name, value)
252 message +=
"\nThe original parameters are:\n" 254 raise ValueError(message)
257 super(_Parameterizable,self).
__setattr__(name,value)
258 elif not name
in self.__dict__:
263 if isinstance(value,_ParameterTypeBase):
264 self.__dict__[name] = value
277 raise ValueError(
"Object already added to a process. It is read only now")
279 self.__parameterNames.remove(name)
282 raise TypeError(name+
" does not already exist, so it can only be set to a CMS python configuration type")
284 specialImportRegistry.registerUse(self)
286 if len(sortedNames) > 200:
295 for name
in sortedNames:
296 param = self.__dict__[name]
298 name2 = name.replace(
'-',
'_')
301 if name.startswith(
"using_"):
302 usings.append(options.indentation()+param.dumpPython(options))
304 others.append((name2, param.dumpPython(options)))
307 resultList =
',\n'.
join(usings)
308 longOthers = options.indentation()+
"**dict(\n" 310 longOthers += options.indentation()+
"[\n" 315 if entriesInList > 200:
318 longOthers += options.indentation()+
"] +\n"+options.indentation()+
"[\n" 321 longOthers += options.indentation()+
'("'+n+
'" , '+v+
' ),\n' 323 longOthers += options.indentation()+
"]\n" 325 longOthers +=options.indentation()+
")\n" 329 ret.append(resultList)
331 ret.append(longOthers)
332 return ",\n".
join(ret)
336 for name
in sortedNames:
337 param = self.__dict__[name]
339 name2 = name.replace(
'-',
'_')
342 if name.startswith(
"using_"):
343 usings.append(options.indentation()+param.dumpPython(options))
345 others.append(options.indentation()+name2+
' = '+param.dumpPython(options))
349 resultList.extend(others)
350 return ',\n'.
join(resultList)+
'\n' 355 param = getattr(self,name)
356 param.insertInto(parameterSet, name)
360 """Base class for classes which are Parameterizable and have a 'type' assigned""" 362 self.__dict__[
'_TypedParameterizable__type'] = type_
368 arg = tuple([x
for x
in arg
if x !=
None])
369 super(_TypedParameterizable,self).
__init__(*arg,**kargs)
372 self._placeImpl(name,proc)
374 """returns the type of the object, e.g. 'FooProducer'""" 377 returnValue =_TypedParameterizable.__new__(type(self))
382 returnValue.__init__(self.__type,*args,
387 """Copies the object and allows one to modify the parameters of the clone. 388 New parameters may be added by specify the exact type 389 Modifying existing parameters can be done by just specifying the new 390 value without having to specify the type. 391 A parameter may be removed from the clone using the value None. 392 #remove the parameter foo.fred 393 mod.toModify(foo, fred = None) 394 A parameter embedded within a PSet may be changed via a dictionary 395 #change foo.fred.pebbles to 3 and foo.fred.friend to "barney" 396 mod.toModify(foo, fred = dict(pebbles = 3, friend = "barney)) ) 398 returnValue =_TypedParameterizable.__new__(type(self))
400 if len(myparams) == 0
and len(params)
and len(args):
405 returnValue.__init__(self.__type,*args,
407 returnValue._isModified =
False 408 returnValue._isFrozen =
False 419 choices.extend(glob.glob(d+
'/*/*/'+label+
'.py'))
429 mod = __import__(name)
430 components = name.split(
'.')
431 for comp
in components[1:]:
432 mod = getattr(mod,comp)
433 if hasattr(mod,label):
434 default = getattr(mod,label)
435 if isinstance(default,_TypedParameterizable):
436 if(default.type_() == type):
438 for name
in default.parameterNames_():
439 params[name] = getattr(default,name)
444 config = self.__type +
' { \n' 446 param = self.__dict__[name]
448 config+=options.indentation()+param.configTypeName()+
' '+name+
' = '+param.configValue(options)+
'\n' 450 config += options.indentation()+
'}\n' 454 specialImportRegistry.registerUse(self)
455 result =
"cms."+
str(type(self).__name__)+
'("'+self.
type_()+
'"' 460 result +=
",\n"+_Parameterizable.dumpPython(self,options)+options.indentation() +
")\n" 464 """ dumps the object with all attributes declared after the constructor""" 467 param = self.__dict__[name]
468 result += options.indentation() + myname +
"." + name +
" = " + param.dumpPython(options) +
"\n" 478 newpset = parameterSet.newPSet()
479 newpset.addString(
True,
"@module_label", self.
moduleLabel_(myname))
480 newpset.addString(
True,
"@module_type", self.
type_())
481 newpset.addString(
True,
"@module_edm_type", type(self).__name__)
488 """A 'mixin' used to denote that the class can be paired with a label (e.g. an EDProducer)""" 490 if not hasattr(self,
"_Labelable__label"):
491 raise RuntimeError(
"module has no label. Perhaps it wasn't inserted into the process?")
494 return hasattr(self,
"_Labelable__label")
and self.
__label is not None 497 if self.
label_() != label
and label
is not None :
498 msg100 =
"Attempting to change the label of a Labelable object, possibly an attribute of the Process\n" 499 msg101 =
"Old label = "+self.
label_()+
" New label = "+label+
"\n" 500 msg102 =
"Type = "+
str(type(self))+
"\n" 501 msg103 =
"Some possible solutions:\n" 502 msg104 =
" 1. Clone modules instead of using simple assignment. Cloning is\n" 503 msg105 =
" also preferred for other types when possible.\n" 504 msg106 =
" 2. Declare new names starting with an underscore if they are\n" 505 msg107 =
" for temporaries you do not want propagated into the Process. The\n" 506 msg108 =
" underscore tells \"from x import *\" and process.load not to import\n" 507 msg109 =
" the name.\n" 508 msg110 =
" 3. Reorganize so the assigment is not necessary. Giving a second\n" 509 msg111 =
" name to the same object usually causes confusion and problems.\n" 510 msg112 =
" 4. Compose Sequences: newName = cms.Sequence(oldName)\n" 511 raise ValueError(msg100+msg101+msg102+msg103+msg104+msg105+msg106+msg107+msg108+msg109+msg110+msg111+msg112)
527 myDeps=knownDeps.get(self.
label_(),
None)
529 if presentDeps != myDeps:
530 raise RuntimeError(
"the module "+self.
label_()+
" has two dependencies \n" 531 +
str(presentDeps)+
"\n" 533 +
"Please modify sequences to rectify this inconsistency")
535 myDeps=set(presentDeps)
536 knownDeps[self.
label_()]=myDeps
537 presentDeps.add(self.
label_())
541 """A 'mixin' used to denote that the class can be used without a label (e.g. a Service)""" 544 class _ValidatingListBase(
list):
545 """Base class for a list which enforces that its entries pass a 'validity' test""" 547 super(_ValidatingListBase,self).
__init__(arg)
549 raise SyntaxError(
"named arguments ("+
','.
join([x
for x
in args])+
") passsed to "+
str(type(self)))
551 raise TypeError(
"wrong types ("+
','.
join([
str(type(value))
for value
in iter(self)])+
552 ") added to "+
str(type(self)))
554 if isinstance(key,slice):
556 raise TypeError(
"wrong type being inserted into this container "+self.
_labelIfAny())
558 if not self._itemIsValid(value):
559 raise TypeError(
"can not insert the type "+
str(type(value))+
" in container "+self.
_labelIfAny())
560 super(_ValidatingListBase,self).
__setitem__(key,value)
563 if isinstance(seq, str):
566 if not self._itemIsValid(item):
570 if not self._itemIsValid(x):
571 raise TypeError(
"wrong type being appended to container "+self.
_labelIfAny())
572 super(_ValidatingListBase,self).
append(x)
575 raise TypeError(
"wrong type being extended to container "+self.
_labelIfAny())
576 super(_ValidatingListBase,self).
extend(x)
579 raise TypeError(
"wrong type being added to container "+self.
_labelIfAny())
581 value = copy.copy(self)
585 if not self._itemIsValid(x):
586 raise TypeError(
"wrong type being inserted to container "+self.
_labelIfAny())
587 super(_ValidatingListBase,self).
insert(i,x)
589 result = type(self).__name__
590 if hasattr(self,
'__label'):
591 result +=
' ' + self.__label
596 _ParameterTypeBase.__init__(self)
597 if len (arg) == 1
and not isinstance(arg[0],str):
602 super(_ValidatingParameterListBase,self).
__init__(*arg,**args)
612 for value
in iter(self):
614 config += options.indentation()
620 config += options.indentation()+
'}\n' 629 specialImportRegistry.registerUse(self)
632 if hasattr(self,
"_nPerLine"):
633 nPerLine = self._nPerLine
636 if n>nPerLine: options.indent()
640 for i, v
in enumerate(self):
642 if n>nPerLine: result +=
'\n'+options.indentation()
645 if i % nPerLine == 0:
646 result +=
'\n'+options.indentation()
650 result +=
'\n'+options.indentation()
661 fInfo = inspect.getframeinfo(sys._getframe(level+1))
662 obj._filename = fInfo.filename
663 obj._lineNumber =fInfo.lineno
668 for key,value
in six.iteritems(newParams):
672 elif isinstance(value, dict):
673 if isinstance(params[key],_Parameterizable):
675 p =pset.parameters_()
676 oldkeys = set(p.keys())
679 (
"%s.%s" if isinstance(key, str)
else "%s[%s]")%(keyDepth,key))
680 for k,v
in six.iteritems(p):
685 elif isinstance(params[key],_ValidatingParameterListBase):
686 if any(
not isinstance(k, int)
for k
in value.keys()):
687 raise TypeError(
"Attempted to change a list using a dict whose keys are not integers")
689 if any((k < 0
or k >= len(plist))
for k
in value.keys()):
690 raise IndexError(
"Attempted to set an index which is not in the list")
691 p =
dict(enumerate(plist))
694 (
"%s.%s" if isinstance(key, str)
else "%s[%s]")%(keyDepth,key))
695 for k,v
in six.iteritems(p):
698 raise ValueError(
"Attempted to change non PSet value "+keyDepth+
" using a dictionary")
699 elif isinstance(value,_ParameterTypeBase)
or (isinstance(key, int))
or isinstance(value, _Parameterizable):
704 if isinstance(value,_ParameterTypeBase)
or isinstance(value, _Parameterizable):
710 if __name__ ==
"__main__":
719 self.assertEqual(t,[1])
721 self.assertEqual(t,[1])
723 self.assertEqual(t,[
"one"])
725 self.assertEqual(t,[1])
727 self.assertEqual(t,[1])
730 self.assertEqual(t,[1,2])
732 self.assertEqual(t,[1,2])
734 self.assertEqual(t,[
"one",
"two"])
736 self.assertEqual(t,[
"one",
"two"])
738 self.assertEqual(t,[1,2])
740 self.assertEqual(t,[1,2])
742 self.assertEqual(t,[1,2])
748 args = [i
for i
in range(0,300)]
751 pdump= t.dumpPython()
755 pythonized = eval( pdump, globals(),{
'cms':
cms()} )
756 self.assertEqual(t,pythonized)
759 self.assert_(isinstance(a, _ParameterTypeBase))
764 def _isValid(self,value):
766 a = __Test(
"MyType",t=__TestType(1), u=__TestType(2))
768 self.assertEqual(b.t.value(),1)
769 self.assertEqual(b.u.value(),2)
774 def _isValid(self,value):
777 def __init__(self,*arg,**args):
779 _ParameterTypeBase.__init__(self)
780 _Parameterizable.__init__(self,*arg,**args)
785 x = __PSet(a = __TestType(4),
787 c = __PSet(gamma = __TestType(5))))
794 c = a.clone(x =
dict(a=
None, c=
None))
795 self.assertEqual(a.t.value(),1)
796 self.assertEqual(a.u.value(),2)
797 self.assertEqual(b.t.value(),3)
798 self.assertEqual(b.u.value(),2)
799 self.assertEqual(b.v.value(),4)
800 self.assertEqual(b.x.a.value(),7)
801 self.assertEqual(b.x.b.value(),6)
802 self.assertEqual(b.x.c.gamma.value(),8)
803 self.assertEqual(b.x.d.value(),9)
804 self.assertEqual(hasattr(b,
"w"),
False)
805 self.assertEqual(hasattr(c.x,
"a"),
False)
806 self.assertEqual(hasattr(c.x,
"c"),
False)
807 self.assertRaises(TypeError,a.clone,
None,**{
"v":1})
810 def _isValid(self,value):
813 self.assertEqual(a.isModified(),
False)
815 self.assertEqual(a.isModified(),
False)
817 self.assertEqual(a.isModified(),
True)
819 self.assertEqual(a.isModified(),
False)
824 def _isValid(self,value):
826 class __DummyModule(
object):
832 self.assertEqual(p.dumpPython(), eval(p.dumpPython(),{
"cms": __DummyModule()}).
dumpPython())
835 reg.registerSpecialImportForType(int,
"import foo")
836 self.assertRaises(
lambda x: reg.registerSpecialImportForType(int,
"import bar"))
837 reg.registerSpecialImportForType(str,
"import bar")
838 self.assertEqual(reg.getSpecialImports(), [])
840 self.assertEqual(reg.getSpecialImports(), [])
842 self.assertEqual(reg.getSpecialImports(), [
"import foo"])
844 self.assertEqual(reg.getSpecialImports(), [
"import foo"])
846 self.assertEqual(reg.getSpecialImports(), [
"import bar",
"import foo"])
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 dumpPython(self, options=PrintOptions())
def __init__(self, arg, kargs)
def dumpPythonAttributes(self, myname, options)
def _valueFromString(value)
def setLabel(self, label)
def registerUse(self, obj)
def nameInProcessDesc_(self, myname)
S & print(S &os, JobReport::InputFile const &f)
bool setValue(Container &, const reco::JetBaseRef &, const JetExtendedData &)
associate jet with value. Returns false and associate nothing if jet is already associated ...
def dumpPython(self, options=PrintOptions())
def testListConstruction(self)
def insertInto(self, parameterSet, myname)
def dumpPython(self, options=PrintOptions())
def __delattr__(self, name)
def _itemsFromStrings(strings, converter)
def clone(self, args, params)
def dumpSequenceConfig(self)
def __init__(self, type_, arg, kargs)
def testLargeParameterizable(self)
def __init__(self, value, s='', loc=0, file='')
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 _itemIsValid(self, item)
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 pythonValueForItem(self, item, options)
def __setitem__(self, key, value)
def pythonValue(self, options=PrintOptions())
def configValueForItem(self, item, options)
def __init__(self, value)
def getParameter(self, params)
def appendToProcessDescList_(self, lst, myname)
def insertContentsInto(self, parameterSet)
def dumpSequencePython(self, options=PrintOptions())
def __init__(self, arg, args)
How EventSelector::AcceptEvent() decides whether to accept an event for output otherwise it is excluding the probing of A single or multiple positive and the trigger will pass if any such matching triggers are PASS or EXCEPTION[A criterion thatmatches no triggers at all is detected and causes a throw.] A single negative with an expectation of appropriate bit checking in the decision and the trigger will pass if any such matching triggers are FAIL or EXCEPTION A wildcarded negative criterion that matches more than one trigger in the trigger list("!*","!HLTx*"if it matches 2 triggers or more) will accept the event if all the matching triggers are FAIL.It will reject the event if any of the triggers are PASS or EXCEPTION(this matches the behavior of"!*"before the partial wildcard feature was incorporated).Triggers which are in the READY state are completely ignored.(READY should never be returned since the trigger paths have been run