Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2023-05-16 00:57:57

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