?? config.py
字號(hào):
class Int(CheckedInt): size = 32; unsigned = Falseclass Unsigned(CheckedInt): size = 32; unsigned = Trueclass Int8(CheckedInt): size = 8; unsigned = Falseclass UInt8(CheckedInt): size = 8; unsigned = Trueclass Int16(CheckedInt): size = 16; unsigned = Falseclass UInt16(CheckedInt): size = 16; unsigned = Trueclass Int32(CheckedInt): size = 32; unsigned = Falseclass UInt32(CheckedInt): size = 32; unsigned = Trueclass Int64(CheckedInt): size = 64; unsigned = Falseclass UInt64(CheckedInt): size = 64; unsigned = Trueclass Counter(CheckedInt): size = 64; unsigned = Trueclass Tick(CheckedInt): size = 64; unsigned = Trueclass TcpPort(CheckedInt): size = 16; unsigned = Trueclass UdpPort(CheckedInt): size = 16; unsigned = Trueclass Percent(CheckedInt): min = 0; max = 100class Float(ParamValue, float): passclass MemorySize(CheckedInt): size = 64 unsigned = True def __new__(cls, value): return super(MemorySize, cls).__new__(cls, toMemorySize(value))class Addr(CheckedInt): size = 64 unsigned = True def __new__(cls, value): try: value = long(toMemorySize(value)) except TypeError: value = long(value) return super(Addr, cls).__new__(cls, value)class AddrRange(Range): type = Addr# String-valued parameter. Just mixin the ParamValue class# with the built-in str class.class String(ParamValue,str): pass# Boolean parameter type. Python doesn't let you subclass bool, since# it doesn't want to let you create multiple instances of True and# False. Thus this is a little more complicated than String.class Bool(ParamValue): def __init__(self, value): try: self.value = toBool(value) except TypeError: self.value = bool(value) def __str__(self): return str(self.value) def ini_str(self): if self.value: return 'true' return 'false'def IncEthernetAddr(addr, val = 1): bytes = map(lambda x: int(x, 16), addr.split(':')) bytes[5] += val for i in (5, 4, 3, 2, 1): val,rem = divmod(bytes[i], 256) bytes[i] = rem if val == 0: break bytes[i - 1] += val assert(bytes[0] <= 255) return ':'.join(map(lambda x: '%02x' % x, bytes))class NextEthernetAddr(object): addr = "00:90:00:00:00:01" def __init__(self, inc = 1): self.value = NextEthernetAddr.addr NextEthernetAddr.addr = IncEthernetAddr(NextEthernetAddr.addr, inc)class EthernetAddr(ParamValue): def __init__(self, value): if value == NextEthernetAddr: self.value = value return if not isinstance(value, str): raise TypeError, "expected an ethernet address and didn't get one" bytes = value.split(':') if len(bytes) != 6: raise TypeError, 'invalid ethernet address %s' % value for byte in bytes: if not 0 <= int(byte) <= 256: raise TypeError, 'invalid ethernet address %s' % value self.value = value def unproxy(self, base): if self.value == NextEthernetAddr: self.addr = self.value().value return self def __str__(self): if self.value == NextEthernetAddr: return self.addr else: return self.value# Special class for NULL pointers. Note the special check in# make_param_value() above that lets these be assigned where a# SimObject is required.# only one copy of a particular nodeclass NullSimObject(object): __metaclass__ = Singleton def __call__(cls): return cls def _instantiate(self, parent = None, path = ''): pass def ini_str(self): return 'Null' def unproxy(self, base): return self def set_path(self, parent, name): pass def __str__(self): return 'Null'# The only instance you'll ever need...Null = NULL = NullSimObject()# Enumerated types are a little more complex. The user specifies the# type as Enum(foo) where foo is either a list or dictionary of# alternatives (typically strings, but not necessarily so). (In the# long run, the integer value of the parameter will be the list index# or the corresponding dictionary value. For now, since we only check# that the alternative is valid and then spit it into a .ini file,# there's not much point in using the dictionary.)# What Enum() must do is generate a new type encapsulating the# provided list/dictionary so that specific values of the parameter# can be instances of that type. We define two hidden internal# classes (_ListEnum and _DictEnum) to serve as base classes, then# derive the new type from the appropriate base class on the fly.# Metaclass for Enum typesclass MetaEnum(type): def __init__(cls, name, bases, init_dict): if init_dict.has_key('map'): if not isinstance(cls.map, dict): raise TypeError, "Enum-derived class attribute 'map' " \\ "must be of type dict" # build list of value strings from map cls.vals = cls.map.keys() cls.vals.sort() elif init_dict.has_key('vals'): if not isinstance(cls.vals, list): raise TypeError, "Enum-derived class attribute 'vals' " \\ "must be of type list" # build string->value map from vals sequence cls.map = {} for idx,val in enumerate(cls.vals): cls.map[val] = idx else: raise TypeError, "Enum-derived class must define "\\ "attribute 'map' or 'vals'" super(MetaEnum, cls).__init__(name, bases, init_dict) def cpp_declare(cls): s = 'enum %s {\\n ' % cls.__name__ s += ',\\n '.join(['%s = %d' % (v,cls.map[v]) for v in cls.vals]) s += '\\n};\\n' return s# Base class for enum types.class Enum(ParamValue): __metaclass__ = MetaEnum vals = [] def __init__(self, value): if value not in self.map: raise TypeError, "Enum param got bad value '%s' (not in %s)" \\ % (value, self.vals) self.value = value def __str__(self): return self.valueticks_per_sec = None# how big does a rounding error need to be before we warn about it?frequency_tolerance = 0.001 # 0.1%# convert a floting-point # of ticks to integer, and warn if rounding# discards too much precisiondef tick_check(float_ticks): if float_ticks == 0: return 0 int_ticks = int(round(float_ticks)) err = (float_ticks - int_ticks) / float_ticks if err > frequency_tolerance: print >> sys.stderr, "Warning: rounding error > tolerance" print >> sys.stderr, " %f rounded to %d" % (float_ticks, int_ticks) #raise ValueError return int_ticks# superclass for "numeric" parameter values, to emulate math# operations in a type-safe way. e.g., a Latency times an int returns# a new Latency object.class NumericParamValue(ParamValue): def __str__(self): return str(self.value) def __float__(self): return float(self.value) def __mul__(self, other): newobj = self.__class__(self) newobj.value *= other return newobj __rmul__ = __mul__ def __div__(self, other): newobj = self.__class__(self) newobj.value /= other return newobjdef getLatency(value): if isinstance(value, Latency) or isinstance(value, Clock): return value.value elif isinstance(value, Frequency) or isinstance(value, RootClock): return 1 / value.value elif isinstance(value, str): try: return toLatency(value) except ValueError: try: return 1 / toFrequency(value) except ValueError: pass # fall through raise ValueError, "Invalid Frequency/Latency value '%s'" % valueclass Latency(NumericParamValue): def __init__(self, value): self.value = getLatency(value) def __getattr__(self, attr): if attr in ('latency', 'period'): return self if attr == 'frequency': return Frequency(self) raise AttributeError, "Latency object has no attribute '%s'" % attr # convert latency to ticks def ini_str(self): return str(tick_check(self.value * ticks_per_sec))class Frequency(NumericParamValue): def __init__(self, value): self.value = 1 / getLatency(value) def __getattr__(self, attr): if attr == 'frequency': return self if attr in ('latency', 'period'): return Latency(self) raise AttributeError, "Frequency object has no attribute '%s'" % attr # convert frequency to ticks per period def ini_str(self): return self.period.ini_str()# Just like Frequency, except ini_str() is absolute # of ticks per sec (Hz).# We can't inherit from Frequency because we don't want it to be directly# assignable to a regular Frequency parameter.class RootClock(ParamValue): def __init__(self, value): self.value = 1 / getLatency(value) def __getattr__(self, attr): if attr == 'frequency': return Frequency(self) if attr in ('latency', 'period'): return Latency(self) raise AttributeError, "Frequency object has no attribute '%s'" % attr def ini_str(self): return str(tick_check(self.value))# A generic frequency and/or Latency value. Value is stored as a latency,# but to avoid ambiguity this object does not support numeric ops (* or /).# An explicit conversion to a Latency or Frequency must be made first.class Clock(ParamValue): def __init__(self, value): self.value = getLatency(value) def __getattr__(self, attr): if attr == 'frequency': return Frequency(self) if attr in ('latency', 'period'): return Latency(self) raise AttributeError, "Frequency object has no attribute '%s'" % attr def ini_str(self): return self.period.ini_str()class NetworkBandwidth(float,ParamValue): def __new__(cls, value): val = toNetworkBandwidth(value) / 8.0 return super(cls, NetworkBandwidth).__new__(cls, val) def __str__(self): return str(self.val) def ini_str(self): return '%f' % (ticks_per_sec / float(self))class MemoryBandwidth(float,ParamValue): def __new__(self, value): val = toMemoryBandwidth(value) return super(cls, MemoryBandwidth).__new__(cls, val) def __str__(self): return str(self.val) def ini_str(self): return '%f' % (ticks_per_sec / float(self))## "Constants"... handy aliases for various values.## Some memory range specifications use this as a default upper bound.MaxAddr = Addr.maxMaxTick = Tick.maxAllMemory = AddrRange(0, MaxAddr)###################################################################### The final hook to generate .ini files. Called from configuration# script once config is built.def instantiate(root): global ticks_per_sec ticks_per_sec = float(root.clock.frequency) root.print_ini() noDot = True # temporary until we fix dot if not noDot: dot = pydot.Dot() instance.outputDot(dot) dot.orientation = "portrait" dot.size = "8.5,11" dot.ranksep="equally" dot.rank="samerank" dot.write("config.dot") dot.write_ps("config.ps")# __all__ defines the list of symbols that get exported when# 'from config import *' is invoked. Try to keep this reasonably# short to avoid polluting other namespaces.__all__ = ['SimObject', 'ParamContext', 'Param', 'VectorParam', 'Parent', 'Self', 'Enum', 'Bool', 'String', 'Float', 'Int', 'Unsigned', 'Int8', 'UInt8', 'Int16', 'UInt16', 'Int32', 'UInt32', 'Int64', 'UInt64', 'Counter', 'Addr', 'Tick', 'Percent', 'TcpPort', 'UdpPort', 'EthernetAddr', 'MemorySize', 'Latency', 'Frequency', 'RootClock', 'Clock', 'Ne
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -