Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-02-22 03:15:54

0001 from __future__ import absolute_import
0002 from .Mixins import PrintOptions, _SimpleParameterTypeBase, _ParameterTypeBase, _Parameterizable, _ConfigureComponent, _Labelable, _TypedParameterizable, _Unlabelable, _modifyParametersFromDict
0003 from .Mixins import _ValidatingParameterListBase, specialImportRegistry
0004 from .Mixins import saveOrigin
0005 from .ExceptionHandling import format_typename, format_outerframe
0006 from past.builtins import long
0007 import codecs
0008 import copy
0009 import math
0010 import builtins
0011 
0012 _builtin_bool = bool
0013 
0014 class _Untracked(object):
0015     """Class type for 'untracked' to allow nice syntax"""
0016     __name__ = "untracked"
0017     @staticmethod
0018     def __call__(param):
0019         """used to set a 'param' parameter to be 'untracked'"""
0020         param.setIsTracked(False)
0021         return param
0022     def __getattr__(self,name):
0023         """A factory which allows syntax untracked.name(value) to construct an
0024         instance of 'name' class which is set to be untracked"""
0025         if name == "__bases__": raise AttributeError  # isclass uses __bases__ to recognize class objects
0026         class Factory(object):
0027             def __init__(self,name):
0028                 self.name = name
0029             def __call__(self,*value,**params):
0030                 param = globals()[self.name](*value,**params)
0031                 return _Untracked.__call__(param)
0032         return Factory(name)
0033 
0034 untracked = _Untracked()
0035 
0036 
0037 class _ProxyParameter(_ParameterTypeBase):
0038     """Base class for Parameters which are proxies for other Parameter types"""
0039     def __init__(self,type):
0040         super(_ProxyParameter,self).__init__()
0041         self.__dict__["_ProxyParameter__type"] = type
0042         self.__dict__["_ProxyParameter__value"] = None
0043         if hasattr(self.__type,"_default") and self.__type._default is not None:
0044             self.setValue(self.__type._default)
0045     def setValue(self, value):
0046         v = self.__type(value)
0047         if not _ParameterTypeBase.isTracked(self):
0048             v = untracked(v)
0049         self.__dict__["_ProxyParameter__value"] = v
0050     def _checkAndReturnValueWithType(self, valueWithType):
0051         if isinstance(valueWithType, type(self)):
0052             return valueWithType
0053         if isinstance(self.__type, type):
0054             if isinstance(valueWithType, self.__type):
0055                 self.__dict__["_ProxyParameter__value"] = valueWithType
0056                 return self
0057             else:
0058                 raise TypeError("type {bad} does not match {expected}".format(bad=str(type(valueWithType)), expected = str(self.__type)))
0059         v = self.__type._setValueWithType(valueWithType)
0060         if not _ParameterTypeBase.isTracked(self):
0061             v = untracked(v)
0062         self.__dict__["_ProxyParameter__value"] = v
0063         return self
0064     def __getattr__(self, name):
0065         v =self.__dict__.get('_ProxyParameter__value', None)
0066         if name == '_ProxyParameter__value':
0067             return v
0068         if (not name.startswith('_')) and v is not None:
0069             return getattr(v, name)
0070         else:
0071             return object.__getattribute__ (self, name)
0072     def __setattr__(self,name, value):
0073         v = self.__dict__.get('_ProxyParameter__value',None)
0074         if v is not None:
0075             return setattr(v,name,value)
0076         else:
0077             if not name.startswith('_'):
0078                  raise AttributeError("%r object has no attribute %r" % (self.__class__.__name__, name))
0079             return object.__setattr__(self, name, value)
0080     #support container like behavior
0081     def __iter__(self):
0082         v =self.__dict__.get('_ProxyParameter__value', None)
0083         if v is not None:
0084             return v.__iter__()
0085         else:
0086             raise TypeError("'_ProxyParameter' object is not iterable")
0087     def __setitem__(self, key, value):
0088         v =self.__dict__.get('_ProxyParameter__value', None)
0089         if v is not None:
0090             return v.__setitem__(key,value)
0091         else:
0092             raise TypeError("'_ProxyParameter' object does not support item assignment")
0093     def __getitem__(self, key):
0094         v =self.__dict__.get('_ProxyParameter__value', None)
0095         if v is not None:
0096             return v.__getitem__(key)
0097         else:
0098             raise TypeError("'_ProxyParameter' object is not subscriptable")
0099     def __bool__(self):
0100         v = self.__dict__.get('_ProxyParameter__value',None)
0101         return _builtin_bool(v)
0102     def dumpPython(self, options=PrintOptions()):
0103         v =self.__dict__.get('_ProxyParameter__value',None)
0104         if v is not None:
0105             return v.dumpPython(options)
0106         specialImportRegistry.registerUse(self)
0107         v = "cms."+self._dumpPythonName()
0108         if not _ParameterTypeBase.isTracked(self):
0109             v+=".untracked"
0110         if hasattr(self.__type, "__name__"):
0111             return v+'.'+self.__type.__name__
0112         return v+'.'+self.__type.dumpPython(options)
0113     def validate_(self,value):
0114         return isinstance(value,self.__type)
0115     def convert_(self,value):
0116         v = self.__type(value)
0117         if not _ParameterTypeBase.isTracked(self):
0118             v = untracked(v)
0119         return v
0120     def isCompatibleCMSType(self,aType):
0121         v = self.__dict__.get('_ProxyParameter__value',None)
0122         if v is not None:
0123             return v.isCompatibleCMSType(aType)
0124         return self.__type == aType
0125 
0126 class _RequiredParameter(_ProxyParameter):
0127     @staticmethod
0128     def _dumpPythonName():
0129         return 'required'
0130     def insertInto(self, parameterSet, myname):
0131         v = self.__dict__.get('_ProxyParameter__value', None)
0132         if v is None:
0133             raise RuntimeError("Required parameter "+myname+" was not set")
0134         v.insertInto(parameterSet,myname)
0135 
0136 class _OptionalParameter(_ProxyParameter):
0137     @staticmethod
0138     def _dumpPythonName():
0139         return 'optional'
0140     def insertInto(self, parameterSet, myname):
0141         v = self.__dict__.get('_ProxyParameter__value', None)
0142         if v is not None:
0143             v.insertInto(parameterSet,myname)
0144     def value(self):
0145         v = self.__dict__.get('_ProxyParameter__value', None)
0146         if v is not None:
0147             return v.value()
0148         return None
0149 
0150 class _ObsoleteParameter(_OptionalParameter):
0151     @staticmethod
0152     def _dumpPythonName():
0153         return 'obsolete'
0154 
0155 class _AllowedParameterTypes(object):
0156     def __init__(self, *args, default=None):
0157         self.__dict__['_AllowedParameterTypes__types'] = args
0158         self.__dict__['_default'] = None
0159         self.__dict__['__name__'] = self.dumpPython()
0160         if default is not None:
0161             self.__dict__['_default'] = self._setValueWithType(default)
0162     def dumpPython(self, options=PrintOptions()):
0163         specialImportRegistry.registerUse(self)
0164         return "allowed("+','.join( ("cms."+t.__name__ if not isinstance(t, _PSetTemplate) else "cms."+t.dumpPython() for t in self.__types))+')'
0165     def __call__(self,value):
0166         chosenType = None
0167         for t in self.__types:
0168             if not isinstance(t, _PSetTemplate) and isinstance(value, t):
0169                 return value
0170             if t._isValid(value):
0171                 if chosenType is not None:
0172                     raise RuntimeError("Ambiguous type conversion for 'allowed' parameter")
0173                 chosenType = t
0174         if chosenType is None:
0175             raise RuntimeError("Cannot convert "+str(value)+" to 'allowed' type")
0176         return chosenType(value)
0177     def _setValueWithType(self, valueWithType):
0178         for t in self.__types:
0179             if isinstance(t, _PSetTemplate):
0180                 if isinstance(valueWithType, PSet):
0181                     return valueWithType
0182             elif isinstance(valueWithType, t):
0183                 return valueWithType
0184         raise TypeError("type {bad} is not one of 'allowed' types {types}".format(bad=str(type(valueWithType)), types = ",".join( (str(t) for t in self.__types))) )
0185             
0186 
0187 
0188 class _PSetTemplate(object):
0189     def __init__(self, *args, **kargs):
0190         self._pset = PSet(*args,**kargs)
0191     def __call__(self, value):
0192         self.__dict__
0193         return self._pset.clone(**value)
0194     def _isValid(self, value):
0195         return isinstance(value,dict) or isinstance(value, PSet)
0196     def dumpPython(self, options=PrintOptions()):
0197         return "PSetTemplate(\n"+_Parameterizable.dumpPython(self._pset, options)+options.indentation()+")"
0198     def _setValueWithType(self, valueWithType):
0199         if not isinstance(valueWithType, PSet):
0200             raise TypeError("type {bad} is not a PSet".format(bas=str(type(valueWithType))))
0201         return valueWithType
0202 
0203 PSetTemplate = _PSetTemplate
0204 
0205 class _ProxyParameterFactory(object):
0206     """Class type for ProxyParameter types to allow nice syntax"""
0207     def __init__(self, type, isUntracked = False):
0208         self.__isUntracked = isUntracked
0209         self.__type = type
0210     def __getattr__(self,name):
0211         if name[0] == '_':
0212             return object.__getattribute__(self,name)
0213         if name == 'untracked':
0214             return _ProxyParameterFactory(self.__type,isUntracked=True)
0215         if name == 'allowed':
0216             class _AllowedWrapper(object):
0217                 def __init__(self, untracked, type):
0218                     self.untracked = untracked
0219                     self.type = type
0220                 def __call__(self, *args, **kargs):
0221                     if self.untracked:
0222                         return untracked(self.type(_AllowedParameterTypes(*args, **kargs)))
0223                     return self.type(_AllowedParameterTypes(*args, **kargs))
0224             
0225             return _AllowedWrapper(self.__isUntracked, self.__type)
0226         if name == 'PSetTemplate':
0227             class _PSetTemplateWrapper(object):
0228                 def __init__(self, untracked, type):
0229                     self.untracked = untracked
0230                     self.type = type
0231                 def __call__(self,*args,**kargs):
0232                     if self.untracked:
0233                         return untracked(self.type(_PSetTemplate(*args,**kargs)))
0234                     return self.type(_PSetTemplate(*args,**kargs))
0235             return _PSetTemplateWrapper(self.__isUntracked, self.__type)
0236 
0237         type = globals()[name]
0238         if not issubclass(type, _ParameterTypeBase):
0239             raise AttributeError
0240         if self.__isUntracked:
0241                 return untracked(self.__type(type))
0242         return self.__type(type)
0243 
0244 required = _ProxyParameterFactory(_RequiredParameter)
0245 optional = _ProxyParameterFactory(_OptionalParameter)
0246 obsolete = _ProxyParameterFactory(_ObsoleteParameter)
0247 
0248 class int32(_SimpleParameterTypeBase):
0249     @staticmethod
0250     def _isValid(value):
0251         return isinstance(value,int)
0252     @staticmethod
0253     def _valueFromString(value):
0254         """only used for cfg-parsing"""
0255         if len(value) >1 and '0x' == value[:2]:
0256             return int32(int(value,16))
0257         return int32(int(value))
0258     def insertInto(self, parameterSet, myname):
0259         parameterSet.addInt32(self.isTracked(), myname, self.value())
0260     def __nonzero__(self):
0261         return self.value()!=0
0262     def __bool__(self):
0263         return self.__nonzero__()
0264 
0265 
0266 class uint32(_SimpleParameterTypeBase):
0267     @staticmethod
0268     def _isValid(value):
0269         return ((isinstance(value,int) and value >= 0) or
0270                 (isinstance(value,long) and value >= 0) and value <= 0xFFFFFFFF)
0271     @staticmethod
0272     def _valueFromString(value):
0273         """only used for cfg-parsing"""
0274         if len(value) >1 and '0x' == value[:2]:
0275             return uint32(long(value,16))
0276         return uint32(long(value))
0277     def insertInto(self, parameterSet, myname):
0278         parameterSet.addUInt32(self.isTracked(), myname, self.value())
0279     def __nonzero__(self):
0280         return self.value()!=0
0281     def __bool__(self):
0282         return self.__nonzero__()
0283 
0284 
0285 
0286 class int64(_SimpleParameterTypeBase):
0287     @staticmethod
0288     def _isValid(value):
0289         return isinstance(value,int) or (
0290             isinstance(value,long) and
0291             (-0x7FFFFFFFFFFFFFFF < value <= 0x7FFFFFFFFFFFFFFF) )
0292     @staticmethod
0293     def _valueFromString(value):
0294         """only used for cfg-parsing"""
0295         if len(value) >1 and '0x' == value[:2]:
0296             return uint32(long(value,16))
0297         return int64(long(value))
0298     def insertInto(self, parameterSet, myname):
0299         parameterSet.addInt64(self.isTracked(), myname, self.value())
0300     def __nonzero__(self):
0301         return self.value()!=0
0302 
0303 
0304 
0305 class uint64(_SimpleParameterTypeBase):
0306     @staticmethod
0307     def _isValid(value):
0308         return ((isinstance(value,int) and value >= 0) or
0309                 (isinstance(value,long) and value >= 0) and value <= 0xFFFFFFFFFFFFFFFF)
0310     @staticmethod
0311     def _valueFromString(value):
0312         """only used for cfg-parsing"""
0313         if len(value) >1 and '0x' == value[:2]:
0314             return uint32(long(value,16))
0315         return uint64(long(value))
0316     def insertInto(self, parameterSet, myname):
0317         parameterSet.addUInt64(self.isTracked(), myname, self.value())
0318     def __nonzero__(self):
0319         return self.value()!=0
0320 
0321 
0322 
0323 class double(_SimpleParameterTypeBase):
0324     @staticmethod
0325     def _isValid(value):
0326         return isinstance(value, (int, long, float))
0327     @staticmethod
0328     def _valueFromString(value):
0329         """only used for cfg-parsing"""
0330         return double(float(value))
0331     def insertInto(self, parameterSet, myname):
0332         parameterSet.addDouble(self.isTracked(), myname, float(self.value()))
0333     def __nonzero__(self):
0334         return self.value()!=0.
0335     def configValue(self, options=PrintOptions()):
0336         return double._pythonValue(self._value)
0337     @staticmethod
0338     def _pythonValue(value):
0339         if math.isinf(value):
0340             if value > 0:
0341                 return "float('inf')"
0342             else:
0343                 return "-float('inf')"
0344         if math.isnan(value):
0345             return "float('nan')"
0346         return str(value)
0347 
0348 
0349 
0350 class bool(_SimpleParameterTypeBase):
0351     @staticmethod
0352     def _isValid(value):
0353         return (isinstance(value,type(False)) or isinstance(value,type(True)))
0354     @staticmethod
0355     def _valueFromString(value):
0356         """only used for cfg-parsing"""
0357         if value.lower() in ('true', 't', 'on', 'yes', '1'):
0358             return bool(True)
0359         if value.lower() in ('false','f','off','no', '0'):
0360             return bool(False)
0361         try:
0362             return bool(builtins.bool(eval(value)))
0363         except:
0364             pass
0365         raise RuntimeError('can not make bool from string '+value)
0366     def insertInto(self, parameterSet, myname):
0367         parameterSet.addBool(self.isTracked(), myname, self.value())
0368     def __nonzero__(self):
0369         return self.value()
0370     def __bool__(self):
0371         return self.__nonzero__()
0372 
0373 
0374 class string(_SimpleParameterTypeBase):
0375     def __init__(self,value):
0376         super(string,self).__init__(value)
0377     @staticmethod
0378     def _isValid(value):
0379         return isinstance(value,type(''))
0380     def configValue(self, options=PrintOptions()):
0381         return self.formatValueForConfig(self.value())
0382     def pythonValue(self, options=PrintOptions()):
0383         return self.configValue(options)
0384     @staticmethod
0385     def formatValueForConfig(value):
0386         l = len(value)
0387         import sys
0388         if sys.version_info >= (3, 0): #python2 and python3 are different due to byptes vs strings
0389             import codecs
0390             t=codecs.escape_encode(value.encode('utf-8'))
0391             value = t[0].decode('utf-8')
0392         else: #be conservative and don't change the python2 version
0393             value = value.encode("string-escape")
0394         newL = len(value)
0395         if l != newL:
0396             #get rid of the hex encoding
0397             value=value.replace('\\x0','\\')
0398         if "'" in value:
0399             return '"'+value+'"'
0400         return "'"+value+"'"
0401     @staticmethod
0402     def _valueFromString(value):
0403         """only used for cfg-parsing"""
0404         return string(value)
0405     def insertInto(self, parameterSet, myname):
0406         value = self.value()
0407         #  doesn't seem to handle \0 correctly
0408         #if value == '\0':
0409         #    value = ''
0410         parameterSet.addString(self.isTracked(), myname, value)
0411     def __nonzero__(self):
0412         return len(self.value()) !=0
0413     def __bool__(self):
0414         return self.__nonzero__()
0415 
0416 
0417 class EventID(_ParameterTypeBase):
0418     def __init__(self, run, *args):
0419         super(EventID,self).__init__()
0420         if isinstance(run, str):
0421             self.__run = self._valueFromString(run).__run
0422             self.__luminosityBlock = self._valueFromString(run).__luminosityBlock
0423             self.__event = self._valueFromString(run).__event
0424         else:
0425             self.__run = run
0426             if len(args) == 1:
0427                 self.__luminosityBlock = 0
0428                 self.__event = args[0]
0429             elif len(args) == 2:
0430                 self.__luminosityBlock = args[0]
0431                 self.__event = args[1]
0432             else:
0433                 raise RuntimeError('EventID ctor must have 2 or 3 arguments')
0434     def run(self):
0435         return self.__run
0436     def luminosityBlock(self):
0437         return self.__luminosityBlock
0438     def event(self):
0439         return self.__event
0440     @staticmethod
0441     def _isValid(value):
0442         return True
0443     @staticmethod
0444     def _valueFromString(value):
0445         parts = value.split(":")
0446         run = parts[0]
0447         try:
0448             lumi = parts[1]
0449             event = parts[2]
0450         except IndexError:
0451             lumi = 0
0452             event = parts[1]             
0453         return EventID(int(run), int(lumi), int(event))
0454     def pythonValue(self, options=PrintOptions()):
0455         return str(self.__run)+ ', '+str(self.__luminosityBlock)+ ', '+str(self.__event)
0456     def cppID(self, parameterSet):
0457         return parameterSet.newEventID(self.run(), self.luminosityBlock(), self.event())
0458     def insertInto(self, parameterSet, myname):
0459         parameterSet.addEventID(self.isTracked(), myname, self.cppID(parameterSet))
0460 
0461 
0462 class LuminosityBlockID(_ParameterTypeBase):
0463     def __init__(self, run, block=None):
0464         super(LuminosityBlockID,self).__init__()
0465         if isinstance(run, str):
0466             self.__run = self._valueFromString(run).__run
0467             self.__block = self._valueFromString(run).__block
0468         else:
0469             self.__run = run
0470             self.__block = block
0471     def run(self):
0472         return self.__run
0473     def luminosityBlock(self):
0474         return self.__block
0475     @staticmethod
0476     def _isValid(value):
0477         return True
0478     @staticmethod
0479     def _valueFromString(value):
0480         """only used for cfg-parsing"""
0481         parts = value.split(":")
0482         return LuminosityBlockID(int(parts[0]), int(parts[1]))
0483     def pythonValue(self, options=PrintOptions()):
0484         return str(self.__run)+ ', '+str(self.__block)
0485     def cppID(self, parameterSet):
0486         return parameterSet.newLuminosityBlockID(self.run(), self.luminosityBlock())
0487     def insertInto(self, parameterSet, myname):
0488         parameterSet.addLuminosityBlockID(self.isTracked(), myname, self.cppID(parameterSet))
0489 
0490 
0491 class LuminosityBlockRange(_ParameterTypeBase):
0492     def __init__(self, start, startSub=None, end=None, endSub=None):
0493         super(LuminosityBlockRange,self).__init__()
0494         if isinstance(start, str):
0495             parsed = self._valueFromString(start)
0496             self.__start    = parsed.__start
0497             self.__startSub = parsed.__startSub
0498             self.__end      = parsed.__end
0499             self.__endSub   = parsed.__endSub
0500         else:
0501             self.__start    = start
0502             self.__startSub = startSub
0503             self.__end      = end
0504             self.__endSub   = endSub
0505         if self.__end < self.__start:
0506             raise RuntimeError('LuminosityBlockRange '+str(self.__start)+':'+str(self.__startSub)+'-'+str(self.__end)+':'+str(self.__endSub)+' out of order')
0507         # 0 luminosity block number is a special case that means no limit
0508         if self.__end == self.__start and (self.__endSub != 0 and self.__endSub < self.__startSub):
0509             raise RuntimeError('LuminosityBlockRange '+str(self.__start)+':'+str(self.__startSub)+'-'+str(self.__end)+':'+str(self.__endSub)+' out of order')
0510     def start(self):
0511         return self.__start
0512     def startSub(self):
0513         return self.__startSub
0514     def end(self):
0515         return self.__end
0516     def endSub(self):
0517         return self.__endSub
0518     @staticmethod
0519     def _isValid(value):
0520         return True
0521     @staticmethod
0522     def _valueFromString(value):
0523         """only used for cfg-parsing"""
0524         value = value.replace(' ','')
0525         parts = value.split("-")
0526         startParts = parts[0].split(":")
0527         try:
0528             endParts = parts[1].split(":")
0529         except IndexError:
0530             endParts = parts[0].split(":") # If just "1:2" turn into "1:2-1:2"
0531 
0532         if startParts[1].lower() == "0":
0533             startParts[1] = "1"
0534         elif startParts[1].lower() == "max":
0535             startParts[1] = "0"
0536         elif startParts[1].lower() == "min":
0537             startParts[1] = "1"
0538         if endParts[1].lower() == "max":
0539             endParts[1] = "0"
0540         elif endParts[1].lower() == "min":
0541             endParts[1] = "1"
0542         return LuminosityBlockRange(int(startParts[0]), int(startParts[1]),
0543                         int(endParts[0]), int(endParts[1]))
0544     def pythonValue(self, options=PrintOptions()):
0545         return str(self.__start) + ', ' + str(self.__startSub) + ', ' \
0546              + str(self.__end)   + ', ' + str(self.__endSub)
0547     def cppID(self, parameterSet):
0548         return parameterSet.newLuminosityBlockRange(self.start(), self.startSub(),self.end(), self.endSub())
0549     def insertInto(self, parameterSet, myname):
0550         parameterSet.addLuminosityBlockRange(self.isTracked(), myname, self.cppID(parameterSet))
0551 
0552 class EventRange(_ParameterTypeBase):
0553     def __init__(self, start, *args):
0554         super(EventRange,self).__init__()
0555         if isinstance(start, str):
0556             parsed = self._valueFromString(start)
0557             self.__start     = parsed.__start
0558             self.__startLumi = parsed.__startLumi
0559             self.__startSub  = parsed.__startSub
0560             self.__end       = parsed.__end
0561             self.__endLumi   = parsed.__endLumi
0562             self.__endSub    = parsed.__endSub
0563         else:
0564             self.__start     = start
0565             if len(args) == 3:
0566                 self.__startLumi = 0
0567                 self.__startSub  = args[0]
0568                 self.__end       = args[1]
0569                 self.__endLumi   = 0
0570                 self.__endSub    = args[2]
0571             elif len(args) == 5:
0572                 self.__startLumi = args[0]
0573                 self.__startSub  = args[1]
0574                 self.__end       = args[2]
0575                 self.__endLumi   = args[3]
0576                 self.__endSub    = args[4]
0577             else:
0578                 raise RuntimeError('EventRange ctor must have 4 or 6 arguments')
0579         if self.__end < self.__start or (self.__end == self.__start and self.__endLumi < self.__startLumi):
0580             raise RuntimeError('EventRange '+str(self.__start)+':'+str(self.__startLumi)+':'+str(self.__startSub)+'-'+str(self.__end)+':'+str(self.__endLumi)+':'+str(self.__endSub)+' out of order')
0581         # 0 event number is a special case that means no limit
0582         if self.__end == self.__start and self.__endLumi == self.__startLumi and (self.__endSub != 0 and self.__endSub < self.__startSub):
0583             raise RuntimeError('EventRange '+str(self.__start)+':'+str(self.__startLumi)+':'+str(self.__startSub)+'-'+str(self.__end)+':'+str(self.__endLumi)+':'+str(self.__endSub)+' out of order')
0584     def start(self):
0585         return self.__start
0586     def startLumi(self):
0587         return self.__startLumi
0588     def startSub(self):
0589         return self.__startSub
0590     def end(self):
0591         return self.__end
0592     def endLumi(self):
0593         return self.__endLumi
0594     def endSub(self):
0595         return self.__endSub
0596     @staticmethod
0597     def _isValid(value):
0598         return True
0599     @staticmethod
0600     def _valueFromString(value):
0601         """only used for cfg-parsing"""
0602         value = value.replace(' ','')
0603         parts = value.split("-")
0604         startParts = parts[0].split(":")
0605         try:
0606             endParts = parts[1].split(":")
0607         except IndexError:
0608             endParts = parts[0].split(":") # If just "1:2" turn into "1:2-1:2"
0609 
0610         brun = startParts[0]
0611         erun = endParts[0]
0612         s = len(startParts)
0613         e = len(endParts)
0614         if s != e or s < 2 or s > 3:
0615             raise RuntimeError('EventRange ctor must have 4 or 6 arguments')
0616         i = s - 1
0617         if startParts[i].lower() == "0":
0618             startParts[i] = "1"
0619         elif startParts[i].lower() == "max":
0620             startParts[i] = "0"
0621         elif startParts[i].lower() == "min":
0622             startParts[i] = "1"
0623         if endParts[i].lower() == "max":
0624             endParts[i] = "0"
0625         elif endParts[i].lower() == "min":
0626             endParts[i] = "1"
0627         if s == 3:
0628             blumi = startParts[1]
0629             elumi = endParts[1]
0630             bevent = startParts[2]
0631             eevent = endParts[2]
0632         elif s == 2:
0633             blumi = 0
0634             elumi = 0
0635             bevent = startParts[1]
0636             eevent = endParts[1]             
0637         else:
0638             raise RuntimeError('EventRange ctor must have 4 or 6 arguments')
0639         # note int will return a long if the value is too large to fit in
0640         # a smaller type
0641         return EventRange(int(brun), int(blumi), int(bevent),
0642                           int(erun), int(elumi), int(eevent))
0643 
0644     def pythonValue(self, options=PrintOptions()):
0645         return str(self.__start) + ', ' + str(self.__startLumi) + ', ' + str(self.__startSub) + ', ' \
0646                + str(self.__end)  + ', ' + str(self.__endLumi) + ', ' + str(self.__endSub)
0647     def cppID(self, parameterSet):
0648         return parameterSet.newEventRange(self.start(), self.startLumi(), self.startSub(), self.end(), self.endLumi(), self.endSub())
0649     def insertInto(self, parameterSet, myname):
0650         parameterSet.addEventRange(self.isTracked(), myname, self.cppID(parameterSet))
0651 
0652 class InputTag(_ParameterTypeBase):
0653     def __init__(self,moduleLabel,productInstanceLabel='',processName=''):
0654         super(InputTag,self).__init__()
0655         self._setValues(moduleLabel, productInstanceLabel, processName)
0656     def getModuleLabel(self):
0657         return self.__moduleLabel
0658     def setModuleLabel(self,label):
0659         if self.__moduleLabel != label:
0660             self.__moduleLabel = label
0661             self._isModified=True
0662     moduleLabel = property(getModuleLabel,setModuleLabel,"module label for the product")
0663     def getProductInstanceLabel(self):
0664         return self.__productInstance
0665     def setProductInstanceLabel(self,label):
0666         if self.__productInstance != label:
0667             self.__productInstance = label
0668             self._isModified=True
0669     productInstanceLabel = property(getProductInstanceLabel,setProductInstanceLabel,"product instance label for the product")
0670     def getProcessName(self):
0671         return self.__processName
0672     def setProcessName(self,label):
0673         if self.__processName != label:
0674             self.__processName = label
0675             self._isModified=True
0676     processName = property(getProcessName,setProcessName,"process name for the product")
0677     @staticmethod
0678     def skipCurrentProcess():
0679         """When used as the process name this value will make the framework skip the current process
0680             when looking backwards in time for the data product.
0681         """
0682         return "@skipCurrentProcess"
0683     @staticmethod
0684     def currentProcess():
0685         """When used as the process name this value will make the framework use the current process
0686             as the process when looking for the data product.
0687         """
0688         return "@currentProcess"
0689     def configValue(self, options=PrintOptions()):
0690         result = self.__moduleLabel
0691         if self.__productInstance != "" or self.__processName != "":
0692             result += ':' + self.__productInstance
0693         if self.__processName != "":
0694             result += ':' + self.__processName
0695         if result == "":
0696             result = '\"\"'
0697         return result;
0698     def pythonValue(self, options=PrintOptions()):
0699         cfgValue = self.configValue(options)
0700         # empty strings already have quotes
0701         if cfgValue == '\"\"':
0702             return cfgValue
0703         colonedValue = "\""+cfgValue+"\""
0704         # change label:instance:process to "label","instance","process"
0705         return colonedValue.replace(":","\",\"")
0706     @staticmethod
0707     def _isValid(value):
0708         return True
0709     def __eq__(self,other):
0710         return ((self.__moduleLabel,self.__productInstance,self.__processName) ==
0711                 (other.moduleLabel,other.productInstanceLabel,other.processName))
0712     def __ne__(self,other):
0713         return ((self.__moduleLabel,self.__productInstance,self.__processName) !=
0714                 (other.moduleLabel,other.productInstanceLabel,other.processName))
0715     def __lt__(self,other):
0716         return ((self.__moduleLabel,self.__productInstance,self.__processName) <
0717                 (other.moduleLabel,other.productInstanceLabel,other.processName))
0718     def __gt__(self,other):
0719         return ((self.__moduleLabel,self.__productInstance,self.__processName) >
0720                 (other.moduleLabel,other.productInstanceLabel,other.processName))
0721     def __le__(self,other):
0722         return ((self.__moduleLabel,self.__productInstance,self.__processName) <=
0723                 (other.moduleLabel,other.productInstanceLabel,other.processName))
0724     def __ge__(self,other):
0725         return ((self.__moduleLabel,self.__productInstance,self.__processName) >=
0726                 (other.moduleLabel,other.productInstanceLabel,other.processName))
0727 
0728 
0729     def value(self):
0730         "Return the string rep"
0731         return self.configValue()
0732     @staticmethod
0733     def formatValueForConfig(value):
0734         return value.configValue()
0735     @staticmethod
0736     def _valueFromString(string):
0737         parts = string.split(":")
0738         return InputTag(*parts)
0739     @staticmethod
0740     def _stringFromArgument(arg):
0741         if isinstance(arg, InputTag):
0742             return arg
0743         elif isinstance(arg, str):
0744             if arg.count(":") > 2:
0745                 raise RuntimeError("InputTag may have at most 3 elements")
0746             return arg
0747         else:
0748             if len(arg) > 3:
0749                 raise RuntimeError("InputTag may have at most 3 elements")
0750             return ":".join(arg)
0751     def setValue(self,v):
0752         self._setValues(v)
0753         self._isModified=True
0754     def _setValues(self,moduleLabel,productInstanceLabel='',processName=''):
0755         self.__moduleLabel = InputTag._stringFromArgument(moduleLabel)
0756         self.__productInstance = productInstanceLabel
0757         self.__processName=processName
0758         if -1 != self.__moduleLabel.find(":"):
0759             toks = self.__moduleLabel.split(":")
0760             if len(toks) > 3:
0761                 raise RuntimeError("InputTag may have at most 3 elements")
0762             self.__moduleLabel = toks[0]
0763             if len(toks) > 1:
0764                 self.__productInstance = toks[1]
0765             if len(toks) > 2:
0766                 self.__processName=toks[2]
0767     # convert to the wrapper class for C++ InputTags
0768     def cppTag(self, parameterSet):
0769         return parameterSet.newInputTag(self.getModuleLabel(),
0770                                         self.getProductInstanceLabel(),
0771                                         self.getProcessName())
0772     def insertInto(self, parameterSet, myname):
0773         parameterSet.addInputTag(self.isTracked(), myname, self.cppTag(parameterSet))
0774 
0775 class ESInputTag(_ParameterTypeBase):
0776     def __init__(self,module='',data= None):
0777         super(ESInputTag,self).__init__()
0778         self._setValues(module, data)
0779     def getModuleLabel(self):
0780         return self.__moduleLabel
0781     def setModuleLabel(self,label):
0782         if self.__moduleLabel != label:
0783             self.__moduleLabel = label
0784             self._isModified=True
0785     moduleLabel = property(getModuleLabel,setModuleLabel,"module label for the product")
0786     def getDataLabel(self):
0787         return self.__data
0788     def setDataLabel(self,label):
0789         if self.__data != label:
0790             self.__data = label
0791             self._isModified=True
0792     dataLabel = property(getDataLabel,setDataLabel,"data label for the product")
0793     def configValue(self, options=PrintOptions()):
0794         result = self.__moduleLabel + ':' + self.__data
0795         if result == "":
0796             result = '\"\"'
0797         return result;
0798     def pythonValue(self, options=PrintOptions()):
0799         cfgValue = self.configValue(options)
0800         # empty strings already have quotes
0801         if cfgValue == '\"\"':
0802             return cfgValue
0803         colonedValue = "\""+cfgValue+"\""
0804         # change label:instance:process to "label","instance","process"
0805         return colonedValue.replace(":","\",\"")
0806     @staticmethod
0807     def _isValid(value):
0808         return True
0809     def __eq__(self,other):
0810         return ((self.__moduleLabel,self.__data) == (other.__moduleLabel,other.__data))
0811     def __ne__(self,other):
0812         return ((self.__moduleLabel,self.__data) != (other.__moduleLabel,other.__data))
0813     def __lt__(self,other):
0814         return ((self.__moduleLabel,self.__data) < (other.__moduleLabel,other.__data))
0815     def __gt__(self,other):
0816         return ((self.__moduleLabel,self.__data) > (other.__moduleLabel,other.__data))
0817     def __le__(self,other):
0818         return ((self.__moduleLabel,self.__data) <= (other.__moduleLabel,other.__data))
0819     def __ge__(self,other):
0820         return ((self.__moduleLabel,self.__data) >= (other.__moduleLabel,other.__data))
0821     def value(self):
0822         "Return the string rep"
0823         return self.configValue()
0824     @staticmethod
0825     def formatValueForConfig(value):
0826         return value.configValue()
0827     @staticmethod
0828     def _valueFromString(string):
0829         parts = string.split(":")
0830         return ESInputTag(*parts)
0831     @staticmethod
0832     def _stringFromArgument(arg, dataLabel=None):
0833         if isinstance(arg, ESInputTag):
0834             return arg
0835         elif isinstance(arg, str):
0836             if arg:
0837                 cnt = arg.count(":")
0838                 if dataLabel is None and cnt == 0:
0839                     raise RuntimeError("ESInputTag passed one string '"+str(arg)+"' which does not contain a ':'. Please add ':' to explicitly separate the module (1st) and data (2nd) label or use two strings.")
0840                 elif arg.count(":") >= 2:
0841                     raise RuntimeError("an ESInputTag was passed the value'"+arg+"' which contains more than one ':'")
0842             return arg
0843         else:
0844             if len(arg) > 2 or len(arg) == 1:
0845                 raise RuntimeError("ESInputTag must have either 2 or 0 elements")
0846             if len(arg) == 2:
0847                 return ":".join(arg)
0848             return ":"
0849     def setValue(self,v):
0850         self._setValues(v)
0851         self._isModified=True
0852     def _setValues(self,moduleLabel='',dataLabel=None):
0853         self.__moduleLabel = ESInputTag._stringFromArgument(moduleLabel, dataLabel)
0854         self.__data = dataLabel
0855         if dataLabel is None:
0856             if self.__moduleLabel:
0857                 toks = self.__moduleLabel.split(":")
0858                 self.__moduleLabel = toks[0]
0859                 if len(toks) > 1:
0860                     self.__data = toks[1]
0861             else:
0862                 self.__data = ''
0863             
0864 
0865     # convert to the wrapper class for C++ ESInputTags
0866     def cppTag(self, parameterSet):
0867         return parameterSet.newESInputTag(self.getModuleLabel(),
0868                                         self.getDataLabel())
0869     def insertInto(self, parameterSet, myname):
0870         parameterSet.addESInputTag(self.isTracked(), myname, self.cppTag(parameterSet))
0871 
0872 class FileInPath(_SimpleParameterTypeBase):
0873     def __init__(self,value):
0874         super(FileInPath,self).__init__(value)
0875     @staticmethod
0876     def _isValid(value):
0877         return True
0878     def configValue(self, options=PrintOptions()):
0879         return string.formatValueForConfig(self.value())
0880     @staticmethod
0881     def formatValueForConfig(value):
0882         return string.formatValueForConfig(value)
0883     @staticmethod
0884     def _valueFromString(value):
0885         return FileInPath(value)
0886     def insertInto(self, parameterSet, myname):
0887         parameterSet.addNewFileInPath( self.isTracked(), myname, self.value() )
0888 
0889 class SecSource(_ParameterTypeBase,_TypedParameterizable,_ConfigureComponent,_Labelable):
0890     def __init__(self,type_,*arg,**args):
0891         _ParameterTypeBase.__init__(self)
0892         _TypedParameterizable.__init__(self,type_,*arg,**args)
0893     def value(self):
0894         return self
0895     @staticmethod
0896     def _isValid(value):
0897         return True
0898     def configTypeName(self):
0899         return "secsource"
0900     def configValue(self, options=PrintOptions()):
0901         return self.dumpConfig(options)
0902     def dumpPython(self, options=PrintOptions()):
0903         return _TypedParameterizable.dumpPython(self, options)
0904     def copy(self):
0905         # TODO is the one in TypedParameterizable better?
0906         return copy.copy(self)
0907     def _place(self,name,proc):
0908         proc._placePSet(name,self)
0909     def __str__(self):
0910         return object.__str__(self)
0911 
0912 class PSet(_ParameterTypeBase,_Parameterizable,_ConfigureComponent,_Labelable):
0913     def __init__(self,*arg,**args):
0914         #need to call the inits separately
0915         _ParameterTypeBase.__init__(self)
0916         _Parameterizable.__init__(self,*arg,**args)
0917     def value(self):
0918         return self
0919     def isRef_(self):
0920         """Returns true if this PSet is actually a reference to a different PSet
0921             """
0922         return hasattr(self,"refToPSet_")
0923     @staticmethod
0924     def _isValid(value):
0925         return isinstance(value,PSet) or isinstance(value,dict)
0926     def setValue(self,value):
0927         if isinstance(value,dict):
0928             for k,v in value.items():
0929                 setattr(self,k,v)
0930 
0931     def configValue(self, options=PrintOptions()):
0932         config = '{ \n'
0933         for name in self.parameterNames_():
0934             param = getattr(self,name)
0935             options.indent()
0936             config+=options.indentation()+param.configTypeName()+' '+name+' = '+param.configValue(options)+'\n'
0937             options.unindent()
0938         config += options.indentation()+'}\n'
0939         return config
0940     def dumpPython(self, options=PrintOptions()):
0941         return self.pythonTypeName()+"(\n"+_Parameterizable.dumpPython(self, options)+options.indentation()+")"
0942     # XXX FIXME handle refToPSet
0943     def directDependencies(self):
0944         return []
0945     def clone(self, **params):
0946         myparams = self.parameters_()
0947         if "allowAnyLabel_" in params:
0948             raise AttributeError("Not allowed to change `allowAnyLabel_` value in call to clone")
0949         _modifyParametersFromDict(myparams, params, self._Parameterizable__raiseBadSetAttr)
0950         if self._Parameterizable__validator is not None:
0951             myparams["allowAnyLabel_"] = self._Parameterizable__validator
0952         returnValue = PSet(**myparams)
0953         returnValue.setIsTracked(self.isTracked())
0954         returnValue._isModified = False
0955         returnValue._isFrozen = False
0956         return returnValue
0957     def copy(self):
0958         return copy.copy(self)
0959     def _place(self,name,proc):
0960         proc._placePSet(name,self)
0961     def __str__(self):
0962         return object.__str__(self)
0963     def insertInto(self, parameterSet, myname):
0964         newpset = parameterSet.newPSet()
0965         self.insertContentsInto(newpset)
0966         parameterSet.addPSet(self.isTracked(), myname, newpset)
0967     def insertContentsInto(self, parameterSet):
0968         if self.isRef_():
0969             ref = parameterSet.getTopPSet_(self.refToPSet_.value())
0970             ref.insertContentsInto(parameterSet)
0971         else:
0972             super(PSet, self).insertContentsInto(parameterSet)
0973 
0974 
0975 class vint32(_ValidatingParameterListBase):
0976     def __init__(self,*arg,**args):
0977         super(vint32,self).__init__(*arg,**args)
0978 
0979     @classmethod
0980     def _itemIsValid(cls,item):
0981         return int32._isValid(item)
0982     @staticmethod
0983     def _valueFromString(value):
0984         return vint32(*_ValidatingParameterListBase._itemsFromStrings(value,int32._valueFromString))
0985     def insertInto(self, parameterSet, myname):
0986         parameterSet.addVInt32(self.isTracked(), myname, self.value())
0987 
0988 
0989 
0990 class vuint32(_ValidatingParameterListBase):
0991     def __init__(self,*arg,**args):
0992         super(vuint32,self).__init__(*arg,**args)
0993     @classmethod
0994     def _itemIsValid(cls,item):
0995         return uint32._isValid(item)
0996     @staticmethod
0997     def _valueFromString(value):
0998         return vuint32(*_ValidatingParameterListBase._itemsFromStrings(value,uint32._valueFromString))
0999     def insertInto(self, parameterSet, myname):
1000         parameterSet.addVUInt32(self.isTracked(), myname, self.value())
1001 
1002 
1003 
1004 class vint64(_ValidatingParameterListBase):
1005     def __init__(self,*arg,**args):
1006         super(vint64,self).__init__(*arg,**args)
1007     @classmethod
1008     def _itemIsValid(cls,item):
1009         return int64._isValid(item)
1010     @staticmethod
1011     def _valueFromString(value):
1012         return vint64(*_ValidatingParameterListBase._itemsFromStrings(value,int64._valueFromString))
1013     def insertInto(self, parameterSet, myname):
1014         parameterSet.addVInt64(self.isTracked(), myname, self.value())
1015 
1016 
1017 
1018 class vuint64(_ValidatingParameterListBase):
1019     def __init__(self,*arg,**args):
1020         super(vuint64,self).__init__(*arg,**args)
1021     @classmethod
1022     def _itemIsValid(cls,item):
1023         return uint64._isValid(item)
1024     @staticmethod
1025     def _valueFromString(value):
1026         return vuint64(*_ValidatingParameterListBase._itemsFromStrings(value,vuint64._valueFromString))
1027     def insertInto(self, parameterSet, myname):
1028         parameterSet.addVUInt64(self.isTracked(), myname, self.value())
1029 
1030 
1031 
1032 class vdouble(_ValidatingParameterListBase):
1033     def __init__(self,*arg,**args):
1034         super(vdouble,self).__init__(*arg,**args)
1035     @classmethod
1036     def _itemIsValid(cls,item):
1037         return double._isValid(item)
1038     @staticmethod
1039     def _valueFromString(value):
1040         return vdouble(*_ValidatingParameterListBase._itemsFromStrings(value,double._valueFromString))
1041     def insertInto(self, parameterSet, myname):
1042         parameterSet.addVDouble(self.isTracked(), myname, self.value())
1043     def pythonValueForItem(self,item, options):
1044         return double._pythonValue(item)
1045 
1046 
1047 
1048 
1049 class vbool(_ValidatingParameterListBase):
1050     def __init__(self,*arg,**args):
1051         super(vbool,self).__init__(*arg,**args)
1052     @classmethod
1053     def _itemIsValid(cls,item):
1054         return bool._isValid(item)
1055     @staticmethod
1056     def _valueFromString(value):
1057         return vbool(*_ValidatingParameterListBase._itemsFromStrings(value,bool._valueFromString))
1058     def insertInto(self, parameterSet, myname):
1059         parameterSet.addVBool(self.isTracked(), myname, self.value())
1060 
1061 
1062 
1063 class vstring(_ValidatingParameterListBase):
1064     def __init__(self,*arg,**args):
1065         super(vstring,self).__init__(*arg,**args)
1066         self._nPerLine = 1
1067     @classmethod
1068     def _itemIsValid(cls,item):
1069         return string._isValid(item)
1070     def configValueForItem(self,item,options):
1071         return string.formatValueForConfig(item)
1072     @staticmethod
1073     def _valueFromString(value):
1074         return vstring(*_ValidatingParameterListBase._itemsFromStrings(value,string._valueFromString))
1075     def insertInto(self, parameterSet, myname):
1076         parameterSet.addVString(self.isTracked(), myname, self.value())
1077 
1078 class VLuminosityBlockID(_ValidatingParameterListBase):
1079     def __init__(self,*arg,**args):
1080         super(VLuminosityBlockID,self).__init__(*arg,**args)
1081     @classmethod
1082     def _itemIsValid(cls,item):
1083         return LuminosityBlockID._isValid(item)
1084     def configValueForItem(self,item,options):
1085         return LuminosityBlockID.formatValueForConfig(item)
1086     def pythonValueForItem(self,item, options):
1087         return item.dumpPython(options)
1088     @staticmethod
1089     def _valueFromString(value):
1090         return VLuminosityBlockID(*_ValidatingParameterListBase._itemsFromStrings(value,LuminosityBlockID._valueFromString))
1091     def insertInto(self, parameterSet, myname):
1092         cppIDs = list()
1093         for i in self:
1094             item = i
1095             if isinstance(item, str):
1096                 item = LuminosityBlockID._valueFromString(item)
1097             cppIDs.append(item.cppID(parameterSet))
1098         parameterSet.addVLuminosityBlockID(self.isTracked(), myname, cppIDs)
1099 
1100 
1101 class VInputTag(_ValidatingParameterListBase):
1102     def __init__(self,*arg,**args):
1103         if len(arg) == 1 and not isinstance(arg[0], str):
1104             try:
1105                 arg = iter(arg[0])
1106             except TypeError:
1107                 pass
1108         super(VInputTag,self).__init__((InputTag._stringFromArgument(x) for x in arg),**args)
1109     @classmethod
1110     def _itemIsValid(cls,item):
1111         return InputTag._isValid(item)
1112     def configValueForItem(self,item,options):
1113         # we tolerate strings as members
1114         if isinstance(item, str):
1115             return '"'+item+'"'
1116         else:
1117             return InputTag.formatValueForConfig(item)
1118     def pythonValueForItem(self,item, options):
1119         # we tolerate strings as members
1120         if isinstance(item, str):
1121             return '"'+item+'"'
1122         else:
1123             return item.dumpPython(options)
1124     @staticmethod
1125     def _valueFromString(value):
1126         return VInputTag(*_ValidatingParameterListBase._itemsFromStrings(value,InputTag._valueFromString))
1127     def _itemFromArgument(self, x):
1128         return InputTag._stringFromArgument(x)
1129     def insertInto(self, parameterSet, myname):
1130         cppTags = list()
1131         for i in self:
1132             item = i
1133             if isinstance(item, str):
1134                 item = InputTag(i)
1135             cppTags.append(item.cppTag(parameterSet))
1136         parameterSet.addVInputTag(self.isTracked(), myname, cppTags)
1137 
1138 class VESInputTag(_ValidatingParameterListBase):
1139     def __init__(self,*arg,**args):
1140         if len(arg) == 1 and not isinstance(arg[0], str):
1141             try:
1142                 arg = iter(arg[0])
1143             except TypeError:
1144                 pass
1145         super(VESInputTag,self).__init__((ESInputTag._stringFromArgument(x) for x in arg),**args)
1146     @classmethod
1147     def _itemIsValid(cls,item):
1148         return ESInputTag._isValid(item)
1149     def configValueForItem(self,item,options):
1150         # we tolerate strings as members
1151         if isinstance(item, str):
1152             return '"'+item+'"'
1153         else:
1154             return ESInputTag.formatValueForConfig(item)
1155     def pythonValueForItem(self,item, options):
1156         # we tolerate strings as members
1157         if isinstance(item, str):
1158             return '"'+item+'"'
1159         else:
1160             return item.dumpPython(options)
1161     @staticmethod
1162     def _valueFromString(value):
1163         return VESInputTag(*_ValidatingParameterListBase._itemsFromStrings(value,ESInputTag._valueFromString))
1164     def _itemFromArgument(self, x):
1165         return ESInputTag._stringFromArgument(x)
1166     def insertInto(self, parameterSet, myname):
1167         cppTags = list()
1168         for i in self:
1169             item = i
1170             if isinstance(item, str):
1171                 item = ESInputTag(i)
1172             cppTags.append(item.cppTag(parameterSet))
1173         parameterSet.addVESInputTag(self.isTracked(), myname, cppTags)
1174 
1175 class VEventID(_ValidatingParameterListBase):
1176     def __init__(self,*arg,**args):
1177         super(VEventID,self).__init__(*arg,**args)
1178     @classmethod
1179     def _itemIsValid(cls,item):
1180         return EventID._isValid(item)
1181     def configValueForItem(self,item,options):
1182         return EventID.formatValueForConfig(item)
1183     def pythonValueForItem(self,item, options):
1184         # we tolerate strings as members
1185         if isinstance(item, str):
1186             return '"'+item+'"'
1187         else:
1188             return item.dumpPython(options)
1189     @staticmethod
1190     def _valueFromString(value):
1191         return VEventID(*_ValidatingParameterListBase._itemsFromStrings(value,EventID._valueFromString))
1192     def insertInto(self, parameterSet, myname):
1193         cppIDs = list()
1194         for i in self:
1195             item = i
1196             if isinstance(item, str):
1197                 item = EventID._valueFromString(item)
1198             cppIDs.append(item.cppID(parameterSet))
1199         parameterSet.addVEventID(self.isTracked(), myname, cppIDs)
1200 
1201 
1202 class VLuminosityBlockRange(_ValidatingParameterListBase):
1203     def __init__(self,*arg,**args):
1204         super(VLuminosityBlockRange,self).__init__(*arg,**args)
1205     @classmethod
1206     def _itemIsValid(cls,item):
1207         return LuminosityBlockRange._isValid(item)
1208     def configValueForItem(self,item,options):
1209         return LuminosityBlockRange.formatValueForConfig(item)
1210     def pythonValueForItem(self,item, options):
1211         if isinstance(item, str):
1212             return '"'+item+'"'
1213         else:
1214             return item.dumpPython(options)
1215     @staticmethod
1216     def _valueFromString(value):
1217         return VLuminosityBlockRange(*_ValidatingParameterListBase._itemsFromStrings(value,VLuminosityBlockRange._valueFromString))
1218     def insertInto(self, parameterSet, myname):
1219         cppIDs = list()
1220         for i in self:
1221             item = i
1222             if isinstance(item, str):
1223                 item = LuminosityBlockRange._valueFromString(item)
1224             cppIDs.append(item.cppID(parameterSet))
1225         parameterSet.addVLuminosityBlockRange(self.isTracked(), myname, cppIDs)
1226 
1227 
1228 class VEventRange(_ValidatingParameterListBase):
1229     def __init__(self,*arg,**args):
1230         super(VEventRange,self).__init__(*arg,**args)
1231     @classmethod
1232     def _itemIsValid(cls,item):
1233         return EventRange._isValid(item)
1234     def configValueForItem(self,item,options):
1235         return EventRange.formatValueForConfig(item)
1236     def pythonValueForItem(self,item, options):
1237         if isinstance(item, str):
1238             return '"'+item+'"'
1239         else:
1240             return item.dumpPython(options)
1241     @staticmethod
1242     def _valueFromString(value):
1243         return VEventRange(*_ValidatingParameterListBase._itemsFromStrings(value,VEventRange._valueFromString))
1244     def insertInto(self, parameterSet, myname):
1245         cppIDs = list()
1246         for i in self:
1247             item = i
1248             if isinstance(item, str):
1249                 item = EventRange._valueFromString(item)
1250             cppIDs.append(item.cppID(parameterSet))
1251         parameterSet.addVEventRange(self.isTracked(), myname, cppIDs)
1252 
1253 
1254 class VPSet(_ValidatingParameterListBase,_ConfigureComponent,_Labelable):
1255     def __init__(self,*arg,**args):
1256         super(VPSet,self).__init__(*arg,**args)
1257         self._nPerLine = 1
1258     @classmethod
1259     def _itemIsValid(cls,item):
1260         return isinstance(item, PSet) and PSet._isValid(item)
1261     def configValueForItem(self,item, options):
1262         return PSet.configValue(item, options)
1263     def pythonValueForItem(self,item, options):
1264         return PSet.dumpPython(item,options)
1265     def copy(self):
1266         return copy.copy(self)
1267     def _place(self,name,proc):
1268         proc._placeVPSet(name,self)
1269     def insertInto(self, parameterSet, myname):
1270         # translate the PSet members into C++ parameterSets
1271         parametersets = list()
1272         for pset in self:
1273             newparameterset = parameterSet.newPSet()
1274             pset.insertContentsInto(newparameterset)
1275             parametersets.append(newparameterset)
1276         parameterSet.addVPSet(self.isTracked(), myname, parametersets)
1277     # XXX FIXME handle refToPSet
1278     def directDependencies(self):
1279         return []
1280     def __repr__(self):
1281         return self.dumpPython()
1282 
1283 def makeCppPSet(module,cppPSetMaker):
1284     """Extracts all PSets from the module and makes C++ equivalent
1285     """
1286     # if this isn't a dictionary, treat it as an object which holds PSets
1287     if not isinstance(module,dict):
1288         module = dict( ( (x,getattr(module,x)) for x in dir(module)) )  
1289 
1290     for x,p in module.items():
1291         if isinstance(p,PSet):
1292             p.insertInto(cppPSetMaker,x)
1293     return cppPSetMaker
1294 
1295 class _ConvertToPSet(object):
1296     def __init__(self):
1297         self.pset = PSet()
1298     def addInt32(self,tracked,label,value):
1299         v = int32(value)
1300         v.setIsTracked(tracked)
1301         setattr(self.pset,label,v)
1302     def addUInt32(self,tracked,label,value):
1303         v = uint32(value)
1304         v.setIsTracked(tracked)
1305         setattr(self.pset,label,v)
1306     def addInt64(self,tracked,label,value):
1307         v = int64(value)
1308         v.setIsTracked(tracked)
1309         setattr(self.pset,label,v)
1310     def addUInt64(self,tracked,label,value):
1311         v = uint64(value)
1312         v.setIsTracked(tracked)
1313         setattr(self.pset,label,v)
1314     def addBool(self,tracked,label,value):
1315         v = bool(value)
1316         v.setIsTracked(tracked)
1317         setattr(self.pset,label,v)
1318     def addDouble(self,tracked,label,value):
1319         v = double(value)
1320         v.setIsTracked(tracked)
1321         setattr(self.pset,label,v)
1322     def addString(self,tracked,label,value):
1323         v = string(value)
1324         v.setIsTracked(tracked)
1325         setattr(self.pset,label,v)
1326     def addInputTag(self,tracked,label,value):
1327         v = copy.deepcopy(value)
1328         v.setIsTracked(tracked)
1329         setattr(self.pset,label,v)
1330     def addESInputTag(self,tracked,label,value):
1331         v = copy.deepcopy(value)
1332         v.setIsTracked(tracked)
1333         setattr(self.pset,label,v)
1334     def addEventID(self,tracked,label,value):
1335         v = copy.deepcopy(value)
1336         v.setIsTracked(tracked)
1337         setattr(self.pset,label,v)
1338     def addEventRange(self,tracked,label,value):
1339         v = copy.deepcopy(value)
1340         v.setIsTracked(tracked)
1341         setattr(self.pset,label,v)
1342     def addLuminosityBlockID(self,tracked,label,value):
1343         v = copy.deepcopy(value)
1344         v.setIsTracked(tracked)
1345         setattr(self.pset,label,v)
1346     def addLuminosityBlockRange(self,tracked,label,value):
1347         v = copy.deepcopy(value)
1348         v.setIsTracked(tracked)
1349         setattr(self.pset,label,v)
1350     def addVInt32(self,tracked,label,value):
1351         v = vint32(value)
1352         v.setIsTracked(tracked)
1353         setattr(self.pset,label,v)
1354     def addVUInt32(self,tracked,label,value):
1355         v = vuint32(value)
1356         v.setIsTracked(tracked)
1357         setattr(self.pset,label,v)
1358     def addVInt64(self,tracked,label,value):
1359         v = vint64(value)
1360         v.setIsTracked(tracked)
1361         setattr(self.pset,label,v)
1362     def addVUInt64(self,tracked,label,value):
1363         v = vuint64(value)
1364         v.setIsTracked(tracked)
1365         setattr(self.pset,label,v)
1366     def addVBool(self,tracked,label,value):
1367         v = vbool(value)
1368         v.setIsTracked(tracked)
1369         setattr(self.pset,label,v)
1370     def addVDouble(self,tracked,label,value):
1371         v = vdouble(value)
1372         v.setIsTracked(tracked)
1373         setattr(self.pset,label,v)
1374     def addVString(self,tracked,label,value):
1375         v = vstring(value)
1376         v.setIsTracked(tracked)
1377         setattr(self.pset,label,v)
1378     def addVInputTag(self,tracked,label,value):
1379         v = VInputTag(value)
1380         v.setIsTracked(tracked)
1381         setattr(self.pset,label,v)
1382     def addVESInputTag(self,tracked,label,value):
1383         v = VESInputTag(value)
1384         v.setIsTracked(tracked)
1385         setattr(self.pset,label,v)
1386     def addVEventID(self,tracked,label,value):
1387         v = VEventID(value)
1388         v.setIsTracked(tracked)
1389         setattr(self.pset,label,v)
1390     def addVEventRange(self,tracked,label,value):
1391         v = VEventRange(value)
1392         v.setIsTracked(tracked)
1393         setattr(self.pset,label,v)
1394     def addVLuminosityBlockID(self,tracked,label,value):
1395         v = VLuminosityBlockID(value)
1396         v.setIsTracked(tracked)
1397         setattr(self.pset,label,v)
1398     def addVLuminosityBlockRange(self,tracked,label,value):
1399         v = VLuminosityBlockRange(value)
1400         v.setIsTracked(tracked)
1401         setattr(self.pset,label,v)
1402     def addNewFileInPath(self,tracked,label,value):
1403         v = FileInPath(value)
1404         v.setIsTracked(tracked)
1405         setattr(self.pset,label,v)
1406     def newInputTag(self, label, instance, process):
1407         return InputTag(label,instance,process)
1408     def newESInputTag(self,moduleLabel,dataLabel):
1409         return ESInputTag(moduleLabel,dataLabel)
1410     def newEventID(self,r,l,e):
1411         return EventID(r,l,e)
1412     def newLuminosityBlockID(self,r,l):
1413         return LuminosityBlockID(r,l)
1414     def newEventRange(self,r,l,e,r2,l2,e2):
1415         return EventRange(r,l,e,r2,l2,e2)
1416     def newLuminosityBlockRange(self,r,l,r2,l2):
1417         return LuminosityBlockRange(r,l,r2,l2)
1418     def newPSet(self):
1419         return _ConvertToPSet()
1420     def addPSet(self,tracked,label,value):
1421         #value is of type _ConvertToPSet so we need
1422         # to extract the internally held PSet
1423         value.pset.setIsTracked(tracked)
1424         setattr(self.pset,label,value.pset)
1425     def addVPSet(self,tracked,label,value):
1426         #for each item in value gets its pset and create a new list
1427         v = VPSet()
1428         v.extend([x.pset for x in value])
1429         v.setIsTracked(tracked)
1430         setattr(self.pset,label,v)
1431 
1432 def convertToPSet(name,module):
1433     convert = _ConvertToPSet()
1434     module.insertInto(convert,name)
1435     return getattr(convert.pset,name)
1436 
1437 def convertToVPSet( **kw ):
1438     returnValue = VPSet()
1439     for name,module in kw.items():
1440         returnValue.append(convertToPSet(name,module))
1441     return returnValue
1442 
1443 
1444 class EDAlias(_ConfigureComponent,_Labelable,_Parameterizable):
1445     def __init__(self,*arg,**kargs):
1446         super(EDAlias,self).__init__(**kargs)
1447 
1448     @staticmethod
1449     def allProducts():
1450         """A helper to specify that all products of a module are to be aliased for. Example usage:
1451         process.someAlias = cms.EDAlias(
1452             aliasForModuleLabel = cms.EDAlias.allProducts()
1453         )
1454         """
1455         return VPSet(PSet(type = string('*')))
1456 
1457     def clone(self, *args, **params):
1458         returnValue = EDAlias.__new__(type(self))
1459         myparams = self.parameters_()
1460         if len(myparams) == 0 and len(params) and len(args):
1461             args.append(None)
1462 
1463         _modifyParametersFromDict(myparams, params, self._Parameterizable__raiseBadSetAttr)
1464 
1465         returnValue.__init__(*args, **myparams)
1466         saveOrigin(returnValue, 1)
1467         return returnValue
1468 
1469     def _place(self,name,proc):
1470         proc._placeAlias(name,self)
1471 
1472     def nameInProcessDesc_(self, myname):
1473         return myname;
1474 
1475     def appendToProcessDescList_(self, lst, myname):
1476         lst.append(self.nameInProcessDesc_(myname))
1477 
1478     def insertInto(self, parameterSet, myname):
1479         newpset = parameterSet.newPSet()
1480         newpset.addString(True, "@module_label", myname)
1481         newpset.addString(True, "@module_type", type(self).__name__)
1482         newpset.addString(True, "@module_edm_type", type(self).__name__)
1483         for name in self.parameterNames_():
1484             param = getattr(self,name)
1485             param.insertInto(newpset, name)
1486         parameterSet.addPSet(True, self.nameInProcessDesc_(myname), newpset)
1487 
1488     def dumpPython(self, options=PrintOptions()):
1489         specialImportRegistry.registerUse(self)
1490         resultList = ['cms.EDAlias(']
1491         separator = ""
1492         for name in self.parameterNames_():
1493             resultList[-1] = resultList[-1] + separator
1494             separator=","
1495             param = self.__dict__[name]
1496             options.indent()
1497             resultList.append(options.indentation()+name+' = '+param.dumpPython(options))
1498             options.unindent()
1499         return '\n'.join(resultList) + '\n' + options.indentation() + ')'
1500 
1501     # an EDAlias only references other modules by label, so it does not need their definition
1502     def directDependencies(self):
1503         return []
1504 
1505 if __name__ == "__main__":
1506 
1507     import unittest
1508     class PSetTester(object):
1509         def addEventID(self,*pargs,**kargs):
1510             pass
1511         def newEventID(self,*pargs,**kargs):
1512             pass
1513         def addVEventID(self,*pargs,**kargs):
1514             pass
1515         def newLuminosityBlockID(self,*pargs,**kargs):
1516             pass
1517         def addLuminosityBlockID(self,*pargs,**kargs):
1518             pass
1519         def addVLuminosityBlockID(self,*pargs,**kargs):
1520             pass
1521         def addEventRange(self,*pargs,**kargs):
1522             pass
1523         def newEventRange(self,*pargs,**kargs):
1524             pass
1525         def addVEventRange(self,*pargs,**kargs):
1526             pass
1527         def newVEventRange(self,*pargs,**kargs):
1528             pass
1529         def addLuminosityBlockRange(self,*pargs,**kargs):
1530             pass
1531         def newLuminosityBlockRange(self,*pargs,**kargs):
1532             pass
1533         def addVLuminosityBlockRange(self,*pargs,**kargs):
1534             pass
1535         def newVLuminosityBlockRange(self,*pargs,**kargs):
1536             pass
1537     class testTypes(unittest.TestCase):
1538         def testint32(self):
1539             i = int32(1)
1540             self.assertEqual(i.value(),1)
1541             self.assertTrue(i)
1542             self.assertRaises(ValueError,int32,"i")
1543             i = int32._valueFromString("0xA")
1544             self.assertEqual(i.value(),10)
1545             self.assertTrue(not int32(0))
1546 
1547         def testuint32(self):
1548             i = uint32(1)
1549             self.assertEqual(i.value(),1)
1550             self.assertTrue(i)
1551             i = uint32(0)
1552             self.assertEqual(i.value(),0)
1553             self.assertTrue(not i)
1554             self.assertRaises(ValueError,uint32,"i")
1555             self.assertRaises(ValueError,uint32,-1)
1556             i = uint32._valueFromString("0xA")
1557             self.assertEqual(i.value(),10)
1558 
1559         def testdouble(self):
1560             d = double(1)
1561             self.assertEqual(d.value(),1)
1562             self.assertEqual(d.pythonValue(),'1')
1563             d = double(float('Inf'))
1564             self.assertEqual(d,float('Inf'))
1565             self.assertEqual(d.pythonValue(),"float('inf')")
1566             d = double(-float('Inf'))
1567             self.assertEqual(d,-float('Inf'))
1568             self.assertEqual(d.pythonValue(),"-float('inf')")
1569             d = double(float('Nan'))
1570             self.assertTrue(math.isnan(d.value()))
1571             self.assertEqual(d.pythonValue(),"float('nan')")
1572         def testvdouble(self):
1573             d = vdouble(1)
1574             self.assertEqual(d.value(),[1])
1575             self.assertEqual(d.dumpPython(),'cms.vdouble(1)')
1576             d = vdouble(float('inf'))
1577             self.assertEqual(d,[float('inf')])
1578             self.assertEqual(d.dumpPython(),"cms.vdouble(float('inf'))")
1579             d = vdouble(-float('Inf'))
1580             self.assertEqual(d,[-float('inf')])
1581             self.assertEqual(d.dumpPython(),"cms.vdouble(-float('inf'))")
1582             d = vdouble(float('nan'))
1583             self.assertTrue(math.isnan(d[0]))
1584             self.assertEqual(d.dumpPython(),"cms.vdouble(float('nan'))")
1585         def testvint32(self):
1586             v = vint32()
1587             self.assertEqual(len(v),0)
1588             self.assertTrue(not v)
1589             v.append(1)
1590             self.assertEqual(len(v),1)
1591             self.assertEqual(v[0],1)
1592             self.assertTrue(v)
1593             v.append(2)
1594             v.insert(1,3)
1595             self.assertEqual(v[1],3)
1596             v[1]=4
1597             self.assertEqual(v[1],4)
1598             v[1:1]=[5]
1599             self.assertEqual(len(v),4)
1600             self.assertEqual([1,5,4,2],list(v))
1601             self.assertEqual(repr(v), "cms.vint32(1, 5, 4, 2)")
1602             self.assertRaises(TypeError,v.append,('blah'))
1603         def testbool(self):
1604             b = bool(True)
1605             self.assertEqual(b.value(),True)
1606             self.assertTrue(b)
1607             b = bool(False)
1608             self.assertEqual(b.value(),False)
1609             self.assertTrue(not b)
1610             b = bool._valueFromString("2")
1611             self.assertEqual(b.value(),True)
1612             self.assertEqual(repr(b), "cms.bool(True)")
1613             self.assertRaises(ValueError, lambda: bool("False"))
1614         def testString(self):
1615             s=string('this is a test')
1616             self.assertEqual(s.value(),'this is a test')
1617             self.assertEqual(repr(s), "cms.string(\'this is a test\')")
1618             self.assertTrue(s)
1619             s=string('\0')
1620             self.assertEqual(s.value(),'\0')
1621             self.assertEqual(s.configValue(),"'\\0'")
1622             s2=string('')
1623             self.assertEqual(s2.value(),'')
1624             self.assertTrue(not s2)
1625         def testvstring(self):
1626             a = vstring("", "Barack", "John", "Sarah", "Joe")
1627             self.assertEqual(len(a), 5)
1628             self.assertEqual(a[0], "")
1629             self.assertEqual(a[3], "Sarah")
1630             ps = PSet(v = vstring('a', 'b'))
1631             ps.v = ['loose']
1632         def testUntracked(self):
1633             p=untracked(int32(1))
1634             self.assertRaises(TypeError,untracked,(1),{})
1635             self.assertFalse(p.isTracked())
1636             p=untracked.int32(1)
1637             self.assertEqual(repr(p), "cms.untracked.int32(1)")
1638             self.assertRaises(TypeError,untracked,(1),{})
1639             self.assertFalse(p.isTracked())
1640             p=untracked.vint32(1,5,3)
1641             self.assertRaises(TypeError,untracked,(1,5,3),{})
1642             self.assertFalse(p.isTracked())
1643             p = untracked.PSet(b=int32(1))
1644             self.assertFalse(p.isTracked())
1645             self.assertEqual(p.b.value(),1)
1646         def testInputTag(self):
1647             it = InputTag._valueFromString("label::proc")
1648             self.assertEqual(it.getModuleLabel(), "label")
1649             self.assertEqual(it.getProductInstanceLabel(), "")
1650             self.assertEqual(it.getProcessName(), "proc")
1651             # tolerate, at least for translation phase
1652             #self.assertRaises(RuntimeError, InputTag,'foo:bar')
1653             it=InputTag('label',processName='proc')
1654             self.assertEqual(it.getModuleLabel(), "label")
1655             self.assertEqual(it.getProductInstanceLabel(), "")
1656             self.assertEqual(it.getProcessName(), "proc")
1657             self.assertEqual(repr(it), "cms.InputTag(\"label\",\"\",\"proc\")")
1658             vit = VInputTag(InputTag("label1"), InputTag("label2"))
1659             self.assertEqual(repr(vit), "cms.VInputTag(cms.InputTag(\"label1\"), cms.InputTag(\"label2\"))")
1660             vit = VInputTag("label1", "label2:label3")
1661             self.assertEqual(repr(vit), "cms.VInputTag(\"label1\", \"label2:label3\")")
1662             vit = VInputTag("label1", "label2", "label3")
1663             self.assertEqual(repr(vit), "cms.VInputTag(\"label1\", \"label2\", \"label3\")")
1664             vit = VInputTag(["label1", "label2", "label3"])
1665             self.assertEqual(repr(vit), "cms.VInputTag(\"label1\", \"label2\", \"label3\")")
1666             it=InputTag('label',processName=InputTag.skipCurrentProcess())
1667             self.assertEqual(it.getModuleLabel(), "label")
1668             self.assertEqual(it.getProductInstanceLabel(), "")
1669             self.assertEqual(it.getProcessName(), "@skipCurrentProcess")
1670             it=InputTag('label','x',InputTag.skipCurrentProcess())
1671             self.assertEqual(it.getModuleLabel(), "label")
1672             self.assertEqual(it.getProductInstanceLabel(), "x")
1673             self.assertEqual(it.getProcessName(), "@skipCurrentProcess")
1674             it = InputTag("label:in:@skipCurrentProcess")
1675             self.assertEqual(it.getModuleLabel(), "label")
1676             self.assertEqual(it.getProductInstanceLabel(), "in")
1677             self.assertEqual(it.getProcessName(), "@skipCurrentProcess")
1678             with self.assertRaises(RuntimeError):
1679                 it = InputTag("label:too:many:elements")
1680             with self.assertRaises(RuntimeError):
1681                 vit = VInputTag("label:too:many:elements")
1682 
1683             pset = PSet(it = InputTag("something"))
1684             # "assignment" from string
1685             pset.it = "label"
1686             self.assertEqual(pset.it.getModuleLabel(), "label")
1687             self.assertEqual(pset.it.getProductInstanceLabel(), "")
1688             self.assertEqual(pset.it.getProcessName(), "")
1689             pset.it = "label:in"
1690             self.assertEqual(pset.it.getModuleLabel(), "label")
1691             self.assertEqual(pset.it.getProductInstanceLabel(), "in")
1692             self.assertEqual(pset.it.getProcessName(), "")
1693             pset.it = "label:in:proc"
1694             self.assertEqual(pset.it.getModuleLabel(), "label")
1695             self.assertEqual(pset.it.getProductInstanceLabel(), "in")
1696             self.assertEqual(pset.it.getProcessName(), "proc")
1697             pset.it = "label::proc"
1698             self.assertEqual(pset.it.getModuleLabel(), "label")
1699             self.assertEqual(pset.it.getProductInstanceLabel(), "")
1700             self.assertEqual(pset.it.getProcessName(), "proc")
1701             with self.assertRaises(RuntimeError):
1702                 pset.it = "label:too:many:elements"
1703             # "assignment" from tuple of strings
1704             pset.it = ()
1705             self.assertEqual(pset.it.getModuleLabel(), "")
1706             self.assertEqual(pset.it.getProductInstanceLabel(), "")
1707             self.assertEqual(pset.it.getProcessName(), "")
1708             pset.it = ("label",)
1709             self.assertEqual(pset.it.getModuleLabel(), "label")
1710             self.assertEqual(pset.it.getProductInstanceLabel(), "")
1711             self.assertEqual(pset.it.getProcessName(), "")
1712             pset.it = ("label", "in")
1713             self.assertEqual(pset.it.getModuleLabel(), "label")
1714             self.assertEqual(pset.it.getProductInstanceLabel(), "in")
1715             self.assertEqual(pset.it.getProcessName(), "")
1716             pset.it = ("label", "in", "proc")
1717             self.assertEqual(pset.it.getModuleLabel(), "label")
1718             self.assertEqual(pset.it.getProductInstanceLabel(), "in")
1719             self.assertEqual(pset.it.getProcessName(), "proc")
1720             pset.it = ("label", "", "proc")
1721             self.assertEqual(pset.it.getModuleLabel(), "label")
1722             self.assertEqual(pset.it.getProductInstanceLabel(), "")
1723             self.assertEqual(pset.it.getProcessName(), "proc")
1724             with self.assertRaises(RuntimeError):
1725                 pset.it = ("label", "too", "many", "elements")
1726             # "assignment" from list of strings
1727             pset.it = []
1728             self.assertEqual(pset.it.getModuleLabel(), "")
1729             self.assertEqual(pset.it.getProductInstanceLabel(), "")
1730             self.assertEqual(pset.it.getProcessName(), "")
1731             pset.it = ["label"]
1732             self.assertEqual(pset.it.getModuleLabel(), "label")
1733             self.assertEqual(pset.it.getProductInstanceLabel(), "")
1734             self.assertEqual(pset.it.getProcessName(), "")
1735             pset.it = ["label", "in"]
1736             self.assertEqual(pset.it.getModuleLabel(), "label")
1737             self.assertEqual(pset.it.getProductInstanceLabel(), "in")
1738             self.assertEqual(pset.it.getProcessName(), "")
1739             pset.it = ["label", "in", "proc"]
1740             self.assertEqual(pset.it.getModuleLabel(), "label")
1741             self.assertEqual(pset.it.getProductInstanceLabel(), "in")
1742             self.assertEqual(pset.it.getProcessName(), "proc")
1743             pset.it = ["label", "", "proc"]
1744             self.assertEqual(pset.it.getModuleLabel(), "label")
1745             self.assertEqual(pset.it.getProductInstanceLabel(), "")
1746             self.assertEqual(pset.it.getProcessName(), "proc")
1747             with self.assertRaises(RuntimeError):
1748                 pset.it = ["label", "too", "many", "elements"]
1749 
1750             vit = VInputTag(("a2",), ("b2", "i"), ("c2", "i", "p"))
1751             self.assertEqual(repr(vit), "cms.VInputTag(\"a2\", \"b2:i\", \"c2:i:p\")")
1752 
1753             pset = PSet(vit = VInputTag())
1754             pset.vit = ["a", "b:i", "c:i:p"]
1755             self.assertEqual(repr(pset.vit), "cms.VInputTag(\"a\", \"b:i\", \"c:i:p\")")
1756             pset.vit = [("a2",), ("b2", "i"), ("c2", "i", "p")]
1757             self.assertEqual(repr(pset.vit), "cms.VInputTag(\"a2\", \"b2:i\", \"c2:i:p\")")
1758             pset.vit = [["a3"], ["b3", "i"], ["c3", "i", "p"]]
1759             self.assertEqual(repr(pset.vit), "cms.VInputTag(\"a3\", \"b3:i\", \"c3:i:p\")")
1760             with self.assertRaises(RuntimeError):
1761                 pset.vit = [("label", "too", "many", "elements")]
1762         def testInputTagModified(self):
1763             a=InputTag("a")
1764             self.assertEqual(a.isModified(),False)
1765             a.setModuleLabel("a")
1766             self.assertEqual(a.isModified(),False)
1767             a.setModuleLabel("b")
1768             self.assertEqual(a.isModified(),True)
1769             a.resetModified()
1770             a.setProductInstanceLabel("b")
1771             self.assertEqual(a.isModified(),True)
1772             a.resetModified()
1773             a.setProcessName("b")
1774             self.assertEqual(a.isModified(),True)
1775             a.resetModified()
1776             a.setValue("b")
1777             self.assertEqual(a.isModified(),True)
1778         def testESInputTag(self):
1779             it = ESInputTag._valueFromString("label:data")
1780             self.assertEqual(it.getModuleLabel(), "label")
1781             self.assertEqual(it.getDataLabel(), "data")
1782             # tolerate, at least for translation phase
1783             #self.assertRaises(RuntimeError, InputTag,'foo:bar')
1784             it=ESInputTag(data='data')
1785             self.assertEqual(it.getModuleLabel(), "")
1786             self.assertEqual(it.getDataLabel(), "data")
1787             self.assertEqual(repr(it), "cms.ESInputTag(\"\",\"data\")")
1788             vit = VESInputTag(ESInputTag("label1:"), ESInputTag("label2:"))
1789             self.assertEqual(repr(vit), 'cms.VESInputTag(cms.ESInputTag("label1",""), cms.ESInputTag("label2",""))')
1790             vit = VESInputTag("label1:", "label2:label3")
1791             self.assertEqual(repr(vit), "cms.VESInputTag(\"label1:\", \"label2:label3\")")
1792             vit = VESInputTag(["label1:", "label2:label3"])
1793             self.assertEqual(repr(vit), "cms.VESInputTag(\"label1:\", \"label2:label3\")")
1794 
1795             with self.assertRaises(RuntimeError):
1796                 it = ESInputTag("label:too:many:elements")
1797             with self.assertRaises(RuntimeError):
1798                 vit = VESInputTag("label:too:many:elements")
1799 
1800             pset = PSet(it = ESInputTag("something:"))
1801             # "assignment" from string
1802             pset.it = ""
1803             self.assertEqual(pset.it.getModuleLabel(), "")
1804             self.assertEqual(pset.it.getDataLabel(), "")
1805             pset.it = "label:"
1806             self.assertEqual(pset.it.getModuleLabel(), "label")
1807             self.assertEqual(pset.it.getDataLabel(), "")
1808             pset.it = "label:data"
1809             self.assertEqual(pset.it.getModuleLabel(), "label")
1810             self.assertEqual(pset.it.getDataLabel(), "data")
1811             pset.it = ":data"
1812             self.assertEqual(pset.it.getModuleLabel(), "")
1813             self.assertEqual(pset.it.getDataLabel(), "data")
1814             with self.assertRaises(RuntimeError):
1815                 pset.it = "too:many:elements"
1816             with self.assertRaises(RuntimeError):
1817                 pset.it = "too_few_elements"
1818             # "assignment" from tuple of strings
1819             pset.it = ()
1820             self.assertEqual(pset.it.getModuleLabel(), "")
1821             self.assertEqual(pset.it.getDataLabel(), "")
1822             pset.it = ("label", "")
1823             self.assertEqual(pset.it.getModuleLabel(), "label")
1824             self.assertEqual(pset.it.getDataLabel(), "")
1825             pset.it = ("label", "data")
1826             self.assertEqual(pset.it.getModuleLabel(), "label")
1827             self.assertEqual(pset.it.getDataLabel(), "data")
1828             pset.it = ("", "data")
1829             self.assertEqual(pset.it.getModuleLabel(), "")
1830             self.assertEqual(pset.it.getDataLabel(), "data")
1831             with self.assertRaises(RuntimeError):
1832                 pset.it = ("too", "many", "elements")
1833             with self.assertRaises(RuntimeError):
1834                 pset.it = ("too_few_elements",)
1835             # "assignment" from list of strings
1836             pset.it = []
1837             self.assertEqual(pset.it.getModuleLabel(), "")
1838             self.assertEqual(pset.it.getDataLabel(), "")
1839             pset.it = ["label", ""]
1840             self.assertEqual(pset.it.getModuleLabel(), "label")
1841             self.assertEqual(pset.it.getDataLabel(), "")
1842             pset.it = ["label", "data"]
1843             self.assertEqual(pset.it.getModuleLabel(), "label")
1844             self.assertEqual(pset.it.getDataLabel(), "data")
1845             pset.it = ["", "data"]
1846             self.assertEqual(pset.it.getModuleLabel(), "")
1847             self.assertEqual(pset.it.getDataLabel(), "data")
1848             with self.assertRaises(RuntimeError):
1849                 pset.it = ["too", "many", "elements"]
1850             with self.assertRaises(RuntimeError):
1851                 pset.it = ["too_few_elements"]
1852 
1853             vit = VESInputTag(("a2", ""), ("b2", "d"), ("", "c"))
1854             self.assertEqual(repr(vit), "cms.VESInputTag(\"a2:\", \"b2:d\", \":c\")")
1855 
1856             pset = PSet(vit = VESInputTag())
1857             pset.vit = ["a:", "b:d", ":c"]
1858             self.assertEqual(repr(pset.vit), "cms.VESInputTag(\"a:\", \"b:d\", \":c\")")
1859             pset.vit = [("a2", ""), ("b2", "d2"), ("", "c2")]
1860             self.assertEqual(repr(pset.vit), "cms.VESInputTag(\"a2:\", \"b2:d2\", \":c2\")")
1861             pset.vit = [["a3", ""], ["b3", "d3"], ["", "c3"]]
1862             self.assertEqual(repr(pset.vit), "cms.VESInputTag(\"a3:\", \"b3:d3\", \":c3\")")
1863             with self.assertRaises(RuntimeError):
1864                 pset.vit = [("too", "many", "elements")]
1865             with self.assertRaises(RuntimeError):
1866                 pset.vit = ["too_few_elements"]
1867             with self.assertRaises(RuntimeError):
1868                 pset.vit = [("too_few_elements")]
1869 
1870         def testPSet(self):
1871             p1 = PSet(anInt = int32(1), a = PSet(b = int32(1)))
1872             self.assertRaises(ValueError, PSet, "foo")
1873             self.assertRaises(TypeError, PSet, foo = "bar")
1874             self.assertEqual(repr(p1), "cms.PSet(\n    a = cms.PSet(\n        b = cms.int32(1)\n    ),\n    anInt = cms.int32(1)\n)")
1875             vp1 = VPSet(PSet(i = int32(2)))
1876             #self.assertEqual(vp1.configValue(), "
1877             self.assertEqual(repr(vp1), "cms.VPSet(cms.PSet(\n    i = cms.int32(2)\n))")
1878             self.assertTrue(p1.hasParameter(['a', 'b']))
1879             self.assertFalse(p1.hasParameter(['a', 'c']))
1880             self.assertEqual(p1.getParameter(['a', 'b']).value(), 1)
1881             # test clones and trackedness
1882             p3 = untracked.PSet(i = int32(1), ui=untracked.int32(2), a = PSet(b = untracked.int32(1)), b = untracked.PSet(b = int32(1)))
1883             p4 = p3.clone()
1884             self.assertFalse(p4.isTracked())
1885             self.assertTrue(p4.i.isTracked())
1886             self.assertFalse(p4.ui.isTracked())
1887             self.assertTrue(p4.a.isTracked())
1888             self.assertFalse(p4.b.isTracked())
1889             self.assertFalse(p4.a.b.isTracked())
1890             self.assertTrue(p4.b.b.isTracked())
1891             p4 = p3.clone( i = None, b = dict(b = 5))
1892             self.assertEqual(p3.i.value(), 1)
1893             self.assertEqual(hasattr(p4,"i"), False)
1894             self.assertEqual(p3.b.b.value(), 1)
1895             self.assertEqual(p4.b.b.value(), 5)
1896             self.assertEqual(p4.a.b.value(), 1)
1897             self.assertEqual(p4.ui.value(), 2)
1898             # couple of cases of "weird" arguments
1899             self.assertRaises(TypeError, p4.clone, dict(b = None))
1900             self.assertRaises(TypeError, p4.clone, [])
1901             self.assertRaises(TypeError, p4.clone, 42)
1902             p5 = PSet(p = PSet(anInt = int32(1), aString=string("foo") ) )
1903             p5.p=dict(aString = "bar")
1904             self.assertEqual(p5.p.aString.value(), "bar")
1905             self.assertEqual(p5.p.anInt.value(), 1)
1906             p5.p = dict(aDouble = double(3.14))
1907             self.assertEqual(p5.p.aString.value(), "bar")
1908             self.assertEqual(p5.p.anInt.value(), 1)
1909             self.assertEqual(p5.p.aDouble, 3.14)
1910             self.assertRaises(TypeError, p5.p , dict(bar = 3) )
1911         def testRequired(self):
1912             p1 = PSet(anInt = required.int32)
1913             self.assertTrue(hasattr(p1,"anInt"))
1914             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    anInt = cms.required.int32\n)')
1915             p1.anInt = 3
1916             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    anInt = cms.int32(3)\n)')
1917             self.assertEqual(p1.anInt.value(), 3)
1918             p1 = PSet(anInt = required.int32)
1919             p1.anInt.setValue(3)
1920             self.assertEqual(p1.anInt.value(), 3)
1921             p1.anInt = 4
1922             self.assertEqual(p1.anInt.value(), 4)
1923             p1 = PSet(anInt = required.untracked.int32)
1924             p1.anInt = 5
1925             self.assertEqual(p1.anInt.value(), 5)
1926             self.assertFalse(p1.anInt.isTracked())
1927             p1 = PSet(anInt = required.untracked.int32)
1928             self.assertEqual(p1.dumpPython(), 'cms.PSet(\n    anInt = cms.required.untracked.int32\n)')
1929             p1.anInt = 6
1930             self.assertEqual(p1.dumpPython(), 'cms.PSet(\n    anInt = cms.untracked.int32(6)\n)')
1931             self.assertTrue(p1.anInt.isCompatibleCMSType(int32))
1932             self.assertFalse(p1.anInt.isCompatibleCMSType(uint32))
1933             p1 = PSet(allowAnyLabel_ = required.int32)
1934             self.assertFalse(p1.hasParameter(['allowAnyLabel_']))
1935             p1.foo = 3
1936             self.assertEqual(p1.foo.value(),3)
1937             self.assertRaises(ValueError,setattr,p1, 'bar', 'bad')
1938             self.assertTrue(p1.foo.isTracked())
1939             p1 = PSet(allowAnyLabel_ = required.untracked.int32)
1940             self.assertFalse(p1.hasParameter(['allowAnyLabel_']))
1941             p1.foo = 3
1942             self.assertEqual(p1.foo.value(),3)
1943             self.assertFalse(p1.foo.isTracked())
1944             self.assertRaises(ValueError,setattr,p1, 'bar', 'bad')
1945             #PSetTemplate use
1946             p1 = PSet(aPSet = required.PSetTemplate())
1947             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aPSet = cms.required.PSetTemplate(\n\n    )\n)')
1948             p1.aPSet = dict()
1949             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aPSet = cms.PSet(\n\n    )\n)')
1950             p1 = PSet(aPSet=required.PSetTemplate(a=required.int32))
1951             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aPSet = cms.required.PSetTemplate(\n        a = cms.required.int32\n    )\n)')
1952             p1.aPSet = dict(a=5)
1953             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aPSet = cms.PSet(\n        a = cms.int32(5)\n    )\n)')
1954             self.assertEqual(p1.aPSet.a.value(), 5)
1955             p1 = PSet(aPSet=required.PSetTemplate(a=required.int32))
1956             p1.aPSet = PSet(a=int32(5))
1957             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aPSet = cms.PSet(\n        a = cms.int32(5)\n    )\n)')
1958             self.assertEqual(p1.aPSet.a.value(), 5)
1959             p1 = PSet(aPSet=required.untracked.PSetTemplate(a=required.int32))
1960             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aPSet = cms.required.untracked.PSetTemplate(\n        a = cms.required.int32\n    )\n)')
1961             p1.aPSet = dict(a=5)
1962             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aPSet = cms.untracked.PSet(\n        a = cms.int32(5)\n    )\n)')
1963             self.assertEqual(p1.aPSet.a.value(), 5)
1964             p1 = PSet(allowAnyLabel_=required.PSetTemplate(a=required.int32))
1965             p1Clone = p1.clone()
1966             self.assertEqual(p1.dumpPython(), 'cms.PSet(\n    allowAnyLabel_=cms.required.PSetTemplate(\n        a = cms.required.int32\n    )\n)')
1967             self.assertEqual(p1Clone.dumpPython(), 'cms.PSet(\n    allowAnyLabel_=cms.required.PSetTemplate(\n        a = cms.required.int32\n    )\n)')
1968             with self.assertRaises(AttributeError):
1969                 p1.clone(allowAnyLabel_=optional.double)
1970             p1.foo = dict(a=5)
1971             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    foo = cms.PSet(\n        a = cms.int32(5)\n    ),\n    allowAnyLabel_=cms.required.PSetTemplate(\n        a = cms.required.int32\n    )\n)')
1972             self.assertEqual(p1.foo.a.value(), 5)
1973             p1 = PSet(anInt = required.int32)
1974             self.assertRaises(TypeError, setattr, p1,'anInt', uint32(2))
1975 
1976         def testOptional(self):
1977             p1 = PSet(anInt = optional.int32)
1978             self.assertTrue(hasattr(p1,"anInt"))
1979             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    anInt = cms.optional.int32\n)')
1980             p1.anInt = 3
1981             self.assertEqual(p1.anInt.value(), 3)
1982             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    anInt = cms.int32(3)\n)')
1983             p1 = PSet(anInt = optional.int32)
1984             p1.anInt.setValue(3)
1985             self.assertEqual(p1.anInt.value(), 3)
1986             p1.anInt = 4
1987             self.assertEqual(p1.anInt.value(), 4)
1988             p1 = PSet(anInt = optional.untracked.int32)
1989             p1.anInt = 5
1990             self.assertEqual(p1.anInt.value(), 5)
1991             self.assertFalse(p1.anInt.isTracked())
1992             p1 = PSet(anInt = optional.untracked.int32)
1993             self.assertEqual(p1.dumpPython(), 'cms.PSet(\n    anInt = cms.optional.untracked.int32\n)')
1994             p1.anInt = 6
1995             self.assertEqual(p1.dumpPython(), 'cms.PSet(\n    anInt = cms.untracked.int32(6)\n)')
1996             self.assertTrue(p1.anInt.isCompatibleCMSType(int32))
1997             self.assertFalse(p1.anInt.isCompatibleCMSType(uint32))
1998             p1 = PSet(f = required.vint32)
1999             self.assertFalse(p1.f)
2000             p1.f = []
2001             self.assertFalse(p1.f)
2002             p1.f.append(3)
2003             self.assertTrue(p1.f)
2004             #PSetTemplate use
2005             p1 = PSet(aPSet = optional.PSetTemplate())
2006             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aPSet = cms.optional.PSetTemplate(\n\n    )\n)')
2007             p1.aPSet = dict()
2008             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aPSet = cms.PSet(\n\n    )\n)')
2009             p1 = PSet(aPSet=optional.PSetTemplate(a=optional.int32))
2010             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aPSet = cms.optional.PSetTemplate(\n        a = cms.optional.int32\n    )\n)')
2011             p1.aPSet = dict(a=5)
2012             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aPSet = cms.PSet(\n        a = cms.int32(5)\n    )\n)')
2013             self.assertEqual(p1.aPSet.a.value(), 5)
2014             p1 = PSet(aPSet=optional.untracked.PSetTemplate(a=optional.int32))
2015             p1Clone = p1.clone()
2016             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aPSet = cms.optional.untracked.PSetTemplate(\n        a = cms.optional.int32\n    )\n)')
2017             self.assertEqual(p1Clone.dumpPython(),'cms.PSet(\n    aPSet = cms.optional.untracked.PSetTemplate(\n        a = cms.optional.int32\n    )\n)')
2018             p1.aPSet = dict(a=5)
2019             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aPSet = cms.untracked.PSet(\n        a = cms.int32(5)\n    )\n)')
2020             self.assertEqual(p1.aPSet.a.value(), 5)
2021             p1 = PSet(allowAnyLabel_=optional.PSetTemplate(a=optional.int32))
2022             self.assertEqual(p1.dumpPython(), 'cms.PSet(\n    allowAnyLabel_=cms.optional.PSetTemplate(\n        a = cms.optional.int32\n    )\n)')
2023             p1.foo = dict(a=5)
2024             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    foo = cms.PSet(\n        a = cms.int32(5)\n    ),\n    allowAnyLabel_=cms.optional.PSetTemplate(\n        a = cms.optional.int32\n    )\n)')
2025             self.assertEqual(p1.foo.a.value(), 5)
2026             #check wrong type failure
2027             p1 = PSet(anInt = optional.int32)
2028             self.assertRaises(TypeError, lambda : setattr(p1,'anInt', uint32(2)))
2029 
2030 
2031         def testAllowed(self):
2032             p1 = PSet(aValue = required.allowed(int32, string))
2033             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aValue = cms.required.allowed(cms.int32,cms.string)\n)')
2034             p1.aValue = 1
2035             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aValue = cms.int32(1)\n)')
2036             self.assertTrue(p1.aValue.isCompatibleCMSType(int32))
2037             self.assertFalse(p1.aValue.isCompatibleCMSType(uint32))
2038             self.assertRaises(RuntimeError, lambda: setattr(p1,'aValue',1.3))
2039             p1 = PSet(aValue = required.allowed(int32, string))
2040             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aValue = cms.required.allowed(cms.int32,cms.string)\n)')
2041             p1.aValue = "foo"
2042             self.assertEqual(p1.dumpPython(),"cms.PSet(\n    aValue = cms.string('foo')\n)")
2043             self.assertTrue(p1.aValue.isCompatibleCMSType(string))
2044             self.assertFalse(p1.aValue.isCompatibleCMSType(uint32))
2045             p1 = PSet(aValue = required.allowed(int32, string))
2046             #assign wrong type
2047             self.assertRaises(TypeError, lambda: setattr(p1, 'aValue', double(3.1)))
2048 
2049             p1 = PSet(aValue = required.allowed(int32, string, default=int32(3)))
2050             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aValue = cms.int32(3)\n)')
2051             p1.aValue = "foo"
2052             self.assertEqual(p1.dumpPython(),"cms.PSet(\n    aValue = cms.string('foo')\n)")
2053             
2054             p1 = PSet(aValue = required.untracked.allowed(int32, string, default=int32(3)))
2055             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aValue = cms.untracked.int32(3)\n)')
2056 
2057             p1 = PSet(aValue = required.untracked.allowed(int32, string))
2058             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aValue = cms.required.untracked.allowed(cms.int32,cms.string)\n)')
2059             p1.aValue = 1
2060             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aValue = cms.untracked.int32(1)\n)')
2061             self.assertRaises(RuntimeError, lambda: setattr(p1,'aValue',1.3))
2062             p1 = PSet(aValue = required.untracked.allowed(int32, string))
2063             self.assertEqual(p1.dumpPython(),'cms.PSet(\n    aValue = cms.required.untracked.allowed(cms.int32,cms.string)\n)')
2064             p1.aValue = "foo"
2065             self.assertEqual(p1.dumpPython(),"cms.PSet(\n    aValue = cms.untracked.string('foo')\n)")
2066 
2067             p2 = PSet(aValue=optional.allowed(int32,PSet))
2068             self.assertEqual(p2.dumpPython(),'cms.PSet(\n    aValue = cms.optional.allowed(cms.int32,cms.PSet)\n)')
2069             p2.aValue = 2
2070             self.assertEqual(p2.aValue.value(),2)
2071             p2 = PSet(aValue=optional.allowed(int32,PSet))
2072             p2.aValue = PSet(i = int32(3))
2073             self.assertEqual(p2.aValue.i.value(),3)
2074             p2 = PSet(aValue=optional.allowed(int32,PSet))
2075             p2.aValue = dict(i = int32(3))
2076             self.assertEqual(p2.aValue.i.value(),3)
2077 
2078             p2 = PSet(aValue=optional.allowed(int32,PSetTemplate(b=optional.int32)))
2079             self.assertEqual(p2.dumpPython(),'cms.PSet(\n    aValue = cms.optional.allowed(cms.int32,cms.PSetTemplate(\n    b = cms.optional.int32\n))\n)')
2080             p2.aValue = 2
2081             self.assertEqual(p2.aValue.value(),2)
2082             p2 = PSet(aValue=optional.allowed(int32,PSetTemplate(b=optional.int32)))
2083             p2.aValue = PSet(b = int32(3))
2084             self.assertEqual(p2.aValue.b.value(),3)
2085             p2 = PSet(aValue=optional.allowed(int32,PSetTemplate(b=optional.int32)))
2086             p2.aValue = dict(b = 3)
2087             self.assertEqual(p2.aValue.b.value(),3)
2088             self.assertEqual(p2.dumpPython(), 'cms.PSet(\n    aValue = cms.PSet(\n        b = cms.int32(3)\n    )\n)')
2089             p2 = PSet(aValue=optional.allowed(int32,PSetTemplate(b=optional.int32)))
2090             self.assertRaises(TypeError, lambda: setattr(p2, "aValue", dict(i = 1)) )
2091             p2 = PSet(aValue=optional.allowed(int32,PSetTemplate(b=optional.int32)))
2092             self.assertRaises(TypeError, lambda: setattr(p2, "aValue", double(3.14)) )
2093             self.assertRaises(ValueError, lambda: setattr(p2, "aValue", dict(b=3.14)) )
2094             p2 = PSet(aValue=optional.allowed(int32,PSetTemplate(b=optional.int32)))
2095             p2.aValue = PSet(b=double(3.14))
2096             self.assertEqual(p2.aValue.b.value(),3.14)
2097 
2098 
2099 
2100             p2 = PSet(aValue=optional.untracked.allowed(int32,PSet))
2101             self.assertEqual(p2.dumpPython(),'cms.PSet(\n    aValue = cms.optional.untracked.allowed(cms.int32,cms.PSet)\n)')
2102             p2.aValue = 2
2103             self.assertEqual(p2.aValue.value(),2)
2104             p2 = PSet(aValue=optional.untracked.allowed(int32,PSet))
2105             p2.aValue = PSet(i = int32(3))
2106             self.assertEqual(p2.aValue.i.value(),3)
2107             p2 = PSet(aValue=optional.untracked.allowed(int32,PSet))
2108             p2.aValue = dict(i = int32(3))
2109             self.assertEqual(p2.aValue.i.value(),3)
2110 
2111             p3 = PSet(aValue=required.allowed(int32,uint32))
2112             p3.aValue = -42
2113             self.assertEqual(p3.aValue.value(), -42)
2114             p3 = PSet(aValue=required.allowed(int32,uint32))
2115             self.assertRaises(RuntimeError, lambda: setattr(p3, "aValue", 42))
2116 
2117             p3 = PSet(aValue=required.untracked.allowed(int32,uint32))
2118             p3.aValue = -42
2119             self.assertEqual(p3.aValue.value(), -42)
2120             p3 = PSet(aValue=required.untracked.allowed(int32,uint32))
2121             self.assertRaises(RuntimeError, lambda: setattr(p3, "aValue", 42))
2122 
2123             p3 = PSet(aValue=optional.allowed(int32,uint32))
2124             p3.aValue = -42
2125             self.assertEqual(p3.aValue.value(), -42)
2126             p3 = PSet(aValue=optional.allowed(int32,uint32))
2127             self.assertRaises(RuntimeError, lambda: setattr(p3, "aValue", 42))
2128 
2129             p3 = PSet(aValue=optional.untracked.allowed(int32,uint32))
2130             p3.aValue = -42
2131             self.assertEqual(p3.aValue.value(), -42)
2132             p3 = PSet(aValue=optional.untracked.allowed(int32,uint32))
2133             self.assertRaises(RuntimeError, lambda: setattr(p3, "aValue", 42))
2134 
2135             p1 = PSet(aValue = required.allowed(int32, string))
2136             self.assertRaises(TypeError, lambda : setattr(p1,'aValue', uint32(2)))
2137 
2138             p1 = PSet(aValue = required.allowed(InputTag, VInputTag, default=InputTag("blah")))
2139             p1.aValue.setValue("foo")
2140             self.assertEqual(p1.aValue.value(), "foo")
2141 
2142             
2143         def testVPSet(self):
2144             p1 = VPSet(PSet(anInt = int32(1)), PSet(anInt=int32(2)))
2145             self.assertEqual(len(p1),2)
2146             self.assertEqual(p1[0].anInt.value(), 1)
2147             self.assertEqual(p1[1].anInt.value(), 2)
2148             self.assertRaises(TypeError, lambda : VPSet(3))
2149             self.assertRaises(TypeError, lambda : VPSet(int32(3)))
2150             self.assertRaises(SyntaxError, lambda : VPSet(foo=PSet()))
2151         def testEDAlias(self):
2152             aliasfoo2 = EDAlias(foo2 = VPSet(PSet(type = string("Foo2"))))
2153             self.assertTrue(hasattr(aliasfoo2,"foo2"))
2154             del aliasfoo2.foo2
2155             self.assertTrue(not hasattr(aliasfoo2,"foo2"))
2156             self.assertTrue("foo2" not in aliasfoo2.parameterNames_())
2157 
2158             aliasfoo2 = EDAlias(foo2 = VPSet(PSet(type = string("Foo2"))))
2159             aliasfoo3 = aliasfoo2.clone(
2160                 foo2 = {0: dict(type = "Foo4")},
2161                 foo3 = VPSet(PSet(type = string("Foo3")))
2162             )
2163             self.assertTrue(hasattr(aliasfoo3, "foo2"))
2164             self.assertTrue(hasattr(aliasfoo3, "foo3"))
2165             self.assertEqual(aliasfoo3.foo2[0].type, "Foo4")
2166             self.assertEqual(aliasfoo3.foo3[0].type, "Foo3")
2167 
2168             aliasfoo4 = aliasfoo3.clone(foo2 = None)
2169             self.assertFalse(hasattr(aliasfoo4, "foo2"))
2170             self.assertTrue(hasattr(aliasfoo4, "foo3"))
2171             self.assertEqual(aliasfoo4.foo3[0].type, "Foo3")
2172 
2173             aliasfoo5 = EDAlias(foo5 = EDAlias.allProducts())
2174             self.assertEqual(len(aliasfoo5.foo5), 1)
2175             self.assertEqual(aliasfoo5.foo5[0].type.value(), "*")
2176             self.assertFalse(hasattr(aliasfoo5.foo5[0], "fromProductInstance"))
2177             self.assertFalse(hasattr(aliasfoo5.foo5[0], "toProductInstance"))
2178 
2179             aliasfoo6 = aliasfoo5.clone(foo5 = None, foo6 = EDAlias.allProducts())
2180             self.assertFalse(hasattr(aliasfoo6, "foo5"))
2181             self.assertTrue(hasattr(aliasfoo6, "foo6"))
2182             self.assertEqual(len(aliasfoo6.foo6), 1)
2183             self.assertEqual(aliasfoo6.foo6[0].type.value(), "*")
2184 
2185             aliasfoo7 = EDAlias(foo5 = EDAlias.allProducts(), foo6 = EDAlias.allProducts())
2186             self.assertEqual(len(aliasfoo7.foo5), 1)
2187             self.assertEqual(len(aliasfoo7.foo6), 1)
2188 
2189         def testFileInPath(self):
2190             f = FileInPath("FWCore/ParameterSet/python/Types.py")
2191             self.assertEqual(f.configValue(), "'FWCore/ParameterSet/python/Types.py'")
2192         def testSecSource(self):
2193             s1 = SecSource("EmbeddedRootSource", fileNames = vstring("foo.root"))
2194             self.assertEqual(s1.type_(), "EmbeddedRootSource")
2195             self.assertEqual(s1.configValue(),
2196 """EmbeddedRootSource { """+"""
2197     vstring fileNames = {
2198         'foo.root'
2199     }
2200 
2201 }
2202 """)
2203             s1=SecSource("EmbeddedRootSource",type=int32(1))
2204             self.assertEqual(s1.type.value(),1)
2205         def testEventID(self):
2206             eid = EventID(2, 0, 3)
2207             self.assertEqual( repr(eid), "cms.EventID(2, 0, 3)" )
2208             pset = PSetTester()
2209             eid.insertInto(pset,'foo')
2210             eid2 = EventID._valueFromString('3:4')
2211             eid2.insertInto(pset,'foo2')
2212         def testVEventID(self):
2213             veid = VEventID(EventID(2, 0, 3))
2214             veid2 = VEventID("1:2", "3:4")
2215             self.assertEqual( repr(veid[0]), "cms.EventID(2, 0, 3)" )
2216             self.assertEqual( repr(veid2[0]), "'1:2'" )
2217             self.assertEqual( veid2.dumpPython(), 'cms.VEventID("1:2", "3:4")')
2218             pset = PSetTester()
2219             veid.insertInto(pset,'foo')
2220 
2221         def testLuminosityBlockID(self):
2222             lid = LuminosityBlockID(2, 3)
2223             self.assertEqual( repr(lid), "cms.LuminosityBlockID(2, 3)" )
2224             pset = PSetTester()
2225             lid.insertInto(pset,'foo')
2226             lid2 = LuminosityBlockID._valueFromString('3:4')
2227             lid2.insertInto(pset,'foo2')
2228 
2229         def testVLuminosityBlockID(self):
2230             vlid = VLuminosityBlockID(LuminosityBlockID(2, 3))
2231             vlid2 = VLuminosityBlockID("1:2", "3:4")
2232             self.assertEqual( repr(vlid[0]), "cms.LuminosityBlockID(2, 3)" )
2233             self.assertEqual( repr(vlid2[0]), "'1:2'" )
2234             pset = PSetTester()
2235             vlid.insertInto(pset,'foo')
2236 
2237         def testEventRange(self):
2238             range1 = EventRange(1, 0, 2, 3, 0, 4)
2239             range2 = EventRange._valueFromString("1:2 - 3:4")
2240             range3 = EventRange._valueFromString("1:MIN - 3:MAX")
2241             self.assertEqual(repr(range1), repr(range1))
2242             self.assertEqual(repr(range3), "cms.EventRange(1, 0, 1, 3, 0, 0)")
2243             pset = PSetTester()
2244             range1.insertInto(pset,'foo')
2245             range2.insertInto(pset,'bar')
2246         def testVEventRange(self):
2247             v1 = VEventRange(EventRange(1, 0, 2, 3, 0, 4))
2248             v2 = VEventRange("1:2-3:4", "5:MIN-7:MAX")
2249             self.assertEqual( repr(v1[0]), "cms.EventRange(1, 0, 2, 3, 0, 4)" )
2250             pset = PSetTester()
2251             v2.insertInto(pset,'foo')
2252 
2253         def testLuminosityBlockRange(self):
2254             range1 = LuminosityBlockRange(1, 2, 3, 4)
2255             range2 = LuminosityBlockRange._valueFromString("1:2 - 3:4")
2256             range3 = LuminosityBlockRange._valueFromString("1:MIN - 3:MAX")
2257             self.assertEqual(repr(range1), repr(range1))
2258             self.assertEqual(repr(range3), "cms.LuminosityBlockRange(1, 1, 3, 0)")
2259             pset = PSetTester()
2260             range1.insertInto(pset,'foo')
2261             range2.insertInto(pset,'bar')
2262         def testVLuminosityBlockRange(self):
2263             v1 = VLuminosityBlockRange(LuminosityBlockRange(1, 2, 3, 4))
2264             v2 = VLuminosityBlockRange("1:2-3:4", "5:MIN-7:MAX")
2265             self.assertEqual( repr(v1[0]), "cms.LuminosityBlockRange(1, 2, 3, 4)" )
2266             pset = PSetTester()
2267             v2.insertInto(pset,'foo')
2268 
2269         def testPSetConversion(self):
2270             p = PSet(a = untracked.int32(7),
2271                      b = untracked.InputTag("b:"),
2272                      c = untracked.ESInputTag("c:"),
2273                      d = EventID(1,1,1),
2274                      e = LuminosityBlockID(1,1),
2275                      f = EventRange(1,1,1,8,8,8),
2276                      g = LuminosityBlockRange(1,1,8,8),
2277                      h = untracked.string('dummy'),
2278                      i = untracked.bool(False),
2279                      j = untracked.uint32(7),
2280                      k = untracked.int64(7),
2281                      l = untracked.uint64(7),
2282                      m = untracked.double(7.0),
2283                      n = FileInPath("xxx"),
2284                      o = untracked.vint32(7,8),
2285                      p = untracked.VInputTag(InputTag("b:"),InputTag("c:")),
2286                      q = untracked.VESInputTag(ESInputTag("c:"),ESInputTag("d:")),
2287                      r = untracked.VEventID(EventID(1,1,1),EventID(2,2,2)),
2288                      s = untracked.VLuminosityBlockID(LuminosityBlockID(1,1),LuminosityBlockID(2,3)),
2289                      t = untracked.VEventRange(EventRange(1,1,1,8,8,8), EventRange(9,9,9,18,18,18)),
2290                      u = untracked.VLuminosityBlockRange(LuminosityBlockRange(1,1,8,8), LuminosityBlockRange(9,9,18,18)),
2291                      v = untracked.vstring('dummy','anotherdummy'),
2292                      w = untracked.vbool(False,True),
2293                      x = untracked.vuint32(7,8),
2294                      y = untracked.vint64(7,8),
2295                      z = untracked.vuint64(7,8),
2296                      A = vdouble(7.0,8.0)
2297             )
2298             convert = _ConvertToPSet()
2299             p.insertInto(convert,"p")
2300             self.assertTrue(hasattr(convert.pset,'p'))
2301             self.assertTrue(hasattr(convert.pset.p,'a'))
2302             self.assertEqual(p.a,convert.pset.p.a)
2303             self.assertEqual(p.a.isTracked(),convert.pset.p.a.isTracked())
2304 
2305             q = PSet(b = int32(1), p = p)
2306             q.insertInto(convert,"q")
2307             self.assertTrue(hasattr(convert.pset,'q'))
2308             self.assertTrue(hasattr(convert.pset.q,'b'))
2309             self.assertEqual(q.b,convert.pset.q.b)
2310             self.assertTrue(hasattr(convert.pset.q,'p'))
2311             self.assertTrue(hasattr(convert.pset.q.p,'a'))
2312             self.assertEqual(p.a,convert.pset.q.p.a)
2313             for i in p.parameterNames_():
2314                 self.assertEqual(str(getattr(p,i)),str(getattr(convert.pset.p,i)))
2315         def testVPSetConversion(self):
2316             p = PSet(a = untracked.int32(7))
2317             q = PSet(b = int32(1), p = p)
2318             v = VPSet(p,q)
2319             convert = _ConvertToPSet()
2320             v.insertInto(convert,'v')
2321             self.assertTrue(hasattr(convert.pset,'v'))
2322             self.assertTrue(len(convert.pset.v)==2)
2323             self.assertEqual(v[0].a,convert.pset.v[0].a)
2324             self.assertEqual(v[1].b,convert.pset.v[1].b)
2325             self.assertEqual(v[1].p.a, convert.pset.v[1].p.a)
2326 
2327     class testInequalities(unittest.TestCase):
2328         def testnumbers(self):
2329             self.assertGreater(int32(5), int32(-1))
2330             self.assertGreater(int64(100), 99)
2331             self.assertLess(3, uint32(4))
2332             self.assertLess(6.999999999, uint64(7))
2333             self.assertLessEqual(-5, int32(-5))
2334             self.assertLessEqual(int32(-5), uint32(1))
2335             self.assertGreaterEqual(double(5.3), uint32(5))
2336             self.assertGreater(double(5.3), uint64(5))
2337             self.assertGreater(double(5.3), uint64(5))
2338             self.assertGreater(6, double(5))
2339             self.assertLess(uint64(0xFFFFFFFFFFFFFFFF), 0xFFFFFFFFFFFFFFFF+1)
2340             self.assertEqual(double(5.0), double(5))
2341         def teststring(self):
2342             self.assertGreater(string("I am a string"), "I am a strinf")
2343             self.assertGreaterEqual("I am a string", string("I am a string"))
2344         def testincompatibletypes(self):
2345             import sys
2346             if sys.version_info < (3, 0): #python 2, comparing incompatible types compares the class name
2347                 self.assertLess(double(3), "I am a string")
2348                 self.assertLess(3, string("I am a string"))
2349                 self.assertLess(double(5), "4")
2350             else:                         #python 3, comparing incompatible types fails
2351                 with self.assertRaises(TypeError):
2352                     double(3) < "I am a string"
2353                 with self.assertRaises(TypeError):
2354                     3 < string("I am a string")
2355         def testinfinity(self):
2356             self.assertLess(1e99, double(float("inf")))
2357             self.assertLess(double(1e99), float("inf"))
2358             self.assertGreater(1e99, double(float("-inf")))
2359             self.assertEqual(double(float("inf")), float("inf"))
2360         def testnan(self):
2361             nan = double(float("nan"))
2362             self.assertNotEqual(nan, nan)
2363             self.assertFalse(nan > 3 or nan < 3 or nan == 3)
2364 
2365     unittest.main()