Skip to content

Symbol

rpps.symbol

Modulation: the symbol layer (channel bits <-> symbols, * and /); the waveform layer is rpps.wave

A signal is built from explicit pieces, and a new kind of signal is a new config or a new piece, not a new special case.

Layer Pieces Operator What flows
Symbol (rp.symbol; codes from rp.sequence) Constellation, Differential, Spread, Carriers * encodes, / decodes bits, symbols, chips (a Pipe each; decoding ends in LLRs)
Waveform (rp.wave; pulses from rp.signal.filters.load("pulse/...")) Shape / Matched, Stagger, FM, FMDemod + symbols and samples (a streaming Stage each; any block length)

Constellations

A constellation is a set of points and the ways of labelling them with bits. PSK, QAM, APSK and ASK are generators (rp.symbol.PSK(8), rp.symbol.QAM(16), rp.symbol.generate("64QAM")); anything else is a config file (config/constellation//.json):

{"points": [{"mag": 1, "pha": 45}, {"re": 0, "im": 2}, [-1.5, 0]],
 "maps": [{"map": [0, 1, 3, 2], "comment": "Grey"}]}

maps[i].map[point] is the value (bits, first bit most significant) the point carries. Points are scaled to unit mean power unless "normalize": false. The first map is also turned by every rotation the points allow, with and without spectral inversion (rp.symbol.load("psk/qpsk", "R090 inverted")): the maps a receiver has to try when it does not know the carrier phase or the IQ sense. Shapes and definitions are separate: DVB-S2's 16APSK is rp.symbol.load("apsk/dvbs2_16apsk", rate="3/4"), not generate("16APSK").

Differential coding

Explicit: bits * rp.symbol.load("psk/bpsk") * rp.symbol.Differential() is DBPSK; the constellation's points are then the phase changes. 802.11b DQPSK is psk/qpsk_axes + Differential(); pi/4-DQPSK the ordinary 45 degree psk/qpsk + Differential(). Bit-level differential coding (NRZ-M, NRZ-I) is rp.code.Line.

Frame structure

Known structure among the symbols of a frame (rpps.symbol.frame), restarted at each frame start a profile gives it:

  • Header: known symbols then a short code carrying fields (config/header/physical, rp.symbol.load_header("dvbs2_pl")). Receiving it decodes the fields (every code word tried, soft) and publishes them for the profile; transmitting it builds them.
  • Pilots: a block of pilots after every few slots (DVB-S2: 36 after every 16 slots of 90).
  • PhaseScramble: each symbol turned by a multiple of 90 degrees from a binary sequence (DVB-S2 PL scrambling).

Recipes

Each is exercised in tests/unit/wave/test_recipes.py and tests/unit/wave/test_wave.py. Shaping needs the symbols' rate, so the bits say theirs: bits = rp.Data(b, Fs=1e6, sps=1).

# 802.11b 1 Mb/s: DBPSK, Barker-11, then 11 Mcps shaped as you like
chips = bits * rp.symbol.load("psk/bpsk") * rp.symbol.Differential() * rp.symbol.Spread(rp.sequence.load("barker11"))

# O-QPSK (half-sine pulses, Q half a symbol late; MSK when the symbols are unit QPSK)
halfsine = rp.signal.filters.load("pulse/halfsine/halfsine")
wave = bits * rp.symbol.load("psk/qpsk") + rp.wave.Shape(8, halfsine) + rp.wave.Stagger()

# 802.15.4 2.4 GHz: 4 bits pick a 32-chip sequence, even chips on I, odd on Q
wave = bits * rp.symbol.Spread(rp.sequence.load("ieee802154_2450"), pair=True) + rp.wave.Shape(4, halfsine) + rp.wave.Stagger()

# GFSK (Bluetooth LE: BT 0.5, h 0.5): levels from an ASK constellation, a pulse, a frequency modulator
c = rp.symbol.ASK(2)
wave = bits * c + rp.wave.Shape(8, rp.signal.filters.load("pulse/gaussian/bt0p5")) + rp.wave.FM(0.5, c.min_distance)
levels = wave + rp.wave.FMDemod(rp.wave.fm_gain(0.5, 8, c.min_distance))   # then integrate over each symbol and sample

Notes

  • BPSK: \(P_b = Q(\sqrt{2E_b/N_0}) = \tfrac12 \text{erfc}(\sqrt{E_b/N_0})\); QPSK (Gray) has the same bit error rate per \(E_b/N_0\), O-QPSK with matched filters too.
  • O-QPSK delays Q by half a symbol, so I and Q never change together and the phase moves by at most 90 degrees at a time. With half-sine pulses \(p(t) = \sin(\pi t/T)\) on both rails the envelope is constant: it is MSK.

Modules:

Name Description
constellation

Constellations: a set of points and the bit maps that say which bits each point carries

despread
differential
frame

Known structure among the symbols of a frame (rpps.symbol): physical headers, pilot blocks, phase scrambling

kernels

Batch kernels of the symbol operators: Demap of a constellation, Rotate of a phase scrambler, Gather of a pilot or

mapping

Bit maps of a constellation: which value (bits, first bit most significant) each point carries, and the maps a receiver that

modulation
ofdm
serial

Constellations: config/constellation/[/].json, loaded with rp.symbol.load("QPSK"); physical headers:

shapes

Constellation generators: points (unit mean power) and the labels that go with them

spread

constellation

Constellations: a set of points and the bit maps that say which bits each point carries

A constellation is data, not code: any point set with any labelling is one, from config/constellation (rp.symbol.load("QPSK")) or built from points (rp.symbol.Constellation(points, maps)). PSK, QAM, APSK and ASK are generators of such point sets.

Classes:

Name Description
Constellation

Symbols from bits and back: bits * c maps bits to points, symbols / c gives one LLR per bit

Functions:

Name Description
PSK

M points on the unit circle with a Gray map; offset: the first point's phase [rad], default pi/M (QPSK at 45 degrees),

QAM

Square (4, 16, 64, 256) and cross (32, 128, 512) QAM; square sizes are Gray, cross sizes as close as a cross allows

APSK

Amplitude-phase keying on rings: APSK(16) is 4+12, APSK(32) 4+12+16; or give the rings, APSK(rings=(8, 8))

ASK

Amplitude levels on the real axis: ASK(2) is on-off keying, ASK(4) has four Gray levels; bipolar: symmetric about zero

Constellation

Constellation(points, maps=None, mapping=None, name=None, normalize=True)

Bases: Modulation

Symbols from bits and back: bits * c maps bits to points, symbols / c gives one LLR per bit

c = rp.symbol.load("QPSK")                       # a definition, or a generated one ("16QAM")
syms = bits * c
llr = syms / c                                # log(P(0)/P(1)), positive means 0
complex points. They are scaled to unit mean power (what the noise estimate and the LLR scale assume) unless

normalize is False. The number must be a power of two; a point carries log2(number) bits.

maps: the ways of labelling the points: Mapping objects, or (labels, comment), or just labels. labels[point] is the value (bits, first bit most significant) the point carries. The first map is the one used unless mapping picks another. A map with a turn (radians; "rotate" in degrees in a definition) uses the points turned by it: a standard that labels the same set turned (DVB-S2 8PSK at k45 degrees on 8PSK at 22.5 + k45) is a map, not another constellation. Such maps are in turned, picked by name; maps holds the ones on the points as given. blind_maps: maps, then each turned map with every turn and inversion of it the points allow, what a blind search tries. The first map is also turned by every rotation the points allow, with and without spectral inversion (see .maps), the maps a receiver that does not know the carrier phase or the IQ sense has to try. No maps: the points in order, 0, 1, 2... mapping: which map to use: an index into maps, words of its comment ("R090", "R090 inverted"), a Mapping, or labels

Methods:

Name Description
turned_name

The name of the turned map m (one of blind_maps) is a turn of ("DVB-S2"), as load(name, mapping) takes it;

takes

Encodes channel bits (data bits too: a link with no channel code), decodes symbols

control

Become another constellation (name, as rp.symbol.load takes it, with the definition's params, a dict) and/or

kernel

The batch demapper, for the constellation as params (live parameters) make it; encoding has none yet

pos_rate

Bits per symbol decoding, symbols per bit encoding (rpps.profile positions)

set_mapping

Choose the bit mapping: an index into maps, words of its comment ("R090", "R090 inverted"), a Mapping, or a list of labels.

labels

Bits of every point under the current map: (points, bits per symbol), first bit first

modulate

Bits to symbols (complex64). A partial last symbol is padded with zeros

estimate_noise

Noise variance E|n|^2 of received symbols (assumes the constellation has unit mean power and the gain is right)

llr

Per-bit log-likelihood ratios of received symbols, log(P(bit=0)/P(bit=1)), positive means 0

draw_refs

Draw the points with their labels (and the unit circle)

load

{"base": "constellation", "points": [...] or "rings": [...], "rotate": 0, "maps": [{"map": [...], "comment": "..."}], "normalize": true}

Attributes:

Name Type Description
order

Number of points

min_distance

Distance between the two closest points

Source code in src/rpps/symbol/constellation.py
def __init__(self, points, maps=None, mapping=None, name=None, normalize=True):
    super().__init__()
    pts = np.asarray(points, dtype=np.complex128).reshape(-1)
    bps = int(round(math.log2(len(pts)))) if len(pts) else 0
    if len(pts) < 2 or 2**bps != len(pts):
        raise ConfigError(f"A constellation needs a power of two points (2, 4, 8...), got {len(pts)}")
    if normalize:
        pts = pts/np.sqrt(np.mean(np.abs(pts)**2))
    self._base = pts # The points as given; a map with a turn uses them turned (`points`)
    self.points = pts
    self.bits_per_symbol = bps
    self._weights = 1 << np.arange(bps - 1, -1, -1) # Bits are most significant first, on every host
    if name is not None:
        self.name = name # The instance's name; `type(self).name` stays the class's (the logger uses it)
    given = [self._as_mapping(m) for m in (maps if maps else [Mapping(np.arange(len(pts)), "natural")])]
    every = expand_maps(pts, given)
    self.maps = [m for m in every if not m.turn] # The maps on these points: what a receiver that does not know the phase tries
    self.turned = [m for m in every if m.turn] # Maps that turn the points (a standard's labelling of the set turned): by name only
    self.blind_maps, self._family = list(self.maps), {} # (_family: id of a turn of a turned map -> that map's name)
    for t in self.turned:
        for m in self._turns_of(pts, t):
            self.blind_maps.append(m)
            self._family[id(m)] = t._comment
    self.mapping = self.maps[0] if mapping is None else self._pick_map(mapping)
order property
order

Number of points

min_distance property
min_distance

Distance between the two closest points

turned_name
turned_name(m)

The name of the turned map m (one of blind_maps) is a turn of ("DVB-S2"), as load(name, mapping) takes it; None for a map on the points as given

Source code in src/rpps/symbol/constellation.py
def turned_name(self, m):
    """The name of the turned map `m` (one of `blind_maps`) is a turn of ("DVB-S2"), as `load(name, mapping)` takes it;
    None for a map on the points as given"""
    return self._family.get(id(m)) if m.turn else None
takes
takes(encode)

Encodes channel bits (data bits too: a link with no channel code), decodes symbols

Source code in src/rpps/symbol/constellation.py
def takes(self, encode):
    """Encodes channel bits (data bits too: a link with no channel code), decodes symbols"""
    return {Rep.CHANNEL, Rep.DATA} if encode else {Rep.SYMBOLS}
control
control(name=None, mapping=None, params=None)

Become another constellation (name, as rp.symbol.load takes it, with the definition's params, a dict) and/or use another of its maps, from here on: what a header that changes the modulation does. Nothing else carries over, so it applies between symbols

Source code in src/rpps/symbol/constellation.py
def control(self, name=None, mapping=None, params=None):
    """Become another constellation (`name`, as `rp.symbol.load` takes it, with the definition's `params`, a dict) and/or
    use another of its maps, from here on: what a header that changes the modulation does. Nothing else carries over,
    so it applies between symbols"""
    if params is not None and name is None:
        raise ValueError("control: params are the definition's, so they come with a name")
    if name is not None:
        from .serial import load
        new = load(name, **(params or {}))
        self._base, self.points, self.bits_per_symbol, self._weights = new._base, new.points, new.bits_per_symbol, new._weights
        self.maps, self.turned, self.blind_maps, self._family = new.maps, new.turned, new.blind_maps, new._family
        self.name = new.name
        if mapping is None:
            self.mapping = new.mapping
    if mapping is not None:
        self.mapping = self._pick_map(mapping)
kernel
kernel(params, how)

The batch demapper, for the constellation as params (live parameters) make it; encoding has none yet

Source code in src/rpps/symbol/constellation.py
def kernel(self, params, how):
    """The batch demapper, for the constellation as `params` (live parameters) make it; encoding has none yet"""
    if how != "/":
        return None
    from .kernels import Demap
    if params:
        self.control(**params)
    return Demap(self.points.copy(), self.labels().astype(bool), _effort.choice("maxlog", self.maxlog), self.name, floor=_MIN_VAR) # (the level when the region is built)
pos_rate
pos_rate(decode)

Bits per symbol decoding, symbols per bit encoding (rpps.profile positions)

Source code in src/rpps/symbol/constellation.py
def pos_rate(self, decode):
    """Bits per symbol decoding, symbols per bit encoding (rpps.profile positions)"""
    return self.bits_per_symbol if decode else 1/self.bits_per_symbol
set_mapping
set_mapping(mapping)

Choose the bit mapping: an index into maps, words of its comment ("R090", "R090 inverted"), a Mapping, or a list of labels. A constellation starts on its first map, so this is only needed for another one

Source code in src/rpps/symbol/constellation.py
def set_mapping(self, mapping):
    """Choose the bit mapping: an index into `maps`, words of its comment ("R090", "R090 inverted"), a `Mapping`, or a list of labels.
    A constellation starts on its first map, so this is only needed for another one"""
    self.mapping = self._pick_map(mapping)
    return self
labels
labels()

Bits of every point under the current map: (points, bits per symbol), first bit first

Source code in src/rpps/symbol/constellation.py
def labels(self):
    """Bits of every point under the current map: (points, bits per symbol), first bit first"""
    arr = np.asarray(self.mapping.arr).astype(np.int64)
    return ((arr[:, None] & self._weights[None, :]) != 0).astype(np.uint8)
modulate
modulate(bits)

Bits to symbols (complex64). A partial last symbol is padded with zeros

Source code in src/rpps/symbol/constellation.py
def modulate(self, bits):
    """Bits to symbols (complex64). A partial last symbol is padded with zeros"""
    b = np.asarray(bits).astype(np.int64).reshape(-1)
    if len(b) % self.bits_per_symbol:
        b = np.concatenate((b, np.zeros(-len(b) % self.bits_per_symbol, dtype=np.int64)))
    value = b.reshape(-1, self.bits_per_symbol) @ self._weights
    return self.points[self._point_of[value]].astype(np.complex64)
estimate_noise
estimate_noise(syms, iters=8)

Noise variance E|n|^2 of received symbols (assumes the constellation has unit mean power and the gain is right)

Expectation-maximisation over the Gaussian mixture of the constellation points

Source code in src/rpps/symbol/constellation.py
def estimate_noise(self, syms, iters=8):
    """Noise variance E|n|^2 of received symbols (assumes the constellation has unit mean power and the gain is right)

    Expectation-maximisation over the Gaussian mixture of the constellation points
    """
    y = np.asarray(syms, dtype=np.complex128).reshape(1, -1)
    d2, dmin = demap.distances(np, y, self.points)
    return float(2*demap.noise_variance(np, d2, dmin, iters, _MIN_VAR)[0]) # E|n|^2 is twice the variance per real dimension
llr
llr(syms, noise_var=None, maxlog=False)

Per-bit log-likelihood ratios of received symbols, log(P(bit=0)/P(bit=1)), positive means 0

complex noise variance E|n|^2 of the symbols, estimated from them when None (the demodulator

always does; passing it is for tests). LLRs are only calibrated when this is right: decoders that are scale-invariant (Viterbi, min-sum LDPC) don't care, log-MAP decoders do

maxlog: use the nearest point of each bit value rather than summing over all of them

Returns a flat array, symbol after symbol, bits in the order modulate takes them. One implementation with the batch demapper (rpps.math.demap): a frame in a batch comes out as it does alone

Source code in src/rpps/symbol/constellation.py
def llr(self, syms, noise_var=None, maxlog=False):
    """Per-bit log-likelihood ratios of received symbols, log(P(bit=0)/P(bit=1)), positive means 0

    noise_var: complex noise variance E|n|^2 of the symbols, estimated from them when None (the demodulator
        always does; passing it is for tests). LLRs are only calibrated when this is right: decoders that are scale-invariant (Viterbi, min-sum LDPC) don't care,
        log-MAP decoders do
    maxlog: use the nearest point of each bit value rather than summing over all of them

    Returns a flat array, symbol after symbol, bits in the order `modulate` takes them. One implementation with the
    batch demapper (rpps.math.demap): a frame in a batch comes out as it does alone
    """
    y = np.asarray(syms, dtype=np.complex128).reshape(1, -1)
    lab = self.labels().astype(bool)
    return demap.llr_rows(np, y, self.points, lab, demap.mask_matrix(lab), noise_var, maxlog, floor=_MIN_VAR)[0]
draw_refs
draw_refs(points: bool = True, ref: bool = True, ax=None)

Draw the points with their labels (and the unit circle)

Source code in src/rpps/symbol/constellation.py
def draw_refs(self, points: bool = True, ref: bool = True, ax=None):
    """Draw the points with their labels (and the unit circle)"""
    import matplotlib.pyplot as plt
    if ax is None:
        ax = plt.figure().add_subplot()
    if points:
        ax.scatter(x=self.points.real, y=self.points.imag, s=200, c="r")
        for p, label in zip(self.points, self.mapping.arr):
            ax.annotate(bin(int(label))[2:].zfill(self.bits_per_symbol), (p.real, p.imag), fontsize=20)
    if ref:
        angle = np.linspace(0, 2*np.pi, 150)
        ax.plot(np.cos(angle), np.sin(angle), "g")
load staticmethod
load(name: str, obj: dict)

{"base": "constellation", "points": [...] or "rings": [...], "rotate": 0, "maps": [{"map": [...], "comment": "..."}], "normalize": true}

A point is {"mag": 1, "pha": 45} (phase in degrees), {"re": 0.7, "im": -0.7} or [re, im]. A ring is {"n": 12, "mag": 2.85, "pha": 15}: n points of magnitude mag (default 1), the first at pha degrees (default 180/n, so a 4-point ring is QPSK at 45 degrees) and the rest evenly round, counter-clockwise; rings are listed innermost first and the points come out ring by ring, so a map indexes them in that order (PSK is one ring, APSK several). rotate: degrees added to every point's phase (QPSK on the axes is QPSK rotated by -45) A map may say "rotate" too: degrees the points are turned by while that map is used (DVB-S2 8PSK on 8PSK)

Source code in src/rpps/symbol/constellation.py
@staticmethod
def load(name: str, obj: dict):
    """{"base": "constellation", "points": [...] or "rings": [...], "rotate": 0, "maps": [{"map": [...], "comment": "..."}], "normalize": true}

    A point is {"mag": 1, "pha": 45} (phase in degrees), {"re": 0.7, "im": -0.7} or [re, im].
    A ring is {"n": 12, "mag": 2.85, "pha": 15}: n points of magnitude mag (default 1), the first at pha degrees (default
    180/n, so a 4-point ring is QPSK at 45 degrees) and the rest evenly round, counter-clockwise; rings are listed innermost
    first and the points come out ring by ring, so a map indexes them in that order (PSK is one ring, APSK several).
    rotate: degrees added to every point's phase (QPSK on the axes is QPSK rotated by -45)
    A map may say "rotate" too: degrees the points are turned by while that map is used (DVB-S2 8PSK on 8PSK)
    """
    def point(p):
        if isinstance(p, dict):
            if "mag" in p:
                return p["mag"]*np.exp(1j*np.deg2rad(p.get("pha", 0.0)))
            return complex(p["re"], p.get("im", 0.0))
        if isinstance(p, (list, tuple)) and len(p) == 2:
            return complex(p[0], p[1])
        return complex(p)
    if ("points" in obj) == ("rings" in obj):
        raise ConfigError(f"{name}: a constellation has 'points' or 'rings' (one of them)")
    if "rings" in obj:
        pts = []
        for r in obj["rings"]:
            n = int(r["n"])
            pha = r.get("pha", 180.0/n)
            pts += [r.get("mag", 1.0)*np.exp(1j*np.deg2rad(pha + 360.0*k/n)) for k in range(n)]
    else:
        pts = [point(p) for p in obj["points"]]
    pts = np.asarray(pts, dtype=np.complex128)*np.exp(1j*np.deg2rad(obj.get("rotate", 0.0)))
    return Constellation(list(pts), obj.get("maps"), name=name, normalize=obj.get("normalize", True))

PSK

PSK(M=4, mapping=None, offset=None)

M points on the unit circle with a Gray map; offset: the first point's phase [rad], default pi/M (QPSK at 45 degrees), 0 for BPSK (+-1, as load("psk/bpsk"))

Source code in src/rpps/symbol/constellation.py
def PSK(M=4, mapping=None, offset=None):
    """M points on the unit circle with a Gray map; offset: the first point's phase [rad], default pi/M (QPSK at 45 degrees),
    0 for BPSK (+-1, as `load("psk/bpsk")`)"""
    pts, lab = shapes.psk(M, offset)
    return _gen(M, pts, lab, "Gray", f"{M}PSK", mapping)

QAM

QAM(M=16, mapping=None)

Square (4, 16, 64, 256) and cross (32, 128, 512) QAM; square sizes are Gray, cross sizes as close as a cross allows

Source code in src/rpps/symbol/constellation.py
def QAM(M=16, mapping=None):
    """Square (4, 16, 64, 256) and cross (32, 128, 512) QAM; square sizes are Gray, cross sizes as close as a cross allows"""
    pts, lab = shapes.qam(M)
    return _gen(M, pts, lab, "Gray", f"{M}QAM", mapping)

APSK

APSK(M=16, mapping=None, rings=None, ratios=None)

Amplitude-phase keying on rings: APSK(16) is 4+12, APSK(32) 4+12+16; or give the rings, APSK(rings=(8, 8)) ratios: radius of the outer rings over the innermost

Source code in src/rpps/symbol/constellation.py
def APSK(M=16, mapping=None, rings=None, ratios=None):
    """Amplitude-phase keying on rings: `APSK(16)` is 4+12, `APSK(32)` 4+12+16; or give the rings, `APSK(rings=(8, 8))`
    ratios: radius of the outer rings over the innermost"""
    rings = _APSK_RINGS[M] if rings is None else tuple(rings)
    pts, lab = shapes.apsk(rings, ratios)
    return _gen(sum(rings), pts, lab, "ring + Gray", f"{sum(rings)}APSK", mapping)

ASK

ASK(M=2, mapping=None, bipolar=None)

Amplitude levels on the real axis: ASK(2) is on-off keying, ASK(4) has four Gray levels; bipolar: symmetric about zero (PAM, the default for M > 2) rather than 0..1

Source code in src/rpps/symbol/constellation.py
def ASK(M=2, mapping=None, bipolar=None):
    """Amplitude levels on the real axis: `ASK(2)` is on-off keying, `ASK(4)` has four Gray levels; bipolar: symmetric about zero
    (PAM, the default for M > 2) rather than 0..1"""
    bipolar = M > 2 if bipolar is None else bipolar
    pts, lab = shapes.ask(M, bipolar)
    return _gen(M, pts, lab, "Gray", f"{M}ASK" if M > 2 else "OOK", mapping)

despread

Classes:

Name Description
Despread

Despread a direct-sequence signal: one value per code period, the correlation with the code

Functions:

Name Description
correlate

Correlate whole code periods of x (len a multiple of code.length*sps) with every sequence of the code: (periods, code.count).

Despread

Despread(code: Code, index=0, offset=0, sps=None)

Bases: Stage

Despread a direct-sequence signal: one value per code period, the correlation with the code

The input is at sps samples per chip (from the stream's sps, or the argument), aligned to the code: the first offset samples (a code phase from acquisition) are skipped, then every N chips are one period. Output rates: Fs / (N*sps), 1 sample per symbol.

code: a Code. index: which of its sequences to correlate with (a set has more than one; for the strongest of a set use correlate and take the argmax). offset: samples to skip at the start of the stream. sps: samples per chip

Source code in src/rpps/symbol/despread.py
def __init__(self, code: Code, index=0, offset=0, sps=None):
    if not 0 <= int(index) < code.count:
        raise ValueError(f"index {index}: the code has {code.count} sequences")
    self.code = code
    self.index = int(index)
    self.offset = int(offset)
    self.sps = None if sps is None else int(sps)
    self._one = Code(code.name, code.chips[self.index], code.rate)

correlate

correlate(x, code: Code, sps=1)

Correlate whole code periods of x (len a multiple of code.length*sps) with every sequence of the code: (periods, code.count). Each correlation is normalised, so a signal that is the sequence times a symbol gives that symbol

Source code in src/rpps/symbol/despread.py
def correlate(x, code: Code, sps=1):
    """Correlate whole code periods of x (len a multiple of code.length*sps) with every sequence of the code: (periods, code.count).
    Each correlation is normalised, so a signal that is the sequence times a symbol gives that symbol"""
    x = np.asarray(x)
    if x.dtype not in (np.complex64, np.complex128):
        x = x.astype(np.complex128)
    sps = int(sps)
    if len(x) % (code.length*sps):
        raise ValueError(f"{len(x)} samples is not a whole number of {code.length} chip periods at {sps} samples/chip")
    if _accel.native is not None:
        return _accel.native.despread(x, np.ascontiguousarray(code.chips), sps)
    chip = x.reshape(-1, code.length, sps).sum(axis=2) # Samples of each chip, summed
    return (chip @ code.chips.T / (code.length*sps)).astype(x.dtype)

differential

Classes:

Name Description
Differential

Differential phase coding of symbols: each one is sent as the phase change from the one before

Differential

Differential()

Bases: Modulation

Differential phase coding of symbols: each one is sent as the phase change from the one before

syms = bits * constellation * Differential()          # the constellation's points are phase changes
bits = syms / Differential() / constellation

The receiver needs no carrier phase, only that it holds over two symbols (a constant phase offset cancels). DBPSK is BPSK (points 1, -1: bit 1 turns the phase by 180 degrees); DQPSK is QPSK, the points on the axes for 802.11b (config/constellation/psk/qpsk_axes) or at 45 degrees for pi/4-DQPSK (psk/qpsk itself), whose phase moves by an odd multiple of 45 degrees every symbol.

The sent symbols have unit magnitude (the phase is what is coded). The phase before the first symbol is 0, so that one symbol of a stream decodes right only when the carrier phase is too; a decoder joined mid-stream is right from its second symbol. Each received symbol is multiplied by the conjugate of the one before (the noncoherent detector): the phase change, with each symbol weighted by its own reliability, as the demapper's LLRs want. Dividing instead (y/prev) gives the same hard decisions, but a weak prev blows the noise up: measured DQPSK into a K=7 Viterbi decoder, BER 5e-3 dividing against 1.6e-5 at Eb/N0 7 dB (over 2 dB). The phase cancels; the signal comes out at the input's amplitude squared, so the input is at unit amplitude as for any demapper (the hard decisions don't depend on it).

Source code in src/rpps/symbol/modulation.py
def __init__(self):
    self.log = Logger().Child("Modulation", _config.LOG_MOD).Child(type(self).name)

frame

Known structure among the symbols of a frame (rpps.symbol): physical headers, pilot blocks, phase scrambling

These work frame by frame. A frame starts wherever a profile applies a change to them (rpps.profile.control): a frame sync publishes each frame's start, a header publishes what follows it, and each step restarts its frame there. Used on their own, a stream starts on a frame.

Header         known symbols (a preamble), then a short block code carrying fields: decoded and published on
               receive, built from the frame's fields on transmit (DVB-S2 PLHEADER: SOF + PLS)
Pilots         a block of known symbols after every few slots: removed on receive, inserted on transmit
PhaseScramble  every symbol turned by a multiple of a step, the multiple from a binary sequence, restarting each
               frame (DVB-S2 PL scrambling)

A header is a definition: config/header/physical/.json, rp.symbol.load_header("dvbs2_pl")

{"base": "header", "type": "physical", "comment": "...", "ref": "...",
 "constellation": "bpsk", "phase": 45, "rotate": 90,      symbol k is the point turned by phase + k*rotate degrees,
 "cycle": 2,                                              k counted modulo cycle (pi/2-BPSK: 0, 90, 0, 90...)
 "known": {"bits": "0x18D2E82", "n": 26},                 the preamble, first bit first
 "code": {"n": 64, "rows": ["0x...", ...],                generator rows, one per message bit, n bits each, and
          "scramble": "0x..."},                           a mask XOR'd onto every code word
 "fields": [{"name": "modcod", "bits": 5}, ...],          the message, first field first, most significant bit first
 "turn": {"field": "s2x", "degrees": 90},                 optional: a message with this one-bit field set has its
                                                          code word sent turned this much more (DVB-S2X's MODCODs)
 "max_errors": 16}                                        receive: a header with more bit errors is refused

Classes:

Name Description
Header

A physical header at the start of every frame: known symbols, then a code word whose message is the fields

Pilots

Blocks of known pilot symbols among a frame's data: removed on receive, inserted on transmit

PhaseScramble

Every symbol of a frame turned by step * R(i) degrees, R(i) = sum_j 2**(J-1-j) z(i + offsets[j]) for a binary

Marker

Known symbols at the start of every frame (a symbol-level sync word: a Zadoff-Chu preamble, a word already mapped)

Puncture

Symbols at fixed places of every period of a frame, removed on receive and inserted on transmit: P25's status

Functions:

Name Description
turns

exp(j(phase + k*rotate)) in degrees for symbols k = start .. start+n-1, k modulo cycle when given

rotating

Symbols of bits on a constellation turned by phase degrees, and by rotate more each symbol (modulo cycle

pilot_layout

(symbols in the frame, start of each pilot block): slots slots of slot symbols, a block of length pilots after

Header

Header(name, constellation, phase, rotate, known, rows, n, scramble, fields, max_errors=None, cycle=None, turn=None)

Bases: _Frame

A physical header at the start of every frame: known symbols, then a code word whose message is the fields

rx: frame -> payload. Each frame's header is decoded (soft, every message tried: the code is short) and its fields
    published from the payload's first symbol (rp.base.control.publish). A header with more than `max_errors` bit errors
    is refused, and the frame dropped. Its estimates are in stream.est[name]: frames, refused, last errors. Each header
    is also emitted as a message (rpps.profile.message) from its first symbol, its fields and bit errors with it:
    crc_ok True when taken, False when refused.
tx: payload -> frame, the header built from the fields as last controlled (`control(modcod=..., ...)`).

Frames start where a profile says (a frame sync before it), or at the start of the stream.

Methods:

Name Description
words

The symbols each message's code word is sent as, after the known part: (2^k, n)

encode_fields

The header's symbols for these field values

decode_fields

(fields, bit errors) of a header's symbols (the known part included)

Source code in src/rpps/symbol/frame.py
def __init__(self, name, constellation, phase, rotate, known, rows, n, scramble, fields, max_errors=None, cycle=None,
             turn=None):
    super().__init__()
    self.name = name
    self.constellation, self.phase, self.rotate, self.cycle = constellation, float(phase), float(rotate), cycle
    self.known_bits = np.asarray(known, dtype=np.uint8)
    self.fields = [(f["name"], int(f["bits"])) for f in fields]
    self.k = sum(b for _, b in self.fields)
    G = np.array([_bits(r, n) for r in rows], dtype=np.uint8)
    if G.shape[0] != self.k:
        raise ConfigError(f"header {name}: {G.shape[0]} code rows for {self.k} field bits")
    self.n = int(n)
    self.mask = np.zeros(self.n, np.uint8) if scramble is None else _bits(scramble, self.n)
    msgs = ((np.arange(2**self.k)[:, None] >> np.arange(self.k - 1, -1, -1)) & 1).astype(np.uint8)
    self.messages = msgs
    self.codebook = ((msgs @ G) % 2) ^ self.mask # (2^k, n)
    self.max_errors = self.n//4 if max_errors is None else int(max_errors)
    self.length = len(self.known_bits) + self.n # Symbols per header (one bit per symbol)
    self.preamble = rotating(self.known_bits, constellation, self.phase, self.rotate, 0, cycle)
    # turn: {"field": f, "degrees": d}: a message with that one-bit field set has its code word sent turned by d more
    # degrees (DVB-S2X: its MODCODs' PLS a quarter turn on from the SOF), so the field is read from the turn and the code
    self.turned = np.zeros(len(self.messages), bool)
    self.turn_deg = 0.0
    if turn:
        names = [f for f, _ in self.fields]
        if turn.get("field") not in names or dict(self.fields)[turn["field"]] != 1:
            raise ConfigError(f"header {name}: turn needs a one-bit field of {names}, not {turn.get('field')!r}")
        self.turned = self.messages[:, names.index(turn["field"])].astype(bool)
        self.turn_deg = float(turn.get("degrees", 0))
    self.CONTROLS = {"frame": "live", **{f: "live" for f, _ in self.fields}}
    self.values = {f: 0 for f, _ in self.fields}
words
words()

The symbols each message's code word is sent as, after the known part: (2^k, n)

Source code in src/rpps/symbol/frame.py
def words(self):
    """The symbols each message's code word is sent as, after the known part: (2^k, n)"""
    return np.array([rotating(w, self.constellation, self.phase + self.turn_deg*t, self.rotate, len(self.known_bits),
                              self.cycle) for w, t in zip(self.codebook, self.turned)])
encode_fields
encode_fields(values)

The header's symbols for these field values

Source code in src/rpps/symbol/frame.py
def encode_fields(self, values):
    """The header's symbols for these field values"""
    bits = np.concatenate([_bits(int(values.get(f, 0)), b) for f, b in self.fields])
    idx = int(bits @ (1 << np.arange(self.k - 1, -1, -1)))
    return np.concatenate((self.preamble, rotating(self.codebook[idx], self.constellation,
                                                   self.phase + self.turn_deg*self.turned[idx], self.rotate,
                                                   len(self.known_bits), self.cycle)))
decode_fields
decode_fields(sym)

(fields, bit errors) of a header's symbols (the known part included)

Source code in src/rpps/symbol/frame.py
def decode_fields(self, sym):
    """(fields, bit errors) of a header's symbols (the known part included)"""
    y = np.asarray(sym[len(self.known_bits):self.length], dtype=np.complex128)
    y = y*np.conj(turns(len(y), self.phase, self.rotate, self.cycle, len(self.known_bits)))
    llr = self.constellation.llr(y) # positive: bit 0
    score = (1.0 - 2.0*self.codebook) @ llr
    if self.turn_deg: # Turned messages scored on the symbols turned back
        llr_t = self.constellation.llr(y*np.exp(-1j*np.deg2rad(self.turn_deg)))
        score = np.where(self.turned, (1.0 - 2.0*self.codebook) @ llr_t, score)
    best = int(np.argmax(score))
    if self.turned[best]:
        llr = llr_t
    errors = int(np.sum((llr < 0) != self.codebook[best].astype(bool)))
    m = self.messages[best]
    out, i = {}, 0
    for f, b in self.fields:
        out[f] = int(m[i:i + b] @ (1 << np.arange(b - 1, -1, -1)))
        i += b
    return out, errors

Pilots

Pilots(slot=90, every=16, length=36, value=(1 + 1j) / np.sqrt(2), slots=None, pilots=True, name='pilots')

Bases: _Frame

Blocks of known pilot symbols among a frame's data: removed on receive, inserted on transmit

The frame has slots slots of slot symbols; with pilots on, a block of length pilots (each value) follows every every slots but the last (DVB-S2: 90, 16, 36, (1+j)/sqrt2). On receive, symbols past the end of a frame are dropped (counted in stream.est[name]["extra"]): the next frame starts where a profile says.

Methods:

Name Description
kernel

The batch pilot remover (decoding), for the frame layout params set: pilots, and what is past the frame, dropped

Source code in src/rpps/symbol/frame.py
def __init__(self, slot=90, every=16, length=36, value=(1 + 1j)/np.sqrt(2), slots=None, pilots=True, name="pilots"):
    super().__init__()
    self.slot, self.every, self.length, self.value = int(slot), int(every), int(length), complex(value)
    self.slots, self.pilots, self.name = slots, bool(pilots), name
kernel
kernel(params, how)

The batch pilot remover (decoding), for the frame layout params set: pilots, and what is past the frame, dropped

Source code in src/rpps/symbol/frame.py
def kernel(self, params, how):
    """The batch pilot remover (decoding), for the frame layout `params` set: pilots, and what is past the frame, dropped"""
    if how != "/":
        return None
    from .kernels import Gather
    if params:
        self.control(**params)
    if self.slots is None:
        return Gather(lambda L: np.ones(L, dtype=bool), str(self))
    total, starts = self.layout()
    def keep(L):
        pil = np.zeros(L, dtype=bool)
        for s in starts:
            pil[s:s + self.length] = True
        return ~pil[:L] & (np.arange(L) < total)
    return Gather(keep, str(self))

PhaseScramble

PhaseScramble(sequence, offsets=(0,), step=90.0, length=None, name='scramble')

Bases: _Frame

Every symbol of a frame turned by step * R(i) degrees, R(i) = sum_j 2**(J-1-j) z(i + offsets[j]) for a binary sequence z (rpps.sequence), i counted from the frame start (and from 0 again every length symbols when that is set). DVB-S2 PL scrambling: z the Gold sequence, offsets (131072, 0), step 90 degrees. Receiving turns them back.

Methods:

Name Description
R

R(0..n-1)

kernel

The batch rotation, for a frame that starts at its first symbol (control marks it) and restarts every length

Source code in src/rpps/symbol/frame.py
def __init__(self, sequence, offsets=(0,), step=90.0, length=None, name="scramble"):
    super().__init__()
    self.sequence, self.offsets, self.step = sequence, [int(o) for o in offsets], float(step)
    self.length, self.name = length, name
    self._R = np.zeros(0, dtype=np.int64)
R
R(n)

R(0..n-1)

Source code in src/rpps/symbol/frame.py
def R(self, n):
    """R(0..n-1)"""
    if len(self._R) < n:
        z = np.asarray(self.sequence.bits(n + max(self.offsets)), dtype=np.int64)
        J = len(self.offsets)
        self._R = sum((z[o:o + n] << (J - 1 - j)) for j, o in enumerate(self.offsets))
    return self._R[:n]
kernel
kernel(params, how)

The batch rotation, for a frame that starts at its first symbol (control marks it) and restarts every length

Source code in src/rpps/symbol/frame.py
def kernel(self, params, how):
    """The batch rotation, for a frame that starts at its first symbol (`control` marks it) and restarts every `length`"""
    if how not in ("/", "*"):
        return None
    from .kernels import Rotate
    if params:
        self.control(**params)
    enc, step, length = how == "*", self.step, self.length
    def phasors(L):
        i = np.arange(L)
        if length:
            i = i % length
        r = self.R(int(i.max()) + 1)[i] if L else np.zeros(0, np.int64)
        return np.exp((1j if enc else -1j)*np.deg2rad(step)*r)
    return Rotate(phasors, self.name)

Marker

Marker(symbols=None, length=None, zc=None, root=None, shift=0, name='marker')

Bases: _Frame

Known symbols at the start of every frame (a symbol-level sync word: a Zadoff-Chu preamble, a word already mapped)

rx: frame -> the symbols after the marker (a frame sync gives each frame from its preamble on); the marker's
    match, |<marker, received>| / (|marker| |received|), is in stream.est[name]["match"]
tx: the marker, then the frame's symbols

symbols: the marker; or zc (a length) and the Zadoff-Chu root and shift, controlled per frame (root, shift), or sequence (a definition with symbols), so a transmitter sends the preamble that says what its frame is. length: symbols of a frame after the marker; None: frames as a profile's control starts them (frame).

Source code in src/rpps/symbol/frame.py
def __init__(self, symbols=None, length=None, zc=None, root=None, shift=0, name="marker"):
    super().__init__()
    self.zc, self.root, self.shift, self.name = zc, root, int(shift or 0), name
    self.length = None if length is None else int(length)
    if self.length is not None and self.length <= 0:
        raise ValueError("symbol Marker: the frame length after the marker is positive (or None: frames by control)")
    self.symbols = None if symbols is None else np.asarray(symbols, dtype=np.complex128)
    if self.symbols is None:
        self._make()

Puncture

Puncture(every, at, value=0.0, name='puncture')

Bases: _Frame

Symbols at fixed places of every period of a frame, removed on receive and inserted on transmit: P25's status symbol after every 35 (every 36, at [35]), counted from the frame start

rx: the frame without them; tx: the frame with `value` put in (a status symbol's level, a known point), its
    last ones (after its last data symbol: P25's status symbol at 359 of 360) when the next frame starts or the
    stream ends
Source code in src/rpps/symbol/frame.py
def __init__(self, every, at, value=0.0, name="puncture"):
    super().__init__()
    self.every = int(every)
    self.at = sorted({int(a) % self.every for a in at})
    if not self.at or len(self.at) >= self.every:
        raise ValueError(f"symbol Puncture: some, not all, of every {self.every} positions")
    self.value, self.name = complex(value), name
    self.keep = np.array([i for i in range(self.every) if i not in self.at]) # where the data of a period goes
    self._hole = np.zeros(self.every, bool)
    self._hole[self.at] = True

turns

turns(n, phase=0.0, rotate=0.0, cycle=None, start=0)

exp(j(phase + k*rotate)) in degrees for symbols k = start .. start+n-1, k modulo cycle when given

Source code in src/rpps/symbol/frame.py
def turns(n, phase=0.0, rotate=0.0, cycle=None, start=0):
    """exp(j(phase + k*rotate)) in degrees for symbols k = start .. start+n-1, k modulo cycle when given"""
    k = start + np.arange(n)
    if cycle:
        k = k % int(cycle)
    return np.exp(1j*np.deg2rad(phase + rotate*k))

rotating

rotating(bits, constellation, phase=0.0, rotate=0.0, start=0, cycle=None)

Symbols of bits on a constellation turned by phase degrees, and by rotate more each symbol (modulo cycle symbols), counting from start (pi/2-BPSK: "bpsk", 45, 90, cycle 2)

Source code in src/rpps/symbol/frame.py
def rotating(bits, constellation, phase=0.0, rotate=0.0, start=0, cycle=None):
    """Symbols of bits on a constellation turned by `phase` degrees, and by `rotate` more each symbol (modulo `cycle`
    symbols), counting from `start` (pi/2-BPSK: "bpsk", 45, 90, cycle 2)"""
    sym = constellation.modulate(np.asarray(bits)).astype(np.complex128)
    return sym*turns(len(sym), phase, rotate, cycle, start)

pilot_layout

pilot_layout(slots, pilots, slot=90, every=16, length=36)

(symbols in the frame, start of each pilot block): slots slots of slot symbols, a block of length pilots after every every slots but the last

Source code in src/rpps/symbol/frame.py
def pilot_layout(slots, pilots, slot=90, every=16, length=36):
    """(symbols in the frame, start of each pilot block): `slots` slots of `slot` symbols, a block of `length` pilots after
    every `every` slots but the last"""
    blocks = (slots - 1)//every if pilots else 0
    starts = [every*slot*(b + 1) + length*b for b in range(blocks)]
    return slots*slot + blocks*length, starts

kernels

Batch kernels of the symbol operators: Demap of a constellation, Rotate of a phase scrambler, Gather of a pilot or header remover

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). Demap on a GPU is a device kernel of its own (DEMAP_SOURCE)

Classes:

Name Description
Demap

Symbols to per-bit LLRs, as Constellation.llr: the noise level of each row (frame) estimated from its own symbols by EM

Rotate

Symbols turned by a fixed phasor each position: the batch of a phase scrambler, or any known rotation. phasors(L): the

Gather

Symbols kept by a fixed selection of positions (pilots and headers removed): keep(L) is the boolean mask of a frame of L

Demap

Demap(points, labels, maxlog=False, name='demap', iters=8, floor=1e-06)

Bases: Kernel

Symbols to per-bit LLRs, as Constellation.llr: the noise level of each row (frame) estimated from its own symbols by EM over the points, then log(P(0)/P(1)) per bit (exact, or max-log). One row in gives bits_per_symbol LLRs per symbol

Source code in src/rpps/symbol/kernels.py
def __init__(self, points, labels, maxlog=False, name="demap", iters=8, floor=1e-6):
    self.floor = floor
    self.points, self.labels, self.maxlog, self.iters = np.asarray(points, np.complex128), np.asarray(labels, bool), bool(maxlog), iters
    self.bps = self.labels.shape[1]
    self._masks = mask_matrix(self.labels)
    self.name = f"demap:{name}"

Rotate

Rotate(phasors, name='rotate')

Bases: Kernel

Symbols turned by a fixed phasor each position: the batch of a phase scrambler, or any known rotation. phasors(L): the unit phasors of a frame of L symbols, made once per length

Source code in src/rpps/symbol/kernels.py
def __init__(self, phasors, name="rotate"):
    self.phasors = _per_length(phasors)
    self.name = f"rotate:{name}"

Gather

Gather(keep, name='gather')

Bases: Kernel

Symbols kept by a fixed selection of positions (pilots and headers removed): keep(L) is the boolean mask of a frame of L

Source code in src/rpps/symbol/kernels.py
def __init__(self, keep, name="gather"):
    self.keep = _per_length(keep)
    self.name = f"gather:{name}"

mapping

Bit maps of a constellation: which value (bits, first bit most significant) each point carries, and the maps a receiver that does not know the carrier phase or the IQ sense has to try (every rotation the constellation allows, with and without spectral inversion)

An "Inverted" map is the labelling a conjugated stream reads right with: on its own it says nothing about the spectrum (a standard's map can be a conjugate of another, DVB-S2's QPSK is "R090 Grey Inverted"). The spectrum's sense is found by rpps.sync.Inversion (known symbols that turn) or a code on a standard's map (rpps.analysis.identify CodeDetection.inverted).

Classes:

Name Description
Mapping

Constellation map

Functions:

Name Description
symmetries

Every (rotation [rad], conjugated) that maps the constellation onto itself, as (angle, flip, permutation)

bit_rotations

A constellation's turns that are bit swaps and inversions. Rotations (no conjugate) acting on its labels as a

expand_maps

The given maps, then the first one turned by every rotation the constellation allows and spectrally inverted

hard_bits

Hard bits of symbols y: the labels (values, first bit most significant) of the nearest points, as uint8 bits

Mapping

Mapping(map=None, comment='', turn=0.0, tags=())

Constellation map

Methods:

Name Description
str

Return map values as str

Source code in src/rpps/symbol/mapping.py
def __init__(self, map=None, comment="", turn=0.0, tags=()):
    self._comment = comment
    self.rotation = 0.0 # Radians the channel turns the constellation by for this map to be the right one
    self.turn = float(turn) # Radians the points sit turned by while this map is used (a standard's labelling of a turned set)
    self.aka = "" # A standard's name for this map, where one is given that is the same labels ("DVB-S2")
    self.tags = list(tags) # The standards that label the points by this map (a definition map's "tags")
    self.arr = np.array([], dtype=np.int64) if map is None else np.array(map)
    self._inv = False
str
str()

Return map values as str

Source code in src/rpps/symbol/mapping.py
def str(self):
    """Return map values as str"""
    return "-".join(self.arr.astype(str))

symmetries

symmetries(points)

Every (rotation [rad], conjugated) that maps the constellation onto itself, as (angle, flip, permutation) A flip (spectral inversion) is applied first, then the rotation.

Source code in src/rpps/symbol/mapping.py
def symmetries(points):
    """Every (rotation [rad], conjugated) that maps the constellation onto itself, as (angle, flip, permutation)
    A flip (spectral inversion) is applied first, then the rotation."""
    pts = np.asarray(points, dtype=np.complex128)
    ref = next((p for p in pts if abs(p) > 1e-9), None)
    out = []
    for flip in (False, True):
        base = np.conj if flip else (lambda z: z)
        angles = {0.0}
        if ref is not None:
            for p in pts:
                if abs(abs(p) - abs(ref)) < 1e-6*abs(ref):
                    angles.add(float(np.angle(p/ref) % (2*np.pi)) if not flip else float(np.angle(p/np.conj(ref)) % (2*np.pi)))
        for th in sorted(angles):
            q = _perm(pts, lambda z, th=th, base=base: base(z)*np.exp(1j*th))
            if q is not None:
                out.append((th, flip, q))
    return out

bit_rotations

bit_rotations(points, labels, bits)

A constellation's turns that are bit swaps and inversions. Rotations (no conjugate) acting on its labels as a permutation and inversion of the bits: [(perm, flip)] with bit j of a turned point's label = bit perm[j] of the point's label, inverted where flip[j] (Gray QPSK's 90 degree turns: a swap and one bit inverted). Rotations that don't (8PSK's, most QAM's) are left out. On LLRs the same turn is new[j] = old[perm[j]] * (-1 if flip[j]): what a receive tries when the carrier's M-fold phase is unknown (rp.sync.Puncture). The identity is first.

Source code in src/rpps/symbol/mapping.py
def bit_rotations(points, labels, bits):
    """A constellation's turns that are bit swaps and inversions. Rotations (no conjugate) acting on its labels as a
    permutation and inversion of the bits: [(perm, flip)] with bit j of a turned point's label = bit perm[j] of the point's label, inverted where flip[j]
    (Gray QPSK's 90 degree turns: a swap and one bit inverted). Rotations that don't (8PSK's, most QAM's) are left out.
    On LLRs the same turn is new[j] = old[perm[j]] * (-1 if flip[j]): what a receive tries when the carrier's M-fold
    phase is unknown (rp.sync.Puncture). The identity is first."""
    import itertools
    pts = np.asarray(points, dtype=np.complex128)
    lab = np.asarray(labels, dtype=np.int64)
    B = ((lab[:, None] >> np.arange(bits - 1, -1, -1)) & 1).astype(bool) # (points, bits): bit j of point i's label
    out = []
    for th, flip, q in symmetries(pts):
        if flip:
            continue
        T = B[q] # the turned point's label bits
        for perm in itertools.permutations(range(bits)):
            f = T[0] ^ B[0][list(perm)]
            if np.array_equal(T, B[:, list(perm)] ^ f[None, :]):
                out.append((tuple(perm), tuple(bool(v) for v in f)))
                break
    ident = (tuple(range(bits)), (False,)*bits)
    return [ident] + [r for r in dict.fromkeys(out) if r != ident]

expand_maps

expand_maps(points, maps)

The given maps, then the first one turned by every rotation the constellation allows and spectrally inverted (conjugated) with each. The point is a receiver that doesn't know the carrier phase or the IQ sense: one of these is the map that decodes. Named R Normal|Inverted. A later map with a name of its own (not R: a standard's labelling, "DVB-S2") that is one of these gives it that name too ("R000 Grey Inverted (DVB-S2)"), so either picks it; one that is none of them (a map that turns the points) comes last, as given. Returns a new list of new maps

Source code in src/rpps/symbol/mapping.py
def expand_maps(points, maps):
    """The given maps, then the first one turned by every rotation the constellation allows and spectrally inverted
    (conjugated) with each. The point is a receiver that doesn't know the carrier phase or the IQ sense: one of
    these is the map that decodes. Named R<degrees> <comment> Normal|Inverted. A later map with a name of its own (not
    R<degrees>: a standard's labelling, "DVB-S2") that is one of these gives it that name too ("R000 Grey Inverted
    (DVB-S2)"), so either picks it; one that is none of them (a map that turns the points) comes last, as given.
    Returns a new list of new maps
    """
    maps = [m.copy() for m in maps] # The caller's maps are not touched
    base = maps[0]
    if not re.match(r"^R\d+", base._comment):
        base._comment = f"R000 {base._comment}".strip() # The map as given is the unrotated one
    rest = re.sub(r"^R\d+(\.\d+)?\s*", "", base._comment).strip()
    named = {} # labels -> a map with a name of its own, the points unturned
    rest_named = [] # Those that turn the points: never one of the turned maps
    out, seen = [], {}
    for i, m in enumerate(maps):
        key = tuple(np.asarray(m.arr).tolist())
        if i and not re.match(r"^R\d+", m._comment):
            if m.turn:
                rest_named.append(m)
            elif key in seen:
                seen[key].aka, seen[key].tags = m._comment, [*seen[key].tags, *m.tags]
            else:
                named[key] = m
            continue
        out.append(m)
        seen[key] = m
    for th, flip, q in symmetries(points):
        arr = np.empty_like(np.asarray(base.arr))
        arr[q] = np.asarray(base.arr) # The point p moved to q, carrying its label
        key = tuple(arr.tolist())
        if key in seen:
            seen[key].rotation, seen[key].inverted = th, flip # A map that was already defined: record what it is
            continue
        deg = np.degrees(th)
        tag = f"R{deg:03.0f}" if abs(deg - round(deg)) < 1e-6 else f"R{deg:05.1f}"
        m = Mapping(arr, f"{tag} {rest}".strip(), base.turn) # (a turned map's turns use its points turned too)
        m.inverted = flip
        m.rotation = th
        if key in named:
            n = named.pop(key)
            m.aka, m.tags = n._comment, list(n.tags)
        seen[key] = m
        out.append(m)
    return out + list(named.values()) + rest_named

hard_bits

hard_bits(y, pts, labels)

Hard bits of symbols y: the labels (values, first bit most significant) of the nearest points, as uint8 bits

Source code in src/rpps/symbol/mapping.py
def hard_bits(y, pts, labels):
    """Hard bits of symbols y: the labels (values, first bit most significant) of the nearest points, as uint8 bits"""
    idx = np.argmin(np.abs(np.asarray(y)[:, None] - np.asarray(pts)[None, :]), axis=1)
    bps = int(np.log2(len(pts)))
    return ((np.asarray(labels, dtype=np.int64)[idx][:, None] >> np.arange(bps-1, -1, -1)) & 1).astype(np.uint8).reshape(-1)

modulation

Classes:

Name Description
Modulation

Modulation parent class

Modulation

Modulation()

Bases: Pipe

Modulation parent class

Methods:

Name Description
encode

Convert bits to IQ samples

decode

Convert IQ samples to bits

draw_refs

Draw constellation points on viz

load

Load modulation from json

Source code in src/rpps/symbol/modulation.py
def __init__(self):
    self.log = Logger().Child("Modulation", _config.LOG_MOD).Child(type(self).name)
encode
encode(data: Digital) -> Mod

Convert bits to IQ samples

Source code in src/rpps/symbol/modulation.py
def encode(self, data: Digital) -> Mod:
    """Convert bits to IQ samples"""
    raise NotImplementedError()
decode
decode(data: Analog) -> Mod

Convert IQ samples to bits

Source code in src/rpps/symbol/modulation.py
def decode(self, data: Analog) -> Mod:
    """Convert IQ samples to bits"""
    raise NotImplementedError()
draw_refs
draw_refs(points: bool = True, ref: bool = True, ax=None)

Draw constellation points on viz

Source code in src/rpps/symbol/modulation.py
def draw_refs(self, points: bool = True, ref: bool = True, ax=None):
    """Draw constellation points on viz"""
    return NotImplemented
load staticmethod
load(name: str, obj: dict)

Load modulation from json

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

ofdm

Classes:

Name Description
Carriers

OFDM carrier allocation, the symbol-transform part of OFDM: data symbols <-> the carrier values of each OFDM symbol

Carriers

Carriers(n_fft=64, used=None, pilots=(-21, -7, 7, 21))

Bases: Modulation

OFDM carrier allocation, the symbol-transform part of OFDM: data symbols <-> the carrier values of each OFDM symbol

carriers = rp.symbol.Carriers()                                     # 64 carriers: 48 data, 4 pilots (802.11a layout)
wave = bits * qam * carriers + rp.wave.OFDMTx(64, 16)             # transmit
syms = wave + rp.wave.OFDMRx(64, 16) + rp.sync.PilotEqualizer(carriers) / carriers   # receive

Encoding puts each data_per_symbol data symbols on the data carriers, the pilots' known values on the pilot carriers (their sign alternating from one OFDM symbol to the next), and zero on the rest: n_fft values per OFDM symbol, in FFT bin order. Decoding takes those n_fft values back to the data symbols. Equalizing them is sync's job (rp.sync.PilotEqualizer), and the FFT and cyclic prefix are the wave transform's (rp.wave.OFDMTx, OFDMRx).

n_fft: carriers. used: carrier numbers (-n_fft/2 .. n_fft/2 - 1, 0 is DC) that carry something, default 52 (802.11a). pilots: carriers (a subset of used) with a known value, default -21 -7 7 21. More pilots follow a longer echo.

Methods:

Name Description
bins

FFT bins of carrier numbers

pilot_values

Pilot values of OFDM symbols number index (an array): (len(index), pilots); the sign alternates by symbol

encode

Data symbols -> n_fft carrier values per OFDM symbol. A partial last OFDM symbol is held, or padded when flushed

decode

n_fft carrier values per OFDM symbol (equalized) -> the data symbols

Source code in src/rpps/symbol/ofdm.py
def __init__(self, n_fft=64, used=None, pilots=(-21, -7, 7, 21)):
    super().__init__()
    self.n_fft = int(n_fft)
    used = [k for k in range(-26, 27) if k != 0] if used is None else sorted(used)
    if max(map(abs, used)) > self.n_fft//2:
        raise ValueError("used carriers don't fit the FFT")
    self.pilots = tuple(pilots)
    self.used = tuple(used)
    self.data = tuple(k for k in used if k not in self.pilots)
    if not set(self.pilots) <= set(used):
        raise ValueError("pilots must be among the used carriers")
    self._pilot_vals = np.array([1, 1, 1, -1][:len(self.pilots)] + [1]*max(0, len(self.pilots) - 4), dtype=np.complex64)
bins
bins(k)

FFT bins of carrier numbers

Source code in src/rpps/symbol/ofdm.py
def bins(self, k):
    """FFT bins of carrier numbers"""
    return np.asarray(k) % self.n_fft
pilot_values
pilot_values(index)

Pilot values of OFDM symbols number index (an array): (len(index), pilots); the sign alternates by symbol

Source code in src/rpps/symbol/ofdm.py
def pilot_values(self, index):
    """Pilot values of OFDM symbols number `index` (an array): (len(index), pilots); the sign alternates by symbol"""
    sign = np.where(np.asarray(index) % 2 == 0, 1.0, -1.0)[:, None]
    return sign*self._pilot_vals[None, :]
encode
encode(data)

Data symbols -> n_fft carrier values per OFDM symbol. A partial last OFDM symbol is held, or padded when flushed

Source code in src/rpps/symbol/ofdm.py
def encode(self, data):
    """Data symbols -> n_fft carrier values per OFDM symbol. A partial last OFDM symbol is held, or padded when flushed"""
    ctx = dict(data.ctx)
    syms = align(ctx, (self, True), np.asarray(data.data), self.data_per_symbol, pad=True)
    n = len(syms)//self.data_per_symbol
    first = ctx.get((self, "count"), 0)
    grid = np.zeros((n, self.n_fft), dtype=np.complex64)
    grid[:, self.bins(self.data)] = syms.reshape(n, self.data_per_symbol)
    grid[:, self.bins(self.pilots)] = self.pilot_values(first + np.arange(n))
    ctx[(self, "count")] = first + n
    return data.derive(grid.reshape(-1), Category.SYMBOL, dtype.SYMBOLS, Mod, ctx)
decode
decode(data)

n_fft carrier values per OFDM symbol (equalized) -> the data symbols

Source code in src/rpps/symbol/ofdm.py
def decode(self, data):
    """n_fft carrier values per OFDM symbol (equalized) -> the data symbols"""
    ctx = dict(data.ctx)
    x = align(ctx, (self, False), np.asarray(data.data), self.n_fft, pad=False, log=self.log)
    grid = x.reshape(-1, self.n_fft)
    out = grid[:, self.bins(self.data)].reshape(-1)
    return data.derive(out.astype(np.complex64), Category.SYMBOL, dtype.SYMBOLS, Mod, ctx)

serial

Constellations: config/constellation/[/].json, loaded with rp.symbol.load("QPSK"); physical headers: config/header/physical/.json, rp.symbol.load_header("dvbs2_pl")

load only loads definitions; the usual shapes by name ("16QAM", "64QAM", "16APSK", "4ASK", "OOK") come from generate, so a DVB-S2 16APSK (load("apsk/dvbs2_16apsk", rate="2/3")) is never confused with the generic one (generate("16APSK")).

constellation   {"base": "constellation",
                 "points": [{"mag": 1, "pha": 45}, {"re": 0.7, "im": -0.7}, [-0.7, 0.7], ...],   where the points are: phase in degrees
                 or "rings": [{"n": 4, "mag": 1, "pha": 45}, {"n": 12, "mag": 2.85, "pha": 15}],    PSK / APSK rings, innermost first
                 "rotate": -45,                                                                      degrees added to every point
                 "maps": [{"map": [0, 1, 3, 2], "comment": "Grey"}, ...],                           the ways of labelling them with bits
                 "normalize": true}                                                                  scale to unit mean power (default)
    maps[i].map[point] is the value (bits, first bit most significant) the point carries. The first map is the default;
    its turns are not listed (the code makes them, below): a map in the file is a labelling of its own (a standard's).
    `rp.symbol.load(name, "R090")` picks another by index or a word of its comment, and every rotation and spectral inversion of
    the first map is added (see rpps.symbol.mapping).
header          {"base": "header", "type": "physical" | "link"}: known symbols then a short code carrying fields
                (rpps.symbol.frame.Header), or a link header (rpps.link.header.Header): one resource, `header`

Functions:

Name Description
load_header

A physical header definition: load_header("dvbs2_pl") (config/header/physical)

ls

List available modulation types: {category: [names]}

load_or_generate

A definition named name, else the shape generate makes of it: for names that come out of a detector ("8PSK",

init

Initialize modulation

generate

Make a constellation from its name: "16QAM", "QAM64", "8PSK", "16APSK", "4ASK", "OOK"... (no definition file)

load

Load a constellation definition, config/constellation//.json: load("psk/qpsk"), load("apsk/dvbs2_16apsk", rate="3/4")

load_header

load_header(name: str, **params) -> Header

A physical header definition: load_header("dvbs2_pl") (config/header/physical)

Source code in src/rpps/symbol/serial.py
def load_header(name: str, **params) -> Header:
    """A physical header definition: `load_header("dvbs2_pl")` (config/header/physical)"""
    from ..link import serial as _link  # noqa: F401 -- registers the header resource (physical and link) with the link definitions
    h = _config.load("header", name, "physical", params=params)
    return h

ls

ls(blind=False)

List available modulation types: {category: [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/symbol/serial.py
def ls(blind=False):
    """List available modulation types: {category: [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("constellation", blind=blind)

load_or_generate

load_or_generate(name: str, mapping=None) -> Constellation

A definition named name, else the shape generate makes of it: for names that come out of a detector ("8PSK", "16QAM"), where either can turn up. Code that knows which it wants calls load or generate

Source code in src/rpps/symbol/serial.py
def load_or_generate(name: str, mapping=None) -> Constellation:
    """A definition named `name`, else the shape `generate` makes of it: for names that come out of a detector ("8PSK",
    "16QAM"), where either can turn up. Code that knows which it wants calls `load` or `generate`"""
    if _config.find("constellation", name) is not None:
        return load(name, mapping)
    mod = generate(name)
    if mapping is not None:
        mod.set_mapping(mapping)
    return mod

init

init(name, obj: dict) -> Modulation

Initialize modulation

Source code in src/rpps/symbol/serial.py
def init(name, obj: dict) -> Modulation:
    """Initialize modulation"""
    return _config.load_obj("constellation", name, obj)

generate

generate(name: str) -> Constellation

Make a constellation from its name: "16QAM", "QAM64", "8PSK", "16APSK", "4ASK", "OOK"... (no definition file)

Source code in src/rpps/symbol/serial.py
def generate(name: str) -> Constellation:
    """Make a constellation from its name: "16QAM", "QAM64", "8PSK", "16APSK", "4ASK", "OOK"... (no definition file)"""
    m = _GENERATED.match(name.strip())
    if m is None:
        raise ConfigError(f"No modulation {name!r}: not a definition ({ls()}) and not a name like 16QAM, 8PSK, 16APSK, 4ASK")
    order, kind = m.group(1) or m.group(3), m.group(2).upper()
    M = int(order) if order else None
    if kind == "BPSK":
        return PSK(2)
    if kind == "QPSK":
        return PSK(4)
    if kind == "OOK":
        return ASK(2)
    if M is None:
        raise ConfigError(f"{name!r} needs an order, like 16{kind}")
    return {"PSK": PSK, "QAM": QAM, "APSK": APSK, "ASK": ASK}[kind](M)

load

load(ref: str, mapping=None, **params) -> Constellation

Load a constellation definition, config/constellation//.json: load("psk/qpsk"), load("apsk/dvbs2_16apsk", rate="3/4") (a bare name works while unique). For the usual shapes by name use generate("16QAM").

mapping: which bit map, if not the first: an index, or a word of its comment (load("psk/qpsk", "R090")) params: values of the definition's "params" (see rp._config.resolve)

Source code in src/rpps/symbol/serial.py
def load(ref: str, mapping=None, **params) -> Constellation:
    """Load a constellation definition, config/constellation/<group>/<name>.json: `load("psk/qpsk")`, `load("apsk/dvbs2_16apsk", rate="3/4")`
    (a bare name works while unique). For the usual shapes by name use `generate("16QAM")`.

    mapping: which bit map, if not the first: an index, or a word of its comment (`load("psk/qpsk", "R090")`)
    params: values of the definition's "params" (see rp._config.resolve)"""
    path = _config.find("constellation", ref)
    if path is None:
        hint = f"; {ref!r} is a shape: rp.symbol.generate({ref!r})" if _GENERATED.match(str(ref).strip()) else ""
        raise ConfigError(f"constellation/{ref}: no definition{hint}; have {ls()}")
    mod = init(ref, _config.resolve(_config.read(path), params, f"constellation/{ref}"))
    if mapping is not None:
        mod.set_mapping(mapping)
    return mod # type: ignore

shapes

Constellation generators: points (unit mean power) and the labels that go with them

A label list is in the form Mapping uses: labels[point] = the value (bits, first bit most significant) it carries.

Functions:

Name Description
gray

Gray code of integers

psk

M points round the unit circle, counter-clockwise from offset (default: pi/M, so QPSK sits at 45 degrees; BPSK at 0,

ask

M amplitudes, evenly spaced, on the real axis (bipolar: -1..1 like PAM, otherwise 0..1 like OOK for M=2). Labels: Gray

qam

Square (4, 16, 64, 256...) or cross (32, 128, 512...) QAM, labels Gray per axis

apsk

Amplitude-phase keying on concentric rings

gray

gray(n)

Gray code of integers

Source code in src/rpps/symbol/shapes.py
def gray(n):
    """Gray code of integers"""
    n = np.asarray(n)
    return n ^ (n >> 1)

psk

psk(M, offset=None)

M points round the unit circle, counter-clockwise from offset (default: pi/M, so QPSK sits at 45 degrees; BPSK at 0, on the real axis, as config/constellation/psk/bpsk). Labels: Gray, going round the circle

Source code in src/rpps/symbol/shapes.py
def psk(M, offset=None):
    """M points round the unit circle, counter-clockwise from `offset` (default: pi/M, so QPSK sits at 45 degrees; BPSK at 0,
    on the real axis, as config/constellation/psk/bpsk). Labels: Gray, going round the circle"""
    offset = (0.0 if M == 2 else np.pi/M) if offset is None else offset
    pts = np.exp(1j*(offset + 2*np.pi*np.arange(M)/M))
    return pts, gray(np.arange(M))

ask

ask(M, bipolar=True)

M amplitudes, evenly spaced, on the real axis (bipolar: -1..1 like PAM, otherwise 0..1 like OOK for M=2). Labels: Gray

Source code in src/rpps/symbol/shapes.py
def ask(M, bipolar=True):
    """M amplitudes, evenly spaced, on the real axis (bipolar: -1..1 like PAM, otherwise 0..1 like OOK for M=2). Labels: Gray"""
    lev = np.arange(M)
    pts = (2*lev - (M-1)) if bipolar else lev
    return _unit_power(pts), gray(lev)

qam

qam(M)

Square (4, 16, 64, 256...) or cross (32, 128, 512...) QAM, labels Gray per axis

Source code in src/rpps/symbol/shapes.py
def qam(M):
    """Square (4, 16, 64, 256...) or cross (32, 128, 512...) QAM, labels Gray per axis"""
    k = int(np.log2(M))
    if 2**k != M or k < 2:
        raise ValueError(f"QAM needs M = 2**k with k >= 2, got {M}")
    if k % 2 == 0:
        L = 2**(k//2)
        i, q = np.meshgrid(np.arange(L), np.arange(L), indexing="ij")
        pts = (2*i - (L-1)) + 1j*(2*q - (L-1))
        lab = (gray(i) << (k//2)) | gray(q)
        return _unit_power(pts.reshape(-1)), lab.reshape(-1)
    # Cross: a square of 6c*6c points without its four c*c corner blocks. No labelling is Gray everywhere, so start from
    # the plain order and swap labels while that cuts the bit differences between nearest neighbours (fixed seed)
    c = 2**((k-5)//2) # Corner block side
    L = 6*c # Side of the square
    pts = np.array([(2*a - (L-1)) + 1j*(2*b - (L-1)) for a in range(L) for b in range(L)
                    if not ((a < c or a >= L-c) and (b < c or b >= L-c))])
    return _unit_power(pts), _best_labels(pts, k)

apsk

apsk(rings=(4, 12), ratios=None, phases=None)

Amplitude-phase keying on concentric rings

rings: points per ring, innermost first, e.g. (4, 12) is 16APSK and (4, 12, 16) is 32APSK ratios: radius of each outer ring over the innermost one (default DVB-S2-like) Labels: the ring picks the top bits, Gray round the ring for the rest (not the DVB-S2 labelling, which is a config definition)

Source code in src/rpps/symbol/shapes.py
def apsk(rings=(4, 12), ratios=None, phases=None):
    """Amplitude-phase keying on concentric rings

    rings: points per ring, innermost first, e.g. (4, 12) is 16APSK and (4, 12, 16) is 32APSK
    ratios: radius of each outer ring over the innermost one (default DVB-S2-like)
    Labels: the ring picks the top bits, Gray round the ring for the rest (not the DVB-S2 labelling, which is a config definition)
    """
    rings = tuple(rings)
    M = sum(rings)
    if 2**int(np.log2(M)) != M:
        raise ValueError(f"APSK needs a power of two points, got {M}")
    if ratios is None:
        ratios = _APSK_RATIO.get(rings, tuple(2.0*(i+1) for i in range(len(rings)-1)))
    ratios = (1.0, *np.atleast_1d(ratios))
    pts, lab, base = [], [], 0
    for r, (n, rad) in enumerate(zip(rings, ratios)):
        ph = np.pi/n if phases is None else phases[r]
        pts += list(rad*np.exp(1j*(ph + 2*np.pi*np.arange(n)/n)))
        # Gray round a ring whose size is a power of two, plain order otherwise
        lab += list(base + (gray(np.arange(n)) if 2**int(np.log2(n)) == n else np.arange(n)))
        base += n
    return _unit_power(pts), np.array(lab)

spread

Classes:

Name Description
Spread

Direct-sequence spreading as an operator: symbols (or bits) to chips and back, one sample per chip (shape and upsample them

Spread

Spread(code: Code, pair=False)

Bases: Modulation

Direct-sequence spreading as an operator: symbols (or bits) to chips and back, one sample per chip (shape and upsample them with the waveform stages)

chips = syms * Spread(code)                 # one sequence (Barker, GPS C/A): every symbol times the sequence
syms = chips / Spread(code)                 # correlate each code period
chips = bits * Spread(set)                  # a set (802.15.4): every log2(count) bits, the first the least significant, pick a sequence
llr = chips / Spread(set)                   # strongest correlations: one LLR per bit

pair: put even chips on I and odd chips on Q (complex chips at half the chip rate), as O-QPSK carries 802.15.4's. Decoding a set through pair needs the carrier phase removed first: the I and Q parts are taken as the two rails of chips. A single-sequence code works on symbols that need a code period of chips each; a partial period is held until the rest arrives.

Methods:

Name Description
takes

A set encodes channel bits (or data bits, uncoded); one sequence encodes symbols. Both decode chips (symbols)

pos_rate

Output items per input item (rpps.profile positions): chips per symbol or bits, or the other way round

Source code in src/rpps/symbol/spread.py
def __init__(self, code: Code, pair=False):
    super().__init__()
    self.code, self.pair = code, bool(pair)
    if pair and code.length % 2:
        raise ValueError("pair needs an even number of chips per sequence")
    if code.count > 1:
        self.bits_per_symbol = int(np.log2(code.count))
        if 2**self.bits_per_symbol != code.count:
            raise ValueError(f"A set of {code.count} sequences is not a power of two")
takes
takes(encode)

A set encodes channel bits (or data bits, uncoded); one sequence encodes symbols. Both decode chips (symbols)

Source code in src/rpps/symbol/spread.py
def takes(self, encode):
    """A set encodes channel bits (or data bits, uncoded); one sequence encodes symbols. Both decode chips (symbols)"""
    if encode and self.code.count > 1:
        return {Rep.CHANNEL, Rep.DATA}
    return {Rep.SYMBOLS}
pos_rate
pos_rate(decode)

Output items per input item (rpps.profile positions): chips per symbol or bits, or the other way round

Source code in src/rpps/symbol/spread.py
def pos_rate(self, decode):
    """Output items per input item (rpps.profile positions): chips per symbol or bits, or the other way round"""
    if self.code.count > 1:
        r = self.bits_per_symbol/(self.code.length//(2 if self.pair else 1))
    else:
        r = 1/self.code.length
    return r if decode else 1/r