Skip to content

Code

rpps.code

Code transform: channel bits <-> data bits

FEC encoders and decoders, interleaving, rate matching, scrambling (code.scram), line codes (Line: NRZI, Manchester, inversion), sync markers among channel bits (Marker), and Uncoded for links with no FEC. Each step takes either channel or data bits, because a code transform is often several steps.

Modules:

Name Description
alist

LDPC parity-check matrices in MacKay's alist format (what GNU Radio's gr-fec and most LDPC tools read and write)

coding

Coding parent classes

factory

Codes from their parameters, without a definition file: rp.code.Hamming(7, 4), rp.code.RS(255, 223)...

kernels

Batch kernels of the code operators: BlockDecode of a block code or interleaver, XorMask of an additive scrambler

line

Line codes: bits <-> bits, one step of the code transform, by name

marker

A sync marker among channel bits: a known word before each block of length bits (CCSDS ASM before each frame)

serial

Code definitions, two resources: config/fec///.json (rp.code.load("block/rs/204_188")) and

uncoded

alist

LDPC parity-check matrices in MacKay's alist format (what GNU Radio's gr-fec and most LDPC tools read and write)

rp.code.import_alist("code.alist") the definition, as a dict (rp.code.init("mine", d) builds it) rp.code.import_alist("code.alist", "mine", dest="my_config") writes my_config/fec/block/ldpc/mine.json, add_config_path("my_config")

Functions:

Name Description
read_alist

(n, checks): code length and, for each parity check, the bit positions (0-based) it covers

import_alist

Definition of the LDPC code in an alist file. fields: more keys for it (comment, k + systematic, iters...).

read_alist

read_alist(path)

(n, checks): code length and, for each parity check, the bit positions (0-based) it covers

Source code in src/rpps/code/alist.py
def read_alist(path):
    """(n, checks): code length and, for each parity check, the bit positions (0-based) it covers"""
    lines = [ln.split() for ln in Path(path).read_text().splitlines() if ln.strip()]
    n, m = int(lines[0][0]), int(lines[0][1])
    if len(lines) < 4 + n + m:
        raise ValueError(f"{path}: an alist for {n} bits and {m} checks has {4 + n + m} lines, found {len(lines)}")
    cols = [[int(x) - 1 for x in ln if int(x) > 0] for ln in lines[4:4 + n]] # Zeros pad the rows to the longest
    rows = [[int(x) - 1 for x in ln if int(x) > 0] for ln in lines[4 + n:4 + n + m]]
    from_cols = [[] for _ in range(m)]
    for j, c in enumerate(cols):
        for i in c:
            from_cols[i].append(j)
    if [sorted(r) for r in rows] != from_cols:
        raise ValueError(f"{path}: the row lines and the column lines describe different matrices")
    return n, rows

import_alist

import_alist(path, name=None, dest=None, **fields)

Definition of the LDPC code in an alist file. fields: more keys for it (comment, k + systematic, iters...).

Without k, the message positions come from GF(2) elimination of H, which only suits small codes: give k and systematic ("head": message first, "tail", or a list of positions) for big ones. name: also write it as config/fec/block/ldpc/.json, under dest (default: the first added config path, else the shipped config); an existing file is not replaced. Returns the file

Source code in src/rpps/code/alist.py
def import_alist(path, name=None, dest=None, **fields):
    """Definition of the LDPC code in an alist file. fields: more keys for it (`comment`, `k` + `systematic`, `iters`...).

    Without `k`, the message positions come from GF(2) elimination of H, which only suits small codes: give `k` and `systematic`
    ("head": message first, "tail", or a list of positions) for big ones.
    name: also write it as config/fec/block/ldpc/<name>.json, under `dest` (default: the first added config path, else the shipped config);
    an existing file is not replaced. Returns the file"""
    n, checks = read_alist(path)
    obj = {"base": "block", "type": "ldpc", "comment": f"LDPC code from {Path(path).name}", **fields, "n": n, "checks": checks}
    if name is None:
        return obj
    return _config.save("fec", "block", f"ldpc/{name}", obj, dest)

coding

Coding parent classes

Classes:

Name Description
Decision

Coding decision type: does the decoder get hard bits or LLRs

Coding

Coding parent class

Block
Convolutional

Parent convolutional coding: separate encoder ("encode") and decoder ("decode") implementations

Interleaver

Functions:

Name Description
puncture_period

Channel bits in one period of a convolutional code's puncture pattern (n, the outputs per step, when unpunctured):

mismatch

Decode hard channel bits, encode the decision again and compare: (bits that differ, bits compared). At the right

mismatch_batch

mismatch() of each row of hard (W, L), decoded together (decode_batch where the decoder has it): (differing

cached

A definition loaded once per process and shared (a DVB-S2 LDPC code takes a moment to build): what control

Decision

Bases: Enum

Coding decision type: does the decoder get hard bits or LLRs

Coding

Coding(e_impl, d_impl)

Bases: Pipe

Coding parent class

Methods:

Name Description
encode

Encode data using specified coding

decode

Decode data using specified coding

control

Become another definition of the same kind (name: "ldpc/dvbs2_64800_3_5"), or nothing at all (None: the

pos_rate

Output bits per input bit (rpps.profile positions)

load

Load coding from json

Attributes:

Name Type Description
decision

SOFT when the decoder can use LLRs (the default for those that can), HARD otherwise. Assign to override

e_num

Return number of encoding data bits

e_den

Return number of total encoded bits

d_num

Return number of decoding data bits

d_den

Return number of total decoded bits

e_rate

Return encoding bits/parity rate

d_rate

Return decoding bits/parity rate

Source code in src/rpps/code/coding.py
def __init__(self, e_impl, d_impl):
    self.log = Logger().Child("Coding", _config.LOG_CODING).Child(type(self).__name__, _config.LOG_CODING)
    self.encoder = e_impl
    self.decoder = d_impl
decision property writable
decision

SOFT when the decoder can use LLRs (the default for those that can), HARD otherwise. Assign to override

e_num property
e_num

Return number of encoding data bits

e_den property
e_den

Return number of total encoded bits

d_num property
d_num

Return number of decoding data bits

d_den property
d_den

Return number of total decoded bits

e_rate property
e_rate

Return encoding bits/parity rate

d_rate property
d_rate

Return decoding bits/parity rate

encode
encode(data)

Encode data using specified coding

Source code in src/rpps/code/coding.py
def encode(self, data):
    """Encode data using specified coding"""
    return self._run(data, True)
decode
decode(data)

Decode data using specified coding

A soft decoder takes the LLRs a demodulator produced; anything else (or data that isn't soft) gets hard bits.

Source code in src/rpps/code/coding.py
def decode(self, data):
    """Decode data using specified coding

    A soft decoder takes the LLRs a demodulator produced; anything else (or data that isn't soft) gets hard bits.
    """
    return self._run(data, False)
control
control(name)

Become another definition of the same kind (name: "ldpc/dvbs2_64800_3_5"), or nothing at all (None: the bits pass as they are, an interleaver a modulation does not use). Applied between codewords, it keeps nothing of the old code; a profile applies it where a header says the new code starts

Source code in src/rpps/code/coding.py
def control(self, name):
    """Become another definition of the same kind (`name`: "ldpc/dvbs2_64800_3_5"), or nothing at all (None: the
    bits pass as they are, an interleaver a modulation does not use). Applied between codewords, it keeps nothing
    of the old code; a profile applies it where a header says the new code starts"""
    if name is None:
        self.encoder = self.decoder = None
    else:
        new = cached(f"{self.folder or type(self).__name__.lower()}/{name}")
        self.encoder, self.decoder = new.encoder, new.decoder
    self.name = name or "none"
    self._restart = True # A frame starts here: a codeword never spans two
pos_rate
pos_rate(decode)

Output bits per input bit (rpps.profile positions)

Source code in src/rpps/code/coding.py
def pos_rate(self, decode):
    """Output bits per input bit (rpps.profile positions)"""
    if self.encoder is None:
        return 1.0
    coder = self.decoder if decode else self.encoder
    return coder.num/coder.den if decode else coder.den/coder.num
load abstractmethod staticmethod
load(name: str, obj: dict)

Load coding from json

Source code in src/rpps/code/coding.py
@staticmethod
@abstractmethod
def load(name: str, obj: dict):
    """Load coding from json"""

Block

Block(e_impl, d_impl)

Bases: Coding

Methods:

Name Description
load

decoder: a registered decoder type to use instead of the code's own (it's built from the encoder),

Attributes:

Name Type Description
SCOPE

Parent block coding

Source code in src/rpps/code/coding.py
def __init__(self, e_impl, d_impl):
    self.log = Logger().Child("Coding", _config.LOG_CODING).Child(type(self).__name__, _config.LOG_CODING)
    self.encoder = e_impl
    self.decoder = d_impl
SCOPE class-attribute instance-attribute
SCOPE = FRAME

Parent block coding

load staticmethod
load(name, obj, decoder=None)

decoder: a registered decoder type to use instead of the code's own (it's built from the encoder), or "name"/"decoder" in the definition. Linear codes decode on their syndrome trellis unless that is too big

Source code in src/rpps/code/coding.py
@staticmethod
def load(name, obj, decoder=None):
    """decoder: a registered decoder type to use instead of the code's own (it's built from the encoder),
    or "name"/"decoder" in the definition. Linear codes decode on their syndrome trellis unless that is too big"""
    from .types.layout import arranged
    log = Logger().Child("Coding", _config.LOG_CODING).Child(name)
    enc = _code_of(obj).from_config(log, obj)
    core = enc.inner if isinstance(enc, arranged) else enc # (an expr code that is linear: its own arrangement)
    want = decoder or obj.get("decoder")
    default = DEFAULT_DECODER.get(obj["type"], DEFAULT_DECODER.get(type(core).__name__))
    dec = core
    if want is None and default is not None:
        try:
            dec = _code_of({"type": default}).from_encoder(log, core)
        except ValueError: # Too many trellis states: the encoder's own (hard) decoder it is
            pass
    elif want is not None and want != obj["type"]:
        dec = _decoder_for(want, core, log, name)
    if isinstance(enc, arranged):
        dec = enc.with_decoder(dec)
    # Where the bits go as sent (rpps.code.types.layout), for any block code
    layout, xor, append = obj.get("layout"), obj.get("xor"), obj.get("append")
    extend = bool(obj.get("extend")) and not getattr(core, "extends", False) # (matrix codes build it in)
    if layout is not None or xor is not None or extend or append:
        keys = dict(layout=layout, xor=xor, extend=extend, append=append)
        enc, dec = arranged(log, enc, **keys), arranged(log, enc, dec=dec, **keys)
    out = _impl(Block, name)(enc, dec)
    out.folder = "block"
    return out

Convolutional

Convolutional(e_impl, d_impl)

Bases: Coding

Parent convolutional coding: separate encoder ("encode") and decoder ("decode") implementations

Methods:

Name Description
load

{"base": "conv", "constraint": K, "generator": [...], "puncture": [...], "decoder": "viterbi"}: one set of keys

Source code in src/rpps/code/coding.py
def __init__(self, e_impl, d_impl):
    self.log = Logger().Child("Coding", _config.LOG_CODING).Child(type(self).__name__, _config.LOG_CODING)
    self.encoder = e_impl
    self.decoder = d_impl
load staticmethod
load(name, obj, decoder=None)

{"base": "conv", "constraint": K, "generator": [...], "puncture": [...], "decoder": "viterbi"}: one set of keys builds the encoder and its decoder. decoder: use this decoder type (viterbi, bcjr) instead of the definition's

Source code in src/rpps/code/coding.py
@staticmethod
def load(name, obj, decoder=None):
    """{"base": "conv", "constraint": K, "generator": [...], "puncture": [...], "decoder": "viterbi"}: one set of keys
    builds the encoder and its decoder. decoder: use this decoder type (viterbi, bcjr) instead of the definition's"""
    log = Logger().Child("Coding", _config.LOG_CODING).Child(name)
    if "encode" in obj or "decode" in obj:
        raise ConfigError(f"{name}: a convolutional code is one set of keys (constraint, generator, puncture, decoder), "
                          "not separate encode / decode blocks")
    if "generator" not in obj:
        raise ConfigError(f"{name}: a convolutional code needs 'generator' (and 'constraint')")
    keys = {k: v for k, v in obj.items() if k not in ("base", "type", "comment", "ref", "tags", "params", "decoder")}
    keys.setdefault("num", 1)
    keys.setdefault("den", len(obj["generator"]))
    e = {**keys, "type": "conv"}
    d = {**keys, "type": decoder or obj.get("decoder", "viterbi")}
    return _impl(Convolutional, name)(_code_of(e).from_config(log, e), _code_of(d).from_config(log, d))

Interleaver

Interleaver(e_impl, d_impl)

Bases: Coding

Attributes:

Name Type Description
kernel

Interleaver: Forney (convolutional: I branches, M symbols of delay increment, state carried along the stream)

Source code in src/rpps/code/coding.py
def __init__(self, e_impl, d_impl):
    self.log = Logger().Child("Coding", _config.LOG_CODING).Child(type(self).__name__, _config.LOG_CODING)
    self.encoder = e_impl
    self.decoder = d_impl
kernel class-attribute instance-attribute
kernel = _block_kernel

Interleaver: Forney (convolutional: I branches, M symbols of delay increment, state carried along the stream) or block (a permutation of each block)

puncture_period

puncture_period(code)

Channel bits in one period of a convolutional code's puncture pattern (n, the outputs per step, when unpunctured): the alignments a decoder can start at. code: anything with an encoder (a loaded Coding)

Source code in src/rpps/code/coding.py
def puncture_period(code):
    """Channel bits in one period of a convolutional code's puncture pattern (n, the outputs per step, when unpunctured):
    the alignments a decoder can start at. `code`: anything with an `encoder` (a loaded Coding)"""
    p = getattr(code.encoder, "puncture", None)
    return int(p.sum()) if p is not None else int(code.encoder.den)

mismatch

mismatch(code, hard)

Decode hard channel bits, encode the decision again and compare: (bits that differ, bits compared). At the right code and alignment only channel errors differ; a wrong one differs about as often as random bits

Source code in src/rpps/code/coding.py
def mismatch(code, hard):
    """Decode hard channel bits, encode the decision again and compare: (bits that differ, bits compared). At the right
    code and alignment only channel errors differ; a wrong one differs about as often as random bits"""
    hard = np.asarray(hard)
    e = code.encoder.encode(code.decoder.decode(hard.astype(np.uint8)).astype(bool))
    n = min(len(e), len(hard))
    return int(np.count_nonzero(e[:n] != hard[:n].astype(bool))), n

mismatch_batch

mismatch_batch(code, hard)

mismatch() of each row of hard (W, L), decoded together (decode_batch where the decoder has it): (differing bits (W,), bits compared)

Source code in src/rpps/code/coding.py
def mismatch_batch(code, hard):
    """mismatch() of each row of hard (W, L), decoded together (decode_batch where the decoder has it): (differing
    bits (W,), bits compared)"""
    hard = np.asarray(hard).astype(np.uint8)
    dec = code.decoder
    u = dec.decode_batch(hard) if hasattr(dec, "decode_batch") else np.array([dec.decode(h) for h in hard])
    enc = code.encoder
    e = enc.encode_batch(u) if hasattr(enc, "encode_batch") else np.array([enc.encode(np.asarray(x).astype(bool)) for x in u])
    n = min(e.shape[1], hard.shape[1])
    return np.count_nonzero(e[:, :n] != hard[:, :n].astype(bool), axis=1).astype(np.int64), n

cached cached

cached(ref)

A definition loaded once per process and shared (a DVB-S2 LDPC code takes a moment to build): what control swaps in, and what the blind tools try: rp.code.cached("conv/k7_171_133/3_4")

Source code in src/rpps/code/coding.py
@functools.lru_cache(maxsize=None)
def cached(ref):
    """A definition loaded once per process and shared (a DVB-S2 LDPC code takes a moment to build): what `control`
    swaps in, and what the blind tools try: `rp.code.cached("conv/k7_171_133/3_4")`"""
    from .serial import load
    return load(ref)

factory

Codes from their parameters, without a definition file: rp.code.Hamming(7, 4), rp.code.RS(255, 223)...

Each returns the same object rp.code.load makes from a definition, so they work the same in a pipeline: link = scr * rp.code.Hamming(7, 4) * rp.symbol.QAM(16)

Functions:

Name Description
Hamming

Hamming code: n = 2r - 1, k = n - r. A shorter k (n a bit smaller than 2r - 1) gives a shortened code

Repetition

Each bit sent count times, decoded by majority (or by summing LLRs)

RS

Reed-Solomon over GF(2m). n < 2m - 1 is a shortened code. poly: the field's primitive polynomial (default for m=8: 285)

Cyclic

Binary cyclic code from its generator polynomial (bit i = coefficient of x^i), message first

Golay

Golay (23,12) or extended Golay (24,12), g(x) = 0xC75

Conv

Rate 1/n convolutional code. generators: n taps lists (or octal/decimal ints) over the constraint length

Hamming

Hamming(n=7, k=4, decoder=None)

Hamming code: n = 2r - 1, k = n - r. A shorter k (n a bit smaller than 2r - 1) gives a shortened code

Source code in src/rpps/code/factory.py
def Hamming(n=7, k=4, decoder=None):
    """Hamming code: n = 2**r - 1, k = n - r. A shorter k (n a bit smaller than 2**r - 1) gives a shortened code"""
    r = n - k
    if r < 2 or n > 2**r - 1 or n < k + r:
        raise ValueError(f"Hamming({n}, {k}) isn't a Hamming code or a shortened one: need n <= 2**(n-k) - 1")
    cols = [v for v in range(1, 2**r) if bin(v).count("1") >= 2][:k] # Parity checks of the data bits: not a unit vector
    p = [[(v >> (r - 1 - b)) & 1 for b in range(r)] for v in cols]
    return _make(f"hamming{n}_{k}", {"type": "linear", "n": n, "k": k, "p": p}, decoder)

Repetition

Repetition(count=3, decoder=None)

Each bit sent count times, decoded by majority (or by summing LLRs)

Source code in src/rpps/code/factory.py
def Repetition(count=3, decoder=None):
    """Each bit sent `count` times, decoded by majority (or by summing LLRs)"""
    return _make(f"repeat{count}", {"type": "repeat", "count": count}, decoder)

RS

RS(n=255, k=223, m=8, poly=None, fcr=0, prim=1, puncture=None, decoder=None)

Reed-Solomon over GF(2m). n < 2m - 1 is a shortened code. poly: the field's primitive polynomial (default for m=8: 285) puncture: codeword positions not sent (negative from the end), decoded as erasures

Source code in src/rpps/code/factory.py
def RS(n=255, k=223, m=8, poly=None, fcr=0, prim=1, puncture=None, decoder=None):
    """Reed-Solomon over GF(2**m). n < 2**m - 1 is a shortened code. poly: the field's primitive polynomial (default for m=8: 285)
    puncture: codeword positions not sent (negative from the end), decoded as erasures"""
    poly = {3: 11, 4: 19, 5: 37, 6: 67, 7: 137, 8: 285, 9: 529, 10: 1033}[m] if poly is None else poly
    obj = {"type": "rs", "n": n, "k": k, "m": m, "poly": poly, "fcr": fcr, "prim": prim}
    if puncture:
        obj["puncture"] = list(puncture)
    return _make(f"rs{n}_{k}", obj, decoder)

Cyclic

Cyclic(n, k, poly, extend=False, shorten=0, t=None, decoder=None)

Binary cyclic code from its generator polynomial (bit i = coefficient of x^i), message first

Cyclic(23, 12, 0xC75)                 Golay
Cyclic(23, 12, 0xC75, extend=True)    extended Golay (24,12)
Cyclic(15, 11, 0b10011)               cyclic Hamming

Decoded by syndrome table up to t errors (default: from the minimum distance); decoder="trellis" for soft MAP

Source code in src/rpps/code/factory.py
def Cyclic(n, k, poly, extend=False, shorten=0, t=None, decoder=None):
    """Binary cyclic code from its generator polynomial (bit i = coefficient of x^i), message first

        Cyclic(23, 12, 0xC75)                 Golay
        Cyclic(23, 12, 0xC75, extend=True)    extended Golay (24,12)
        Cyclic(15, 11, 0b10011)               cyclic Hamming
    Decoded by syndrome table up to t errors (default: from the minimum distance); decoder="trellis" for soft MAP
    """
    obj = {"type": "cyclic", "n": n, "k": k, "poly": poly, "extend": extend, "shorten": shorten}
    if t is not None:
        obj["t"] = t
    k_out, n_out = k - shorten, n + int(extend) - shorten
    return _make(f"cyclic{n_out}_{k_out}", obj, decoder)

Golay

Golay(n=23, decoder=None)

Golay (23,12) or extended Golay (24,12), g(x) = 0xC75

Source code in src/rpps/code/factory.py
def Golay(n=23, decoder=None):
    """Golay (23,12) or extended Golay (24,12), g(x) = 0xC75"""
    if n not in (23, 24):
        raise ValueError(f"Golay({n}): 23 or 24")
    return _make(f"golay{n}_12", {"type": "cyclic", "n": 23, "k": 12, "poly": 0xC75, "extend": n == 24}, decoder)

Conv

Conv(generators, constraint=None, puncture=None, decoder='viterbi', termination='truncated')

Rate 1/n convolutional code. generators: n taps lists (or octal/decimal ints) over the constraint length

Conv([0o133, 0o171], 7)                          K=7 rate 1/2 (the IESS-308 generators)
Conv([[1,0,1],[1,1,1]], puncture=[[1,1,0],[1,0,1]])

puncture: pattern with one row per output and 1 where a bit is sent decoder: "viterbi" or "bcjr" termination: "truncated" (default), "zero" (flushed with K-1 zeros) or "tailbiting"

Source code in src/rpps/code/factory.py
def Conv(generators, constraint=None, puncture=None, decoder="viterbi", termination="truncated"):
    """Rate 1/n convolutional code. generators: n taps lists (or octal/decimal ints) over the constraint length

        Conv([0o133, 0o171], 7)                          K=7 rate 1/2 (the IESS-308 generators)
        Conv([[1,0,1],[1,1,1]], puncture=[[1,1,0],[1,0,1]])
    puncture: pattern with one row per output and 1 where a bit is sent
    decoder: "viterbi" or "bcjr"
    termination: "truncated" (default), "zero" (flushed with K-1 zeros) or "tailbiting"
    """
    if all(isinstance(g, (int, np.integer)) for g in generators):
        if constraint is None:
            raise ValueError("constraint is needed when generators are numbers")
        generators = [[(g >> (constraint - 1 - i)) & 1 for i in range(constraint)] for g in generators]
    generators = [list(map(int, g)) for g in generators]
    constraint = len(generators[0])
    obj = {"base": "conv", "constraint": constraint, "generator": generators,
           "termination": termination, "decoder": decoder}
    if puncture is not None:
        obj["puncture"] = [list(map(int, row)) for row in puncture]
    return serial.init(f"conv{len(generators)}_{constraint}", obj)

kernels

Batch kernels of the code operators: BlockDecode of a block code or interleaver, XorMask of an additive scrambler

Checked row for row against the operator run frame by frame (tests/unit/parallel/test_batch_kernels.py); they use only what numpy and cupy share, so xp can be either (rpps.parallel)

Classes:

Name Description
BlockDecode

A decoder or deinterleaver of whole blocks, over a batch: the frames' blocks go through the coder in one call (a block code's

XorMask

Bits XOR a fixed mask repeated from the start of each frame (a scrambler restarted every len(mask) bits). LLRs

LdpcDecode

BlockDecode of a layered min-sum LDPC code that decodes on the device it is given: the batch's codewords in one

Identity

A code or interleaver that a frame's parameters switch off (control(name=None)): the items pass as they are, now

Permute

BlockDecode of a block interleaver that is a permutation: every block of a row gathered by one index, on whichever

BchDecode

BlockDecode of a binary BCH code (bchgf) that finds the errors on the device it is given: every codeword's

Functions:

Name Description
permutation_of

The index a block deinterleaver gathers with (decoding positions 0 .. block-1), or None when it is not a pure

BlockDecode

BlockDecode(coder, block, soft, category, rep, name='block')

Bases: Kernel

A decoder or deinterleaver of whole blocks, over a batch: the frames' blocks go through the coder in one call (a block code's decoder already runs its codewords on several threads, so a batch is more of them at once, not more calls). Each block is independent of the others, so a row comes out as it would alone. A frame is whole blocks; items past the last block are dropped and reported, as the operator does at the end of a flushed stream.

