Ejemplo n.º 1
0
    def __init__(self, m, r=None, infolength=None):
        F = np.array([[1, 0], [1, 1]]) # polar kernel matrix
        Fkron = np.ones((1, 1))
        self.m = m
        self.r = r
        # take Kronecker product m times
        for i in range(m):
            Fkron = np.kron(Fkron, F)
        assert Fkron.shape == (2**m, 2**m)
        # filter rows that have weight < 2**(m-r)
        if r is not None:
            assert r <= m
            assert infolength is None
            Fkron = Fkron[Fkron.sum(1) >= 2**(m-r)]
            name = 'RM({},{})'.format(r, m)
        else:
            weight = 2
            while Fkron.shape[0] > infolength:
                Fkron = Fkron[Fkron.sum(1) >= weight]
                weight *= 2
            cutIndices = (Fkron.sum(1) == weight)[:(Fkron.shape[0] - infolength)]
            Fkron = Fkron[[i for i in range(Fkron.shape[0]) if i not in cutIndices]]
            name = '({},{}) RM'.format(2**m, infolength)

        BinaryLinearBlockCode.__init__(self, generatorMatrix=Fkron, name=name)
Ejemplo n.º 2
0
    def __init__(self, m, r=None, infolength=None):
        F = np.array([[1, 0], [1, 1]]) # polar kernel matrix
        Fkron = np.ones((1, 1))
        self.m = m
        self.r = r
        # take Kronecker product m times
        for i in range(m):
            Fkron = np.kron(Fkron, F)
        assert Fkron.shape == (2**m, 2**m)
        # filter rows that have weight < 2**(m-r)
        if r is not None:
            assert r <= m
            assert infolength is None
            Fkron = Fkron[Fkron.sum(1) >= 2**(m-r)]
            name = 'RM({},{})'.format(r, m)
        else:
            weight = 2
            while Fkron.shape[0] > infolength:
                Fkron = Fkron[Fkron.sum(1) >= weight]
                weight *= 2
            cutIndices = (Fkron.sum(1) == weight)[:(Fkron.shape[0] - infolength)]
            Fkron = Fkron[[i for i in range(Fkron.shape[0]) if i not in cutIndices]]
            name = '({},{}) RM'.format(2**m, infolength)

        BinaryLinearBlockCode.__init__(self, generatorMatrix=Fkron, name=name)
Ejemplo n.º 3
0
 def __init__(self, q, m):
     assert m <= q
     self.q, self.m = q, m
     hmatrix = np.zeros((q * m, q * q), dtype=np.int)
     for row in range(m):
         for column in range(q):
             shift = row * column
             for i in range(q):
                 hmatrix[row*q+((shift + i) % q), column * q + i] = 1
     BinaryLinearBlockCode.__init__(self, parityCheckMatrix=hmatrix,
                                    name="({0},{1}) Array LDPC Code".format(q, m))
Ejemplo n.º 4
0
 def __init__(self, q, m):
     assert m <= q
     self.q, self.m = q, m
     hmatrix = np.zeros((q * m, q * q), dtype=np.int)
     for row in range(m):
         for column in range(q):
             shift = row * column
             for i in range(q):
                 hmatrix[row * q + ((shift + i) % q), column * q + i] = 1
     BinaryLinearBlockCode.__init__(self,
                                    parityCheckMatrix=hmatrix,
                                    name="({0},{1}) Array LDPC Code".format(
                                        q, m))
Ejemplo n.º 5
0
 def test_example(self):
     code = BinaryLinearBlockCode(
         parityCheckMatrix=testData('Alist_N155_M93.txt'))
     nb = makeNonBinary(code, 5)
     from lpdec import matrices
     print(matrices.numpyToString(nb.parityCheckMatrix))
     self.assertEquals(nb.q, 5)
Ejemplo n.º 6
0
def makeRandomCode(n, m, density, q=2, seed=1337):
    """
    Creates a random linear code over the prime field :math:`\mathbb F_q`. The code is created by randomly choosing a
    parity-check matrix.

    Args
    ----
    n : int
        Block length
    m : int
        Number of rows in the parity-check matrix. Design information length is k=n-m but can be larger if rows happen
        to be linearly dependent.
    density : float
        Probabilty of non-zero entry in the parity-check matrix.
    q : int
        Arity of the code. Defaults to 2 for binary codes.
    seed : int
        Random seed.
    """
    state = np.random.RandomState(seed)

    H = state.randint(1, q, (m, n))
    mask = state.random_sample((m, n)) >= density
    H[mask] = 0
    name = 'Random({}, {})Code[density={},q={},seed={}]'.format(
        n, n - m, density, q, seed)
    if q == 2:
        return BinaryLinearBlockCode(name=name, parityCheckMatrix=H)
    else:
        return NonbinaryLinearBlockCode(name=name, parityCheckMatrix=H, q=q)
Ejemplo n.º 7
0
 def __init__(self, r, extended=False):
     blocklength = 2 ** r - (0 if extended else 1)
     infolength = 2 ** r - r - 1
     name = '({},{}) {}Hamming Code'.format(blocklength, infolength,
                                            'Extended ' if extended else '')
     pcm = np.zeros((blocklength - infolength, blocklength), dtype=np.int)
     colIndex = 0
     for numOnes in range(1, r + 1):
         for positions in itertools.combinations(range(r), numOnes):
             column = [0] * r + ([1] if extended else [])
             for pos in positions:
                 column[pos] = 1
             pcm[:, colIndex] = column
             colIndex += 1
     if extended:
         pcm[r, blocklength - 1] = 1
     BinaryLinearBlockCode.__init__(self, name=name, parityCheckMatrix=pcm)
     self.r = r
     self.extended = extended
Ejemplo n.º 8
0
 def __init__(self, r, extended=False):
     blocklength = 2 ** r - (0 if extended else 1)
     infolength = 2 ** r - r - 1
     name = '({},{}) {}Hamming Code'.format(blocklength, infolength,
                                            'Extended ' if extended else '')
     pcm = np.zeros((blocklength - infolength, blocklength), dtype=np.int)
     colIndex = 0
     for numOnes in range(1, r + 1):
         for positions in itertools.combinations(range(r), numOnes):
             column = [0] * r + ([1] if extended else [])
             for pos in positions:
                 column[pos] = 1
             pcm[:, colIndex] = column
             colIndex += 1
     if extended:
         pcm[r, blocklength - 1] = 1
     BinaryLinearBlockCode.__init__(self, name=name, parityCheckMatrix=pcm)
     self.r = r
     self.extended = extended
Ejemplo n.º 9
0
    def __init__(self, vertices, name):
        """Create the code with TurboVertices *vertices* and a given *name*.

        *vertices* must be a list of TurboVertex instances. The attributes *blocklength*,
        *infolength* and *rate* are computed automatically from the code layout.

        After initialization, the information source vertex is stored in the *infoVertex*
        attribute, the code vertex as *codeVertex*, and all encoder vertices are put in the tuple
        *encoders*.
        """

        encoders = []
        self.infoVertex = self.codeVertex = None
        for vertex in vertices:
            if isinstance(vertex, InformationSource):
                assert self.infoVertex is None
                self.infoVertex = vertex
            elif isinstance(vertex, CodeVertex):
                assert self.codeVertex is None
                self.codeVertex = vertex
            elif isinstance(vertex, EncoderVertex):
                encoders.append(vertex)
        self.vertices = vertices[:]
        self.encoders = encoders
        self.blocklength = self.codeVertex.inSize
        self.codeVertex._inWord = np.empty(self.blocklength, dtype=np.int)
        self.infolength = self.infoVertex.infobits
        BinaryLinearBlockCode.__init__(self, name=name)
        self.stoppers = [self.infoVertex] + self.encoders + [self.codeVertex]

        for vertex in self.stoppers:
            vertex.finalize()
        for i in range(self.blocklength):
            sals = self.segmentsForCodeBit(i)
            for seg, lab in sals:
                if lab == trellis.INFO:
                    seg.info_code_bit = i
                    seg.info_code_ratio = 1/len(sals)
                else:
                    seg.parity_code_bit = i
                    seg.parity_code_ratio = 1/len(sals)
Ejemplo n.º 10
0
    def __init__(self, vertices, name):
        """Create the code with TurboVertices *vertices* and a given *name*.

        *vertices* must be a list of TurboVertex instances. The attributes *blocklength*,
        *infolength* and *rate* are computed automatically from the code layout.

        After initialization, the information source vertex is stored in the *infoVertex*
        attribute, the code vertex as *codeVertex*, and all encoder vertices are put in the tuple
        *encoders*.
        """

        encoders = []
        self.infoVertex = self.codeVertex = None
        for vertex in vertices:
            if isinstance(vertex, InformationSource):
                assert self.infoVertex is None
                self.infoVertex = vertex
            elif isinstance(vertex, CodeVertex):
                assert self.codeVertex is None
                self.codeVertex = vertex
            elif isinstance(vertex, EncoderVertex):
                encoders.append(vertex)
        self.vertices = vertices[:]
        self.encoders = encoders
        self.blocklength = self.codeVertex.inSize
        self.codeVertex._inWord = np.empty(self.blocklength, dtype=np.int)
        self.infolength = self.infoVertex.infobits
        BinaryLinearBlockCode.__init__(self, name=name)
        self.stoppers = [self.infoVertex] + self.encoders + [self.codeVertex]

        for vertex in self.stoppers:
            vertex.finalize()
        for i in range(self.blocklength):
            sals = self.segmentsForCodeBit(i)
            for seg, lab in sals:
                if lab == trellis.INFO:
                    seg.info_code_bit = i
                    seg.info_code_ratio = 1 / len(sals)
                else:
                    seg.parity_code_bit = i
                    seg.parity_code_ratio = 1 / len(sals)
Ejemplo n.º 11
0
 def __init__(self, n, frozen=None, name=None, **kwargs):
     if frozen is None:
         try:
             mu = kwargs['mu']
             SNR = kwargs['SNR']
             rate = kwargs['rate']
             SNR_is_SNRb = kwargs.get('SNR_is_SNRb', False)
         except KeyError:
             raise ValueError('Either frozen bits or all of (SNR, mu, rate) must be specified')
         chan = BMSChannel.AWGNC(SNR, 1000, rate=(rate if SNR_is_SNRb else 1))
         frozen = computeFrozenIndices(chan, n, mu, rate=rate)
         if name is None:
             name = 'PolarCode(n={}, SNR{}={}, mu={}, rate={})'.format(
                 n, 'b' if SNR_is_SNRb else '', SNR, mu, rate)
     frozen = sorted(frozen)
     if name is None:
         name = 'PolarCode(n={}, frozen={})'.format(n, repr(frozen))
     BinaryLinearBlockCode.__init__(self, name=name)
     self.n = n
     self.blocklength = 2 ** n
     self.infolength = self.blocklength - len(frozen)
     self.frozen = frozen
Ejemplo n.º 12
0
 def test_different_classes(self):
     code1 = BinaryLinearBlockCode(
         parityCheckMatrix=testData('Alist_N23_M11.txt'))
     code2 = HammingCode(3)
     for code in code1, code2:
         channel = AWGNC(0, code.rate, seed=1337)
         decoders = [
             cls(code, maxRPCrounds=0)
             for cls in (AdaptiveLPDecoder, AdaptiveLPDecoderGurobi)
         ]
         sig = channel.signalGenerator(code, wordSeed=1337)
         for i in range(1000):
             llr = next(sig)
             for decoder in decoders:
                 decoder.decode(llr)
             for decoder in decoders[1:]:
                 self.assertTrue(
                     np.allclose(decoder.solution, decoders[0].solution))
Ejemplo n.º 13
0
 def test_decoding(self):
     code1 = BinaryLinearBlockCode(
         parityCheckMatrix=testData('Alist_N23_M11.txt'))
     code2 = HammingCode(3)
     for code in code1, code2:
         channel = AWGNC(0, code.rate, seed=1337)
         decoders = [
             AdaptiveLPDecoder(code, maxRPCrounds=i) for i in [0, 3, -1]
         ]
         sig = channel.signalGenerator(code, wordSeed=1337)
         errors = {decoder: 0 for decoder in decoders}
         for i in range(100):
             llr = next(sig)
             for decoder in decoders:
                 solution = decoder.decode(llr)
                 if not np.allclose(solution, sig.codeword):
                     errors[decoder] += 1
         for i in range(len(decoders) - 1):
             self.assertGreaterEqual(errors[decoders[i]],
                                     errors[decoders[i + 1]])
Ejemplo n.º 14
0
 def test_Persistence(self):
     for code in self.codes:
         deserialized = BinaryLinearBlockCode.fromJSON(code.toJSON())
         self.assertEqual(code, deserialized)
         deserialized.parityCheckMatrix[0, 0] = 1 - deserialized.parityCheckMatrix[0, 0]
         self.assertNotEqual(code, deserialized)
Ejemplo n.º 15
0
 def setUp(self):
     self.smallCode = BinaryLinearBlockCode(parityCheckMatrix=testData('Alist_N8_M4.txt'))
     self.tannerCode = BinaryLinearBlockCode(parityCheckMatrix=testData('Alist_N155_M93.txt'))
     self.codes = (self.smallCode, self.tannerCode)
Ejemplo n.º 16
0
 def setUp(self):
     self.code = BinaryLinearBlockCode(
         parityCheckMatrix=testData('Alist_N23_M11.txt'))
Ejemplo n.º 17
0
 def setUp(self):
     self.code = BinaryLinearBlockCode(
         parityCheckMatrix=testData('BCH_127_85_6_strip.alist'))
Ejemplo n.º 18
0
 def codes(self):
     yield BinaryLinearBlockCode(
         parityCheckMatrix=testData('Alist_N23_M11.txt')), 7
     yield BinaryLinearBlockCode(
         parityCheckMatrix=testData('Alist_N155_M93.txt')), 20
     yield HammingCode(4), 3