atomic_propositions_base.py 1.58 KB
Newer Older
Aravind Bk's avatar
Aravind Bk committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
class Bits(object):
    """A bit-control class that allows us bit-wise manipulation as shown in the
    example::

        bits = Bits()
        bits[0] = False
        bits[2] = bits[0]
    """

    def __init__(self, value=0):
        self._d = value

    def __getitem__(self, index):
        return (self._d >> index) & 1

    def __setitem__(self, index, value):
        value = (value & 1) << index
        mask = 1 << index
        self._d = (self._d & ~mask) | value

    def __getslice__(self, start, end):
        mask = 2**(end - start) - 1
        return (self._d >> start) & mask

    def __setslice__(self, start, end, value):
        mask = 2**(end - start) - 1
        value = (value & mask) << start
        mask = mask << start
        self._d = (self._d & ~mask) | value
        return (self._d >> start) & mask

    def __int__(self):
        return self._d


class AtomicPropositionsBase(Bits):
    """An AP-control base class for AP-wise manipulation.
       the dictionary APdict and its length APdict_len has
       to be given in the subclass
    """

    APdict = None

    def __init__(self):
        Bits.__init__(self)
        self.APdict_len = 0 if self.APdict is None else len(self.APdict)

    def __setitem__(self, index, value):
        if index in self.APdict:
            index = self.APdict[index]
        assert 0 <= index <= self.APdict_len
        Bits.__setitem__(self, index, value)

    def __getitem__(self, index):
        if index in self.APdict:
            index = self.APdict[index]
        assert 0 <= index <= self.APdict_len
        return Bits.__getitem__(self, index)