coder: what the operator decodes with (decode(bits or LLRs) -> bits or LLRs, any number of blocks); block: items a block takes in; soft: it takes LLRs when it is given them

Source code in src/rpps/code/kernels.py
def __init__(self, coder, block, soft, category, rep, name="block"):
    self.coder, self.block, self.soft, self.category, self.rep = coder, int(block), bool(soft), category, rep
    self.name = f"decode:{name}"

XorMask

XorMask(mask, category, rep, name='xor')

Bases: Kernel

Bits XOR a fixed mask repeated from the start of each frame (a scrambler restarted every len(mask) bits). LLRs stay LLRs, their signs flipped (as the additive scrambler descrambles them)

Source code in src/rpps/code/kernels.py
def __init__(self, mask, category, rep, name="xor"):
    self.mask, self.category, self.rep = np.asarray(mask, dtype=bool), category, rep
    self.name = f"xor:{name}"

LdpcDecode

LdpcDecode(coder, block, soft, category, rep, name='block')

Bases: BlockDecode

BlockDecode of a layered min-sum LDPC code that decodes on the device it is given: the batch's codewords in one run of launches, the graph uploaded once. On numpy (and on an array module without kernels of its own) it is BlockDecode, the host decoder: the oracle. Sum-product (check at the effort level) decodes on the host

Source code in src/rpps/code/kernels.py
def __init__(self, coder, block, soft, category, rep, name="block"):
    super().__init__(coder, block, soft, category, rep, name)
    self.name = f"decode:{name}@device"

Identity

Identity(category, name='none')

Bases: Kernel

A code or interleaver that a frame's parameters switch off (control(name=None)): the items pass as they are, now the code's category, as the operator gives them

Source code in src/rpps/code/kernels.py
def __init__(self, category, name="none"):
    self.category = category
    self.name = f"pass:{name}"

Permute

Permute(perm, coder, block, soft, category, rep, name='block')

Bases: BlockDecode

BlockDecode of a block interleaver that is a permutation: every block of a row gathered by one index, on whichever xp it is given (the index goes to a device once). perm: what the deinterleaver gives for the input positions 0 .. block-1

Source code in src/rpps/code/kernels.py
def __init__(self, perm, coder, block, soft, category, rep, name="block"):
    super().__init__(coder, block, soft, category, rep, name)
    self.perm = np.asarray(perm, dtype=np.int64)
    self.name = f"permute:{name}"

BchDecode

BchDecode(coder, block, soft, category, rep, name='block')

Bases: BlockDecode

BlockDecode of a binary BCH code (bchgf) that finds the errors on the device it is given: every codeword's syndromes in one launch; only the words that have errors (few, after an LDPC code) come to the host to be located (Berlekamp-Massey and Chien, as the host decoder), and their bits are flipped on the device. On numpy, and on an array module without kernels of its own, it is BlockDecode

Source code in src/rpps/code/kernels.py
def __init__(self, coder, block, soft, category, rep, name="block"):
    super().__init__(coder, block, soft, category, rep, name)
    self.name = f"decode:{name}@device"

permutation_of

permutation_of(coder, block)

The index a block deinterleaver gathers with (decoding positions 0 .. block-1), or None when it is not a pure permutation (it changes values, or loses some)

Source code in src/rpps/code/kernels.py
def permutation_of(coder, block):
    """The index a block deinterleaver gathers with (decoding positions 0 .. block-1), or None when it is not a pure
    permutation (it changes values, or loses some)"""
    try:
        y = np.asarray(coder.decode(np.arange(block, dtype=np.float64)))
    except Exception: # (a decoder that takes only bits)
        return None
    if y.shape != (block,) or not np.array_equal(np.sort(y), np.arange(block)):
        return None
    return y.astype(np.int64)

line

Line codes: bits <-> bits, one step of the code transform, by name

bits * rp.code.Line("nrzi")              # AX.25: a 0 is a transition, a 1 no change
bits * rp.code.Line("nrzm")              # differential bits: a 1 is a transition
bits * rp.code.Line("manchester")        # 0 -> 10, 1 -> 01 (IEEE 802.3); "thomas": 0 -> 01, 1 -> 10
bits * rp.code.Line("invert")            # every bit inverted (data inversion)
bits * rp.code.Line("biphase_m")         # IRIG-106 Bi-phi-M: a transition at every bit start, and mid-bit for a 1
bits * rp.code.Line("biphase_s")         # Bi-phi-S: the same, mid-bit for a 0
bits * rp.code.Line("miller")            # delay modulation (DM-M): mid-bit for a 1, at the boundary between two 0s

Bi-phase-M/S and Miller are 2 channel bits a data bit and decode from the two halves alone (a mid-bit transition or not), so they need no reference level and ignore an inverted signal.

Decoding keeps soft values soft: an inversion negates LLRs, a differential code takes the box-plus of neighbours (sign times the smaller magnitude), Manchester the difference of the two halves. In a profile: {"code": "line", "name": "nrzi"}. Manchester as a pulse (first half +1, second -1, at the sample level) is rp.signal.filters.ShapingBiphase instead (rpps.base, Grey areas): this is the bit-level form, 2 channel bits per data bit.

Classes:

Name Description
Line

Line

Line(name='nrzi')

Bases: Pipe

Source code in src/rpps/code/line.py
def __init__(self, name="nrzi"):
    if name not in NAMES:
        raise ValueError(f"line code is one of {NAMES}, not {name!r}")
    self.name = name
    self.pairs = name in ("manchester", "thomas") or name in MID

marker

A sync marker among channel bits: a known word before each block of length bits (CCSDS ASM before each frame)

coded = frames * rp.code.Marker(0x1ACFFC1D, 32, length=8160)     # transmit: the word, then 8160 bits, again...
frames = aligned / rp.code.Marker(0x1ACFFC1D, 32, length=8160)   # receive: the word stripped, mismatches counted

Attaching the marker is a code transform (known structure among channel bits); finding it in an unaligned stream is sync: rp.sync.Delimiter(word, bits, length=..., keep=True) gives each frame from its word on, aligned, which this then strips. In a profile: {"sync": "delimit", "word": "0x1ACFFC1D", "bits": 32, "length": 8160, "keep": true} then {"code": "marker", "word": "0x1ACFFC1D", "bits": 32, "length": 8160}; or both name a sequence of type "word". Without length the frames are whatever a profile's control delimits (frame, from a header on transmit, a delimiter on receive): the word goes before each, and is stripped from the start of each (Mode S: a preamble before frames of 56 or 112 bits). Soft values pass through; the decoded data's errors holds the word's mismatched bits per frame stripped.

serial

Code definitions, two resources: config/fec///.json (rp.code.load("block/rs/204_188")) and config/interleave//.json (rp.code.load("interleave/forney/12_17"))

Folders are kind (base), then the structure of the code; the standard goes in ref/comment. Names are parameters.

block       {"base": "block", "type": ..., "decoder": optional type to decode with instead}
              any block code also takes, as sent (rpps.code.types.layout): "append": check bits after the codeword,
              each the XOR of the codeword bits listed ([[14, 15]]); "extend": an overall parity bit; "layout": the
              sent position of each codeword bit, or {"message": [...], "parity": [...] | "rest"}; "xor": a pattern on
              the sent word (inverted parity, a coset)
  linear      "n", "k" and "p": parity block rows (one per message bit)    or    "parity": one list per parity bit of the
              message bits it XORs, as standards write P0 = I0 + I1 + I3    or    "g": generator rows, "h": check
              rows; "extend" (decoded on its syndrome "trellis" when small)
  expr        "k", "bits": an expression per codeword bit over m0.. (and c0.., the bits before), ^ & | ~: loaded as a
              linear code (in its arrangement) when affine, else decoded from its 2^k codebook (k <= 16), "t"
  cyclic      "n", "k", "poly": generator polynomial as a number, bit i = x^i (polynomial order: "0xb" is x^3 + x + 1;
              a convolutional or turbo generator is the other way round, its first or most significant bit the
              current input), "extend": overall parity bit, "shorten": leading
              message bits dropped, "t": errors to correct (default from d_min); decoded by "syndrome" table
  repeat      "count": 3
  fsm         trellis code as a state machine: "k", "n", "next", "output" tables, "start", "end", "tail",
              "symbols": {"bits", "levels"} to decode amplitudes (P25 trellis, ATSC 8VSB) or {"bits", "points"}: [re, im]
              pairs to decode constellation symbols (trellis-coded modulation)
  turbo       LTE turbo code: "length", "g0", "g1", "constraint", "qpp" or "qpp_table", "iters", "scale"; or multiplexed
              bit time by bit time (CCSDS): "g0", "forward": {"1": g1, ...}, "interleave" (a definition), "outputs"
  polar       "n", "k", "frozen": [...] or "order": "pw" | "bhattacharyya" (+ "design_db"), "list": paths (1: SC),
              "crc": a CRC definition for CRC-aided list decoding
  rm          Reed-Muller RM("r", "m")
  ratematch   LTE rate matching: "mode": "conv" | "turbo", "length" (bits per stream), "out" (E), "rv", "ncb"
  product     block product code: "rows", "cols" (block definitions), "reserved", "lead", "iters" (DMR BPTC);
              "chase": p decodes it soft as a turbo product code (Chase-Pyndiah)
  rs          "n", "k", "m": 8, "poly": field polynomial, "fcr": 0, "prim": 1, "puncture": codeword positions not
              sent (negative from the end; decoded as erasures), "basis": "dual" + "beta" (CCSDS: 117)
Every block decoder leaves `errors` per codeword after a decode: bits (RS: symbols) corrected, -1 for a failure.
  bch         "n", "k", "t", "m": 16, "poly": "0x1002D"
  ldpc        "n" and the checks as "checks" (positions per check), "h" (dense rows), "table" + "k" + "group" (DVB-S2 address
              table), "shifts" + "z" (quasi-cyclic: a matrix of shifts of the z x z identity, -1 a zero block: 802.11n, 802.16e)
              or "gallager": {...}; optional "k" + "systematic": "head" | "tail" | [positions], "iters": 50, "alpha": 0.8,
              "schedule": "layered" | "flooding"
conv        {"base": "conv", "constraint": K, "generator": den rows of K bits, "puncture": den rows, "decoder": "viterbi"}
              one set of keys for the encoder and its decoder ("viterbi", or "bcjr": soft output; also "maxlog",
              "hard_llr", "termination", "invert"). A mother code is a file (fec/conv/k7_171_133.json); its punctured
              rates extend it with their "puncture" (fec/conv/k7_171_133/3_4.json)
interleave  {"base": "interleave", "type": "forney", "I": 12, "M": 17, "symbol": 8}
            {"base": "interleave", "type": "block", "perm": [...] or {"each": "<i>", "n": N}, "map": "from" | "to", "symbol": 1}
            {"base": "interleave", "type": "block", "length": D, "cols": 32, "col_perm": [...], "fill": "front"}
Any value can be a load-time parameter: "params": {"ncbps": null}, then {"param": "ncbps"} or {"expr": "..."}.

A reference is the path below config/fec or config/interleave with the kind first: "block/rs/204_188", "conv/k7_171_133/3_4", "interleave/forney/12_17". A bare name ("204_188") works while one definition of any kind has it.

Decoding only runs from a definition loaded here; analysis.result.Guess.save turns a guessed structure into one, rp.code.import_alist an LDPC alist file. CRC and framing are in rpps.link.

Functions:

Name Description
root

Directory holding the coding definitions

ls

List available FEC definitions by family: {"block/rs": [names], "conv/dvbs": [names], ...}

names

References of the definitions of a kind ("block", "conv", "interleave"), as load(kind, ref) takes them ("rs/204_188"), across families or just one

init

Initialize coding. decoder: a decoder type to use instead of the definition's (see coding.Block.load)

locate

(file, kind, name) of a definition: ref is "/" ("block/rs/204_188", "interleave/forney/12_17"), or

mother

The configured mother code (fec/conv/.json) with these generators, as "k7_171_133", or None: what a found

find

File of a definition (see locate)

load

Load a code: load("block/rs/204_188"), load("conv/k7_171_133/3_4"), load("interleave/forney/12_17")

root

root() -> Path

Directory holding the coding definitions

Source code in src/rpps/code/serial.py
def root() -> Path:
    """Directory holding the coding definitions"""
    return _config.find_config("fec")

ls

ls(path=None, blind=False)

List available FEC definitions by family: {"block/rs": [names], "conv/dvbs": [names], ...}

blind: only what the blind tools try (rp._config.ls): no definitions tagged "example", and only the selected tags (rp.select_tags)

Source code in src/rpps/code/serial.py
def ls(path=None, blind=False):
    """List available FEC definitions by family: {"block/rs": [names], "conv/dvbs": [names], ...}

    blind: only what the blind tools try (rp._config.ls): no definitions tagged "example", and only the selected tags (rp.select_tags)"""
    return {**_config.ls("fec", path, blind=blind),
            **{f"interleave/{k}" if k != "interleave" else k: v for k, v in _config.ls("interleave", path, blind=blind).items()}}

names

names(kind: str, sub=None, path=None, blind=False)

References of the definitions of a kind ("block", "conv", "interleave"), as load(kind, ref) takes them ("rs/204_188"), across families or just one

blind: only what the blind tools try (rp._config.ls): no definitions tagged "example", and only the selected tags (rp.select_tags)

Source code in src/rpps/code/serial.py
def names(kind: str, sub=None, path=None, blind=False):
    """References of the definitions of a kind ("block", "conv", "interleave"), as `load(kind, ref)` takes them ("rs/204_188"), across families or just one

    blind: only what the blind tools try (rp._config.ls): no definitions tagged "example", and only the selected tags (rp.select_tags)"""
    out = []
    for key, v in ls(path, blind).items():
        k, _, family = key.partition("/")
        if k == kind and (sub is None or family == sub):
            out += [f"{family}/{n}" if family else n for n in v]
    return sorted(out)

init

init(name: str, obj: dict, decoder=None) -> coding.Coding

Initialize coding. decoder: a decoder type to use instead of the definition's (see coding.Block.load)

Source code in src/rpps/code/serial.py
def init(name: str, obj: dict, decoder=None) -> coding.Coding:
    """Initialize coding. decoder: a decoder type to use instead of the definition's (see `coding.Block.load`)"""
    base = str(obj["base"]).lower()
    if base not in _LOADERS:
        raise ConfigError(f"Unknown coding base {obj.get('base')!r} in {name}: have {sorted(_LOADERS)}")
    return _LOADERS[base].load(name, obj, decoder)

locate

locate(ref: str, path=None)

(file, kind, name) of a definition: ref is "/" ("block/rs/204_188", "interleave/forney/12_17"), or a bare name one definition of any kind has. name is the path below the kind ("rs/204_188"): what the loaded code is called

Source code in src/rpps/code/serial.py
def locate(ref: str, path=None):
    """(file, kind, name) of a definition: `ref` is "<kind>/<path below it>" ("block/rs/204_188", "interleave/forney/12_17"), or
    a bare name one definition of any kind has. name is the path below the kind ("rs/204_188"): what the loaded code is called"""
    ref = str(ref).strip("/")
    kind, _, rest = ref.partition("/")
    if kind in KINDS and rest:
        file, name = _find(kind, rest, path)
        hits = [(file, kind, name)] if file is not None else []
    else:
        hits = [(f, k, n) for k in KINDS for f, n in [_find(k, ref, path)] if f is not None]
    if len(hits) > 1:
        raise ConfigError(f"{ref} is ambiguous: {[f'{k}/{n}' for _, k, n in hits]}")
    if not hits:
        raise FileNotFoundError(f"{ref}: no code definition (give <kind>/<name>, kind one of {KINDS}), see rp.code.ls()")
    return hits[0]

mother

mother(generator, constraint=None)

The configured mother code (fec/conv/.json) with these generators, as "k7_171_133", or None: what a found punctured code extends

Source code in src/rpps/code/serial.py
def mother(generator, constraint=None):
    """The configured mother code (fec/conv/<mother>.json) with these generators, as "k7_171_133", or None: what a found
    punctured code extends"""
    from .types.conv import generators_of
    want = generators_of({"generator": generator, "constraint": constraint}).astype(int).tolist()
    for root in _config.layers("fec"):
        for f in sorted((root / "conv").glob("*.json")):
            obj = _config.read_raw(f)
            if "generator" in obj and generators_of(obj).astype(int).tolist() == want:
                return f.stem
    return None

find

find(ref: str, path=None) -> Path

File of a definition (see locate)

Source code in src/rpps/code/serial.py
def find(ref: str, path=None) -> Path:
    """File of a definition (see `locate`)"""
    return locate(ref, path)[0]

load

load(ref: str, path=None, decoder=None, **params) -> coding.Coding

