4 """Denotes a class that can be used by the Processes class"""
20 """base class for classes which are used as the 'parameters' for a ParameterSet"""
22 self.__dict__[
"_isFrozen"] =
False
31 return type(self).__name__
32 return 'untracked '+type(self).__name__
35 return 'cms.'+type(self).__name__
36 return 'cms.untracked.'+type(self).__name__
51 """base class for parameter classes which only hold a single value"""
53 super(_SimpleParameterTypeBase,self).
__init__()
55 if not self._isValid(value):
56 raise ValueError(str(value)+
" is not a valid "+str(type(self)))
60 if not self._isValid(value):
61 raise ValueError(str(value)+
" is not a valid "+str(type(self)))
70 if isinstance(other,_SimpleParameterTypeBase):
71 return self.
_value == other._value
72 return self.
_value == other
74 if isinstance(other,_SimpleParameterTypeBase):
75 return self.
_value != other._value
76 return self.
_value != other
80 """For injection purposes, pretend this is a new parameter type
81 then have a post process step which strips these out
83 def __init__(self,value, s='', loc=0, file=''):
84 super(UsingBlock,self).
__init__(value)
91 return isinstance(value,str)
93 """only used for cfg-parsing"""
100 parameterSet.addString(self.
isTracked(), myname, value)
103 return "process."+self.
value()
109 """Base class for classes which allow addition of _ParameterTypeBase data"""
111 self.__dict__[
'_Parameterizable__parameterNames'] = []
112 self.__dict__[
"_isFrozen"] =
False
113 """The named arguments are the 'parameters' which are added as 'python attributes' to the object"""
117 if type(block).__name__ !=
"PSet":
118 raise ValueError(
"Only PSets can be passed as unnamed argument blocks. This is a "+type(block).__name__)
124 """Returns the name of the parameters"""
125 return self.__parameterNames[:]
130 param = self.__dict__[name]
131 if isinstance(param, _Parameterizable)
and param.isModified():
140 check that pset provided has the attribute chain
143 Eg, if params is [ 'attr1', 'attr2', 'attr3' ]
144 check for pset.attr1.attr2.attr3
146 returns True if parameter exists, False if not
154 Retrieve the specified parameter from the PSet Provided
155 given the attribute chain
157 returns None if not found
161 if type(params).__name__ ==
'str':
162 return getattr(self, params,
None)
164 lastParam = getattr(lastParam, param,
None)
166 if lastParam ==
None:
171 """Returns a dictionary of copies of the user-set parameters"""
175 result[name]=copy.deepcopy(self.__dict__[name])
179 if not isinstance(value,_ParameterTypeBase):
181 if name
in self.__dict__:
182 message =
"Duplicate insert of member " + name
183 message +=
"\nThe original parameters are:\n"
185 raise ValueError(message)
186 self.__dict__[name]=value
187 self.__parameterNames.append(name)
191 for name,value
in parameters.iteritems():
197 if self.
isFrozen()
and not (name
in [
"_Labelable__label",
"_isFrozen"]
or name.startswith(
'_')):
198 message =
"Object already added to a process. It is read only now\n"
199 message +=
" %s = %s" %(name, value)
200 message +=
"\nThe original parameters are:\n"
202 raise ValueError(message)
205 super(_Parameterizable,self).
__setattr__(name,value)
206 elif not name
in self.__dict__:
211 if isinstance(value,_ParameterTypeBase):
212 self.__dict__[name] = value
225 raise ValueError(
"Object already added to a process. It is read only now")
227 self.__parameterNames.remove(name)
230 raise TypeError(name+
" does not already exist, so it can only be set to a CMS python configuration type")
233 if len(sortedNames) > 200:
242 for name
in sortedNames:
243 param = self.__dict__[name]
245 name2 = name.replace(
'-',
'_')
248 if name.startswith(
"using_"):
249 usings.append(options.indentation()+param.dumpPython(options))
251 others.append((name2, param.dumpPython(options)))
254 resultList =
',\n'.
join(usings)
255 longOthers = options.indentation()+
"**dict(\n"
257 longOthers += options.indentation()+
"[\n"
262 if entriesInList > 200:
265 longOthers += options.indentation()+
"] +\n"+options.indentation()+
"[\n"
268 longOthers += options.indentation()+
'("'+n+
'" , '+v+
' ),\n'
270 longOthers += options.indentation()+
"]\n"
272 longOthers +=options.indentation()+
")\n"
276 ret.append(resultList)
278 ret.append(longOthers)
279 return ",\n".
join(ret)
283 for name
in sortedNames:
284 param = self.__dict__[name]
286 name2 = name.replace(
'-',
'_')
289 if name.startswith(
"using_"):
290 usings.append(options.indentation()+param.dumpPython(options))
292 others.append(options.indentation()+name2+
' = '+param.dumpPython(options))
296 resultList.extend(others)
297 return ',\n'.
join(resultList)+
'\n'
302 param = getattr(self,name)
303 param.insertInto(parameterSet, name)
307 """Base class for classes which are Parameterizable and have a 'type' assigned"""
309 self.__dict__[
'_TypedParameterizable__type'] = type_
315 arg = tuple([x
for x
in arg
if x !=
None])
316 super(_TypedParameterizable,self).
__init__(*arg,**kargs)
319 self._placeImpl(name,proc)
321 """returns the type of the object, e.g. 'FooProducer'"""
324 returnValue =_TypedParameterizable.__new__(type(self))
329 returnValue.__init__(self.__type,*args,
334 """Copies the object and allows one to modify the parameters of the clone.
335 New parameters may be added by specify the exact type
336 Modifying existing parameters can be done by just specifying the new
337 value without having to specify the type.
338 A parameter may be removed from the clone using the value None.
339 #remove the parameter foo.fred
340 mod.toModify(foo, fred = None)
341 A parameter embedded within a PSet may be changed via a dictionary
342 #change foo.fred.pebbles to 3 and foo.fred.friend to "barney"
343 mod.toModify(foo, fred = dict(pebbles = 3, friend = "barney)) )
345 returnValue =_TypedParameterizable.__new__(type(self))
347 if len(myparams) == 0
and len(params)
and len(args):
352 returnValue.__init__(self.__type,*args,
354 returnValue._isModified =
False
355 returnValue._isFrozen =
False
366 choices.extend(glob.glob(d+
'/*/*/'+label+
'.py'))
376 mod = __import__(name)
377 components = name.split(
'.')
378 for comp
in components[1:]:
379 mod = getattr(mod,comp)
380 if hasattr(mod,label):
381 default = getattr(mod,label)
382 if isinstance(default,_TypedParameterizable):
383 if(default.type_() == type):
385 for name
in default.parameterNames_():
386 params[name] = getattr(default,name)
391 config = self.__type +
' { \n'
393 param = self.__dict__[name]
395 config+=options.indentation()+param.configTypeName()+
' '+name+
' = '+param.configValue(options)+
'\n'
397 config += options.indentation()+
'}\n'
401 result =
"cms."+str(type(self).__name__)+
'("'+self.
type_()+
'"'
406 result +=
",\n"+_Parameterizable.dumpPython(self,options)+options.indentation() +
")\n"
410 """ dumps the object with all attributes declared after the constructor"""
413 param = self.__dict__[name]
414 result += options.indentation() + myname +
"." + name +
" = " + param.dumpPython(options) +
"\n"
422 newpset = parameterSet.newPSet()
423 newpset.addString(
True,
"@module_label", self.
moduleLabel_(myname))
424 newpset.addString(
True,
"@module_type", self.
type_())
425 newpset.addString(
True,
"@module_edm_type", type(self).__name__)
432 """A 'mixin' used to denote that the class can be paired with a label (e.g. an EDProducer)"""
434 if not hasattr(self,
"_Labelable__label"):
435 raise RuntimeError(
"module has no label. Perhaps it wasn't inserted into the process?")
438 return hasattr(self,
"_Labelable__label")
and self.
__label is not None
441 if self.
label_() != label
and label
is not None :
442 msg100 =
"Attempting to change the label of a Labelable object, possibly an attribute of the Process\n"
443 msg101 =
"Old label = "+self.
label_()+
" New label = "+label+
"\n"
444 msg102 =
"Type = "+str(type(self))+
"\n"
445 msg103 =
"Some possible solutions:\n"
446 msg104 =
" 1. Clone modules instead of using simple assignment. Cloning is\n"
447 msg105 =
" also preferred for other types when possible.\n"
448 msg106 =
" 2. Declare new names starting with an underscore if they are\n"
449 msg107 =
" for temporaries you do not want propagated into the Process. The\n"
450 msg108 =
" underscore tells \"from x import *\" and process.load not to import\n"
451 msg109 =
" the name.\n"
452 msg110 =
" 3. Reorganize so the assigment is not necessary. Giving a second\n"
453 msg111 =
" name to the same object usually causes confusion and problems.\n"
454 msg112 =
" 4. Compose Sequences: newName = cms.Sequence(oldName)\n"
455 raise ValueError(msg100+msg101+msg102+msg103+msg104+msg105+msg106+msg107+msg108+msg109+msg110+msg111+msg112)
468 return 'process.'+str(self.
__label)
471 myDeps=knownDeps.get(self.
label_(),
None)
473 if presentDeps != myDeps:
474 raise RuntimeError(
"the module "+self.
label_()+
" has two dependencies \n"
475 +str(presentDeps)+
"\n"
477 +
"Please modify sequences to rectify this inconsistency")
479 myDeps=set(presentDeps)
480 knownDeps[self.
label_()]=myDeps
481 presentDeps.add(self.
label_())
485 """A 'mixin' used to denote that the class can be used without a label (e.g. a Service)"""
488 class _ValidatingListBase(
list):
489 """Base class for a list which enforces that its entries pass a 'validity' test"""
491 super(_ValidatingListBase,self).
__init__(arg)
493 raise SyntaxError(
"named arguments ("+
','.
join([x
for x
in args])+
") passsed to "+str(type(self)))
495 raise TypeError(
"wrong types ("+
','.
join([str(type(value))
for value
in iter(self)])+
496 ") added to "+str(type(self)))
498 if isinstance(key,slice):
500 raise TypeError(
"wrong type being inserted into this container "+self.
_labelIfAny())
502 if not self._itemIsValid(value):
503 raise TypeError(
"can not insert the type "+str(type(value))+
" in container "+self.
_labelIfAny())
504 super(_ValidatingListBase,self).
__setitem__(key,value)
507 if isinstance(seq, str):
510 if not self._itemIsValid(item):
514 if not self._itemIsValid(x):
515 raise TypeError(
"wrong type being appended to container "+self.
_labelIfAny())
516 super(_ValidatingListBase,self).
append(x)
519 raise TypeError(
"wrong type being extended to container "+self.
_labelIfAny())
520 super(_ValidatingListBase,self).
extend(x)
523 raise TypeError(
"wrong type being added to container "+self.
_labelIfAny())
525 value = copy.copy(self)
529 if not self._itemIsValid(x):
530 raise TypeError(
"wrong type being inserted to container "+self.
_labelIfAny())
531 super(_ValidatingListBase,self).
insert(i,x)
533 result = type(self).__name__
534 if hasattr(self,
'__label'):
535 result +=
' ' + self.__label
540 _ParameterTypeBase.__init__(self)
541 if len (arg) == 1
and not isinstance(arg[0],str):
546 super(_ValidatingParameterListBase,self).
__init__(*arg,**args)
556 for value
in iter(self):
558 config += options.indentation()
564 config += options.indentation()+
'}\n'
579 for i, v
in enumerate(self):
581 if hasattr(self,
"_nPerLine"):
582 nPerLine = self._nPerLine
590 if i % nPerLine == 0:
591 result +=
'\n'+options.indentation()
606 frame = inspect.getframeinfo(inspect.currentframe(level+1))
610 obj._filename = frame[0]
611 obj._lineNumber = frame[1]
616 for key,value
in newParams.iteritems():
620 elif isinstance(value, dict):
621 if isinstance(params[key],_Parameterizable):
623 p =pset.parameters_()
626 (
"%s.%s" if type(key)==str
else "%s[%s]")%(keyDepth,key))
627 for k,v
in p.iteritems():
629 elif isinstance(params[key],_ValidatingParameterListBase):
630 if any(type(k) != int
for k
in value.keys()):
631 raise TypeError(
"Attempted to change a list using a dict whose keys are not integers")
633 if any((k < 0
or k >= len(plist))
for k
in value.keys()):
634 raise IndexError(
"Attempted to set an index which is not in the list")
635 p =
dict(enumerate(plist))
638 (
"%s.%s" if type(key)==str
else "%s[%s]")%(keyDepth,key))
639 for k,v
in p.iteritems():
642 raise ValueError(
"Attempted to change non PSet value "+keyDepth+
" using a dictionary")
643 elif isinstance(value,_ParameterTypeBase)
or (type(key) == int):
648 if isinstance(value,_ParameterTypeBase):
654 if __name__ ==
"__main__":
663 self.assertEqual(t,[1])
665 self.assertEqual(t,[1])
667 self.assertEqual(t,[
"one"])
669 self.assertEqual(t,[1])
671 self.assertEqual(t,[1])
674 self.assertEqual(t,[1,2])
676 self.assertEqual(t,[1,2])
678 self.assertEqual(t,[
"one",
"two"])
680 self.assertEqual(t,[
"one",
"two"])
682 self.assertEqual(t,[1,2])
684 self.assertEqual(t,[1,2])
686 self.assertEqual(t,[1,2])
692 args = [i
for i
in xrange(0,300)]
695 pdump= t.dumpPython()
699 pythonized = eval( pdump, globals(),{
'cms':
cms()} )
700 self.assertEqual(t,pythonized)
703 self.assert_(isinstance(a, _ParameterTypeBase))
708 def _isValid(self,value):
710 a = __Test(
"MyType",t=__TestType(1), u=__TestType(2))
712 self.assertEqual(b.t.value(),1)
713 self.assertEqual(b.u.value(),2)
718 def _isValid(self,value):
721 def __init__(self,*arg,**args):
723 _ParameterTypeBase.__init__(self)
724 _Parameterizable.__init__(self,*arg,**args)
729 x = __PSet(a = __TestType(4),
731 c = __PSet(gamma = __TestType(5))))
738 self.assertEqual(a.t.value(),1)
739 self.assertEqual(a.u.value(),2)
740 self.assertEqual(b.t.value(),3)
741 self.assertEqual(b.u.value(),2)
742 self.assertEqual(b.v.value(),4)
743 self.assertEqual(b.x.a.value(),7)
744 self.assertEqual(b.x.b.value(),6)
745 self.assertEqual(b.x.c.gamma.value(),8)
746 self.assertEqual(b.x.d.value(),9)
747 self.assertEqual(hasattr(b,
"w"),
False)
748 self.assertRaises(TypeError,a.clone,
None,**{
"v":1})
751 def _isValid(self,value):
754 self.assertEqual(a.isModified(),
False)
756 self.assertEqual(a.isModified(),
False)
758 self.assertEqual(a.isModified(),
True)
760 self.assertEqual(a.isModified(),
False)
765 def _isValid(self,value):
767 class __DummyModule(object):
773 self.assertEqual(p.dumpPython(), eval(p.dumpPython(),{
"cms": __DummyModule()}).
dumpPython())
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 ...
static std::string join(char **cmd)
def _modifyParametersFromDict
def testLargeParameterizable
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