Load a code: load("block/rs/204_188"), load("conv/k7_171_133/3_4"), load("interleave/forney/12_17") (config/fec//..., config/interleave/...; or below path instead of the shipped config)

decoder: decode with another type than the definition's: "bcjr" or "viterbi" for conv, "trellis" for linear block codes params: values of the definition's "params" (load("interleave/block/wifi_ofdm", ncbps=96, nbpsc=2))

Source code in src/rpps/code/serial.py
def load(ref: str, path=None, decoder=None, **params) -> coding.Coding:
    """Load a code: `load("block/rs/204_188")`, `load("conv/k7_171_133/3_4")`, `load("interleave/forney/12_17")`
    (config/fec/<kind>/..., config/interleave/...; or below `path` instead of the shipped config)

    decoder: decode with another type than the definition's: "bcjr" or "viterbi" for conv, "trellis" for linear block codes
    params: values of the definition's "params" (`load("interleave/block/wifi_ofdm", ncbps=96, nbpsc=2)`)
    """
    file, kind, name = locate(ref, path)
    return init(name, _config.resolve(_config.read(file), params, f"{kind}/{name}"), decoder)

uncoded

Classes:

Name Description
Uncoded

No channel code: the channel bits are the data bits. The code step of a link that has no FEC (ADS-B, many

Uncoded

Bases: Pipe

No channel code: the channel bits are the data bits. The code step of a link that has no FEC (ADS-B, many packet radios), so that what the demodulator gives becomes what the link layer takes

payload = syms / bpsk / rp.code.Uncoded() / crc

Decoding keeps LLRs as LLRs (and hard bits as bits), only saying they are now data bits.

rpps.code.scram

Scramblers, a step of the code transform: additive (a sequence of rpps.sequence XOR'd in) and self-synchronizing (feedthrough)

Modules:

Name Description
scrambler

Scramblers: how a sequence is applied to bits (the scramble resource; the sequences are rpps.sequence)

serial

Scrambler definitions: config/scramble//.json, loaded with rp.code.scram.load("dvb_energy")

scrambler

Scramblers: how a sequence is applied to bits (the scramble resource; the sequences are rpps.sequence)

Classes:

Name Description
Scram

Scrambler parent class

Feedthrough

Feedthrough (self-synchronizing) scrambler: the scrambled bits go through the register, so the keystream depends on the

Additive

Additive (synchronous) scrambler: data XOR a sequence that does not depend on the data (rpps.sequence)

Scram

Scram()

Bases: Pipe

Scrambler parent class

Methods:

Name Description
control

A frame starts here: an additive sequence restarts from its seed. With length (DVB-S2: a BBFRAME of Kbch bits)

load

Load modulation from json

Source code in src/rpps/code/scram/scrambler.py
def __init__(self):
    self.log = Logger().Child("Scram", _config.LOG_SCRAM).Child(type(self).__name__, _config.LOG_SCRAM)
control
control(length=None, frame=None)

A frame starts here: an additive sequence restarts from its seed. With length (DVB-S2: a BBFRAME of Kbch bits) also every length bits after; with frame (what a delimiter or frame sync publishes: Bluetooth whitening restarts after the access address) just here. A self-synchronizing scrambler has nothing to restart

Source code in src/rpps/code/scram/scrambler.py
def control(self, length=None, frame=None):
    """A frame starts here: an additive sequence restarts from its seed. With `length` (DVB-S2: a BBFRAME of Kbch bits)
    also every `length` bits after; with `frame` (what a delimiter or frame sync publishes: Bluetooth whitening restarts
    after the access address) just here. A self-synchronizing scrambler has nothing to restart"""
    if length is not None or frame is None:
        self.length = None if length is None else int(length)
    self._restart = True
load abstractmethod staticmethod
load(name: str, obj: dict)

Load modulation from json

Source code in src/rpps/code/scram/scrambler.py
@staticmethod
@abstractmethod
def load(name: str, obj: dict):
    """Load modulation from json"""

Feedthrough

Feedthrough(scram_lfsr: LFSR, descram_lfsr: LFSR)

Bases: Scram

Feedthrough (self-synchronizing) scrambler: the scrambled bits go through the register, so the keystream depends on the data. y[n] = d[n] ^ y[n-t] for each tap t; descrambling is d[n] = y[n] ^ y[n-t], which needs no seed once a register length of bits has passed (a bit slip or a mid-stream start is lost after that), and turns one bit error into one per tap

Methods:

Name Description
reset

Reset LFSR

descramble

d[n] = y[n] ^ y[n-t] for every tap t, on a whole array at once (the first max(taps) bits are not fully

delays

The delays t whose bits through the register (what went in, scrambling; what came in, descrambling) the

encode

Scramble, continuing from where the last call left this scrambler

Source code in src/rpps/code/scram/scrambler.py
def __init__(self, scram_lfsr: lfsr.LFSR, descram_lfsr: lfsr.LFSR):
    super().__init__()
    self.s_lfsr = scram_lfsr
    self.d_lfsr = descram_lfsr
    self._delays = None
reset
reset()

Reset LFSR

Source code in src/rpps/code/scram/scrambler.py
def reset(self):
    """Reset LFSR"""
    self.s_lfsr.reset()
    self.d_lfsr.reset()
descramble staticmethod
descramble(bits, taps)

d[n] = y[n] ^ y[n-t] for every tap t, on a whole array at once (the first max(taps) bits are not fully descrambled: the register before them is unknown). What a search over taps runs (rpps.analysis.sequence)

Source code in src/rpps/code/scram/scrambler.py
@staticmethod
def descramble(bits, taps):
    """d[n] = y[n] ^ y[n-t] for every tap t, on a whole array at once (the first max(taps) bits are not fully
    descrambled: the register before them is unknown). What a search over taps runs (rpps.analysis.sequence)"""
    return gf2.fir(bits, [int(t) for t in taps if 0 < int(t)])
delays
delays()

The delays t whose bits through the register (what went in, scrambling; what came in, descrambling) the keystream XORs: found by sending one 1 into a cleared register (every register form here is linear)

Source code in src/rpps/code/scram/scrambler.py
def delays(self):
    """The delays t whose bits through the register (what went in, scrambling; what came in, descrambling) the
    keystream XORs: found by sending one 1 into a cleared register (every register form here is linear)"""
    if self._delays is None:
        reg = self.s_lfsr.clone()
        reg.lfsr[:] = 0
        out = [reg.advance(b, True) for b in [1] + [0]*len(reg.lfsr)]
        self._delays = [t for t in range(1, len(out)) if out[t]]
    return self._delays
encode
encode(data)

Scramble, continuing from where the last call left this scrambler

Source code in src/rpps/code/scram/scrambler.py
def encode(self, data):
    """Scramble, continuing from where the last call left this scrambler"""
    out, self.s_lfsr = self._run_bits(data, self.s_lfsr, False)
    return out

Additive

Additive(sequence, frame=None, period=None)

Bases: Scram

Additive (synchronous) scrambler: data XOR a sequence that does not depend on the data (rpps.sequence)

encode(bits, start) and decode (the same) XOR the sequence from position start; soft(llr, start) flips LLRs instead. As an operator (bits * scr, bits / scr) its position carries along the stream, and restarts: period: every period bits (an LTE PBCH over four radio frames, a P25 phase 2 superframe) frame: packet structure for byte streams, as in DVB energy dispersal: bytes: restart period; sync_period/sync_bytes: leading bytes of each packet the sequence skips over (it still advances, those bytes just aren't touched); skip_first: bytes before it starts (default sync_bytes); marker: the first byte of each frame as sent (DVB: the inverted sync byte, 0xB8), written on encode, and sync (default marker ^ 0xFF) written on decode. The stream must start on a frame boundary. length (a profile's control): every length bits from where a frame starts (a DVB-S2 BBFRAME)

Methods:

Name Description
mask

Bits XOR'd onto one frame (frame bytes * 8), or onto one period

encode

data XOR the sequence from position start (0: a frame or period boundary)

soft

Descramble LLRs (positive = 0): the sign flips where the sequence is 1

kernel

The batch scrambler of a frame restarted every length bits (what a profile's control gives); the periodic and

Source code in src/rpps/code/scram/scrambler.py
def __init__(self, sequence, frame=None, period=None):
    super().__init__()
    self.seq = sequence
    self.frame = frame
    self.period = None if period is None else int(period)
    self.marker = None if frame is None else frame.get("marker")
    self._mask = None
mask
mask()

Bits XOR'd onto one frame (frame bytes * 8), or onto one period

Source code in src/rpps/code/scram/scrambler.py
def mask(self):
    """Bits XOR'd onto one frame (frame bytes * 8), or onto one period"""
    if self._mask is None:
        self._mask = self._make_mask() if self.frame is not None else self.seq.bits(self.period)
    return self._mask
encode
encode(data, start=0)

data XOR the sequence from position start (0: a frame or period boundary)

Source code in src/rpps/code/scram/scrambler.py
def encode(self, data, start=0):
    """data XOR the sequence from position `start` (0: a frame or period boundary)"""
    bits = np.asarray(data).astype(np.uint8)
    return (bits ^ self._bits(len(bits), start)).astype(bool)
soft
soft(llr, start=0)

Descramble LLRs (positive = 0): the sign flips where the sequence is 1

Source code in src/rpps/code/scram/scrambler.py
def soft(self, llr, start=0):
    """Descramble LLRs (positive = 0): the sign flips where the sequence is 1"""
    llr = np.asarray(llr, dtype=np.float64)
    return llr*(1.0 - 2.0*self._bits(len(llr), start))
kernel
kernel(params, how)

The batch scrambler of a frame restarted every length bits (what a profile's control gives); the periodic and packet-structured forms have none

Source code in src/rpps/code/scram/scrambler.py
def kernel(self, params, how):
    """The batch scrambler of a frame restarted every `length` bits (what a profile's control gives); the periodic and
    packet-structured forms have none"""
    if how not in ("/", "*"):
        return None
    if params:
        self.control(**params)
    if not self.length or self.frame is not None or self.period is not None:
        return None
    from ..kernels import XorMask
    return XorMask(self.seq.bits(self.length), Category.CODE, Rep.CHANNEL if how == "*" else Rep.DATA, self.seq.name)

serial

Scrambler definitions: config/scramble//.json, loaded with rp.code.scram.load("dvb_energy")

How a sequence is applied to bits; the sequences are their own resource (rpps.sequence), which a scrambler names.

additive     data XOR a sequence that ignores the data
     {"base": "scramble", "type": "additive",
      "sequence": "dvb_energy" | {"name": "lte_gold", "args": {"c_init": {"expr": "..."}}},   with its parameters
      "period": 1920,                    optional: restart every `period` bits
      "frame": {"bytes": 1504, "sync_period": 188, "sync_bytes": 1, "marker": 184}}  optional: packet structure (see Additive)
feedthrough  self-synchronizing: the output feeds the register, so the register is the scrambler's own
     {"base": "scramble", "type": "feedthrough", "register": "fibonacci" | "galois_left" | "galois_right",
      "poly": [16, 14, 13, 11],          the polynomial's exponents, as standards write it (1 + x^14 + x^17: [14, 17]):
                                         the delays of the feedback taps, 1 = the first stage. (A recurrence's
                                         "taps", in rpps.sequence, are positions from 0: another key, another thing)
      "seed": [1, 0, 1, ...]}            register bits, first stage first
Seeds, sequence arguments and any other value can be load-time parameters ("params", then {"param": ...} / {"expr": ...}).

Functions:

Name Description
ls

The scramblers there are: {type: [names]}

init

A scrambler from a definition object

load

Load a scrambler by name: load("dvb_energy"), load("ble_whiten", channel=37). params: values of its "params"

ls

ls(blind=False)

The scramblers there are: {type: [names]}

blind: only what the blind tools try (rp._config.ls): no definitions tagged "example", and only the selected tags (rp.select_tags)

Source code in src/rpps/code/scram/serial.py
def ls(blind=False):
    """The scramblers there are: {type: [names]}

    blind: only what the blind tools try (rp._config.ls): no definitions tagged "example", and only the selected tags (rp.select_tags)"""
    return _config.ls("scramble", blind=blind)

init

init(name: str, obj: dict) -> scrambler.Scram

A scrambler from a definition object

Source code in src/rpps/code/scram/serial.py
def init(name: str, obj: dict) -> scrambler.Scram:
    """A scrambler from a definition object"""
    return _config.load_obj("scramble", name, obj)

load

load(name: str, **params) -> scrambler.Scram

Load a scrambler by name: load("dvb_energy"), load("ble_whiten", channel=37). params: values of its "params"

Source code in src/rpps/code/scram/serial.py
def load(name: str, **params) -> scrambler.Scram:
    """Load a scrambler by name: `load("dvb_energy")`, `load("ble_whiten", channel=37)`. params: values of its "params" """
    return _config.load("scramble", name, params=params)

rpps.code.types

Code types: the FEC encoders and decoders the definitions in config/fec and config/interleave build

A code type subclasses rpps.code.types._code._code and defines _decode(x, ...) -> (output, errors per codeword or None), keeping nothing of the call on itself, so one loaded (cached) code decodes on several threads at once. Soft or path outputs are methods that return them too (app of BCJR and turbo, paths of fsm), never attributes.

A trellis, worked

The rate 1/2, constraint length 3 code with generators 101 and 111 (state = the last two input bits):

State In Out Next
00 0 00 00
1 11 10
01 0 11 00
1 00 10
10 0 01 01
1 10 11
11 0 10 01
1 01 11
graph LR
    S00((00)) -- 0/00 --> T00((00))
    S00 -- 1/11 --> T10((10))
    S01((01)) -- 0/11 --> T00
    S01 -- 1/00 --> T10
    S10((10)) -- 0/01 --> T01((01))
    S10 -- 1/10 --> T11((11))
    S11((11)) -- 0/10 --> T01
    S11 -- 1/01 --> T11

fsm holds such tables for any code (output[s][u], next[s][u]); viterbi and bcjr decode on them.

Modules:

Name Description
bchgf
conv
cyclic
expr
fsm
interleave
ira
layout

Where a block code's bits go in the word sent, and what is done to them on the way: keys of any block definition

ldpc
linear
nr_ldpc

5G NR LDPC code with its rate matching (3GPP TS 38.212 5.2.2, 5.3.2, 5.4.2): one code block, K' bits to E bits

nr_polar

5G NR polar code with its rate matching (3GPP TS 38.212 5.3.1, 5.4.1): K bits, CRC included, to E bits

polar

Polar codes (Arikan): encoding, successive cancellation (SC) and list decoding (SCL), CRC-aided

product
ratematch
repeat
rm

Reed-Muller codes RM(r, m): the evaluations of every Boolean polynomial of degree at most r in m variables

rs
syndrome
trellis

Trellis (BCJR / MAP) decoding

turbo
viterbi

bchgf

Classes:

Name Description
bchgf

Binary BCH code over GF(2^m), shortened to (n, k), as in DVB-S2 (m=16, or 14 for short frames)

bchgf

bchgf(log, n, k, m=16, poly=65581, t=12)

Bases: _code

Binary BCH code over GF(2^m), shortened to (n, k), as in DVB-S2 (m=16, or 14 for short frames)

poly: field polynomial (0x1002D = 1+x^2+x^3+x^5+x^16). t: correctable bit errors. The generator is the product of the distinct minimal polynomials of alpha^1, alpha^3, ..., alpha^(2t-1), so n-k = m*t. encode/decode take whole codewords as bits. After a decode errors is the corrected bit count per word (-1: failed).

Methods:

Name Description
syndromes

S_j = r(alpha^j), j=1..2t, for words (W, n) of bits

Source code in src/rpps/code/types/bchgf.py
def __init__(self, log, n, k, m=16, poly=0x1002D, t=12):
    super().__init__(log, None, k, n)
    self.m, self.t, self.poly = m, t, poly
    self.gf = GF(m, poly)
    self.size, self.exp, self.log = self.gf.size, self.gf.exp, self.gf.log
    self.gen = _generator(m, poly, t)
    if len(self.gen) - 1 != n - k:
        raise ValueError(f"BCH generator has degree {len(self.gen)-1}, but n-k={n-k}")
syndromes
syndromes(words)

S_j = r(alpha^j), j=1..2t, for words (W, n) of bits

Source code in src/rpps/code/types/bchgf.py
def syndromes(self, words):
    """S_j = r(alpha^j), j=1..2t, for words (W, n) of bits"""
    words = np.asarray(words)
    if _accel.native is not None:
        return _accel.native.gf_syndromes(np.ascontiguousarray(words, dtype=np.int64), self.gf.exp, self.gf.log, 2*self.t, 1, 1)
    e = np.arange(self.den - 1, -1, -1) # Power of x of each bit
    S = np.zeros((len(words), 2*self.t), dtype=np.int64)
    for j in range(1, 2*self.t + 1):
        S[:, j-1] = self.gf.evaluate(words, e*j)
    return S

conv

Classes:

Name Description
conv

Convolutional encoder, rate 1/n. See viterbi for the conventions

Functions:

Name Description
termination_of

A definition's "termination": "zero" | "tailbiting" | "truncated" (the default)

generators_of

(den, K) generator rows of a definition. Rows of K bits, or numbers ("0o133", 91) with "constraint": the most

conv

conv(log, num: int, den: int, generator, constraint: int, puncture=None, termination='truncated', invert=None)

Bases: _code

Convolutional encoder, rate 1/n. See viterbi for the conventions

puncture: optional (n, P) 0/1 pattern, 1 = send invert: optional n 0/1 flags: outputs sent inverted (CCSDS 131.0-B inverts the second, G2), before puncturing termination: "zero" flushes the register with K-1 zeros so the decoder can end in state 0 (the older termination="zero"); "tailbiting" starts the register with the frame's last K-1 bits, so it ends where it began and nothing is added (LTE); "truncated" (default) just stops. A tail-biting code works on whole frames: in a stream the bits are collected until the stream is flushed.

Methods:

Name Description
encode

Encode a message. Without state it is a frame of its own, starting from the zero register.

encode_batch

Rows of bits (W, L), each a frame of its own, as encode() without state gives it: (W, coded bits)

Source code in src/rpps/code/types/conv.py
def __init__(self, log, num: int, den: int, generator, constraint: int, puncture=None, termination="truncated", invert=None):
    super().__init__(log, None, num, den)
    self.generator = np.asarray(generator, dtype=bool).reshape(den, constraint)
    self.con = constraint
    self.puncture = None if puncture is None else np.asarray(puncture, dtype=bool)
    self.invert = None if invert is None or not any(invert) else np.asarray(invert, dtype=np.int64)
    self.termination = termination_of({"termination": termination})
    self.stream = self.termination != "tailbiting"
encode
encode(bits, state=None, final=True)

Encode a message. Without state it is a frame of its own, starting from the zero register.

With state (a dict, the encoder's part of the stream) the register carries on from the previous call, and a terminated code only gets its tail when final, which also ends the stream (the state is cleared).

Source code in src/rpps/code/types/conv.py
def encode(self, bits, state=None, final=True):
    """Encode a message. Without `state` it is a frame of its own, starting from the zero register.

    With `state` (a dict, the encoder's part of the stream) the register carries on from the previous call, and
    a terminated code only gets its tail when `final`, which also ends the stream (the state is cleared).
    """
    bits = np.asarray(bits).astype(bool)
    reg = np.zeros(self.con, dtype=bool) if not state or "reg" not in state else state["reg"].copy()
    if self.termination == "tailbiting":
        if state is not None and not final:
            raise ValueError("A tail-biting code encodes whole frames")
        past = bits[::-1][:self.con - 1] # Newest past bit first: the frame's last bits
        reg[1:1 + len(past)] = past
    if self.terminated and final:
        bits = np.concatenate((bits, np.zeros(self.con-1, dtype=bool)))
    blocks = bits[:len(bits)//self.num*self.num].reshape(-1, self.num)
    self.log.trace(f"encoding {len(bits)}, {blocks.shape}")

    # reg[k] at input i is u[i-k]: past bits (reg[1:], newest first) then the input, one window of K per output
    K = self.con
    ext = np.concatenate((reg[1:][::-1], blocks[:, 0] if len(blocks) else np.zeros(0, dtype=bool))).astype(np.uint8)
    if len(blocks):
        win = np.lib.stride_tricks.sliding_window_view(ext, K)[:, ::-1] # win[i, k] = u[i-k]
        encoded = (win.astype(np.int64) @ self.generator.T.astype(np.int64)) & 1
    else:
        encoded = np.zeros((0, self.den), dtype=np.int64)
    reg = np.zeros(K, dtype=bool)
    reg[1:] = ext[::-1][:K - 1].astype(bool) # Newest first, the next input's slot empty

    if state is not None:
        if final:
            state.clear()
        else:
            state["reg"] = reg
    if self.invert is not None:
        encoded = encoded ^ self.invert[None, :]
    if self.puncture is not None:
        P = self.puncture.shape[1]
        full = len(encoded)//P*P
        mask = np.tile(self.puncture.T, (full//P, 1))
        encoded = encoded[:full][mask]
    encoded = encoded.reshape(-1).astype(bool)
    self.log.trace(f"encoded {len(encoded)}")
    return encoded
encode_batch
encode_batch(bits)

Rows of bits (W, L), each a frame of its own, as encode() without state gives it: (W, coded bits)

Source code in src/rpps/code/types/conv.py
def encode_batch(self, bits):
    """Rows of bits (W, L), each a frame of its own, as encode() without `state` gives it: (W, coded bits)"""
    b = np.asarray(bits).astype(np.uint8)
    if self.termination == "tailbiting" or self.num != 1 or b.ndim != 2:
        return np.array([self.encode(r) for r in b], dtype=bool).reshape(len(b), -1)
    W, K = len(b), self.con
    if self.terminated:
        b = np.concatenate((b, np.zeros((W, K - 1), dtype=np.uint8)), axis=1)
    ext = np.concatenate((np.zeros((W, K - 1), dtype=np.uint8), b), axis=1) # The zero register, then the input
    win = np.lib.stride_tricks.sliding_window_view(ext, K, axis=1)[:, :, ::-1] # win[w, i, k] = u[w, i-k]
    encoded = (win.astype(np.int64) @ self.generator.T.astype(np.int64)) & 1 # (W, L, n)
    if self.invert is not None:
        encoded = encoded ^ self.invert[None, None, :]
    if self.puncture is not None:
        P = self.puncture.shape[1]
        full = encoded.shape[1]//P*P
        mask = np.tile(self.puncture.T, (full//P, 1))
        encoded = encoded[:, :full][:, mask]
    return encoded.reshape(W, -1).astype(bool)

termination_of

termination_of(obj)

A definition's "termination": "zero" | "tailbiting" | "truncated" (the default)

Source code in src/rpps/code/types/conv.py
def termination_of(obj):
    """A definition's "termination": "zero" | "tailbiting" | "truncated" (the default)"""
    t = obj.get("termination", "truncated")
    if t not in TERMINATIONS:
        raise ValueError(f"termination {t!r}: one of {TERMINATIONS}")
    return t

generators_of

generators_of(obj)

(den, K) generator rows of a definition. Rows of K bits, or numbers ("0o133", 91) with "constraint": the most significant of the K bits multiplies the current input

Source code in src/rpps/code/types/conv.py
def generators_of(obj):
    """(den, K) generator rows of a definition. Rows of K bits, or numbers ("0o133", 91) with "constraint": the most
    significant of the K bits multiplies the current input"""
    g = obj["generator"]
    K = obj.get("constraint")
    if all(isinstance(x, (int, str)) for x in g):
        if K is None:
            raise ValueError("Generators given as numbers need \"constraint\"")
        nums = [int(x, 0) if isinstance(x, str) else int(x) for x in g]
        for x in nums:
            if x >= 1 << K:
                raise ValueError(f"Generator {x:#o} is longer than the constraint length {K}")
        return np.array([[(x >> (K - 1 - i)) & 1 for i in range(K)] for x in nums], dtype=bool)
    return np.array(g, dtype=bool)

cyclic

Classes:

Name Description
cyclic

Binary cyclic code from its generator polynomial, systematic with the message first: Golay, Hamming, BCH...

cyclic

cyclic(log, n, k, poly, extend=False, shorten=0, t=None)

Bases: linear

Binary cyclic code from its generator polynomial, systematic with the message first: Golay, Hamming, BCH...

poly: g(x) as an integer, bit i the coefficient of x^i (Golay (23,12): 0xC75), degree n - k, dividing x^n + 1. extend: append an overall parity bit (Golay (24,12)). shorten: drop that many leading message bits (sent as 0). t: errors the decoder should correct (default: from the minimum distance). A codeword is the message followed by the remainder of m(x) x^(n-k) mod g(x), highest power first.

Source code in src/rpps/code/types/cyclic.py
def __init__(self, log, n, k, poly, extend=False, shorten=0, t=None):
    r = n - k
    if poly.bit_length() - 1 != r:
        raise ValueError(f"cyclic ({n},{k}): generator {poly:#x} has degree {poly.bit_length()-1}, need n-k={r}")
    if pmod(1 << n | 1, poly) != 0:
        raise ValueError(f"cyclic ({n},{k}): {poly:#x} does not divide x^{n}+1")
    if not 0 <= shorten < k:
        raise ValueError(f"cyclic ({n},{k}): can't shorten by {shorten}")
    p = np.array([[(pmod(1 << (r + k - 1 - i), poly) >> (r - 1 - j)) & 1 for j in range(r)] for i in range(k)], dtype=np.uint8)
    if extend: # Overall parity: of the message bit and its parity row
        p = np.concatenate((p, ((1 + p.sum(axis=1)) % 2)[:, None]), axis=1)
    p = p[shorten:]
    kk = k - shorten
    G, H = parity_to_gh(kk + p.shape[1], kk, p)
    super().__init__(log, G, H)
    self.poly, self.extend, self.shorten, self.t = poly, extend, shorten, t

expr

Classes:

Name Description
expr

A small block code whose codeword bits are expressions of the message bits: "k", "bits": one expression per

Functions:

Name Description
codebook

Every codeword (2^k, n) of codeword-bit expressions over m0..m{k-1} (and the bits before, c0..), message i's bits

affine

(G, offset) when every codeword is offset + m G over GF(2), else None

expr

expr(log, book, t=None)

Bases: _code

A small block code whose codeword bits are expressions of the message bits: "k", "bits": one expression per codeword bit over m0..m{k-1} and the bits before it (c0, c1...), with ^ & | ~ and constants

{"base": "block", "type": "expr", "k": 4, "bits": ["m0", "m1", "m2", "m3", "m0 ^ m1 ^ m3", "(m1 & m2) ^ 1"]}

Loaded as a linear code (and its xor pattern) when the map is affine over GF(2), so it decodes on its syndrome trellis like any; otherwise decoded by nearest codeword over the whole codebook (k <= 16): soft, the codeword whose signs best match the LLRs. errors is the distance to the codeword chosen (-1 past t, when given)

Source code in src/rpps/code/types/expr.py
def __init__(self, log, book, t=None):
    book = np.asarray(book, dtype=np.uint8)
    k = int(np.log2(len(book)))
    super().__init__(log, None, k, book.shape[1])
    self.book, self.t = book, t
    self._signs = 1.0 - 2.0*book.astype(np.float64) # (2^k, n): +1 for a 0
    self._msgs = ((np.arange(1 << k)[:, None] >> np.arange(k - 1, -1, -1)) & 1).astype(bool)

codebook

codebook(bits, k)

Every codeword (2^k, n) of codeword-bit expressions over m0..m{k-1} (and the bits before, c0..), message i's bits MSB first

Source code in src/rpps/code/types/expr.py
def codebook(bits, k):
    """Every codeword (2^k, n) of codeword-bit expressions over m0..m{k-1} (and the bits before, c0..), message i's bits
    MSB first"""
    from ... import _config
    if not 0 < k <= MAX_K:
        raise ValueError(f"expr code: k={k}, need 1..{MAX_K} (its codebook has 2^k words)")
    msgs = ((np.arange(1 << k)[:, None] >> np.arange(k - 1, -1, -1)) & 1).astype(np.int64)
    values = {f"m{i}": msgs[:, i] for i in range(k)}
    out = np.zeros((1 << k, len(bits)), dtype=np.uint8)
    for j, e in enumerate(bits):
        v = _config.evaluate(str(e), values, f"expr code bit {j}") if isinstance(e, str) else e
        out[:, j] = np.broadcast_to(np.asarray(v, dtype=np.int64) & 1, (1 << k,))
        values[f"c{j}"] = out[:, j].astype(np.int64)
    return out

affine

affine(book, k)

(G, offset) when every codeword is offset + m G over GF(2), else None

Source code in src/rpps/code/types/expr.py
def affine(book, k):
    """(G, offset) when every codeword is offset + m G over GF(2), else None"""
    off = book[0]
    units = 1 << np.arange(k - 1, -1, -1) # message of unit vector e_i: bit i set (MSB first)
    G = book[units] ^ off
    msgs = ((np.arange(1 << k)[:, None] >> np.arange(k - 1, -1, -1)) & 1).astype(np.uint8)
    if not np.array_equal(((msgs @ G) % 2).astype(np.uint8) ^ off, book):
        return None
    return G, off

fsm

Classes:

Name Description
fsm

Trellis code given as a finite state machine: P25's 1/2 and 3/4 rate trellis codes, ATSC's 8VSB trellis code

fsm

fsm(log, k, n, next_state, output, start=0, end=None, tail=0, symbols=None, length=None)

Bases: _code

Trellis code given as a finite state machine: P25's 1/2 and 3/4 rate trellis codes, ATSC's 8VSB trellis code

Each step takes k input bits (most significant first) in state s, sends the n-bit word output[s][u] (most significant first) and moves to next[s][u]. Tables are (states, 2^k), or flat lists of states*2^k (row = state). start: the state the encoder starts in (default 0); null: unknown (the decoder starts from any) tail: input words of zeros appended by the encoder (P25: one), decoded and dropped; end: the state the path must end in (null: any) length: message bits of a codeword (P25 TSBK: 96): each codeword a trellis of its own, from start, with its tail; encode / decode then take any number of whole codewords. Without it a call is one sequence symbols: {"bits": b, "levels": [...]} to decode received amplitudes instead of bits: each b-bit group of a word is sent as levels[group] (ATSC: 3 bits -> -7..7). decode() then takes the amplitudes, n/b per step, and the branch metric is the squared distance. {"bits": b, "points": [[re, im], ...]}: the same with points of a constellation (trellis-coded modulation: Ungerboeck, pragmatic), in label order, decoding complex symbols Bit decoding takes hard bits or LLRs (positive = 0). decode() takes one sequence, decode_batch() a (W, ...) array of independent ones (all the same length) and returns the input bits of each. With status=True, each sequence's errors are the received bits (hard decided) that differ from its decoded path's words.

Methods:

Name Description
modulate

Encoded bits -> the amplitudes the symbols mapping sends

decode_batch

Sequences (W, ...) decoded together: bits (W, ...), or (bits, errors per sequence) with status=True

paths

Sequences (W, ...) decoded together: (bits (W, ...), the encoder's output word at every step of each decoded path

Source code in src/rpps/code/types/fsm.py
def __init__(self, log, k, n, next_state, output, start=0, end=None, tail=0, symbols=None, length=None):
    nxt = np.asarray(next_state, dtype=np.int64)
    out = np.asarray(output, dtype=np.int64)
    U = 1 << k
    nxt, out = nxt.reshape(-1, U), out.reshape(-1, U)
    S = len(nxt)
    if out.shape != nxt.shape:
        raise ValueError(f"next {nxt.shape} and output {out.shape} tables differ")
    if nxt.min() < 0 or nxt.max() >= S or out.min() < 0 or out.max() >= 1 << n:
        raise ValueError("Table entries out of range")
    self.k, self.n, self.S, self.U = k, n, S, U
    self.next, self.out = nxt, out
    self.start, self.end, self.tail = start, end, int(tail)
    self.levels, self.dims = None, 1
    if symbols is not None:
        b = int(symbols["bits"])
        if n % b:
            raise ValueError(f"{n}-bit words don't split into {b}-bit symbols")
        if ("levels" in symbols) == ("points" in symbols):
            raise ValueError("symbols: give \"levels\" (amplitudes) or \"points\" ([re, im] pairs)")
        if "points" in symbols:
            pts = np.asarray(symbols["points"], dtype=np.float64).reshape(-1, 2)
            self.sym_bits, self.levels, self.dims = b, pts[:, 0] + 1j*pts[:, 1], 2
        else:
            self.sym_bits, self.levels = b, np.asarray(symbols["levels"], dtype=np.float64)
        if len(self.levels) != 1 << b:
            raise ValueError(f"{1 << b} levels needed for {b}-bit symbols")
    self.length = None if length is None else int(length)
    if self.length is not None and (self.length <= 0 or self.length % k):
        raise ValueError(f"length {self.length}: a positive number of {k}-bit input words")
    if self.length is None:
        super().__init__(log, None, k, n)
    else: # Whole codewords: the message bits in, its steps and tail's words out (as amplitudes: n/bits of them a step)
        per = n // int(symbols["bits"]) if symbols is not None else n
        super().__init__(log, None, self.length, (self.length//k + self.tail)*per)
    # Predecessors of each state: every (state, input) pair that leads there
    pred = [[] for _ in range(S)]
    for s in range(S):
        for u in range(U):
            pred[nxt[s, u]].append((s, u))
    P = max(len(p) for p in pred)
    if min(len(p) for p in pred) == 0:
        raise ValueError("Some state can't be reached")
    self.pred_s = np.array([[p[i % len(p)][0] for i in range(P)] for p in pred]) # (S, P), padded by repeating
    self.pred_u = np.array([[p[i % len(p)][1] for i in range(P)] for p in pred])
    self.out_bits = ((out[..., None] >> np.arange(n - 1, -1, -1)) & 1).astype(np.uint8) # (S, U, n)
    # For rpps._native: branch j into s sends word _pat[s, j]; _tab holds each word's bits (or its amplitudes)
    self._pred = np.ascontiguousarray(self.pred_s, dtype=np.int32)
    self._pat = np.ascontiguousarray(out[self.pred_s, self.pred_u], dtype=np.int32)
    word_bits = ((np.arange(1 << n)[:, None] >> np.arange(n - 1, -1, -1)) & 1)
    if self.levels is None:
        self._tab = word_bits.astype(np.float64)
    else:
        m = n // self.sym_bits
        idx = (word_bits.reshape(-1, m, self.sym_bits) * (1 << np.arange(self.sym_bits - 1, -1, -1))).sum(axis=2)
        self._tab = np.ascontiguousarray(self._coords(self.levels[idx]).reshape(1 << n, -1), dtype=np.float64)
modulate
modulate(bits)

Encoded bits -> the amplitudes the symbols mapping sends

Source code in src/rpps/code/types/fsm.py
def modulate(self, bits):
    """Encoded bits -> the amplitudes the `symbols` mapping sends"""
    g = np.asarray(bits).astype(np.int64).reshape(-1, self.sym_bits)
    return self.levels[(g * (1 << np.arange(self.sym_bits - 1, -1, -1))).sum(axis=1)]
decode_batch
decode_batch(x, soft=None, status=False)

Sequences (W, ...) decoded together: bits (W, ...), or (bits, errors per sequence) with status=True

Source code in src/rpps/code/types/fsm.py
def decode_batch(self, x, soft=None, status=False):
    """Sequences (W, ...) decoded together: bits (W, ...), or (bits, errors per sequence) with status=True"""
    bits, errors, _ = self._batch(x, soft)
    return (bits, errors) if status else bits
paths
paths(x, soft=None)

Sequences (W, ...) decoded together: (bits (W, ...), the encoder's output word at every step of each decoded path (W, T): what the decoder decided was sent, before any mapping to levels)

Source code in src/rpps/code/types/fsm.py
def paths(self, x, soft=None):
    """Sequences (W, ...) decoded together: (bits (W, ...), the encoder's output word at every step of each decoded path
    (W, T): what the decoder decided was sent, before any mapping to levels)"""
    bits, _, out = self._batch(x, soft)
    return bits, out

interleave

Classes:

Name Description
forney

Forney convolutional interleaver: I branches, branch j delays by jM symbols (deinterleaver: (I-1-j)M)

block_interleaver

Block interleaver: a fixed permutation of each block of n items of symbol bits (dibits: symbol=2)

Functions:

Name Description
rowcol

from permutation of a row-column interleaver: written by rows (dummies first, or last with fill="back"),

forney

forney(log, I=12, M=17, symbol=8)

Bases: _code

Forney convolutional interleaver: I branches, branch j delays by jM symbols (deinterleaver: (I-1-j)M)

Works on symbols of symbol bits (8: bytes). The first symbol must sit on branch 0 (a packet sync byte). The deinterleaver has a start-up of (I-1)IM symbols before it carries data. LLRs go through as LLRs (each symbol's bits kept together; the start-up gives 0: unknown), so the Reed-Solomon decoder after it gets the soft values a soft-output inner decoder gives, for its erasures.

Source code in src/rpps/code/types/interleave.py
def __init__(self, log, I=12, M=17, symbol=8):
    super().__init__(log, None, 1, 1)
    self.I, self.M, self.symbol = I, M, symbol
    self.delay = (I-1)*I*M # Symbols of start-up delay of interleaver + deinterleaver together

block_interleaver

block_interleaver(log, perm, mapping='from', symbol=1)

Bases: _code

Block interleaver: a fixed permutation of each block of n items of symbol bits (dibits: symbol=2)

the permutation, as a list or {"each": "", "n": N} in the definition.

map "from" (default): item i of the interleaved block is item perm[i] of the input map "to": item i of the input goes to position perm[i]

Or the row-column form (LTE sub-block interleaver, 36.212 5.1.4.2.1): cols, col_perm (default: in order), length n (rows = ceil(n/cols)): written row by row with the filler (rows*cols - n dummies) at the front, columns permuted, read column by column; dummies are dropped encode() interleaves, decode() undoes it, on bits or on soft values (any dtype), whole blocks at a time.

Source code in src/rpps/code/types/interleave.py
def __init__(self, log, perm, mapping="from", symbol=1):
    perm = np.asarray(perm, dtype=np.int64)
    n = len(perm)
    if not np.array_equal(np.sort(perm), np.arange(n)):
        raise ValueError(f"Not a permutation of 0..{n-1} (repeated or missing positions)")
    if mapping not in ("from", "to"):
        raise ValueError(f"map {mapping!r}: 'from' or 'to'")
    src = perm if mapping == "from" else np.argsort(perm)
    super().__init__(log, None, n*symbol, n*symbol)
    self.n, self.symbol = n, symbol
    self.src = src                       # Output item i = input item src[i]
    self.dst = np.argsort(src)           # Input item j lands at dst[j]
    self.block_bits = n*symbol

rowcol

rowcol(length, cols, col_perm=None, fill='front', row_perm=None)

from permutation of a row-column interleaver: written by rows (dummies first, or last with fill="back"), columns permuted by col_perm (rows by row_perm), read by columns; dummy positions dropped

Source code in src/rpps/code/types/interleave.py
def rowcol(length, cols, col_perm=None, fill="front", row_perm=None):
    """`from` permutation of a row-column interleaver: written by rows (dummies first, or last with fill="back"),
    columns permuted by col_perm (rows by row_perm), read by columns; dummy positions dropped"""
    rows = -(-length//cols)
    dummies = rows*cols - length
    y = np.full(rows*cols, -1)
    if fill == "front":
        y[dummies:] = np.arange(length)
    else:
        y[:length] = np.arange(length)
    mat = y.reshape(rows, cols)
    if row_perm is not None:
        mat = mat[np.asarray(row_perm)]
    order = np.arange(cols) if col_perm is None else np.asarray(col_perm)
    out = mat[:, order].T.reshape(-1)
    return out[out >= 0]

ira

Functions:

Name Description
ira_checks

Parity checks of a DVB-S2 style irregular repeat-accumulate LDPC code from its address table

ira_encode

Systematic encoder for the same construction: [information | parity]

ira_checks

ira_checks(n, k, table, group=360)

Parity checks of a DVB-S2 style irregular repeat-accumulate LDPC code from its address table

table: one row of parity addresses per group of group information bits. Information bit j of group i adds to parity bits (x + (j mod group) * q) mod (n-k) for every address x in the row, q = (n-k)/group, and the parity bits are accumulated (p[m] ^= p[m-1]). Returns [positions] per check, information bits first.

Source code in src/rpps/code/types/ira.py
def ira_checks(n, k, table, group=360):
    """Parity checks of a DVB-S2 style irregular repeat-accumulate LDPC code from its address table

    table: one row of parity addresses per group of `group` information bits. Information bit j of group i adds to
    parity bits (x + (j mod group) * q) mod (n-k) for every address x in the row, q = (n-k)/group, and the parity
    bits are accumulated (p[m] ^= p[m-1]). Returns [positions] per check, information bits first.
    """
    m = n - k
    q = m // group
    if q*group != m:
        raise ValueError(f"n-k={m} is not a multiple of the group size {group}")
    if len(table) * group != k:
        raise ValueError(f"{len(table)} table rows of {group} bits do not cover k={k}")
    # Every (check, bit) edge in the order the table gives them, then each check's own parity bit and the one before it
    # (the accumulator); a stable sort by check keeps that order within each check
    j = np.arange(group, dtype=np.int64)
    rows = [(i, int(x)) for i, row in enumerate(table) for x in row]
    i_of = np.array([i for i, _ in rows], dtype=np.int64)[:, None]
    x_of = np.array([x for _, x in rows], dtype=np.int64)[:, None]
    c = np.arange(m, dtype=np.int64)
    check = np.concatenate((((x_of + j*q) % m).ravel(), c, c[1:]))
    bit = np.concatenate(((i_of*group + j).ravel(), k + c, k + c[1:] - 1))
    flat = bit[np.argsort(check, kind="stable")]
    ends = np.cumsum(np.bincount(check, minlength=m)).tolist()
    return [flat[a:b] for a, b in zip([0] + ends[:-1], ends)]

ira_encode

ira_encode(bits, n, k, table, group=360)

Systematic encoder for the same construction: [information | parity]

Source code in src/rpps/code/types/ira.py
def ira_encode(bits, n, k, table, group=360):
    """Systematic encoder for the same construction: [information | parity]"""
    m = n - k
    q = m // group
    u = np.asarray(bits, dtype=np.uint8).reshape(-1, k)
    out = np.zeros((len(u), n), dtype=np.uint8)
    out[:, :k] = u
    p = np.zeros((len(u), m), dtype=np.uint8)
    for i, row in enumerate(table):
        for x in row:
            addr = (np.asarray(x) + np.arange(group)*q) % m
            p[:, addr] ^= u[:, i*group:(i+1)*group]
    p = np.bitwise_xor.accumulate(p, axis=1)
    out[:, k:] = p
    return out.reshape(-1).astype(bool)

layout

Where a block code's bits go in the word sent, and what is done to them on the way: keys of any block definition

"layout": the sent position of each codeword bit (codeword order: the code's own, message first for linear, cyclic,
          bch, rs...), as a list (or {"each": ..., "n": N}), or {"message": [...], "parity": [...]} with "rest" for
          one of them (the positions the other leaves, in order)
"xor":    a fixed pattern on the sent word (a coset: inverted or masked parity), a number of n bits (first sent bit
          most significant) or a list of bits
"append": check bits after the codeword (before the layout), each the XOR of the codeword bits it lists (indices
          into the codeword and the bits appended before it): P25's NID bit 64 is [[14, 15]]. Checked after the
          inner decode: a mismatch is one more error, a failure past the code's `t`
"extend": an overall parity bit, of every bit before it (an extended code); a code with matrices (linear, cyclic,
          expr) builds it into them, any other gets it appended here

On encode: the code, the appended bits, the layout, the pattern; on decode the same undone in reverse, on bits or LLRs alike.

Classes:

Name Description
arranged

A block code with check bits appended (append, extend), its bits placed (layout) and masked (xor) as sent.

Functions:

Name Description
layout_perm

to map of a layout spec: codeword bit j goes to sent position perm[j], for an n-bit word

arranged

arranged(log, inner, layout=None, xor=None, extend=False, dec=None, append=None)

Bases: _code

A block code with check bits appended (append, extend), its bits placed (layout) and masked (xor) as sent. inner: the code (its encoder), dec: what decodes it (default: the code itself). Decode status is the decoder's, plus each appended bit that disagrees with the decision

Methods:

Name Description
with_decoder

The same arrangement decoded by dec (a decoder built from inner)

Source code in src/rpps/code/types/layout.py
def __init__(self, log, inner, layout=None, xor=None, extend=False, dec=None, append=None):
    eqs = [np.asarray(e, dtype=np.int64) for e in (append or [])]
    n0 = inner.den
    for j, e in enumerate(eqs):
        if len(e) == 0 or e.min() < 0 or e.max() >= n0 + j:
            raise ValueError(f"append {j}: codeword bits 0..{n0 + j - 1}, not {e.tolist()}")
    if extend: # Overall parity: of every bit before it
        eqs.append(np.arange(n0 + len(eqs)))
    n = n0 + len(eqs)
    super().__init__(log, getattr(inner, "name", None), inner.num, n)
    self.inner, self.eqs = inner, eqs
    self.dec = inner if dec is None else dec
    self.soft = getattr(self.dec, "soft", False)
    self.t = getattr(self.dec, "t", None)
    if self.t is None:
        self.t = getattr(inner, "t", None)
    self.to = None if layout is None else layout_perm(layout, n) # codeword bit j -> sent position to[j]
    self.mask = None if xor is None else xor_mask(xor, n)
with_decoder
with_decoder(dec)

The same arrangement decoded by dec (a decoder built from inner)

Source code in src/rpps/code/types/layout.py
def with_decoder(self, dec):
    """The same arrangement decoded by `dec` (a decoder built from `inner`)"""
    import copy
    out = copy.copy(self)
    out.dec, out.soft = dec, getattr(dec, "soft", False)
    out.t = getattr(dec, "t", None) if getattr(dec, "t", None) is not None else self.t
    return out

layout_perm

layout_perm(spec, n)

to map of a layout spec: codeword bit j goes to sent position perm[j], for an n-bit word

Source code in src/rpps/code/types/layout.py
def layout_perm(spec, n):
    """`to` map of a layout spec: codeword bit j goes to sent position perm[j], for an n-bit word"""
    if isinstance(spec, dict):
        if set(spec) - {"message", "parity", "comment"} or not {"message", "parity"} <= set(spec):
            raise ValueError(f"layout {spec}: give \"message\" and \"parity\" (one of them may be \"rest\")")
        msg, par = spec["message"], spec["parity"]
        if msg == "rest" and par == "rest":
            raise ValueError("layout: only one of message / parity can be \"rest\"")
        given = [int(p) for p in (par if msg == "rest" else msg)]
        rest = [p for p in range(n) if p not in set(given)]
        perm = rest + given if msg == "rest" else given + ([int(p) for p in par] if par != "rest" else rest)
    else:
        perm = [int(p) for p in spec]
    perm = np.asarray(perm, dtype=np.int64)
    if len(perm) != n or not np.array_equal(np.sort(perm), np.arange(n)):
        raise ValueError(f"layout: not a placement of the {n} codeword bits on {n} positions (repeated, missing or out of range)")
    return perm

ldpc

Classes:

Name Description
ldpc

Linear code defined by sparse parity checks, decoded by belief propagation (normalised min-sum or sum-product)

Functions:

Name Description
gallager

Regular (wc, wr) parity-check matrix by Gallager's construction. n must be a multiple of wr

qc_checks

The checks of a quasi-cyclic code: (n, checks) from a base matrix of shifts (an entry s >= 0 is the z x z identity

ldpc

ldpc(log, n, checks, k=None, systematic_pos=None, iters=50, alpha=0.8)

Bases: _code

Linear code defined by sparse parity checks, decoded by belief propagation (normalised min-sum or sum-product)

n: codeword length checks: for each parity check, the codeword positions it covers k/systematic: the message length, and where the message sits in the codeword: "head", "tail" or a list of positions. When omitted both come from GF(2) elimination, which needs a dense H (small codes only) iters/alpha: maximum iterations / min-sum normalisation schedule: "layered" (the default: a layer of checks at a time, each codeword stopping once every check holds) or "flooding" (every check from the same totals, iters iterations: what flood gives the blind tools) check: the layered schedule's check update, "minsum" (the default: alpha times the smallest other |q|) or "sumproduct" (exact: phi of the sum of the others' phi|q|, phi(x) = -log tanh(x/2); about 0.3 dB on DVB-S2 1/2 in fewer iterations, each dearer). The effort level picks it (rpps._effort: max decodes sum-product); flooding is always min-sum decode() takes hard bits or LLRs (log(P(0)/P(1)), positive means 0) for whole codewords, returns the message. decode(x, status=True) also gives each codeword's status: -1 where it did not satisfy every parity check. With rpps._native the codewords are decoded on several threads, each stopping as soon as it converges (the numpy decoder iterates the whole batch until every codeword has).

Methods:

Name Description
check_of

The check update a definition names (default min-sum)

syndrome

Parity check failures for words (B, N), without a dense H: (B, M), or (B, checks) for only the first checks

decode_codewords

Min-sum on (B, N) LLRs: hard decisions (B, N) and which codewords satisfied every check (B,)

layers

The checks in layers that share no variable (greedy colouring, rows in order), computed once per code: the layered

flood

Flooding normalized min-sum on (B, N) LLRs for iters iterations (default the code's), every check from the same

propagate

Belief propagation by the code's schedule: (hard decisions (B, N), converged (B,))

layered

Layered belief propagation on (B, N) LLRs, normalized min-sum or sum-product (check, as the effort level says):

Source code in src/rpps/code/types/ldpc.py
def __init__(self, log, n, checks, k=None, systematic_pos=None, iters=50, alpha=0.8):
    self.n = n
    self.checks = [np.asarray(c, dtype=np.int64) for c in checks]
    self._G = None
    if systematic_pos is None and k is None:
        self._G, info = systematic(self.dense())
        k = len(info)
    elif isinstance(systematic_pos, str):
        info = np.arange(k) if systematic_pos == "head" else np.arange(n-k, n)
    elif systematic_pos is None:
        raise ValueError("k needs `systematic` (head, tail or positions), or neither")
    else:
        info = np.asarray(systematic_pos, dtype=np.int64)
        k = len(info)
    self.info = info
    super().__init__(log, None, k, n)
    self.iters = iters
    self.alpha = alpha

    M = len(self.checks)
    self.M, self.N = M, n
    deg = np.array([len(c) for c in self.checks])
    self.deg = deg.astype(np.int64)
    self.var = np.concatenate(self.checks) # Edges, grouped by check
    self.dmax = int(deg.max())
    self.cstart = np.concatenate(([0], np.cumsum(deg)[:-1]))
    self.slot = np.full((M, self.dmax), -1, dtype=np.int64) # Edge index per (check, slot)
    for d in range(self.dmax):
        ok = deg > d
        self.slot[ok, d] = self.cstart[ok] + d
    self.valid = self.slot >= 0
check_of classmethod
check_of(obj)

The check update a definition names (default min-sum)

Source code in src/rpps/code/types/ldpc.py
@classmethod
def check_of(cls, obj):
    """The check update a definition names (default min-sum)"""
    check = obj.get("check", "minsum")
    if check not in cls.CHECKS:
        raise ValueError(f"ldpc: check {check!r}, one of {cls.CHECKS}")
    return check
syndrome
syndrome(words, checks=None)

Parity check failures for words (B, N), without a dense H: (B, M), or (B, checks) for only the first checks

Source code in src/rpps/code/types/ldpc.py
def syndrome(self, words, checks=None):
    """Parity check failures for words (B, N), without a dense H: (B, M), or (B, checks) for only the first `checks`"""
    w = np.asarray(words, dtype=np.uint8)
    if checks is None or checks >= self.M:
        var, start = self.var, self.cstart
    else:
        start = self.cstart[:checks]
        var = self.var[:int(self.cstart[checks])]
    return (np.add.reduceat(w[:, var], start, axis=1) % 2).astype(np.uint8)
decode_codewords
decode_codewords(llr)

Min-sum on (B, N) LLRs: hard decisions (B, N) and which codewords satisfied every check (B,)

Source code in src/rpps/code/types/ldpc.py
def decode_codewords(self, llr):
    """Min-sum on (B, N) LLRs: hard decisions (B, N) and which codewords satisfied every check (B,)"""
    return self.propagate(llr)
layers
layers()

The checks in layers that share no variable (greedy colouring, rows in order), computed once per code: the layered schedule updates a layer at a time, each layer seeing what the ones before it found

Source code in src/rpps/code/types/ldpc.py
def layers(self):
    """The checks in layers that share no variable (greedy colouring, rows in order), computed once per code: the layered
    schedule updates a layer at a time, each layer seeing what the ones before it found"""
    key = (self.N, self.M, hash(self.var.tobytes()), hash(self.deg.tobytes()))
    if key not in _LAYERS:
        used, rows = [], []
        for r, c in enumerate(self.checks):
            vs = set(c.tolist())
            for u, lst in zip(used, rows):
                if not (u & vs):
                    u |= vs
                    lst.append(r)
                    break
            else:
                used.append(vs)
                rows.append([r])
        _LAYERS[key] = [np.array(l, dtype=np.int64) for l in rows]
    return _LAYERS[key]
flood
flood(llr, iters=None)

Flooding normalized min-sum on (B, N) LLRs for iters iterations (default the code's), every check from the same totals: the a-posteriori LLRs (B, N), what the checks say about each bit. The C++ kernel ldpc_flood runs the same loop (this is its reference)

Source code in src/rpps/code/types/ldpc.py
def flood(self, llr, iters=None):
    """Flooding normalized min-sum on (B, N) LLRs for `iters` iterations (default the code's), every check from the same
    totals: the a-posteriori LLRs (B, N), what the checks say about each bit. The C++ kernel ldpc_flood runs the same loop
    (this is its reference)"""
    iters = self.iters if iters is None else int(iters)
    llr = np.asarray(llr, dtype=np.float64)
    idx = np.where(self.valid, self.var[np.maximum(self.slot, 0)], 0)
    if _accel.native is not None:
        return _accel.native.ldpc_flood(np.ascontiguousarray(llr), np.ascontiguousarray(idx), self.deg, iters, float(self.alpha))
    B, dmax, valid, alpha = len(llr), self.dmax, self.valid, self.alpha
    msg = np.zeros((B, self.M, dmax))
    total = llr.copy()
    flat = idx[valid]
    for _ in range(iters):
        q = total[:, idx] - msg # (B, c, dmax): variable to check, without the check's own message
        a = np.where(valid[None], np.abs(q), np.inf)
        neg = (q < 0) & valid[None]
        sgn = np.where(neg.sum(axis=2, keepdims=True) % 2 == 1, -1.0, 1.0)*np.where(neg, -1.0, 1.0)
        i1 = np.argmin(a, axis=2)[..., None]
        m1 = np.take_along_axis(a, i1, axis=2)
        a2 = a.copy()
        np.put_along_axis(a2, i1, np.inf, axis=2)
        m2 = a2.min(axis=2, keepdims=True)
        m2 = np.where(np.isinf(m2), m1, m2)
        msg = np.where(valid[None], alpha*sgn*np.where(np.arange(dmax)[None, None, :] == i1, m2, m1), 0.0)
        total = llr.copy()
        np.add.at(total.T, flat, msg[:, valid].T)
    return total
propagate
propagate(llr)

Belief propagation by the code's schedule: (hard decisions (B, N), converged (B,))

Source code in src/rpps/code/types/ldpc.py
def propagate(self, llr):
    """Belief propagation by the code's schedule: (hard decisions (B, N), converged (B,))"""
    if self.schedule == "flooding":
        total = self.flood(llr, _effort.scale("iters", self.iters))
        return total < 0, ~self.syndrome(total < 0).any(axis=1)
    return self.layered(llr)
layered
layered(llr)

Layered belief propagation on (B, N) LLRs, normalized min-sum or sum-product (check, as the effort level says): (hard decisions (B, N), converged (B,)). Each codeword stops when every check holds. Layered (a layer of checks at a time, the variables updated after each) converges in about half the iterations of flooding: at Eb/N0 0.9 dB (DVB-S2 1/2 normal frame) 50 layered iterations decode what 100 flooding did. Keeps nothing on the code, so threads can share it

Source code in src/rpps/code/types/ldpc.py
def layered(self, llr):
    """Layered belief propagation on (B, N) LLRs, normalized min-sum or sum-product (`check`, as the effort level says):
    (hard decisions (B, N), converged (B,)). Each codeword stops when every check holds. Layered (a layer of checks at
    a time, the variables updated after each) converges in about half the iterations of flooding: at Eb/N0 0.9 dB
    (DVB-S2 1/2 normal frame) 50 layered iterations decode what 100 flooding did. Keeps nothing on the code, so
    threads can share it"""
    layers = self.layers()
    iters = _effort.scale("iters", self.iters)
    sp = _effort.choice("check", self.check) == "sumproduct"
    if _accel.native is not None:
        args = (np.ascontiguousarray(llr, dtype=np.float64), self.var, self.cstart.astype(np.int64), self.deg, np.concatenate(layers), iters)
        return _accel.native.ldpc_sumproduct(*args) if sp else _accel.native.ldpc_minsum(*args, float(self.alpha))
    total = np.array(llr, dtype=np.float64) # (B, N): the a-posteriori values
    r = np.zeros((total.shape[0], len(self.var))) # check to variable messages, per edge
    done = np.zeros(total.shape[0], dtype=bool)
    cols = np.arange(self.dmax)
    for _ in range(iters):
        act = np.nonzero(~done)[0] # (a codeword that has converged stops, as in the C++ decoder)
        if not len(act):
            break
        t, rr = total[act], r[act]
        for rows in layers:
            ok = self.valid[rows]
            e = np.where(ok, self.slot[rows], 0) # (rows, dmax) edges
            q = np.where(ok[None], t[:, self.var[e]] - rr[:, e], np.inf) # variable to check, without this check's own
            a = np.abs(q)
            neg = (q < 0) & ok[None]
            sgn = np.where(neg.sum(axis=2, keepdims=True) % 2 == 1, -1.0, 1.0)*np.where(neg, -1.0, 1.0)
            if sp:
                p = np.where(ok[None], _phi(a), 0.0)
                new = sgn*_phi(p.sum(axis=2, keepdims=True) - p)
            else:
                i1 = np.argmin(a, axis=2)
                m1 = np.take_along_axis(a, i1[..., None], axis=2)
                a2 = a.copy()
                np.put_along_axis(a2, i1[..., None], np.inf, axis=2)
                m2 = a2.min(axis=2, keepdims=True)
                new = self.alpha*sgn*np.where(cols[None, None, :] == i1[..., None], m2, m1)
            ev = e[ok]
            rr[:, ev] = new[:, ok]
            t[:, self.var[ev]] = q[:, ok] + new[:, ok]
        total[act], r[act] = t, rr
        done[act] = ~self.syndrome(t < 0).any(axis=1)
    return total < 0, done

gallager

gallager(n, wc=3, wr=6, seed=0)

Regular (wc, wr) parity-check matrix by Gallager's construction. n must be a multiple of wr

Source code in src/rpps/code/types/ldpc.py
def gallager(n, wc=3, wr=6, seed=0):
    """Regular (wc, wr) parity-check matrix by Gallager's construction. n must be a multiple of wr"""
    if n % wr:
        raise ValueError(f"n={n} must be a multiple of wr={wr}")
    rng = np.random.default_rng(seed)
    rows = n // wr
    base = np.zeros((rows, n), dtype=bool)
    for r in range(rows):
        base[r, r*wr:(r+1)*wr] = True
    return np.vstack([base] + [base[:, rng.permutation(n)] for _ in range(wc-1)])

qc_checks

qc_checks(base, z)

The checks of a quasi-cyclic code: (n, checks) from a base matrix of shifts (an entry s >= 0 is the z x z identity shifted right by s: row r of the block has its 1 at column (r + s) % z; -1 or None is a zero block)

Source code in src/rpps/code/types/ldpc.py
def qc_checks(base, z):
    """The checks of a quasi-cyclic code: (n, checks) from a base matrix of shifts (an entry s >= 0 is the z x z identity
    shifted right by s: row r of the block has its 1 at column (r + s) % z; -1 or None is a zero block)"""
    z = int(z)
    B = [[-1 if v is None else int(v) for v in row] for row in base]
    nb = len(B[0])
    checks = []
    for row in B:
        if len(row) != nb:
            raise ValueError("every row of the base matrix has the same number of blocks")
        for r in range(z):
            checks.append(np.array([j*z + (r + s) % z for j, s in enumerate(row) if s >= 0], dtype=np.int64))
    return nb*z, checks

linear

Classes:

Name Description
linear

Linear block code from its matrices, systematic with the message first. Own decoder: single-error syndrome

Functions:

Name Description
parity_rows

The (k, n-k) parity block of parity equations: parity bit j is the XOR of the message bits parity[j] lists

extended

(G, H) with an overall parity bit after the codeword: each generator row gets its weight's parity, and the check

linear

linear(log, generator, check)

Bases: _code

Linear block code from its matrices, systematic with the message first. Own decoder: single-error syndrome correction (the trellis decoder is the default, syndrome corrects up to t errors)

Methods:

Name Description
from_config

One of: "g" + "h" (the matrices), "p" (the k rows of the parity block, n and k) or "parity" (each of the n-k

Source code in src/rpps/code/types/linear.py
def __init__(self, log, generator, check):
    super().__init__(log, None, generator.shape[0], generator.shape[1])
    self.generator = generator
    self.check = np.transpose(check)
from_config classmethod
from_config(log, obj)

One of: "g" + "h" (the matrices), "p" (the k rows of the parity block, n and k) or "parity" (each of the n-k parity bits as the message bits it XORs: [[0, 1, 3], ...], the way standards write P0 = I0 + I1 + I3; n and k). "extend": an overall parity bit after the codeword

Source code in src/rpps/code/types/linear.py
@classmethod
def from_config(cls, log, obj):
    """One of: "g" + "h" (the matrices), "p" (the k rows of the parity block, n and k) or "parity" (each of the n-k
    parity bits as the message bits it XORs: [[0, 1, 3], ...], the way standards write P0 = I0 + I1 + I3; n and k).
    "extend": an overall parity bit after the codeword"""
    forms = [f for f in ("p", "parity", "g") if obj.get(f) is not None]
    if len(forms) != 1:
        raise ValueError(f"linear code: give one of \"g\" (with \"h\"), \"p\" or \"parity\", not {forms or 'none'}")
    if forms == ["g"]: # Explicit generator and check matrices: (n, k) are their shape
        g, h = np.array(obj["g"], dtype=np.uint8), np.array(obj["h"], dtype=np.uint8)
    else:
        n, k = int(obj["n"]), int(obj["k"])
        p = np.array(obj["p"], dtype=np.uint8) if forms == ["p"] else parity_rows(obj["parity"], n, k)
        g, h = parity_to_gh(n, k, p)
    if obj.get("extend"):
        g, h = extended(g, h)
    code = cls(log, g, h)
    code.t = obj.get("t") # errors a syndrome decoder corrects: needed where the minimum distance is too costly to find
    return code

parity_rows

parity_rows(parity, n, k)

The (k, n-k) parity block of parity equations: parity bit j is the XOR of the message bits parity[j] lists

Source code in src/rpps/code/types/linear.py
def parity_rows(parity, n, k):
    """The (k, n-k) parity block of parity equations: parity bit j is the XOR of the message bits parity[j] lists"""
    if len(parity) != n - k:
        raise ValueError(f"parity: {len(parity)} equations for {n - k} parity bits")
    p = np.zeros((k, n - k), dtype=np.uint8)
    for j, eq in enumerate(parity):
        for i in eq:
            if not 0 <= int(i) < k:
                raise ValueError(f"parity bit {j}: message bit {i} is not one of 0..{k-1}")
            p[int(i), j] ^= 1
    return p

extended

extended(G, H)

(G, H) with an overall parity bit after the codeword: each generator row gets its weight's parity, and the check matrix a row of ones over every bit

Source code in src/rpps/code/types/linear.py
def extended(G, H):
    """(G, H) with an overall parity bit after the codeword: each generator row gets its weight's parity, and the check
    matrix a row of ones over every bit"""
    G, H = np.asarray(G, dtype=np.uint8), np.asarray(H, dtype=np.uint8)
    G2 = np.concatenate((G, (G.sum(axis=1) % 2)[:, None].astype(np.uint8)), axis=1)
    H2 = np.concatenate((np.concatenate((H, np.zeros((len(H), 1), np.uint8)), axis=1), np.ones((1, G2.shape[1]), np.uint8)))
    return G2, H2

nr_ldpc

5G NR LDPC code with its rate matching (3GPP TS 38.212 5.2.2, 5.3.2, 5.4.2): one code block, K' bits to E bits

{"base": "block", "type": "nr_ldpc", "bg": 1,
 "graph": [[[column, V(set 0), ..., V(set 7)], ...], ...],   the base graph's rows (Tables 5.3.2-2, 5.3.2-3)
 "kp": 8448,               K': the code block's bits (CRC included); the rest of its K = 22 Z (BG2: 10 Z) are filler
 "z": 0,                   the lifting size (0: the smallest Z of any set with Kb Z >= K', 5.2.2)
 "kb": null,               BG2's Kb (default from K' as one block's B: 10 above 640, 9 above 560, 8 above 192, else 6)
 "e": 25344, "rv": 0,      bits sent and the redundancy version (where the circular buffer is read from)
 "qm": 1,                  the modulation order the bit interleaver groups by (5.4.2.2; 1: none)
 "ncb": null,              the circular buffer (limited buffer rate matching; default N)
 "iters": 25, "alpha": 0.8}

The parity-check matrix lifts the base graph by Z: an entry V of row i, column j is the Z x Z identity shifted right by V mod Z (the set of Table 5.3.2-1 that holds Z picks V's column). The codeword is the K bits and the parity, 68 Z bits (BG2 52 Z), of which the first 2 Z are never sent: N = 66 Z (50 Z) go into the circular buffer. Encoding solves the 4 Z core parity bits through the core's inverse (once per graph and Z), then every extension row in turn (each ends on an identity). Decoding: the punctured bits erased, the filler known, layered min-sum (rpps.code.types.ldpc).

encode(): K' bits a block to E. decode(): E soft bits (positive = 0) a block to K' bits; errors -1 where the checks did not all hold (the transport block's CRC is its caller's). segment(B, bg) and base_graph(A, R) give what a transport block's size picks (5.2.2, 7.2.2).

Classes:

Name Description
nr_ldpc

One 5G NR LDPC code block (see the module)

Functions:

Name Description
lifting

The smallest Z of any set with kb Z >= K'

base_graph

The base graph of a transport block of A bits at code rate R (7.2.2)

segment

Code block segmentation (5.2.2) of B bits (the transport block and its CRC): (C blocks, K' bits each with their

nr_ldpc

nr_ldpc(log, bg, graph, kp, e, z=None, kb=None, rv=0, qm=1, ncb=None, iters=25, alpha=0.8)

Bases: ldpc

One 5G NR LDPC code block (see the module)

Methods:

Name Description
codeword

The 68 Z (52 Z) bits of each row of K bits (filler as 0)

codeword_llr

(W, E) soft bits to (W, 68 Z) of the codeword: the punctured erased, the filler known, repetitions added

Source code in src/rpps/code/types/nr_ldpc.py
def __init__(self, log, bg, graph, kp, e, z=None, kb=None, rv=0, qm=1, ncb=None, iters=25, alpha=0.8):
    self.bg, self.kp, self.E, self.rv, self.qm = int(bg), int(kp), int(e), int(rv), int(qm)
    rows, cols, ks = SHAPE[self.bg]
    if len(graph) != rows:
        raise ValueError(f"nr_ldpc: base graph {bg} has {rows} rows, the definition {len(graph)}")
    self.Z = int(z) if z else lifting(self.kp, int(kb) if kb is not None else kb_of(self.bg, self.kp))
    Z, ils = self.Z, set_of(self.Z)
    self.K = ks*Z
    if self.kp > self.K:
        raise ValueError(f"nr_ldpc: K' {self.kp} is more than K = {self.K} (Z {Z})")
    self.graph = [[(int(r[0]), int(r[1 + ils]) % Z) for r in row] for row in graph]
    key = (self.bg, hash(str(graph)))
    _GRAPHS.setdefault(key, graph)
    self._key = key
    base = [[-1]*cols for _ in range(rows)]
    for i, row in enumerate(self.graph):
        for j, s in row:
            base[i][j] = s
    from .ldpc import qc_checks
    n, checks = qc_checks(base, Z)
    super().__init__(log, n, checks, self.K, "head", iters, alpha)
    self.num, self.den = self.kp, self.E # (K' bits in, E out: what the operators count)
    self.Nd = (cols - 2)*Z # N: what goes into the buffer, from the codeword's bit 2Z on
    self.ncb = self.Nd if ncb is None else min(int(ncb), self.Nd)
    filler = np.zeros(self.Nd, bool)
    filler[self.kp - 2*Z:self.K - 2*Z] = True # (the filler is in the systematic part, past the punctured 2Z)
    k0 = K0[self.bg][self.rv]*self.ncb//((cols - 2)*Z)*Z
    sel, j = [], 0
    while len(sel) < self.E:
        p = (k0 + j) % self.ncb
        if not filler[p]:
            sel.append(p)
        j += 1
        if j > self.E + 4*self.ncb:
            raise ValueError("nr_ldpc: nothing to send in the circular buffer")
    sel = np.array(sel, np.int64)
    if self.qm > 1: # 5.4.2.2: f[i + j Qm] = e[i E/Qm + j]
        if self.E % self.qm:
            raise ValueError(f"nr_ldpc: E {self.E} is not a multiple of Qm {self.qm}")
        sel = sel.reshape(self.qm, self.E//self.qm).T.reshape(-1)
    self.index = sel + 2*Z # Codeword bit of each bit sent
codeword
codeword(c)

The 68 Z (52 Z) bits of each row of K bits (filler as 0)

Source code in src/rpps/code/types/nr_ldpc.py
def codeword(self, c):
    """The 68 Z (52 Z) bits of each row of K bits (filler as 0)"""
    c = np.atleast_2d(np.asarray(c, np.uint8))
    W, Z = len(c), self.Z
    rows, cols, ks = SHAPE[self.bg]
    x = np.zeros((W, cols, Z), np.uint8)
    x[:, :ks] = c.reshape(W, ks, Z)
    lam = np.zeros((W, 4, Z), np.uint8)
    for i in range(4):
        for j, s in self.graph[i]:
            if j < ks:
                lam[:, i] ^= _rot(x[:, j], s)
    p = (lam.reshape(W, 4*Z).astype(np.int64) @ _core_inverse(self._key, self.bg, Z).T.astype(np.int64)) % 2
    x[:, ks:ks + 4] = p.reshape(W, 4, Z)
    for i in range(4, rows):
        acc = np.zeros((W, Z), np.uint8)
        for j, s in self.graph[i]:
            if j < ks + 4:
                acc ^= _rot(x[:, j], s)
        x[:, ks + i] = acc # (row i ends on the identity at column ks + i)
    return x.reshape(W, cols*Z)
codeword_llr
codeword_llr(llr)

(W, E) soft bits to (W, 68 Z) of the codeword: the punctured erased, the filler known, repetitions added

Source code in src/rpps/code/types/nr_ldpc.py
def codeword_llr(self, llr):
    """(W, E) soft bits to (W, 68 Z) of the codeword: the punctured erased, the filler known, repetitions added"""
    llr = np.atleast_2d(np.asarray(llr, float))
    full = np.zeros((len(llr), self.n))
    np.add.at(full, (slice(None), self.index), llr)
    full[:, self.kp:self.K] = KNOWN
    return full

lifting

lifting(kp, kb)

The smallest Z of any set with kb Z >= K'

Source code in src/rpps/code/types/nr_ldpc.py
def lifting(kp, kb):
    """The smallest Z of any set with kb Z >= K'"""
    return min(z for s in SETS for z in s if kb*z >= kp)

base_graph

base_graph(A, R)

The base graph of a transport block of A bits at code rate R (7.2.2)

Source code in src/rpps/code/types/nr_ldpc.py
def base_graph(A, R):
    """The base graph of a transport block of A bits at code rate R (7.2.2)"""
    return 2 if (A <= 292 or (A <= 3824 and R <= 0.67) or R <= 0.25) else 1

segment

segment(B, bg)

Code block segmentation (5.2.2) of B bits (the transport block and its CRC): (C blocks, K' bits each with their CRC-24B when C > 1, K bits after the filler, Z)

Source code in src/rpps/code/types/nr_ldpc.py
def segment(B, bg):
    """Code block segmentation (5.2.2) of B bits (the transport block and its CRC): (C blocks, K' bits each with their
    CRC-24B when C > 1, K bits after the filler, Z)"""
    kcb = 8448 if bg == 1 else 3840
    if B <= kcb:
        C, Bp = 1, B
    else:
        C = -(-B//(kcb - 24))
        Bp = B + 24*C
    kp = -(-Bp//C)
    Z = lifting(kp, kb_of(bg, B))
    return C, kp, SHAPE[bg][2]*Z, Z

nr_polar

5G NR polar code with its rate matching (3GPP TS 38.212 5.3.1, 5.4.1): K bits, CRC included, to E bits

{"base": "block", "type": "nr_polar", "K": 56, "E": 864,
 "nmax": 9,                    the largest code, 2^nmax bits (9: downlink, 10: uplink)
 "interleave": true,           the input interleaver of 5.3.1.1 (I_IL: downlink)
 "bil": false,                 the coded-bit interleaver of 5.4.1.3 (I_BIL: uplink)
 "crc": "crc/crc24_nr_c",      the CRC the last bits of the K carry (the list decoder picks the path it checks)
 "ones": 24,                   the CRC computed over that many ones before the message (a DCI's)
 "list": 8}

N = 2^n from E and K (5.3.1); the K information positions are the most reliable of the polar sequence (config table nr/polar_sequence) below N, past those the rate matching punctures or shortens (5.4.1.1); the N coded bits go through the 32-part sub-block interleaver into a circular buffer, read by repetition (E >= N), puncturing (K/E <= 7/16: the first N - E not sent) or shortening (the last N - E not sent, known zeros). No parity-check bits (n_PC = 0: an uplink control message of 12 to 19 bits is not covered).

encode(): messages of K - crc bits, the CRC attached (mask: XORed onto the last 16 CRC bits, an RNTI), to E bits each. decode(): E soft bits (positive = 0) a codeword; the punctured positions erased, the shortened known, repetitions added; then a list decoder (rpps.code.types.polar.scl) and the first path whose CRC checks; errors -1 when none does. paths(x): every path's K bits (deinterleaved, CRC included) and metric, for a blind search over masks (a PDCCH's RNTIs).

Classes:

Name Description
nr_polar

The 5G NR polar code of K bits sent as E (see the module)

Functions:

Name Description
sequence

Bit indices below N from least to most reliable (5.3.1.2)

input_pattern

Pi(k) of the input interleaver for K bits (5.3.1.1)

code_size

n of N = 2^n (5.3.1)

subblock

J(n): the coded bit the sub-block interleaver puts at n (5.4.1.1)

triangle

The coded-bit interleaver (5.4.1.3): f_k = e_order[k]

nr_polar

nr_polar(log, K, E, nmax=9, interleave=True, bil=False, crc=None, ones=0, size=8, mask=0)

Bases: _code

The 5G NR polar code of K bits sent as E (see the module)

Methods:

Name Description
attach

The K bits: the message and its CRC (over ones ones and the message), the mask on the CRC's last 16 bits

residue

CRC field XOR what the message's CRC is, per row of K bits (..., K): the mask a codeword carries (0: none)

coded_llr

(W, E) soft bits to (W, N) soft bits of d, the code's output

paths

(K bits of every path (W, P, K), deinterleaved, CRC included; metrics (W, P), best first)

Source code in src/rpps/code/types/nr_polar.py
def __init__(self, log, K, E, nmax=9, interleave=True, bil=False, crc=None, ones=0, size=8, mask=0):
    self.K, self.E, self.nmax = int(K), int(E), int(nmax)
    self.crc, self.ones, self.size, self.mask = crc, int(ones), int(size), int(mask)
    self.width = 0 if crc is None else crc.width
    if self.K > self.E or self.K <= self.width:
        raise ValueError(f"nr_polar: K {self.K} needs E >= K and more than the {self.width} CRC bits")
    n = code_size(self.K, self.E, self.nmax)
    N = self.N = 1 << n
    self.J = subblock(N)
    Q = sequence(N)
    frozen_tmp = set()
    if self.E < N:
        if self.K/self.E <= 7/16: # Puncturing
            frozen_tmp |= set(self.J[:N - self.E].tolist())
            top = int(np.ceil(3*N/4 - self.E/2)) if self.E >= 3*N/4 else int(np.ceil(9*N/16 - self.E/4))
            frozen_tmp |= set(range(top))
        else: # Shortening
            frozen_tmp |= set(self.J[self.E:].tolist())
    info = [q for q in Q if q not in frozen_tmp][-self.K:]
    self.info = np.sort(np.array(info, np.int64))
    self.frozen = np.ones(N, bool)
    self.frozen[self.info] = False
    self.pi = input_pattern(self.K) if interleave else np.arange(self.K)
    self.bil = triangle(self.E) if bil else None
    self.punctured = self.E < N and self.K/self.E <= 7/16
    super().__init__(log, f"nr_polar_{self.K}_{self.E}", self.K - self.width, self.E)
attach
attach(msg, mask=None)

The K bits: the message and its CRC (over ones ones and the message), the mask on the CRC's last 16 bits

Source code in src/rpps/code/types/nr_polar.py
def attach(self, msg, mask=None):
    """The K bits: the message and its CRC (over `ones` ones and the message), the mask on the CRC's last 16 bits"""
    msg = np.asarray(msg, np.uint8)
    if self.crc is None:
        return msg
    p = np.asarray(self.crc.field(np.r_[np.ones(self.ones, np.uint8), msg])).astype(np.uint8)
    return np.r_[msg, p ^ self._mask_bits(self.mask if mask is None else mask)]
residue
residue(c)

CRC field XOR what the message's CRC is, per row of K bits (..., K): the mask a codeword carries (0: none)

Source code in src/rpps/code/types/nr_polar.py
def residue(self, c):
    """CRC field XOR what the message's CRC is, per row of K bits (..., K): the mask a codeword carries (0: none)"""
    c = np.asarray(c, np.uint8)
    flat = c.reshape(-1, self.K)
    out = []
    for w in flat:
        p = np.asarray(self.crc.field(np.r_[np.ones(self.ones, np.uint8), w[:self.K - self.width]])).astype(np.uint8)
        r = 0
        for b in (w[self.K - self.width:] ^ p):
            r = (r << 1) | int(b)
        out.append(r)
    return np.array(out).reshape(c.shape[:-1])
coded_llr
coded_llr(llr)

(W, E) soft bits to (W, N) soft bits of d, the code's output

Source code in src/rpps/code/types/nr_polar.py
def coded_llr(self, llr):
    """(W, E) soft bits to (W, N) soft bits of d, the code's output"""
    llr = np.atleast_2d(np.asarray(llr, float))
    W = len(llr)
    if self.bil is not None:
        e = np.zeros_like(llr)
        e[:, self.bil] = llr
        llr = e
    y = np.zeros((W, self.N))
    if self.E >= self.N:
        np.add.at(y, (slice(None), np.arange(self.E) % self.N), llr)
    elif self.punctured:
        y[:, self.N - self.E:] = llr
    else:
        y[:, :self.E] = llr
        y[:, self.E:] = KNOWN
    d = np.zeros_like(y)
    d[:, self.J] = y
    return d
paths
paths(x, soft=None)

(K bits of every path (W, P, K), deinterleaved, CRC included; metrics (W, P), best first)

Source code in src/rpps/code/types/nr_polar.py
def paths(self, x, soft=None):
    """(K bits of every path (W, P, K), deinterleaved, CRC included; metrics (W, P), best first)"""
    llr = as_llr(np.asarray(x), soft)
    llr = llr[:len(llr)//self.E*self.E].reshape(-1, self.E)
    u, pm = scl(self.coded_llr(llr), self.frozen, _effort.scale("list", self.size))
    cp = u[:, :, self.info]
    c = np.zeros_like(cp)
    c[:, :, self.pi] = cp
    return c, pm

sequence

sequence(N)

Bit indices below N from least to most reliable (5.3.1.2)

Source code in src/rpps/code/types/nr_polar.py
def sequence(N):
    """Bit indices below N from least to most reliable (5.3.1.2)"""
    return np.array([q for q in _table("nr/polar_sequence") if q < N], np.int64)

input_pattern

input_pattern(K)

Pi(k) of the input interleaver for K bits (5.3.1.1)

Source code in src/rpps/code/types/nr_polar.py
def input_pattern(K):
    """Pi(k) of the input interleaver for K bits (5.3.1.1)"""
    p = _table("nr/polar_interleave")
    if K > len(p):
        raise ValueError(f"nr_polar: the input interleaver takes up to {len(p)} bits, not {K}")
    return np.array([v - (len(p) - K) for v in p if v >= len(p) - K], np.int64)

code_size

code_size(K, E, nmax)

n of N = 2^n (5.3.1)

Source code in src/rpps/code/types/nr_polar.py
def code_size(K, E, nmax):
    """n of N = 2^n (5.3.1)"""
    le = int(np.ceil(np.log2(E)))
    n1 = le - 1 if (E <= 9/8*2**(le - 1) and K/E < 9/16) else le
    n2 = int(np.ceil(np.log2(8*K)))
    return max(min(n1, n2, nmax), 5)

subblock

subblock(N)

J(n): the coded bit the sub-block interleaver puts at n (5.4.1.1)

Source code in src/rpps/code/types/nr_polar.py
def subblock(N):
    """J(n): the coded bit the sub-block interleaver puts at n (5.4.1.1)"""
    n = np.arange(N)
    return np.array(SUBBLOCK)[32*n//N]*(N//32) + n % (N//32)

triangle

triangle(E)

The coded-bit interleaver (5.4.1.3): f_k = e_order[k]

Source code in src/rpps/code/types/nr_polar.py
def triangle(E):
    """The coded-bit interleaver (5.4.1.3): f_k = e_order[k]"""
    T = int(np.ceil((np.sqrt(8*E + 1) - 1)/2))
    v = -np.ones((T, T), np.int64)
    k = 0
    for i in range(T):
        for j in range(T - i):
            if k < E:
                v[i, j] = k
            k += 1
    order = [v[i, j] for j in range(T) for i in range(T - j) if v[i, j] >= 0]
    return np.array(order, np.int64)

polar

Polar codes (Arikan): encoding, successive cancellation (SC) and list decoding (SCL), CRC-aided

{"base": "block", "type": "polar", "n": 256, "k": 128,
 "frozen": [...]                       the frozen positions of u, or
 "order": "pw" | "bhattacharyya",      the N - K least reliable positions of a construction (polarization weight,
 "design_db": 0.0,                     the beta-expansion NR follows; Bhattacharyya parameters at Es/N0 design_db)
 "list": 8,                            paths kept (1: successive cancellation)
 "crc": "crc/crc16_xmodem"}            CRC-aided: the last `width` information bits carry a CRC of the others, and the
                                       list decoder picks the best path whose CRC checks (k counts the CRC bits)

A codeword is x = u G, G = F^(x n) with F = [[1, 0], [1, 1]] (no bit reversal); u holds the message at the information positions (in increasing order) and 0 at the frozen ones. G is its own inverse.

Decoding works on LLRs (log P(0)/P(1)), hard bits becoming +-1. SC decides each u_i in order from its LLR given the decisions before it; SCL keeps the list most likely paths, each scored by the penalty sum of log(1 + e^-(1-2u)L) (Balatsoukas-Stimming, Parizi, Burg, "LLR-based successive cancellation list decoding of polar codes", IEEE TSP 2015). Every frame of a call is decoded at once (arrays over frames and paths). errors per codeword: bits the chosen codeword differs from the hard decisions, or -1 when a CRC-aided decoder found no path that checks.

sc(llr, decide), transform, pw_order and bhattacharyya_order are what the blind tools build on (rpps.analysis.code.block.polar).

Classes:

Name Description
polar

A polar code (see the module): info the information positions, crc the CRC the last bits of the message carry

Functions:

Name Description
transform

G = F^(x n) for N = 2^n, uint8

encode_u

x = u G for rows u (..., N), by the butterflies (N log N XORs)

pw_order

Positions from least to most reliable by polarization weight (sum of 2^(j/4) over the index's set bits j: the

bhattacharyya_order

Positions from least to most reliable by the Bhattacharyya parameter on a BI-AWGN channel at Es/N0 design_db

box

LLR of the parity of two bits (exact box-plus)

sc

Successive-cancellation decoding of frames (W, N) of LLRs, every frame at once. decide(i, L) -> (W,) bits: u_i of

scl

List decoding of frames (W, N) of LLRs: the size best paths of each frame, best first. frozen: (N,) bool.

polar

polar(log, n, k, frozen, size=1, crc=None)

Bases: _code

A polar code (see the module): info the information positions, crc the CRC the last bits of the message carry

Source code in src/rpps/code/types/polar.py
def __init__(self, log, n, k, frozen, size=1, crc=None):
    self.N, self.K = int(n), int(k)
    transform(self.N)
    frozen = np.sort(np.asarray(frozen, dtype=np.int64))
    if len(frozen) != self.N - self.K or len(np.unique(frozen)) != len(frozen) or (len(frozen) and not 0 <= frozen[0] <= frozen[-1] < self.N):
        raise ValueError(f"polar ({self.N}, {self.K}): needs {self.N - self.K} distinct frozen positions below {self.N}")
    self.frozen = np.zeros(self.N, bool)
    self.frozen[frozen] = True
    self.info = np.flatnonzero(~self.frozen)
    self.size, self.crc = int(size), crc
    self.width = 0 if crc is None else crc.width
    if self.width >= self.K:
        raise ValueError(f"polar ({self.N}, {self.K}): a {self.width}-bit CRC leaves no message")
    super().__init__(log, f"polar_{self.N}_{self.K}", self.K - self.width, self.N)

transform

transform(N)

G = F^(x n) for N = 2^n, uint8

Source code in src/rpps/code/types/polar.py
def transform(N):
    """G = F^(x n) for N = 2^n, uint8"""
    n = int(np.log2(N)) if N > 0 else -1
    if n < 0 or 2**n != N:
        raise ValueError(f"polar: N {N} is not a power of 2")
    G = np.array([[1]], np.uint8)
    F = np.array([[1, 0], [1, 1]], np.uint8)
    for _ in range(n):
        G = np.kron(G, F)
    return G

encode_u

encode_u(u)

x = u G for rows u (..., N), by the butterflies (N log N XORs)

Source code in src/rpps/code/types/polar.py
def encode_u(u):
    """x = u G for rows u (..., N), by the butterflies (N log N XORs)"""
    x = np.array(u, dtype=np.uint8, copy=True)
    N = x.shape[-1]
    h = 1
    while h < N:
        y = x.reshape(*x.shape[:-1], N//(2*h), 2, h)
        y[..., 0, :] ^= y[..., 1, :]
        h *= 2
    return x

pw_order

pw_order(N)

Positions from least to most reliable by polarization weight (sum of 2^(j/4) over the index's set bits j: the beta-expansion 3GPP's NR sequence follows; SNR-independent)

Source code in src/rpps/code/types/polar.py
def pw_order(N):
    """Positions from least to most reliable by polarization weight (sum of 2^(j/4) over the index's set bits j: the
    beta-expansion 3GPP's NR sequence follows; SNR-independent)"""
    n = int(np.log2(N))
    i = np.arange(N)
    pw = sum(((i >> j) & 1)*2**(j/4) for j in range(n))
    return np.argsort(pw, kind="stable")

bhattacharyya_order

bhattacharyya_order(N, design_db=0.0)

Positions from least to most reliable by the Bhattacharyya parameter on a BI-AWGN channel at Es/N0 design_db (Z = exp(-Es/N0) a channel, then 2Z - Z^2 / Z^2 down the tree, the index's top bit first)

Source code in src/rpps/code/types/polar.py
def bhattacharyya_order(N, design_db=0.0):
    """Positions from least to most reliable by the Bhattacharyya parameter on a BI-AWGN channel at Es/N0 design_db
    (Z = exp(-Es/N0) a channel, then 2Z - Z^2 / Z^2 down the tree, the index's top bit first)"""
    n = int(np.log2(N))
    z = np.full(N, np.exp(-10**(design_db/10)))
    for lev in range(n - 1, -1, -1):
        bit = (np.arange(N) >> lev) & 1
        z = np.where(bit == 1, z**2, 2*z - z**2)
    return np.argsort(-z, kind="stable")

box

box(a, b)

LLR of the parity of two bits (exact box-plus)

Source code in src/rpps/code/types/polar.py
def box(a, b):
    """LLR of the parity of two bits (exact box-plus)"""
    return 2*np.arctanh(np.clip(np.tanh(np.clip(a, -30, 30)/2)*np.tanh(np.clip(b, -30, 30)/2), -1 + 1e-15, 1 - 1e-15))

sc

sc(llr, decide)

Successive-cancellation decoding of frames (W, N) of LLRs, every frame at once. decide(i, L) -> (W,) bits: u_i of every frame from its SC LLR L (W,) (a frozen position returns zeros; this is where a blind test looks at it). Returns (u (W, N) uint8, Lu (W, N): each u_i's LLR given the u before it as decided)

Source code in src/rpps/code/types/polar.py
def sc(llr, decide):
    """Successive-cancellation decoding of frames (W, N) of LLRs, every frame at once. decide(i, L) -> (W,) bits: u_i of
    every frame from its SC LLR L (W,) (a frozen position returns zeros; this is where a blind test looks at it).
    Returns (u (W, N) uint8, Lu (W, N): each u_i's LLR given the u before it as decided)"""
    L = np.asarray(llr, dtype=np.float64)
    W, N = L.shape
    _check_n(N)
    u = np.zeros((W, N), np.uint8)
    Lu = np.zeros((W, N))

    def node(Ln, i0):
        m = Ln.shape[1]
        if m == 1:
            Lu[:, i0] = Ln[:, 0]
            b = np.asarray(decide(i0, Ln[:, 0]), dtype=np.uint8)
            u[:, i0] = b
            return b[:, None]
        h = m//2
        a, c = Ln[:, :h], Ln[:, h:]
        v = node(box(a, c), i0) # u_a G' = x_first + x_second
        w = node(c + (1 - 2.0*v)*a, i0 + h) # u_b G' = x_second
        return np.concatenate((v ^ w, w), axis=1)

    node(L, 0)
    return u, Lu

scl

scl(llr, frozen, size)

List decoding of frames (W, N) of LLRs: the size best paths of each frame, best first. frozen: (N,) bool. Returns (u (W, P, N) uint8, metric (W, P): each path's penalty, smaller is likelier)

Source code in src/rpps/code/types/polar.py
def scl(llr, frozen, size):
    """List decoding of frames (W, N) of LLRs: the `size` best paths of each frame, best first. frozen: (N,) bool.
    Returns (u (W, P, N) uint8, metric (W, P): each path's penalty, smaller is likelier)"""
    L = np.asarray(llr, dtype=np.float64)
    W, N = L.shape
    _check_n(N)
    frozen = np.asarray(frozen, dtype=bool)
    if _accel.native is not None: # (the C++ kernel: this function is its reference)
        u, pm = _accel.native.polar_scl(np.ascontiguousarray(L), np.ascontiguousarray(frozen), int(size))
        return u, pm
    return _scl(L, frozen, size)

product

Classes:

Name Description
product

Product code (block product turbo code, BPTC): message in a k2 x k1 matrix, every row encoded with the row

product

product(log, rows, cols, reserved=0, lead=0, iters=4, offset=None, chase=None)

Bases: _code

Product code (block product turbo code, BPTC): message in a k2 x k1 matrix, every row encoded with the row code (n1, k1), then every column (parity columns too) with the column code (n2, k2); sent row by row

rows, cols: the two block codes, as references to block definitions ("hamming/dmr_15_11") or definitions
reserved: zero bits at the start of the message area (DMR: R(2..0)); the message is k1 k2 - reserved bits
lead: zero bits sent before the matrix (DMR: R(3)), so n = lead + n1 n2
offset: a fixed word XOR'd onto every codeword (a coset of the product code: parity bits sent inverted, fill), as
    a hex string of n bits, the lead first then the matrix row by row; decoding takes it off first
iters: decoding rounds of all columns then all rows (hard decisions, each code's own syndrome decoder)
chase: decode soft instead, as a turbo product code (Pyndiah, "Near-optimum decoding of product codes: block turbo
    codes", IEEE Trans. Commun. 1998): each row and column by Chase-II over its `chase` least reliable bits (2^chase
    test patterns through the component's algebraic decoder, the candidate nearest the input chosen). The channel
    LLRs are normalized to mean |R| = 1; the extrinsic information W of a bit is the metric difference to the best
    candidate that disagrees with the decision on it, minus the input, or beta times the decision when no candidate
    disagrees; W is normalized to mean 1 and the next half iteration decodes R + alpha W (ALPHA and BETA per half
    iteration). A row whose test patterns all fail keeps its hard decision. `iters` rounds, stopping early on
    a word whose rows and columns are all codewords

After a decode errors is the bits corrected per word, -1 where a row or column still fails its check.

Source code in src/rpps/code/types/product.py
def __init__(self, log, rows, cols, reserved=0, lead=0, iters=4, offset=None, chase=None):
    self.chase = None if chase is None else int(chase)
    self.soft = self.chase is not None
    self.rows, self.cols = rows, cols # Coding objects (encoder + hard decoder)
    self.k1, self.n1 = rows.encoder.num, rows.encoder.den
    self.k2, self.n2 = cols.encoder.num, cols.encoder.den
    self.reserved, self.lead, self.iters = int(reserved), int(lead), int(iters)
    super().__init__(log, None, self.k1*self.k2 - self.reserved, self.lead + self.n1*self.n2)
    self.offset = None if offset is None else _bits_of_hex(offset, self.den)

ratematch

Classes:

Name Description
ratematch

LTE rate matching (3GPP TS 36.212 5.1.4): three coded streams -> E bits through a circular buffer

ratematch

ratematch(log, mode, length, out, rv=0, ncb=None)

Bases: _code

LTE rate matching (3GPP TS 36.212 5.1.4): three coded streams -> E bits through a circular buffer

mode "conv" (5.1.4.2): input as a convolutional encoder sends it (three bits per step); each stream sub-block
    interleaved (32 columns, CONV_PERM), the buffer is the three one after the other, read from k0 = 0
mode "turbo" (5.1.4.1): input as the turbo code sends it (d0, d1, d2 one after the other); d0 and d1 sub-block
    interleaved with TURBO_PERM, d2 with its own permutation, buffer = v0 then v1 / v2 bit by bit, read from
    k0 = R (2 ceil(Ncb / 8R) rv + 2); ncb: soft buffer size (default the whole buffer)
length: bits per stream (D: K for conv, K + 4 for turbo); out: E, bits sent

The filler is skipped; reading wraps round the buffer (repetition) or stops early (puncturing). encode() selects the E bits. decode() takes E LLRs and returns 3 D LLRs in the input layout, repetitions added (positions never sent stay 0: erasures), ready for the decoder.

Source code in src/rpps/code/types/ratematch.py
def __init__(self, log, mode, length, out, rv=0, ncb=None):
    D, E = int(length), int(out)
    super().__init__(log, None, 3*D, E)
    self.mode, self.D, self.E, self.rv = mode, D, E, rv
    if mode == "conv":
        p = rowcol(D, 32, CONV_PERM)
        buf = [(i, int(k)) for i in range(3) for k in p]
        idx = [buf[t % len(buf)] for t in range(E)]
        self.index = np.array([k*3 + i for i, k in idx], dtype=np.int64) # Steps of three bits
    elif mode == "turbo":
        C = 32
        R = -(-D//C)
        Kp = R*C
        y = np.full(Kp, -1)
        y[Kp - D:] = np.arange(D)
        v01 = y.reshape(R, C)[:, TURBO_PERM].T.reshape(-1)
        v2 = y[np.array([(TURBO_PERM[k//R] + C*(k % R) + 1) % Kp for k in range(Kp)])]
        w = [(0, int(i)) for i in v01] + [t for k in range(Kp) for t in ((1, int(v01[k])), (2, int(v2[k])))]
        Ncb = len(w) if ncb is None else int(ncb)
        k0 = R*(2*(-(-Ncb//(8*R)))*rv + 2)
        sel, j = [], 0
        while len(sel) < E:
            s, k = w[(k0 + j) % Ncb]
            if k >= 0:
                sel.append(s*D + k)
            j += 1
            if j > 4*Ncb + 4*E:
                raise ValueError("Nothing to send in the circular buffer")
        self.index = np.array(sel, dtype=np.int64)
    else:
        raise ValueError(f"mode {mode!r}: 'conv' or 'turbo'")

repeat

rm

Reed-Muller codes RM(r, m): the evaluations of every Boolean polynomial of degree at most r in m variables

{"base": "block", "type": "rm", "r": 1, "m": 5}       RM(1, 5): (32, 6, 16), Mariner 9's code

n = 2^m, k = sum over i <= r of C(m, i), minimum distance 2^(m-r). Codeword position p is the point whose variable j is bit j of p; the message is the polynomial's coefficients, monomials by degree (1, x_0 .. x_{m-1}, x_0 x_1, ...), each degree's in lexicographic order of their variables.

Decoding: RM(1, m) by the fast Hadamard transform, maximum likelihood on LLRs (the correlation with every affine function at once: Green's "Green machine" of Mariner 9); higher orders by Reed's majority logic on hard decisions, the top degree first (each monomial's coefficient is the majority of the 2^(m - d) sums over the subcubes its variables span), which corrects up to 2^(m-r-1) - 1 errors. errors: bits the chosen codeword differs from the hard decisions.

Classes:

Name Description
rm

Functions:

Name Description
monomials

The variable sets of the monomials of degree <= r, in message order

rm

rm(log, r, m)

Bases: _code

Source code in src/rpps/code/types/rm.py
def __init__(self, log, r, m):
    self.r, self.m = int(r), int(m)
    if not 0 <= self.r <= self.m or self.m < 1:
        raise ValueError(f"RM({r}, {m}): needs 0 <= r <= m, m >= 1")
    n = 2**self.m
    self.mono = monomials(self.r, self.m)
    pts = (np.arange(n)[:, None] >> np.arange(self.m)[None, :]) & 1 # (n, m) variable values at each position
    self.G = np.array([np.prod(pts[:, list(s)], axis=1) if s else np.ones(n, np.int64) for s in self.mono], np.uint8)
    super().__init__(log, f"rm_{self.r}_{self.m}", len(self.mono), n)

monomials

monomials(r, m)

The variable sets of the monomials of degree <= r, in message order

Source code in src/rpps/code/types/rm.py
def monomials(r, m):
    """The variable sets of the monomials of degree <= r, in message order"""
    return [s for d in range(r + 1) for s in itertools.combinations(range(m), d)]

rs

Classes:

Name Description
rs

Reed-Solomon code over GF(2^m), shortened to (n, k): symbols are bytes for m=8

rs

rs(log, num: int, den: int, m=8, poly=285, fcr=0, prim=1, puncture=None, basis='conventional', beta=None)

Bases: _code

Reed-Solomon code over GF(2^m), shortened to (n, k): symbols are bytes for m=8

poly: field polynomial (0x11D). fcr/prim: first consecutive root and primitive element power of the generator (DVB: fcr=0, prim=1, 16 roots; P25: fcr=1). Bits are grouped MSB first into m-bit symbols. puncture: positions of the n-symbol codeword that are not sent (negative counts from the end, so [-4, -3, -2, -1] drops the last four parity symbols). They are decoded as erasures; a word has n - len(puncture) symbols on the wire.

basis: "conventional" (the polynomial basis: a symbol's bits are its coefficients) or "dual": the bits are the symbol in the Berlekamp dual basis of {1, beta, ..., beta^(m-1)}, beta = alpha^beta: bit j (most significant first) is Tr(z beta^j). CCSDS sends RS(255, 223) that way, beta = alpha^117 (131.0-B, Annex F). Symbols given with symbols=True are field elements (conventional) either way. encode/decode take bits (or symbols with symbols=True) of whole codewords as sent. decode(..., erasures=...) also takes symbols known to be unreliable: a (words, sent symbols) bool array, or one list of positions per word. e erasures and r errors are corrected while 2r + e <= n - k. Soft input (LLRs, positive = 0): a word that fails errors-only decoding is tried again with its least reliable symbols erased (2, 4, ... up to n - k), the generalized minimum distance idea. After a decode, errors is the number of corrected symbols per codeword (-1: uncorrectable).

Methods:

Name Description
dual_table

Each field element (conventional) in the dual basis of {1, b, ..., b^(m-1)}, b = alpha^beta: bit j, most

syndromes

Syndromes (W, nroots) of full-length codewords (W, n): S_i = r(alpha^((fcr+i)*prim)); only the first count

Source code in src/rpps/code/types/rs.py
def __init__(self, log, num: int, den: int, m=8, poly=0x11D, fcr=0, prim=1, puncture=None, basis="conventional", beta=None):
    n = den
    if n > 2**m - 1:
        raise ValueError(f"RS({n}, {num}) is longer than GF(2^{m}) allows ({2**m - 1})")
    punct = sorted({p % n for p in (puncture or ())})
    super().__init__(log, None, num, n - len(punct))
    self.n = n # Codeword length before puncturing; `den` is what is sent
    self.puncture = np.array(punct, dtype=np.int64)
    self.sent = np.setdiff1d(np.arange(n), self.puncture)
    self.gf = GF(m, poly)
    self.m, self.fcr, self.prim = m, fcr, prim
    self.nroots = n - num
    if len(punct) > self.nroots:
        raise ValueError(f"RS({n}, {num}): {len(punct)} punctured symbols, more than the {self.nroots} parity symbols")
    self.t = self.nroots // 2
    # Generator polynomial, highest degree first
    g = np.array([1], dtype=np.int64)
    for i in range(self.nroots):
        root = self.gf.pow_alpha((fcr + i)*prim)
        g = self.gf.polymul(g, np.array([1, root]))
    self.gen = g
    self.basis = basis
    self._to_dual = self._from_dual = None
    if basis == "dual":
        if beta is None:
            raise ValueError("RS dual basis: needs \"beta\", the power of alpha whose powers it is the dual of")
        self._to_dual = self.dual_table(int(beta))
        self._from_dual = np.argsort(self._to_dual)
        if not np.array_equal(np.sort(self._to_dual), np.arange(2**m)):
            raise ValueError(f"RS dual basis: alpha^{beta}'s powers are not a basis")
    elif basis != "conventional":
        raise ValueError(f"RS basis {basis!r}: conventional or dual")
dual_table
dual_table(beta)

Each field element (conventional) in the dual basis of {1, b, ..., b^(m-1)}, b = alpha^beta: bit j, most significant first, is the trace of z b^j

Source code in src/rpps/code/types/rs.py
def dual_table(self, beta):
    """Each field element (conventional) in the dual basis of {1, b, ..., b^(m-1)}, b = alpha^beta: bit j, most
    significant first, is the trace of z b^j"""
    m, size = self.m, 2**self.m
    z = np.arange(size)
    out = np.zeros(size, dtype=np.int64)
    for j in range(m):
        y = np.where(z == 0, 0, self.gf.exp[(self.gf.log[z] + beta*j) % (size - 1)]) # z b^j
        t = np.zeros(size, dtype=np.int64)
        for _ in range(m): # trace: y + y^2 + y^4 + ...
            t ^= y
            y = np.where(y == 0, 0, self.gf.exp[(2*self.gf.log[y]) % (size - 1)])
        out |= (t & 1) << (m - 1 - j)
    return out
syndromes
syndromes(words, count=None)

Syndromes (W, nroots) of full-length codewords (W, n): S_i = r(alpha^((fcr+i)*prim)); only the first count

Source code in src/rpps/code/types/rs.py
def syndromes(self, words, count=None):
    """Syndromes (W, nroots) of full-length codewords (W, n): S_i = r(alpha^((fcr+i)*prim)); only the first `count`"""
    words = np.asarray(words)
    count = self.nroots if count is None else min(int(count), self.nroots)
    if _accel.native is not None:
        return _accel.native.gf_syndromes(np.ascontiguousarray(words, dtype=np.int64), self.gf.exp, self.gf.log,
                                          count, self.fcr, self.prim)
    e = np.arange(words.shape[1] - 1, -1, -1) # Power of x at each position
    S = np.zeros((len(words), count), dtype=np.int64)
    for i in range(count):
        S[:, i] = self.gf.evaluate(words, e*(self.fcr + i)*self.prim)
    return S

syndrome

Classes:

Name Description
syndrome

Hard decoder of a linear block code by syndrome lookup: corrects every pattern of up to t bit errors

Functions:

Name Description
min_distance_t

(d_min - 1)//2 of the code generated by G, from all its codewords

syndrome

syndrome(log, G, H, t=None)

Bases: _code

Hard decoder of a linear block code by syndrome lookup: corrects every pattern of up to t bit errors

Built from the code (from_encoder): the table maps each syndrome to the lightest error pattern that gives it. t defaults to the code's own (d_min - 1)//2, found by listing the codewords (k <= 20), or the code's t. A syndrome of no pattern within t is a detected failure: errors is -1 for that word and its message bits are returned as received. Soft input is hard decided first. The message is the first k bits of each word.

Source code in src/rpps/code/types/syndrome.py
def __init__(self, log, G, H, t=None):
    G, H = np.asarray(G, dtype=np.uint8), np.asarray(H, dtype=np.uint8)
    k, n = G.shape
    r = H.shape[0]
    if r > MAX_CHECK_BITS:
        raise ValueError(f"Syndrome table needs 2^{r} entries: too many (limit 2^{MAX_CHECK_BITS})")
    super().__init__(log, None, k, n)
    self.H = H
    self.t = min_distance_t(G) if t is None else int(t)
    self._weights = 1 << np.arange(r - 1, -1, -1)
    self.weight = np.full(1 << r, -1, dtype=np.int64) # Error weight per syndrome, -1: not within t
    self.pattern = np.zeros((1 << r, n), dtype=np.uint8)
    self.weight[0] = 0
    cols = (H.astype(np.int64) * self._weights[:, None]).sum(axis=0) # Syndrome of each single-bit error
    for w in range(1, self.t + 1):
        if comb(n, w) > 1 << 22:
            raise ValueError(f"t={self.t}: too many error patterns of weight {w} in {n} bits")
        for pos in itertools.combinations(range(n), w):
            s = int(np.bitwise_xor.reduce(cols[list(pos)]))
            if self.weight[s] < 0:
                self.weight[s] = w
                self.pattern[s, list(pos)] = 1

min_distance_t

min_distance_t(G)

(d_min - 1)//2 of the code generated by G, from all its codewords

Source code in src/rpps/code/types/syndrome.py
def min_distance_t(G):
    """(d_min - 1)//2 of the code generated by G, from all its codewords"""
    G = np.asarray(G, dtype=np.uint8)
    k = G.shape[0]
    if k > 20:
        raise ValueError(f"k={k}: too many codewords to find the minimum distance, give t")
    msgs = ((np.arange(1, 1 << k)[:, None] >> np.arange(k - 1, -1, -1)) & 1).astype(np.uint8)
    d = int(((msgs @ G) % 2).sum(axis=1).min())
    return (d - 1)//2

trellis

Trellis (BCJR / MAP) decoding

A trellis lists, for every section of the code, which state each branch leaves and enters and which coded bits it carries. bcjr runs the forward-backward algorithm over it and returns, for every section, the a-posteriori log-likelihood ratio of the branch bit. The branch bit is whatever the trellis is built around:

  • convolutional codes (bcjr decoder): the information bit. States are the encoder register
  • linear block codes (trellis decoder): the coded bit. States are the syndrome so far (Wolf's trellis), so it has 2^(n-k) states: practical for short codes (Hamming, small BCH), not for LDPC

Unlike Viterbi it gives soft outputs (usable by an iterative decoder) and it minimises the bit error rate rather than the sequence error rate. LLRs are log(P(0)/P(1)), positive means 0, as everywhere else. In the log domain (maxlog=False) the inputs have to be true LLRs: scale them wrong and the output is over or under confident. maxlog=True is the cheap approximation (Viterbi-like) and does not care about scale.

Classes:

Name Description
Trellis

Sections of a trellis

bcjr_conv

BCJR (MAP) decoder for feed-forward convolutional codes: same definition as viterbi

trellis

Maximum a-posteriori decoder for a linear block code, on its syndrome trellis

Functions:

Name Description
bcjr

Forward-backward over a trellis

Trellis

Trellis(next_state, label)

Sections of a trellis

next: (P, S, 2) state reached from each state by each branch bit; section t uses next[t % P] label: (P, S, 2, L) the L coded bits each branch carries Every state needs exactly two branches in, which holds for convolutional and syndrome trellises.

Methods:

Name Description
syndrome

Syndrome trellis of a parity-check matrix H (m, n): sections are coded bits, states the partial syndrome

Source code in src/rpps/code/types/trellis.py
def __init__(self, next_state, label):
    self.next = np.asarray(next_state, dtype=np.int64)
    self.label = np.asarray(label, dtype=np.uint8)
    self.P, self.S, _ = self.next.shape
    self.L = self.label.shape[-1]
    self.sign = 1.0 - 2.0*self.label.astype(np.float64) # +1 for a 0 bit, -1 for a 1 bit
    # Predecessors of each state: (P, S, 2) previous state and branch bit
    self.pred_state = np.zeros((self.P, self.S, 2), dtype=np.int64)
    self.pred_bit = np.zeros((self.P, self.S, 2), dtype=np.int64)
    for p in range(self.P):
        src = np.repeat(np.arange(self.S), 2)
        bit = np.tile(np.arange(2), self.S)
        order = np.argsort(self.next[p].reshape(-1), kind="stable")
        dst = self.next[p].reshape(-1)[order]
        if not np.array_equal(dst, np.repeat(np.arange(self.S), 2)):
            raise ValueError("Every trellis state needs exactly two incoming branches")
        self.pred_state[p] = src[order].reshape(self.S, 2)
        self.pred_bit[p] = bit[order].reshape(self.S, 2)
syndrome staticmethod
syndrome(H)

Syndrome trellis of a parity-check matrix H (m, n): sections are coded bits, states the partial syndrome

Source code in src/rpps/code/types/trellis.py
@staticmethod
def syndrome(H):
    """Syndrome trellis of a parity-check matrix H (m, n): sections are coded bits, states the partial syndrome"""
    H = np.asarray(H, dtype=np.uint8)
    m, n = H.shape
    if m > MAX_STATE_BITS:
        raise ValueError(f"Syndrome trellis needs 2^{m} states: too many (limit 2^{MAX_STATE_BITS})")
    cols = (H.astype(np.int64) * (1 << np.arange(m - 1, -1, -1))[:, None]).sum(axis=0) # Each column as an integer
    S = 1 << m
    states = np.arange(S)
    nxt = np.stack([np.stack((states, states ^ cols[t]), axis=1) for t in range(n)])
    label = np.zeros((n, S, 2, 1), dtype=np.uint8)
    label[:, :, 1, 0] = 1
    return Trellis(nxt, label)

bcjr_conv

bcjr_conv(log, num, den, constraint, generator, puncture=None, termination='truncated', maxlog=False, hard_llr=2.94)

Bases: viterbi

BCJR (MAP) decoder for feed-forward convolutional codes: same definition as viterbi

maxlog: max-log-MAP (no log-sum-exp, insensitive to the LLR scale) hard_llr: the LLR magnitude given to hard input bits (log-MAP needs a guess at the channel; this is p = 5%) decode() takes hard bits or LLRs; app() returns the a-posteriori LLR of every information bit.

Methods:

Name Description
app

A-posteriori LLR of each information bit (the tail of a terminated code is left out)

Source code in src/rpps/code/types/trellis.py
def __init__(self, log, num, den, constraint, generator, puncture=None, termination="truncated", maxlog=False, hard_llr=2.94):
    super().__init__(log, num, den, constraint, generator, puncture, termination)
    self.maxlog, self.hard_llr = maxlog, hard_llr
    self.trellis = Trellis(self.next_state[None], self.out_bits[None])
app
app(bits, soft=None)

A-posteriori LLR of each information bit (the tail of a terminated code is left out)

Source code in src/rpps/code/types/trellis.py
def app(self, bits, soft=None):
    """A-posteriori LLR of each information bit (the tail of a terminated code is left out)"""
    llr = as_llr(bits, soft, self.hard_llr)
    llr = self.depuncture(llr)                                   # (T, n)
    if self.termination == "tailbiting": # Three laps from and to any state, the middle one kept
        T = len(llr)
        return bcjr(self.trellis, np.tile(llr, (3, 1))[None], start=None, end=None, maxlog=_effort.choice("maxlog", self.maxlog))[0][T:2*T]
    out = bcjr(self.trellis, llr[None], start=0, end=0 if self.terminated else None, maxlog=_effort.choice("maxlog", self.maxlog))[0]
    return out[:len(out)-(self.con-1)] if self.terminated else out

trellis

trellis(log, H, maxlog=False, hard_llr=2.94)

Bases: _code

Maximum a-posteriori decoder for a linear block code, on its syndrome trellis

Corrects what the code can correct (a single error for Hamming) from hard bits, and uses LLRs when given. The message is the first k bits of each word (systematic). Built from the code's own parity-check matrix.

Methods:

Name Description
app

A-posteriori LLRs of the coded bits, (words, n)

Source code in src/rpps/code/types/trellis.py
def __init__(self, log, H, maxlog=False, hard_llr=2.94):
    H = np.asarray(H, dtype=np.uint8)
    m, n = H.shape
    super().__init__(log, None, n - m, n)
    self.maxlog, self.hard_llr = maxlog, hard_llr
    self.H = H
    self.trellis = Trellis.syndrome(H)
app
app(bits, soft=None)

A-posteriori LLRs of the coded bits, (words, n)

Source code in src/rpps/code/types/trellis.py
def app(self, bits, soft=None):
    """A-posteriori LLRs of the coded bits, (words, n)"""
    llr = as_llr(bits, soft, self.hard_llr)
    llr = llr[:len(llr)//self.den*self.den].reshape(-1, self.den)
    return bcjr(self.trellis, llr[:, :, None], start=0, end=0, maxlog=_effort.choice("maxlog", self.maxlog))

bcjr

bcjr(tr, llr, start=0, end=0, maxlog=False)

Forward-backward over a trellis

llr: (W, T, L) channel LLRs of the L coded bits of each of T sections, for W independent blocks start/end: the state every block starts / ends in (None: free) Returns (W, T) a-posteriori LLRs of the branch bits. Needs memory for 2 floats per state per section.

Source code in src/rpps/code/types/trellis.py
def bcjr(tr, llr, start=0, end=0, maxlog=False):
    """Forward-backward over a trellis

    llr: (W, T, L) channel LLRs of the L coded bits of each of T sections, for W independent blocks
    start/end: the state every block starts / ends in (None: free)
    Returns (W, T) a-posteriori LLRs of the branch bits. Needs memory for 2 floats per state per section.
    """
    llr = np.asarray(llr, dtype=np.float64)
    W, T, L = llr.shape
    S = tr.S
    if _accel.native is not None: # The blocks on several threads
        return _accel.native.bcjr(np.ascontiguousarray(llr), np.ascontiguousarray(tr.sign.reshape(tr.P, S, 2, L)), tr.next,
                                  tr.pred_state, tr.pred_bit, -1 if start is None else int(start), -1 if end is None else int(end),
                                  bool(maxlog))
    comb = np.maximum if maxlog else np.logaddexp
    sgn = tr.sign.reshape(tr.P, S, 2, L)

    def gamma(t):
        return 0.5*np.einsum("sil,wl->wsi", sgn[t % tr.P], llr[:, t])  # (W, S, 2)

    alpha = np.full((T+1, W, S), -np.inf)
    if start is None:
        alpha[0] = 0.0
    else:
        alpha[0, :, start] = 0.0
    for t in range(T):
        p = t % tr.P
        g = gamma(t)
        ps, pb = tr.pred_state[p], tr.pred_bit[p]
        a = alpha[t]
        a_next = comb(a[:, ps[:, 0]] + g[:, ps[:, 0], pb[:, 0]], a[:, ps[:, 1]] + g[:, ps[:, 1], pb[:, 1]])
        alpha[t+1] = a_next - a_next.max(axis=1, keepdims=True)

    beta = np.full((W, S), -np.inf)
    if end is None:
        beta[:] = 0.0
    else:
        beta[:, end] = 0.0
    out = np.empty((W, T))
    for t in range(T-1, -1, -1):
        p = t % tr.P
        g = gamma(t)
        nxt = tr.next[p]
        m = alpha[t][:, :, None] + g + beta[:, nxt]  # (W, S, 2)
        reduce = (lambda x: x.max(axis=1)) if maxlog else (lambda x: np.logaddexp.reduce(x, axis=1))
        out[:, t] = reduce(m[:, :, 0]) - reduce(m[:, :, 1])
        b_new = comb(g[:, :, 0] + beta[:, nxt[:, 0]], g[:, :, 1] + beta[:, nxt[:, 1]])
        beta = b_new - b_new.max(axis=1, keepdims=True)
    return np.nan_to_num(out, nan=0.0, posinf=1e4, neginf=-1e4)

turbo

Classes:

Name Description
rsc

Recursive systematic convolutional code: feedback g0 and feedforward g1 over K taps (D^0 first, octal as

turbo

Parallel concatenated (turbo) code, LTE layout (3GPP TS 36.212 5.1.3.2)

turbo_mux

Parallel concatenated code with its outputs multiplexed bit time by bit time (CCSDS 131.0-B 6): the layout turbo

Functions:

Name Description
qpp

Quadratic permutation polynomial interleaver: pi(i) = (f1 i + f2 i^2) mod K

rsc

rsc(g0, g1, K)

Recursive systematic convolutional code: feedback g0 and feedforward g1 over K taps (D^0 first, octal as usual: LTE g0 = 0o13 = 1 + D^2 + D^3, g1 = 0o15 = 1 + D + D^3). State: the register, newest bit most significant

Methods:

Name Description
encode

(parity, tail systematic bits, tail parity bits); the tail drives the register to zero (m steps)

Source code in src/rpps/code/types/turbo.py
def __init__(self, g0, g1, K):
    self.K, self.m = K, K - 1
    self.g0, self.g1 = _poly_bits(g0, K), _poly_bits(g1, K)
    S = 1 << self.m
    self.S = S
    self.next = np.zeros((S, 2), dtype=np.int64)
    self.par = np.zeros((S, 2), dtype=np.uint8)
    self.fb = np.zeros(S, dtype=np.uint8) # Feedback of each state (the input that drives it towards zero)
    for s in range(S):
        r = [(s >> (self.m - 1 - i)) & 1 for i in range(self.m)] # r[0] newest
        f = 0
        for i in range(1, K):
            f ^= self.g0[i] & r[i - 1]
        self.fb[s] = f
        for x in (0, 1):
            a = x ^ f
            p = self.g1[0] & a
            for i in range(1, K):
                p ^= self.g1[i] & r[i - 1]
            self.par[s, x] = p
            self.next[s, x] = (a << (self.m - 1)) | (s >> 1)
    label = np.stack((np.broadcast_to(np.arange(2), (S, 2)), self.par), axis=-1) # (S, 2, 2): systematic, parity
    self.trellis = Trellis(self.next[None], label[None])
encode
encode(x, terminate=True)

(parity, tail systematic bits, tail parity bits); the tail drives the register to zero (m steps)

Source code in src/rpps/code/types/turbo.py
def encode(self, x, terminate=True):
    """(parity, tail systematic bits, tail parity bits); the tail drives the register to zero (m steps)"""
    s, z = 0, np.zeros(len(x), dtype=np.uint8)
    for i, b in enumerate(x):
        z[i] = self.par[s, b]
        s = self.next[s, b]
    tx, tz = [], []
    if terminate:
        for _ in range(self.m):
            b = int(self.fb[s])
            tx.append(b)
            tz.append(int(self.par[s, b]))
            s = self.next[s, b]
    return z, np.array(tx, np.uint8), np.array(tz, np.uint8)

turbo

turbo(log, length, g0, g1, constraint, qpp_f, iters=8, scale=0.75, maxlog=True)

Bases: _code

Parallel concatenated (turbo) code, LTE layout (3GPP TS 36.212 5.1.3.2)

Two identical RSC codes (feedback g0, feedforward g1, constraint K), the second fed through a QPP interleaver; each terminated by m tail steps. Output: three streams d0 (systematic), d1 (parity 1), d2 (parity 2) of length+4 each, one after the other, with the 12 tail bits placed as 5.1.3.2.2 does. length: block size; qpp: [f1, f2], or qpp_table: {"": [f1, f2], ...} iters: decoder iterations, scale: extrinsic scaling (max-log), maxlog: max-log-MAP (default) or log-MAP decode() takes LLRs (positive = 0) of the 3 (length + 4) bits and returns the length message bits; app() gives the final a-posteriori LLRs of the message bits instead (decode's bits are app() < 0). Status (status=True): systematic bits that the decoder changed (a CRC is the real check).

Methods:

Name Description
app

The a-posteriori LLRs of the message bits (positive = 0), every word's K one after the other

Source code in src/rpps/code/types/turbo.py
def __init__(self, log, length, g0, g1, constraint, qpp_f, iters=8, scale=0.75, maxlog=True):
    self.code = rsc(g0, g1, constraint)
    if self.code.m != 3:
        raise ValueError("The LTE tail layout needs constraint length 4")
    super().__init__(log, None, length, 3*(length + 4))
    self.Kb = length
    self.pi = qpp(length, *qpp_f)
    self.inv = np.argsort(self.pi)
    self.iters, self.scale, self.maxlog = iters, scale, maxlog
app
app(bits, soft=None)

The a-posteriori LLRs of the message bits (positive = 0), every word's K one after the other

Source code in src/rpps/code/types/turbo.py
def app(self, bits, soft=None):
    """The a-posteriori LLRs of the message bits (positive = 0), every word's K one after the other"""
    return self._iterate(bits, soft)[0].reshape(-1)

turbo_mux

turbo_mux(log, length, g0, forward, constraint, perm, outputs, iters=10, scale=0.75, maxlog=True)

Bases: _code

Parallel concatenated code with its outputs multiplexed bit time by bit time (CCSDS 131.0-B 6): the layout turbo takes when a definition gives "outputs"

length: block size k
g0: the feedback (backward connection) polynomial, D^0 first ("0b10011", or octal as LTE writes it)
forward: {"1": g1, "2": g2, ...}: the forward polynomials the outputs name
constraint: taps of each polynomial
interleave: an interleave definition giving the second encoder's input order ("block/ccsds_turbo"), with `args`
outputs: what is sent at each bit time, a list of periods: [["0a", "1a"], ["0a", "1b"]] sends the systematic bit
    and encoder a's parity 1 at even times, the systematic bit and encoder b's parity 1 at odd ones. "0a" is the
    systematic stream (with encoder a's tail), "<p>a" / "<p>b" encoder a's / b's output of forward polynomial p

Both encoders start at zero and are terminated (constraint - 1 steps with the input from the feedback), so a word is (k + constraint - 1) bit times. Decoded by iterative BCJR (max-log by default, extrinsic scaling scale).

Methods:

Name Description
app

The a-posteriori LLRs of the message bits (positive = 0), every word's K one after the other

Source code in src/rpps/code/types/turbo.py
def __init__(self, log, length, g0, forward, constraint, perm, outputs, iters=10, scale=0.75, maxlog=True):
    self.Kb, self.K = int(length), int(constraint)
    self.perm = np.asarray(perm, dtype=np.int64)
    if len(self.perm) != self.Kb or not np.array_equal(np.sort(self.perm), np.arange(self.Kb)):
        raise ValueError(f"turbo: the interleaver is not a permutation of {self.Kb}")
    self.inv = np.argsort(self.perm)
    self.polys = {str(p): g for p, g in forward.items()}
    self.outputs = [list(o) for o in outputs]
    for o in (x for period in self.outputs for x in period):
        if o != "0a" and (o[-1] not in "ab" or o[:-1] not in self.polys):
            raise ValueError(f"turbo: output {o!r} names no forward polynomial")
    self.codes = {p: rsc(g0, g, self.K) for p, g in self.polys.items()}
    first = next(iter(self.codes.values()))
    self.m = first.m
    self.T = self.Kb + self.m
    # One trellis per encoder: label = (systematic, parity of each forward polynomial in `order`)
    self.order = sorted(self.polys)
    label = np.stack([np.broadcast_to(np.arange(2), (first.S, 2))] + [self.codes[p].par for p in self.order], axis=-1)
    self.trellis = Trellis(first.next[None], label[None])
    self.slots = [] # (time, stream) of each sent bit, in order
    for t in range(self.T):
        for o in self.outputs[t % len(self.outputs)]:
            self.slots.append((t, o))
    self.iters, self.scale, self.maxlog = iters, scale, maxlog
    super().__init__(log, None, self.Kb, len(self.slots))
app
app(bits, soft=None)

The a-posteriori LLRs of the message bits (positive = 0), every word's K one after the other

Source code in src/rpps/code/types/turbo.py
def app(self, bits, soft=None):
    """The a-posteriori LLRs of the message bits (positive = 0), every word's K one after the other"""
    return self._iterate(bits, soft)[0].reshape(-1)

qpp

qpp(K, f1, f2)

Quadratic permutation polynomial interleaver: pi(i) = (f1 i + f2 i^2) mod K

Source code in src/rpps/code/types/turbo.py
def qpp(K, f1, f2):
    """Quadratic permutation polynomial interleaver: pi(i) = (f1 i + f2 i^2) mod K"""
    i = np.arange(K, dtype=np.int64)
    p = (f1*i + f2*i*i) % K
    if len(np.unique(p)) != K:
        raise ValueError(f"QPP ({f1}, {f2}) is not a permutation of {K}")
    return p

viterbi

Classes:

Name Description
viterbi

Viterbi decoder for feed-forward convolutional codes (rate 1/n, any constraint length)

viterbi

viterbi(log, num, den, constraint, generator, puncture=None, termination='truncated', invert=None)

Bases: _code

Viterbi decoder for feed-forward convolutional codes (rate 1/n, any constraint length)

generator: (n, K) taps. generator[j][i] multiplies the input delayed by i, the same convention as conv puncture: optional (n, P) 0/1 pattern, 1 = bit was sent. Punctured positions are decoded as erasures invert: optional n 0/1 flags: outputs the encoder sent inverted (their values are turned back before decoding) terminated: the encoder was flushed with K-1 zeros, so the path ends in state 0 (and the tail is dropped). Or a termination name: "zero" (the same), "truncated" (no tail: the best end state), "tailbiting" (the path ends where it started: decoded on three laps round the frame, keeping the middle one; frames only)

decode() takes hard bits (0/1) or soft values. Soft values are LLRs, log(P(bit=0)/P(bit=1)): positive means 0. Pass soft=True to force soft, otherwise integer/bool input is treated as hard bits.

Without state decode() takes a whole frame. With state (a dict) it is a stream: the path metrics and the survivor decisions carry over, and a bit is released once it is depth trellis steps old (it is then settled for practical purposes). final ends the stream and releases the rest, ending in state 0 if terminated.

Methods:

Name Description
depuncture

Insert zeros (erasures) for the punctured positions. Returns (T, n) array

decode_batch

Words (W, L), each decoded as a frame of its own: decisions (W, T), the same as decode() on each row. In C++

Source code in src/rpps/code/types/viterbi.py
def __init__(self, log, num, den, constraint, generator, puncture=None, termination="truncated", invert=None):
    super().__init__(log, None, num, den)
    self.con = constraint
    self.gen = np.asarray(generator, dtype=np.uint8).reshape(den, constraint)
    self.puncture = None if puncture is None else np.asarray(puncture, dtype=bool)
    self.invert = None if invert is None or not any(invert) else np.where(np.asarray(invert, dtype=bool), -1.0, 1.0)
    self.termination = termination_of({"termination": termination})
    if self.termination == "tailbiting":
        self.stream = False # Whole frames: a stream is collected until it ends
    self.depth = 10*constraint # Traceback depth of a stream

    K, n = self.con, self.den
    S = 2**(K-1)
    self.n_states = S

    # Register for (state, input): [input, newest past bit, ..., oldest]. State bit K-2 is the newest past bit
    state = np.arange(S)
    reg = np.zeros((S, 2, K), dtype=np.uint8)
    reg[:, :, 0] = np.arange(2)[None, :]
    for i in range(1, K):
        reg[:, :, i] = ((state >> (K-1-i)) & 1)[:, None]
    self.out_bits = (np.einsum("sik,nk->sin", reg, self.gen) & 1).astype(np.uint8) # (S, 2, n)
    pow2 = 2**np.arange(n-1, -1, -1)
    self.out_pat = (self.out_bits.astype(int) * pow2).sum(axis=2) # Code word as an integer (S, 2)
    self.patterns = ((np.arange(2**n)[:, None] >> np.arange(n-1, -1, -1)) & 1).astype(np.float64) # (2^n, n)

    self.next_state = (np.arange(2)[None, :] << (K-2)) | (state[:, None] >> 1) # (S, 2)
    ns = np.arange(S)
    self.prev = np.stack([((ns << 1) & (S-1)) | b for b in (0, 1)], axis=1) # (S, 2) predecessors
    self.prev_in = ns >> (K-2) # Input bit that leads into each state
    # The same trellis for rpps._native: branch j into state s comes from prev[s, j] and sends pattern _pat[s, j]
    self._pred = np.ascontiguousarray(self.prev, dtype=np.int32)
    self._pat = np.ascontiguousarray(np.stack([self.out_pat[self.prev[:, j], self.prev_in] for j in (0, 1)], axis=1), dtype=np.int32)
depuncture
depuncture(values)

Insert zeros (erasures) for the punctured positions. Returns (T, n) array

Source code in src/rpps/code/types/viterbi.py
def depuncture(self, values):
    """Insert zeros (erasures) for the punctured positions. Returns (T, n) array"""
    n = self.den
    if self.puncture is None or self.puncture.all():
        return values[:len(values)//n*n].reshape(-1, n)
    P = self.puncture.shape[1]
    per_period = int(self.puncture.sum())
    periods = len(values) // per_period
    mask = np.tile(self.puncture, (1, periods)) # (n, T)
    out = np.zeros((n, periods*P))
    out.T[mask.T] = values[:periods*per_period]
    return out.T
decode_batch
decode_batch(words, soft=None)

Words (W, L), each decoded as a frame of its own: decisions (W, T), the same as decode() on each row. In C++ (rpps._native.viterbi_batch) on several threads; a loop over decode() without the kernels

Source code in src/rpps/code/types/viterbi.py
def decode_batch(self, words, soft=None):
    """Words (W, L), each decoded as a frame of its own: decisions (W, T), the same as decode() on each row. In C++
    (rpps._native.viterbi_batch) on several threads; a loop over decode() without the kernels"""
    words = np.asarray(words)
    if _accel.native is None or len(words) == 0:
        return np.array([self.decode(w, soft) for w in words], dtype=bool).reshape(len(words), -1)
    llr = self._depuncture_batch(as_llr(words, soft)) # (W, T, n)
    if self.invert is not None:
        llr = llr*self.invert[None, None, :]
    S = self.n_states
    T = llr.shape[1]
    if self.termination == "tailbiting": # Three laps from no particular state, the best end, the middle lap (_path)
        llr, pm0 = np.tile(llr, (1, 3, 1)), np.zeros(S)
    else:
        pm0 = np.full(S, np.inf)
        pm0[0] = 0.0
    end = np.full(len(llr), 0 if self.terminated else -1, dtype=np.int64) # -1: the best end state, as decode()'s argmin
    states, _, _ = _accel.native.viterbi_batch(np.ascontiguousarray(llr, dtype=np.float64), self.patterns, 1, self._pred,
                                               self._pat, pm0, end)
    out = self.prev_in[states]
    if self.termination == "tailbiting":
        return out[:, T:2*T].astype(bool)
    if self.terminated:
        out = out[:, :max(0, out.shape[1]-(self.con-1))]
    return out.astype(bool)