Skip to content

Base

rpps.base

The design: data, operators, categories, contracts and the streaming rules

RPPS stays signal agnostic: a new kind of signal should be new definitions plus existing operators.

The model

samples  ->  symbols  ->  channel bits  ->  data bits  ->  packets / messages

Channel bits are what crosses the channel (after FEC, interleaving, scrambling, sync markers); on receive they are LLRs until the code transform decides them. Data bits are what the link layer carries.

  • Transforms turn one representation into the next, as an invertible transmit/receive pair: wave, symbol, code, link.
  • Conditioning (signal) changes samples without knowing what they carry.
  • Sync estimates something unknown and corrects or aligns the data with it, at any representation: carrier and timing on samples, phase on symbols, codeword boundaries on channel bits, packet starts on data bits. A receiver uses it many times.

A profile (rpps.profile) puts these together for one signal, both directions. Data flows down the chain; control flows back up it: a header decoded late can change earlier steps' parameters from a known position onward, without losing lock (rpps.base.control, rpps.profile.control).

The rule

A function belongs to the category named by what it takes and what it gives, not by what a standard calls it.

  • Changes the representation: the transform for that step.
  • Estimates an unknown and corrects or aligns with it: sync, at whatever representation.
  • Changes samples without knowledge of the signal: signal.
  • Inserting or removing known structure belongs to the transform where the structure lives: pilots and physical headers among symbols (symbol), sync markers among channel bits (code), headers and CRCs among data bits (link). Finding where it starts is sync.

Two implementations of one function share a signature, so they land in the same category.

Categories

Receive direction; transmit runs the transforms in reverse, and sync has no transmit side.

Category Package Takes → gives Operator
Source source outside world ↔ any representation Source(n), block >> sink
Conditioning signal samples → samples Stage, +
Sync sync any representation → the same, corrected or aligned; timing recovery takes samples to symbols Stage, +, one-way
Wave wave samples ↔ symbols Stage pairs
Symbol symbol symbols ↔ channel bits (LLRs on receive) Pipe, * and /
Code code channel bits ↔ data bits Pipe, * and /
Link link data bits ↔ packets Pipe, * and /
Profile profile one whole signal, both directions builds the above
Parallel parallel a profile's frame-parallel region profile.rx(parallel=...)

"Framing" is two things on opposite sides of the decoder: sync markers (CCSDS ASM, DVB-S sync bytes, DVB-S2 SOF, 802.15.4 SHR) live among symbols or channel bits, are found by sync and inserted by symbol or code; link framing (HDLC, headers, lengths, CRCs) lives among data bits and belongs to link.

A DVB-S2 receiver in order: channelize, decimate (signal) → AGC, coarse frequency (sync) → matched filter (wave) → timing (sync, gives symbols) → SOF, fine frequency and phase from pilots (sync) → PL descrambling, header and pilot removal, demapping (symbol, gives LLRs) → deinterleaving, LDPC, BCH, BB descrambling (code) → BBHEADER, packets (link). DVB-S puts sync between two code steps: Viterbi (code) → byte alignment and polarity from the sync bytes (sync) → Forney deinterleaving, Reed-Solomon, energy dispersal (code).

Contracts

tests/unit/policy/test_contracts.py checks these over every registered implementation.

  • source: produces blocks at any representation and says which, and which sync was already applied (for example timed, carrier not removed). Sets the rates it knows (Fs, cf, symbol rate) and each block's absolute position. Sinks take any representation.
  • signal: SAMPLES or REAL in, the same out. May change Fs, never needs sps, same in both directions. Includes signal.channel, the simulated medium tests use as the counterpart of sync.
  • sync: any representation in, the same out, corrected or aligned. The one exception is timing recovery, the sampler (SAMPLES at sps > 1 → SYMBOLS); the matched filter before it is wave. Estimates (offset, timing, lock, SNR, detection, frame start, polarity) go to meta.stream, never into the data. No inverse.
  • wave: transmit takes SYMBOLS and raises sps (shaping, FM/CPM, stagger, IFFT + CP); receive prepares samples for the sampler (matched filter, discriminator, rail realignment, CP removal + FFT) without choosing the instant. Comes in pairs (rpps.wave).
  • symbol: encode takes channel bits, gives symbols. Decode gives SYMBOLS (differential, despreading, removing pilots and headers, descrambling) or LLR (demapping); the last symbol step always gives soft output.
  • code: encode data bits → channel bits; decode channel bits (LLRs or hard) → data bits, LLRs when it can. FEC, interleaving, rate matching, puncturing, scrambling, line codes, sync markers; all invertible. Needs codeword boundaries known (finding them is sync).
  • link: decode aligned data bits into packets (split at lengths or flags, check CRCs, strip headers and stuffing; status in ctx); encode builds them.

Grey areas

Each settled by the rule.

Function Category Why
Matched filter wave prepares samples; does not decide when to sample
Timing recovery (OerderMeyr, MatTrack, Mat, Known) sync estimates the instant; the one sync step that changes representation
Differential coding on symbols / on bits (NRZI) symbol / code symbols ↔ symbols / bits ↔ bits
Manchester as a pulse / as 0 → 01, 1 → 10 wave / code symbols ↔ samples / bits ↔ bits
Spreading at one sample per chip (Spread), Despread at sps with a known code phase symbol chips are symbols
Code-phase and Doppler search, preamble correlation, sync-marker and HDLC-flag search, phase ambiguity sync find a start or estimate an unknown
Attaching a sync marker code known structure among channel bits
Pilots, physical headers, padding, OFDM carrier allocation symbol known structure among symbols
Reading a physical header's fields (DVB-S2 PLS) symbol symbol.Header decodes its short code into fields
Equalizer, OFDM pilot equalization, squelch sync estimate the channel / presence
OFDM IFFT/FFT and CP; FMDemod, AMDemod, SSBDemod wave symbols ↔ samples, carrier ↔ baseband
De-emphasis, DC block; channel impairments signal samples → samples
CRC guarding a packet / inside FEC (LTE code-block CRC) link / code resources are shared across categories

Soft information only flows down the receive chain: symbol gives LLRs, code takes and gives them, link takes hard bits and their reliability, and sync on channel bits passes LLRs through. Order matters inside sync: a step sits where what it corrects can still be separated (coarse frequency before the matched filter, fine phase after timing, a staggered signal's carrier before its rails are realigned).

Type tags

Every block carries a form (dtype: SAMPLES, REAL, SYMBOLS, LLR, BITS, BYTES, MSG; how values are stored) and a representation (Rep: SAMPLES, SYMBOLS, CHANNEL, DATA, PACKETS; where in the chain). Forms cross representations: LLRs exist before the decoder and after a soft-output one. Each operator declares takes(encode) and checks it before working, so a link decoder refuses channel bits and a constellation refuses samples; CATEGORY says which category it is.

Category Accepts Gives
signal SAMPLES (form SAMPLES or REAL) the same
sync any the same; timing gives SYMBOLS from SAMPLES
wave SYMBOLS (tx), SAMPLES (rx) SAMPLES
symbol CHANNEL (encode), SYMBOLS (decode) SYMBOLS; SYMBOLS or CHANNEL as LLR
code DATA or CHANNEL (both ways) CHANNEL; DATA as LLR or BITS
link PACKETS (encode), DATA (decode) DATA; PACKETS (BYTES or MSG)

A code transform is often several steps, so code steps take channel and data bits alike; the enforced boundary is the link's. rp.code.Uncoded() is the code step of a link with no FEC. rp.Data(x) on a complex array is SAMPLES, rp.Data(x, sps=1) is SYMBOLS; BitStage takes channel or data bits and keeps their form.

Data and operators

Data (base/data.py) wraps an array with its Meta: Fs, sps, centre frequency, group delay, stream state, and meta.pos, the absolute position of its first item (meta.time_of(k) gives source time). Samples a source lost (a radio's overrun, a dropped block) are counted in it, and a stage carries a gap in its input into its output positions, so positions stay true to time. Nothing needs setting up or resetting.

Operator Means On
data * pipe, data / pipe encode / decode Pipe (invertible transform)
data + stage process Stage, BitStage
pipe * pipe, stage + stage a reusable Pipeline either
data >> sink write out Sink

A Stage keeps its settings on the object and everything that carries between blocks in new_state(meta), held by the stream; step(samples, st, meta) processes a block and sets meta.op. SCOPE is STREAM (state crosses frames) or FRAME. Stream holds states, estimates (stream.est[name]), detections (det), control (stream.control) and load statistics. data + rp.Tee(a=..., b=...) runs each branch in its own stream (FM stereo L+R and L-R).

Streaming rules

Tested by cutting the same input differently (tests/unit/base/, per-stage tests):

  1. Any block length, including 0; never drop or repeat items across blocks.
  2. State lives in the stream state, so one stage can serve several streams.
  3. Whole blocks through rp.base.rpps.align(ctx, key, x, block, pad): the leftover waits, a flush pads (encode) or drops and reports (decode).
  4. Positions are absolute; a stage that drops or inserts items anchors it.
  5. Feedforward estimators follow the rules in rpps.sync (windows at absolute positions, tracked across windows).
  6. Soft information flows down; sync on channel bits passes LLRs through.

Modules:

Name Description
control

The control path, as operators see it (rpps.profile.control)

data

Data containers

frequency

Frequencies as numbers or as people write them

kernel

Kernels: the batch face of an operator, beside the operator it belongs to (rpps.parallel)

meta

Rate information and stream state that travel with data

rpps

RPPS parent classes

types

Type tags every block of data carries (see rpps.base, Type tags)

control

The control path, as operators see it (rpps.profile.control)

A header step (a physical header, a link header) and a frame sync publish what they decoded, with the absolute stream position it applies from; a step that drops or inserts items anchors positions. They live on meta.stream.control. What a profile does with them (tables, controls, runners) is rpps.profile.control.

Both directions:

publish(meta, op, {"modcod": 12, "pilots": 1}, at=<input position>, out=<index in this call's output>, span=None,
        group=None)
    at: absolute position in the op's input from which the fields apply. out: where that is in what the op gives in
    this call (None: nothing it gives is affected). span: input items the fields hold for, after which they go back
    to the controls' defaults (a PLCP rate holds for its payload only). group: publications made from one header
    share it (default: `at`), so a runner that re-runs keeps them together
anchor(meta, op, at, out, rate=None)
    a step that drops or inserts items says which output item an input position became, so positions translate
    exactly through it
emit(meta, op, kind, fields, bits=None, ok=None, at=<input position>, frame=None, parts=None)
    a decoded frame, for whoever reads the profile's messages (rpps.profile.message): its fields, its payload bits,
    whether its check passed, from absolute position `at` in the op's input (where the frame starts). frame: the
    whole frame's bits as received (header, payload, FCS) when the op has more than the payload; parts: where each
    part is in them, {"header" | "payload" | "fcs" | ...: (first bit, bits)}. The op's `check_name`, when it has
    one, names the check behind `ok`

Classes:

Name Description
Control

The control path of one stream (stream.control)

Functions:

Name Description
of

The stream's Control, made on first use

publish

Fields an op decoded (or was given, transmitting), applying from absolute input position at onward (see module)

anchor

Absolute input position at became item out of this call's output (a step that drops or inserts items)

emit

A decoded frame (see module): kind None takes the profile step's id

Control

Control()

The control path of one stream (stream.control)

published, anchors, messages: what operators reported since the runner last collected them (the runner empties these) log: every change the runner accepted, in order: {"step", "fields", "at", "targets"} reports: what did not go as announced: late changes re-run or dropped, restarts, fields with no table row rerun: re-runs done; buffer: the re-run buffer's current size, in items at its first step

Methods:

Name Description
fields

The field sets published so far, oldest first: [(step id, fields, position)]

Source code in src/rpps/base/control.py
def __init__(self):
    self.published, self.anchors, self.messages, self.log, self.reports = [], [], [], [], []
    self.rerun, self.buffer = 0, 0
fields
fields(step=None)

The field sets published so far, oldest first: [(step id, fields, position)]

Source code in src/rpps/base/control.py
def fields(self, step=None):
    """The field sets published so far, oldest first: [(step id, fields, position)]"""
    return [(e["step"], e["fields"], e["at"]) for e in self.log if step is None or e["step"] == step]

of

of(stream)

The stream's Control, made on first use

Source code in src/rpps/base/control.py
def of(stream):
    """The stream's Control, made on first use"""
    if stream.control is None:
        stream.control = Control()
    return stream.control

publish

publish(meta, op, fields, at, out=None, span=None, group=None)

Fields an op decoded (or was given, transmitting), applying from absolute input position at onward (see module)

Source code in src/rpps/base/control.py
def publish(meta, op, fields, at, out=None, span=None, group=None):
    """Fields an op decoded (or was given, transmitting), applying from absolute input position `at` onward (see module)"""
    of(meta.stream).published.append((op, dict(fields), int(at), None if out is None else int(out),
                                      None if span is None else int(span), int(at) if group is None else group))

anchor

anchor(meta, op, at, out, rate=None)

Absolute input position at became item out of this call's output (a step that drops or inserts items)

Source code in src/rpps/base/control.py
def anchor(meta, op, at, out, rate=None):
    """Absolute input position `at` became item `out` of this call's output (a step that drops or inserts items)"""
    of(meta.stream).anchors.append((op, int(at), int(out), rate))

emit

emit(meta, op, kind, fields, bits=None, ok=None, at=0, frame=None, parts=None)

A decoded frame (see module): kind None takes the profile step's id

Source code in src/rpps/base/control.py
def emit(meta, op, kind, fields, bits=None, ok=None, at=0, frame=None, parts=None):
    """A decoded frame (see module): kind None takes the profile step's id"""
    of(meta.stream).messages.append((op, kind, dict(fields or {}), None if bits is None else bits, ok, int(at),
                                     None if frame is None else (frame, dict(parts or {}))))

data

Data containers

Every block carries three tags (see rpps.base.types): CAT the Category of the operation that made it last REP its representation: SAMPLES, SYMBOLS, CHANNEL bits, DATA bits, PACKETS DT its form (dtype): complex samples, LLRs, bits, bytes...

Analog   samples and symbols
Mod      symbols, and demodulated bits (LLRs or hard) on the way to the decoder
Digital  bits and bytes

Classes:

Name Description
Analog

Analog data

Mod

(De)Modulation data

Digital

Digital data

Functions:

Name Description
Data

Wrapper to get correct Data type, and set PP and DT

expect

Refuse data an operator does not take: takes is the set of representations it accepts (None: anything).

Analog

Analog(data=None, cat=Category.UNK, dt=None, ctx=None, meta=None, rep=None)

Bases: _Data

Analog data

Source code in src/rpps/base/data.py
def __init__(self, data=None, cat=Category.UNK, dt=None, ctx=None, meta=None, rep=None):
    self._data: np.ndarray = data # type: ignore
    self.CAT = cat
    self.DT = dt
    self.REP = rep if rep is not None else REP_OF.get(dt) # Inferred from the form unless the maker says
    self.ctx = {} if ctx is None else ctx # State the coding/scrambling pipes carry between calls (see `derive`)
    self.meta: Meta = Meta() if meta is None else meta # Rates and the stream of the signal
    # Bool mask, True where a decoder could not decode the item (rpps.code.Coding sets it from its codewords' status):
    # it goes along with the items (a step that keeps their number keeps it), and a link header drops such frames
    self.failed = None
    # The decode that made this block, per codeword: bits (Reed-Solomon: symbols) corrected, -1 where it failed. None
    # unless a code with codewords decoded it (a marker: its word's bit errors per frame). Not carried to later blocks
    self.errors = None

Mod

Mod(data=None, cat=Category.SYMBOL, dt=None, ctx=None, meta=None, rep=None)

Bases: _Data

(De)Modulation data

Symbols (rep SYMBOLS), or demodulated bits (rep CHANNEL, or DATA from a soft-output decoder): either hard bits (MAPPED_HARD), or one LLR per bit (LLR). An LLR is log(P(bit=0)/P(bit=1)), so positive means 0 and the magnitude is the confidence.

Methods:

Name Description
bits

Hard decided bits, leaving this data as it is

get_soft

Per-bit LLRs. Hard bits give +-hard_llr if it's set, otherwise None

to_analog

Convert to Analog

to_digital

Convert to Digital

as_hard

Make hard decisions: bit 1 where the LLR is negative

as_bits

Covert to Digital as bits

as_bytes

Convert to Digital as bytes

Attributes:

Name Type Description
is_soft

Does this carry LLRs (rather than hard bits)

Source code in src/rpps/base/data.py
def __init__(self, data=None, cat=Category.SYMBOL, dt=None, ctx=None, meta=None, rep=None):
    if dt is None:
        dt = dtype.LLR if np.asarray(data).dtype.kind == "f" else dtype.MAPPED_HARD
    super().__init__(data, cat, dt, ctx, meta, rep)
is_soft property
is_soft

Does this carry LLRs (rather than hard bits)

bits
bits()

Hard decided bits, leaving this data as it is

Source code in src/rpps/base/data.py
def bits(self):
    """Hard decided bits, leaving this data as it is"""
    if self.REP not in (Rep.CHANNEL, Rep.DATA):
        raise ValueError(f"Cannot get bits of Mod {self.REP}/{self.DT}!")
    return self._data < 0 if self.DT == dtype.LLR else self._data.astype(bool)
get_soft
get_soft(hard_llr=None)

Per-bit LLRs. Hard bits give +-hard_llr if it's set, otherwise None

Source code in src/rpps/base/data.py
def get_soft(self, hard_llr=None):
    """Per-bit LLRs. Hard bits give +-hard_llr if it's set, otherwise None"""
    if self.is_soft:
        return self._data
    if hard_llr is not None and self.DT == dtype.MAPPED_HARD:
        return hard_llr * (1.0 - 2.0*self._data.astype(np.float32))
    return None
to_analog
to_analog()

Convert to Analog

Source code in src/rpps/base/data.py
def to_analog(self):
    """Convert to Analog"""
    if self.REP == Rep.SYMBOLS:
        return Analog(self._data, self.CAT, self.DT, self.ctx, self.meta, self.REP)
    raise ValueError(f"Cannot convert Mod {self.REP}/{self.DT} to Analog!")
to_digital
to_digital()

Convert to Digital

Source code in src/rpps/base/data.py
def to_digital(self):
    """Convert to Digital"""
    if self.REP in (Rep.CHANNEL, Rep.DATA):
        self.as_hard()
        return Digital(self._data, self.CAT, dtype.BITS, self.ctx, self.meta, self.REP)
    raise ValueError(f"Cannot convert Mod {self.REP}/{self.DT} to Digital!")
as_hard
as_hard()

Make hard decisions: bit 1 where the LLR is negative

Source code in src/rpps/base/data.py
def as_hard(self):
    """Make hard decisions: bit 1 where the LLR is negative"""
    if self.DT == dtype.LLR:
        self._data = self._data < 0
        self.DT = dtype.MAPPED_HARD
    return self
as_bits
as_bits()

Covert to Digital as bits

Source code in src/rpps/base/data.py
def as_bits(self):
    """Covert to Digital as bits"""
    return self.to_digital().as_bits()
as_bytes
as_bytes()

Convert to Digital as bytes

Source code in src/rpps/base/data.py
def as_bytes(self):
    """Convert to Digital as bytes"""
    return self.to_digital().as_bytes()

Digital

Digital(data=None, cat=Category.UNK, dt=None, ctx=None, meta=None, rep=None)

Bases: _Data

Digital data

Methods:

Name Description
is_bit

Check if data is bits

is_byte

Check if data is bytes

as_bits

Return self as bits

as_bytes

Return self as bytes

bits

The data as bits, leaving this data as it is

get_bytes

Return self.data as bytes

get_bits

Return self.data as bits

from_bytes

Create Digital from bytes

from_bits

Create Digital from bits

Attributes:

Name Type Description
bin

Return binary representation

hex

Return hexadecimal implementation

Source code in src/rpps/base/data.py
def __init__(self, data=None, cat=Category.UNK, dt=None, ctx=None, meta=None, rep=None):
    self._data: np.ndarray = data # type: ignore
    self.CAT = cat
    self.DT = dt
    self.REP = rep if rep is not None else REP_OF.get(dt) # Inferred from the form unless the maker says
    self.ctx = {} if ctx is None else ctx # State the coding/scrambling pipes carry between calls (see `derive`)
    self.meta: Meta = Meta() if meta is None else meta # Rates and the stream of the signal
    # Bool mask, True where a decoder could not decode the item (rpps.code.Coding sets it from its codewords' status):
    # it goes along with the items (a step that keeps their number keeps it), and a link header drops such frames
    self.failed = None
    # The decode that made this block, per codeword: bits (Reed-Solomon: symbols) corrected, -1 where it failed. None
    # unless a code with codewords decoded it (a marker: its word's bit errors per frame). Not carried to later blocks
    self.errors = None
bin property
bin

Return binary representation

hex property
hex

Return hexadecimal implementation

is_bit
is_bit(strict=True)

Check if data is bits

Source code in src/rpps/base/data.py
def is_bit(self, strict=True):
    """Check if data is bits"""
    idt = self.DT == dtype.BITS
    ndt = self._data.dtype == dtype.BITS.dtype
    if strict:
        return idt and ndt
    else:
        return idt or ndt
is_byte
is_byte(strict=True)

Check if data is bytes

Source code in src/rpps/base/data.py
def is_byte(self, strict=True):
    """Check if data is bytes"""
    idt = self.DT == dtype.BYTES
    ndt = self._data.dtype == dtype.BYTES.dtype
    if strict:
        return idt and ndt
    else:
        return idt or ndt
as_bits
as_bits()

Return self as bits

Source code in src/rpps/base/data.py
def as_bits(self):
    """Return self as bits"""
    if not self.is_bit():
        self._data = self.get_bits() # type: ignore
        self.DT = dtype.BITS
    return self
as_bytes
as_bytes()

Return self as bytes

Source code in src/rpps/base/data.py
def as_bytes(self):
    """Return self as bytes"""
    if not self.is_byte():
        self._data = self.get_bytes() # type: ignore
        self.DT = dtype.BYTES
    return self
bits
bits()

The data as bits, leaving this data as it is

Source code in src/rpps/base/data.py
def bits(self):
    """The data as bits, leaving this data as it is"""
    return self.get_bits()
get_bytes
get_bytes()

Return self.data as bytes

Source code in src/rpps/base/data.py
def get_bytes(self):
    """Return self.data as bytes"""
    if self.is_bit(False):
        return np.packbits(self._data)
    elif self.is_byte(False):
        return self._data
    else:
        raise ValueError(f"({self.REP}/{self.DT}) {self._data.dtype} cannot get bytes")
get_bits
get_bits()

Return self.data as bits

Source code in src/rpps/base/data.py
def get_bits(self):
    """Return self.data as bits"""
    if self.is_bit(False):
        return self._data
    elif self.is_byte(False):
        return np.unpackbits(self._data)
    else:
        raise ValueError(f"({self.REP}/{self.DT}) {self._data.dtype} cannot get bits")
from_bytes classmethod
from_bytes(data, cat=Category.UNK, dt=dtype.BYTES, ctx=None, meta=None, rep=None)

Create Digital from bytes

Source code in src/rpps/base/data.py
@classmethod
def from_bytes(cls, data, cat=Category.UNK, dt=dtype.BYTES, ctx=None, meta=None, rep=None):
    """Create Digital from bytes"""
    if isinstance(data, bytes):
        return cls(np.frombuffer(data, dtype=dtype.BYTES.dtype), cat, dt, ctx, meta, rep)
    elif isinstance(data, np.ndarray):
        if data.dtype == dtype.BYTES.dtype:
            return cls(data, cat, dt, ctx, meta, rep)
        raise TypeError(f"Cannot convert {type(data)} {data.shape} {data.dtype} to {cls.__name__}")
    raise TypeError(f"Cannot convert {type(data)} to {cls.__name__}")
from_bits classmethod
from_bits(data, cat=Category.UNK, dt=dtype.BITS, ctx=None, meta=None, rep=None)

Create Digital from bits

Source code in src/rpps/base/data.py
@classmethod
def from_bits(cls, data, cat=Category.UNK, dt=dtype.BITS, ctx=None, meta=None, rep=None):
    """Create Digital from bits"""
    if isinstance(data, np.ndarray):
        if data.dtype == dtype.BITS.dtype:
            return cls(data, cat, dt, ctx, meta, rep)
        raise TypeError(f"Cannot convert {type(data)} {data.shape} {data.dtype} to {cls.__name__}")
    raise TypeError(f"Cannot convert {type(data)} to {cls.__name__}")

Data

Data(data, ctx=None, flush=False, Fs=None, sps=None, cf=None, stream=None, delay=0.0, t0=None) -> Digital | Analog

Wrapper to get correct Data type, and set PP and DT

bool -> bits, uint8/bytes/str -> bytes, complex64 -> samples, float -> real samples ctx: the state of earlier data (out.ctx) to continue a stream of bits in chunks flush: this ends the stream. Otherwise a partial last block is held for the next data; flushed, it is padded (encode) or dropped (decode) Fs, sps, cf: sample rate [Hz], samples per symbol and centre frequency [Hz] of a signal stream: the stream of earlier signal blocks (out.stream), which keeps the state of the stages across blocks t0: time [s] of the stream's first item, if known (a radio's timestamp): meta.time_of then gives any item's time Each block gets its absolute position in the stream (meta.pos): the items its stream produced before it

Source code in src/rpps/base/data.py
def Data(data, ctx=None, flush=False, Fs=None, sps=None, cf=None, stream=None, delay=0.0, t0=None) -> Digital | Analog:
    """Wrapper to get correct Data type, and set PP and DT

    bool -> bits, uint8/bytes/str -> bytes, complex64 -> samples, float -> real samples
    ctx: the state of earlier data (`out.ctx`) to continue a stream of bits in chunks
    flush: this ends the stream. Otherwise a partial last block is held for the next data; flushed, it is padded (encode) or dropped (decode)
    Fs, sps, cf: sample rate [Hz], samples per symbol and centre frequency [Hz] of a signal
    stream: the stream of earlier signal blocks (`out.stream`), which keeps the state of the stages across blocks
    t0: time [s] of the stream's first item, if known (a radio's timestamp): `meta.time_of` then gives any item's time
    Each block gets its absolute position in the stream (`meta.pos`): the items its stream produced before it
    """
    d = None
    ctx = dict(ctx) if ctx else {}
    ctx[FLUSH] = bool(flush)
    meta = Meta(1.0 if Fs is None else Fs, 0.0 if sps is None else sps, 0.0 if cf is None else cf, delay, stream)
    if t0 is not None:
        meta.stream.t0 = float(t0)
    if isinstance(data, np.ndarray):
        if data.dtype == bool:
            d = Digital(data, dt=dtype.BITS, ctx=ctx, meta=meta)
        elif data.dtype == np.uint8:
            d = Digital(data, dt=dtype.BYTES, ctx=ctx, meta=meta)
        elif data.dtype == dtype.SAMPLES.dtype:
            d = Analog(data, dt=dtype.SYMBOLS if meta.state.sps == 1 else dtype.SAMPLES, ctx=ctx, meta=meta)
        elif data.dtype == np.complex128:
            d = Analog(data.astype(np.complex64), dt=dtype.SAMPLES, ctx=ctx, meta=meta)
        elif data.dtype.kind == "f":
            d = Analog(data, dt=dtype.REAL, ctx=ctx, meta=meta)
        else:
            raise TypeError(f"Cannot convert {type(data)} {data.shape} {data.dtype}")
    elif isinstance(data, str):
        d = Digital.from_bytes(data.encode("utf-8"), dt=dtype.BYTES, ctx=ctx, meta=meta)
    elif isinstance(data, bytes):
        d = Digital.from_bytes(data, dt=dtype.BYTES, ctx=ctx, meta=meta)

    if d is None:
        raise TypeError(f"Cannot convert {type(data)}")
    d.meta.pos = d.meta.stream.pos # The stream's source position: this block follows what it produced before
    d.meta.timed = True
    d.meta.stream.pos += len(d)
    return d # type: ignore

expect

expect(op, data, takes, encode)

Refuse data an operator does not take: takes is the set of representations it accepts (None: anything). Raised before any work, with what was expected

Source code in src/rpps/base/data.py
def expect(op, data, takes, encode):
    """Refuse `data` an operator does not take: `takes` is the set of representations it accepts (None: anything).
    Raised before any work, with what was expected"""
    if takes is None or not isinstance(data, _Data):
        return
    if data.REP not in takes:
        names = ", ".join(sorted(r.name for r in takes))
        raise StreamError(f"{op} {'encodes' if encode else 'decodes'} {names}, not {data.REP} ({data.name}/{data.DT})")

frequency

Frequencies as numbers or as people write them

Classes:

Name Description
Frequency

A frequency in Hz. Built from a number or text: Frequency(99.5e6), Frequency("99.5M"), Frequency("2.4 GHz"), Frequency("1e6")

Frequency

Bases: float

A frequency in Hz. Built from a number or text: Frequency(99.5e6), Frequency("99.5M"), Frequency("2.4 GHz"), Frequency("1e6")

It is a float, so it goes anywhere a frequency is wanted (Fs=Frequency("2.4M")).

Attributes:

Name Type Description
raw

The frequency in Hz

mult

Divisor of the unit it is shown in (1, 1e3, 1e6, 1e9)

short

The value in its unit

raw property
raw

The frequency in Hz

mult property
mult

Divisor of the unit it is shown in (1, 1e3, 1e6, 1e9)

short property
short

The value in its unit

kernel

Kernels: the batch face of an operator, beside the operator it belongs to (rpps.parallel)

A region frame is whole, so what an operator does to it is a function of the frame and of the parameters controls gave it: no state across calls. A Kernel is that function over a batch of frames, one frame per row of an [N, L] array:

batch = kernel.run(xp, batch)

xp is the array module (numpy; cupy on a GPU), so a kernel is written once. A kernel is immutable once built and holds its constants (a keystream, a permutation, a code's graph), made once for its parameters, so they can live on a device and be exported (describe). A constant goes to a device once: self.const(xp, key, make) keeps what make() gives, as an array of xp. Rows that cannot be processed are marked in batch.bad (with a reason) and carry zeros on: the shape of a batch never changes with the data.

Where a batch lives: b.x is an array of xp (on a device, a device array); bad, why, code_failed, notes and pos stay on the host (small). A kernel that needs numpy says so (where = "host", a C++ decoder, a LoopKernel): a plan on another array module puts a ToHost before it and a ToDevice after, so every crossing is in describe(). Nothing converts implicitly: to_host(a) is the one way back.

Most kernels are array code over xp. A loop that array code does badly (LDPC's layers, the demapper's sums over points) is a device kernel of its own: portable CUDA C that NVRTC and hiprtc compile as it is, built by device_functions when has_device_kernels(xp); on numpy the kernel runs its host path, the reference.

An operator gives one with op.kernel(params, how) (params: its controlled parameters; how: / decode, * encode, + stage; returns None for what it has no kernel for). A step whose operators do not is run by LoopKernel: the existing per-frame operator, through Data. That path is also the oracle every kernel is compared with.

Classes:

Name Description
Batch

N frames that share a key, as one array. x: [N, L]; form: what the rows are; pos: each row's absolute input position;

Kernel

A batch function. Subclasses set name and give run; shape says the output length for an input length (None: not

ToHost

The batch back to the host (before a kernel that needs numpy)

ToDevice

The batch onto the device of xp (after a kernel that ran on the host)

Functions:

Name Description
to_host

A numpy array of a (a device array's copy back, a.get(); a numpy array as it is)

has_device_kernels

True when xp compiles and launches kernels of its own (CuPy, on CUDA or HIP); not numpy, not a pretend device

device_functions

The functions names of the device kernel source (portable CUDA C: NVRTC or hiprtc compile it as it is), compiled

Batch dataclass

Batch(x: ndarray, form: Form, pos: list, n_in: int, bad: ndarray = None, why: dict = dict(), code_failed: ndarray = None, notes: dict = dict())

N frames that share a key, as one array. x: [N, L]; form: what the rows are; pos: each row's absolute input position; n_in: the frame length they started as; bad: rows that failed, why: {row: reason}; notes: {row: [report, ...]}

Kernel

A batch function. Subclasses set name and give run; shape says the output length for an input length (None: not known before running; given None, None), consts the arrays it was built with. where: "any" (runs on the xp it is given) or "host" (numpy only)

Methods:

Name Description
const

make() as an array of xp, made and moved once per array module and key (a constant stays on its device)

describe

A JSON-able description: what a backend (a device kernel library, an HLS generator) needs to build it

const
const(xp, key, make)

make() as an array of xp, made and moved once per array module and key (a constant stays on its device)

Source code in src/rpps/base/kernel.py
def const(self, xp, key, make):
    """`make()` as an array of `xp`, made and moved once per array module and key (a constant stays on its device)"""
    cache = self.__dict__.setdefault("_consts", {})
    k = (xp.__name__ if hasattr(xp, "__name__") else id(xp), key)
    v = cache.get(k)
    if v is None:
        v = cache[k] = xp.asarray(make())
    return v
describe
describe(n_in)

A JSON-able description: what a backend (a device kernel library, an HLS generator) needs to build it

Source code in src/rpps/base/kernel.py
def describe(self, n_in):
    """A JSON-able description: what a backend (a device kernel library, an HLS generator) needs to build it"""
    return {"kernel": self.name, "in": n_in, "out": self.shape(n_in),
            "consts": {k: {"shape": list(np.shape(v)), "dtype": str(np.asarray(v).dtype)} for k, v in self.consts().items()}}

ToHost

Bases: Kernel

The batch back to the host (before a kernel that needs numpy)

ToDevice

Bases: Kernel

The batch onto the device of xp (after a kernel that ran on the host)

to_host

to_host(a)

A numpy array of a (a device array's copy back, a.get(); a numpy array as it is)

Source code in src/rpps/base/kernel.py
def to_host(a):
    """A numpy array of `a` (a device array's copy back, `a.get()`; a numpy array as it is)"""
    if type(a) is np.ndarray:
        return a
    get = getattr(a, "get", None)
    return get() if get is not None else np.asarray(a)

has_device_kernels

has_device_kernels(xp)

True when xp compiles and launches kernels of its own (CuPy, on CUDA or HIP); not numpy, not a pretend device

Source code in src/rpps/base/kernel.py
def has_device_kernels(xp):
    """True when `xp` compiles and launches kernels of its own (CuPy, on CUDA or HIP); not numpy, not a pretend device"""
    return xp is not np and hasattr(xp, "RawModule") and hasattr(xp, "cuda")

device_functions

device_functions(xp, source, names)

The functions names of the device kernel source (portable CUDA C: NVRTC or hiprtc compile it as it is), compiled once per process, device and source

Source code in src/rpps/base/kernel.py
def device_functions(xp, source, names):
    """The functions `names` of the device kernel `source` (portable CUDA C: NVRTC or hiprtc compile it as it is), compiled
    once per process, device and source"""
    key = (xp.__name__, xp.cuda.Device().id, source)
    with _MODULES_LOCK:
        f = _MODULES.get(key)
        if f is None:
            mod = xp.RawModule(code=source)
            f = _MODULES[key] = {n: mod.get_function(n) for n in names}
    return f

meta

Rate information and stream state that travel with data

Users don't build these: give rp.Data an Fs / sps / cf and the stages take care of the rest.

Classes:

Name Description
Rate

Sample rate (Fs), samples per symbol (sps) and centre frequency (cf)

Stream

Everything that follows one source across its blocks, shared by every block (and every data derived from it)

Meta

The rate information of one block of data, as a stage sees it

Functions:

Name Description
forward

A read-only property that reads name of the object in attribute to: self.Fs is self.state.Fs

timed

fn(*args), its time charged to op in stream.busy: its own time only (an operator timed inside it takes its own

Rate

Rate(Fs, sps, cf)

Sample rate (Fs), samples per symbol (sps) and centre frequency (cf)

Source code in src/rpps/base/meta.py
def __init__(self, Fs, sps, cf):
    self.set(Fs, sps, cf)

Stream

Stream(Fs=None)

Everything that follows one source across its blocks, shared by every block (and every data derived from it)

the carried state of each stage (filter history, oscillator phase, loop filters...), keyed by the stage,

so a stage object is reusable and the same stage in two streams has two states

det: detection result (baud, modulation, timing, cfo...), see rpps.sync.detect busy: seconds each operator spent on this stream's blocks (a stage's step, a pipe's encode or decode), its own time only (what it ran inside it is the inner one's); air: seconds of signal the source produced. busy/air (load) is the operator's share of real time: 1.0 exactly keeps up, over 1 it can't. realtime() is the one number lanes: {thread: how many run its work at once} (a parallel region's workers); a thread not named is one thread_of: {operator: the thread it ran on}: what realtime adds up per thread dropped: source samples lost: a radio's overruns (Device, as pysdrlib reports them) and blocks a threaded source discarded because the stages fell behind (Blocks.threaded(drop=True), counted at the source's rate) pos: items the source has produced so far: the absolute position of its next block t0: time [s] of the source's item 0, when the source knows it (a radio's timestamp); None otherwise out_pos: items each stage has produced so far in this stream: the absolute position of its next output block in_pos: the position each stage expects its next input block at; one further on is a gap, which the stage carries into its own output positions est: what sync stages estimated, by name ({"align": {...}}), for whoever wants to know (det stays Acquire's) control: the control path (rpps.base.control.Control): fields header steps published, position anchors, and what a profile runner did with them (applied, re-run, dropped). None until a step publishes rx: how the source's samples were received (a pysdrlib RxContext: the chain and its LO, whether it inverts, the reference and its correction), None when the source doesn't know; rx_conjugated: the source conjugated them because the chain inverts (rpps.source.Source). Both survive restart

Threads (Blocks.threaded): each stage's state is used only by the thread running that stage. det and src_sps have one writer (Acquire); gen lets blocks already on their way pick up a new sps (Meta.refresh). det here is the latest: a stage reads its block's (Meta.det), which Acquire stamps, so a stage running behind Acquire in another thread uses the detection its block went through with, not one made for a later block.

Methods:

Name Description
add_air

The source made seconds more of signal (a source calls this per block)

load

Share of real time each operator takes, {operator: busy/air}: 1.0 exactly keeps up, over 1 it falls behind.

realtime

The stream's load as one number: per thread, the sum of the loads of what ran on it (divided by the thread's

restart

Forget everything but the source's rate: the next block starts a new stream

Source code in src/rpps/base/meta.py
def __init__(self, Fs=None):
    self.states = {}
    self.det = None
    self.blocks = 0 # Blocks the source has produced
    self.src_Fs = Fs # Rate of the source
    self.src_sps = None # sps at the source, once a stage has learned it (Acquire): the next blocks start from it
    self.gen = 0 # Bumped when src_sps changes
    self.busy = {}
    self.thread_of = {}
    self.lanes = {}
    self._snaps = deque(maxlen=1024) # (air, busy) every SNAP seconds of signal: what `load(window)` measures over
    self.air = 0.0
    self.dropped = 0
    self.pos = 0
    self.t0 = None
    self.out_pos = {}
    self.in_pos = {}
    self.est = {}
    self.control = None
    self.rx, self.rx_conjugated = getattr(self, "rx", None), getattr(self, "rx_conjugated", False) # (kept by restart)
add_air
add_air(seconds)

The source made seconds more of signal (a source calls this per block)

Source code in src/rpps/base/meta.py
def add_air(self, seconds):
    """The source made `seconds` more of signal (a source calls this per block)"""
    self.air += seconds
    if not self._snaps or self.air - self._snaps[-1][0] >= self.SNAP:
        self._snaps.append((self.air, dict(self.busy))) # (dict() of a dict is one step under the GIL: safe while stages run)
load
load(window=None)

Share of real time each operator takes, {operator: busy/air}: 1.0 exactly keeps up, over 1 it falls behind.

window: None, since the stream started; seconds, over about the last window seconds of signal (what a live view wants: a stage that slows down shows at once)

Source code in src/rpps/base/meta.py
def load(self, window=None):
    """Share of real time each operator takes, {operator: busy/air}: 1.0 exactly keeps up, over 1 it falls behind.

    window: None, since the stream started; seconds, over about the last `window` seconds of signal (what a live view
    wants: a stage that slows down shows at once)"""
    busy, air = dict(self.busy), self.air
    if window is not None and self._snaps:
        a0, b0 = self._snaps[0]
        for a, b in reversed(self._snaps):
            if air - a >= window:
                a0, b0 = a, b
                break
        if air - a0 > 0:
            return {op: (t - b0.get(op, 0.0))/(air - a0) for op, t in busy.items()}
    return {op: t/air for op, t in busy.items()} if air > 0 else {}
realtime
realtime(window=None)

The stream's load as one number: per thread, the sum of the loads of what ran on it (divided by the thread's lanes), and the busiest thread's. Serial work is one thread (the sum); Blocks.pipelined gives a thread per stage (the slowest); a parallel region counts its workers' time over their number. <= 1 keeps up in real time. 0.0 before the source has made any signal

Source code in src/rpps/base/meta.py
def realtime(self, window=None):
    """The stream's load as one number: per thread, the sum of the loads of what ran on it (divided by the thread's
    `lanes`), and the busiest thread's. Serial work is one thread (the sum); `Blocks.pipelined` gives a thread per
    stage (the slowest); a parallel region counts its workers' time over their number. <= 1 keeps up in real time.
    0.0 before the source has made any signal"""
    per = {}
    for op, v in self.load(window).items():
        t = self.thread_of.get(op)
        per[t] = per.get(t, 0.0) + v
    return max((v/self.lanes.get(t, 1) for t, v in per.items()), default=0.0)
restart
restart()

Forget everything but the source's rate: the next block starts a new stream

Source code in src/rpps/base/meta.py
def restart(self):
    """Forget everything but the source's rate: the next block starts a new stream"""
    gen = self.gen + 1
    self.__init__(self.src_Fs)
    self.gen = gen

Meta

Meta(Fs=1.0, sps=0.0, cf=0.0, delay=0.0, stream=None, pos=0)

The rate information of one block of data, as a stage sees it

Fs, sps, cf, isps, Ts: the rates of the block coming in (read-only for stages) op: the rates of the block going out. A stage changes these (meta.op.Fs /= 2), the carrier applies them delay: group delay of the data so far [s]. A stage adds its own stream: the Stream this block belongs to (stage state, detection) pos: absolute position of the block's first item in the stream, counted in items at this block's rate. It does not depend on how the stream was cut into blocks, so estimators can place their windows by it. Samples a source lost (a radio's overrun, a dropped block) are counted: positions stay true to time across a gap timed: pos counts this block's own items (a source's block, a stage's output), so a jump in it is a gap; a pipe's output keeps its input's position and is not timed flush: this block ends the stream: a stage gives out what it was holding back det: the detection this block went through Acquire with (the stream's, stream.det, until an Acquire stamps one)

Methods:

Name Description
time_of

Source time [s] of item k of this block: the stream's t0, plus the position at this rate, less the group delay.

fork

Meta for the data a stage produces: the output rates become the input rates. Stream is shared

refresh

Pick up an sps learned after this block left the source

calibrate_sps

Declare the sps at the current stage of the chain

state_of

Get (creating on first use) the carried state of a stage

Source code in src/rpps/base/meta.py
def __init__(self, Fs=1.0, sps=0.0, cf=0.0, delay=0.0, stream=None, pos=0):
    self.stream = Stream(Fs) if stream is None else stream
    if self.stream.src_Fs is None:
        self.stream.src_Fs = Fs
    if self.stream.src_sps is not None:
        sps = self.stream.src_sps # A stage already learned the source's sps
    self.state = Rate(Fs, sps, cf)
    self.op = Rate(Fs, sps, cf)
    self.delay = delay
    self.gen = self.stream.gen
    self.pos = int(pos)
    self.timed = False
    self.flush = False
    self._det = None
time_of
time_of(k=0)

Source time [s] of item k of this block: the stream's t0, plus the position at this rate, less the group delay. None when the source gave no time anchor

Source code in src/rpps/base/meta.py
def time_of(self, k=0):
    """Source time [s] of item k of this block: the stream's t0, plus the position at this rate, less the group delay.
    None when the source gave no time anchor"""
    t0 = self.stream.t0
    return None if t0 is None else t0 + (self.pos + k)/self.state.Fs - self.delay
fork
fork()

Meta for the data a stage produces: the output rates become the input rates. Stream is shared

Source code in src/rpps/base/meta.py
def fork(self):
    """Meta for the data a stage produces: the output rates become the input rates. Stream is shared"""
    m = Meta.__new__(Meta)
    m.stream = self.stream
    m.state = self.op.copy()
    m.op = self.op.copy()
    m.delay = self.delay
    m.gen = self.gen
    m.pos = self.pos
    m.timed = False
    m.flush = False
    m._det = self._det
    return m
refresh
refresh()

Pick up an sps learned after this block left the source

One thread: never needed, every block starts after the last one finished. Threaded, blocks already between the source and Acquire carry the old sps: scale the source's new one by the Fs ratio, as the stages would have.

Source code in src/rpps/base/meta.py
def refresh(self):
    """Pick up an sps learned after this block left the source

    One thread: never needed, every block starts after the last one finished. Threaded, blocks already between
    the source and Acquire carry the old sps: scale the source's new one by the Fs ratio, as the stages would have.
    """
    s = self.stream
    if self._det is not None: # Past Acquire: its sps is the one Acquire gave this block, not a later block's
        self.gen = s.gen
        return
    if self.gen != s.gen:
        self.gen = s.gen
        if s.src_sps is not None and s.src_Fs:
            sps = s.src_sps * self.state.Fs / s.src_Fs
            self.state.sps = sps
            self.op.sps = sps
calibrate_sps
calibrate_sps(sps)

Declare the sps at the current stage of the chain

Blocks come from the source with the source's sps, so the sps at the source is worked out through the Fs ratio (decimation/resampling scale both) and handed to the blocks that follow.

Source code in src/rpps/base/meta.py
def calibrate_sps(self, sps):
    """Declare the sps at the current stage of the chain

    Blocks come from the source with the source's sps, so the sps at the source is worked out through the
    Fs ratio (decimation/resampling scale both) and handed to the blocks that follow.
    """
    self.stream.src_sps = sps * self.stream.src_Fs / self.state.Fs
    self.stream.gen += 1
    self.gen = self.stream.gen
    self.state.sps = sps
    self.op.sps = sps
state_of
state_of(stage)

Get (creating on first use) the carried state of a stage

Source code in src/rpps/base/meta.py
def state_of(self, stage):
    """Get (creating on first use) the carried state of a stage"""
    try:
        return self.stream.states[stage]
    except KeyError:
        st = self.stream.states[stage] = stage.new_state(self)
        return st

forward

forward(to, name, doc=None)

A read-only property that reads name of the object in attribute to: self.Fs is self.state.Fs

Source code in src/rpps/base/meta.py
def forward(to, name, doc=None):
    """A read-only property that reads `name` of the object in attribute `to`: self.Fs is self.state.Fs"""
    return property(lambda self: getattr(getattr(self, to), name), doc=doc)

timed

timed(stream, op, fn, *args)

fn(*args), its time charged to op in stream.busy: its own time only (an operator timed inside it takes its own off), so nothing is counted twice. stream None: run, not charged

Source code in src/rpps/base/meta.py
def timed(stream, op, fn, *args):
    """fn(*args), its time charged to `op` in `stream.busy`: its own time only (an operator timed inside it takes its own
    off), so nothing is counted twice. stream None: run, not charged"""
    if stream is None:
        return fn(*args)
    stack = _tls.__dict__.setdefault("stack", [])
    stack.append(0.0)
    t = perf_counter()
    try:
        return fn(*args)
    finally:
        spent = perf_counter() - t
        inner = stack.pop()
        if stack:
            stack[-1] += spent
        busy = stream.busy
        busy[op] = busy.get(op, 0.0) + spent - inner
        stream.thread_of[op] = threading.get_ident()

rpps

RPPS parent classes

Classes:

Name Description
Pipe

Parent class for RPPS implementations

Pipeline

Pipes (and stages) applied in order. Build one by combining pipes: a * b * c or a + b + c

Stage

A DSP stage operating on a continuous stream of blocks: block + stage

BitStage

A stage on a stream of bits: channel bits or data bits, as LLRs or hard bits (sync on bits: alignment, polarity)

Tee

The same blocks through several branches: data + Tee(name=stage_or_pipeline, ...) gives {name: data out}

Functions:

Name Description
align

Whole blocks of x for a stage that works on block items at a time

failed_of

The data's failed mask (True where a decoder before could not decode it), or None: nothing known to have failed

tag_stages

Give every Stage class defined in package (a module or package name, submodules included) the Category category,

Pipe

Parent class for RPPS implementations

A pipe works on data with the operators: data * pipe encodes, data / pipe decodes (and data + pipe for stages that process a signal). Two pipes multiplied/added together give a Pipeline, a reusable chain:

link = scr * ecc * mod          # scrambler, then code, then modulation
syms = bits * link              # same as bits * scr * ecc * mod
bits = syms / link              # the decoders, run backwards

Methods:

Name Description
takes

The representations (rpps.base.types.Rep) this accepts to encode (True) or decode (False); None: not checked

encode

Encode data

decode

Decode data

takes
takes(encode)

The representations (rpps.base.types.Rep) this accepts to encode (True) or decode (False); None: not checked

Source code in src/rpps/base/rpps.py
def takes(self, encode):
    """The representations (rpps.base.types.Rep) this accepts to encode (True) or decode (False); None: not checked"""
    return None
encode
encode(data)

Encode data

Source code in src/rpps/base/rpps.py
def encode(self, data):
    """Encode data"""
    return NotImplemented
decode
decode(data)

Decode data

Source code in src/rpps/base/rpps.py
def decode(self, data):
    """Decode data"""
    return NotImplemented

Pipeline

Pipeline(*items)

Bases: Pipe

Pipes (and stages) applied in order. Build one by combining pipes: a * b * c or a + b + c

data * pipeline: every item encodes in order. data / pipeline: every item decodes, last item first. data + pipeline: every item processes in order (stages). Pipelines nest and flatten. A stage that splits the data (rp.sync.Burst) makes the rest run on every piece, and the pipeline gives the list of what they made.

Source code in src/rpps/base/rpps.py
def __init__(self, *items):
    flat = []
    for it in items:
        flat += it.items if isinstance(it, Pipeline) else [it]
    self.items = tuple(flat)

Stage

Bases: Pipe

A DSP stage operating on a continuous stream of blocks: block + stage

Settings (constructor args) live on the stage. Anything that must carry from one block to the next lives in a state object returned by new_state, kept in the stream the block belongs to, so the stage itself stays reusable. Stages never see Meta being created or reset: the data carries it.

A stage must accept any block length (including 0), and neither drop nor repeat samples across blocks.

Methods:

Name Description
new_state

Create this stage's carried state

step

Process a block, returning the output. Set meta.op (the output rates) and add to meta.delay as needed

takes

Representations this stage processes (rpps.base.types.Rep): samples and symbols

new_state
new_state(meta)

Create this stage's carried state

Source code in src/rpps/base/rpps.py
def new_state(self, meta):
    """Create this stage's carried state"""
    return None
step
step(samples, st, meta)

Process a block, returning the output. Set meta.op (the output rates) and add to meta.delay as needed

Source code in src/rpps/base/rpps.py
def step(self, samples, st, meta):
    """Process a block, returning the output. Set meta.op (the output rates) and add to meta.delay as needed"""
    raise NotImplementedError()
takes
takes(encode=True)

Representations this stage processes (rpps.base.types.Rep): samples and symbols

Source code in src/rpps/base/rpps.py
def takes(self, encode=True):
    """Representations this stage processes (rpps.base.types.Rep): samples and symbols"""
    from .types import Rep
    return {Rep.SAMPLES, Rep.SYMBOLS}

BitStage

Bases: Stage

A stage on a stream of bits: channel bits or data bits, as LLRs or hard bits (sync on bits: alignment, polarity)

step gets a numpy array: float LLRs (positive means 0) or bools, and gives the same form back. The output keeps the input's representation and form; state carries across blocks as for any stage, so any block length works.

Tee

Tee(**branches)

Bases: Pipe

The same blocks through several branches: data + Tee(name=stage_or_pipeline, ...) gives {name: data out}

out = mpx + rp.Tee(mono=audio, stereo=pilot + audio)     # one `audio` pipeline serves both
left, right = out["mono"].data + out["stereo"].data, ...

Each branch runs in a stream of its own (kept in the stream's state under the tee), so a stage can sit in several branches, each with its state, and every branch is as independent of the block cut as a chain is. A branch's estimates and states are on its output (out["stereo"].state(pilot), out["stereo"].stream.est). A tee ends a chain: what follows takes one branch's output.

Source code in src/rpps/base/rpps.py
def __init__(self, **branches):
    if not branches:
        raise ValueError("a Tee needs at least one branch: Tee(name=stage, ...)")
    self.branches = branches

align

align(ctx, key, x, block, pad, log=None)

Whole blocks of x for a stage that works on block items at a time

ctx: the stream state (a dict this call updates) holding the leftover of the previous call under key. A leftover waits for the next call. Only when the stream is flushed is it zero padded up to a whole block (pad: encoding) or dropped (decoding, where padding would invent data).

Source code in src/rpps/base/rpps.py
def align(ctx, key, x, block, pad, log=None):
    """Whole blocks of x for a stage that works on `block` items at a time

    ctx: the stream state (a dict this call updates) holding the leftover of the previous call under `key`.
    A leftover waits for the next call. Only when the stream is flushed is it zero padded up to a whole block
    (pad: encoding) or dropped (decoding, where padding would invent data).
    """
    x = np.asarray(x)
    prev = ctx.pop(key, None)
    if prev is not None and len(prev):
        x = np.concatenate((prev, x))
    n = len(x)//block*block
    rest = x[n:]
    if len(rest):
        if not ctx.get(FLUSH):
            ctx[key] = rest
        elif pad:
            x = np.concatenate((x[:n], rest, np.zeros(block - len(rest), dtype=x.dtype)))
            n = len(x)
        else:
            ctx.setdefault(DROPPED, []).append(len(rest)) # (a parallel region's worker reports it: a frame cut short)
            if log is not None:
                log.warn(f"Dropped {len(rest)} trailing items short of a block of {block}")
    return x[:n]

failed_of

failed_of(data)

The data's failed mask (True where a decoder before could not decode it), or None: nothing known to have failed

Source code in src/rpps/base/rpps.py
def failed_of(data):
    """The data's `failed` mask (True where a decoder before could not decode it), or None: nothing known to have failed"""
    m = getattr(data, "failed", None)
    return m if m is not None and len(m) == len(data) else None

tag_stages

tag_stages(package, category)

Give every Stage class defined in package (a module or package name, submodules included) the Category category, unless the class sets its own. In this architecture the package is the category (rpps.base)

Source code in src/rpps/base/rpps.py
def tag_stages(package, category):
    """Give every Stage class defined in `package` (a module or package name, submodules included) the Category `category`,
    unless the class sets its own. In this architecture the package is the category (rpps.base)"""
    import importlib, pkgutil, sys
    root = importlib.import_module(package)
    names = [package]
    if hasattr(root, "__path__"):
        names += [m.name for m in pkgutil.walk_packages(root.__path__, package + ".")]
    for name in names:
        mod = sys.modules.get(name) or importlib.import_module(name)
        for obj in vars(mod).values():
            if isinstance(obj, type) and issubclass(obj, Stage) and obj.__module__ == name and "CATEGORY" not in vars(obj):
                obj.CATEGORY = category

types

Type tags every block of data carries (see rpps.base, Type tags)

Category  the kind of operation that made the data last
Rep       where in the chain the data is: samples -> symbols -> channel bits -> data bits -> packets
dtype     how the values are stored (the form): complex samples, LLRs, bits, bytes...

Rep and dtype are separate because forms cross representations: LLRs and hard bits exist both before the decoder (channel bits) and after it (data bits).

Classes:

Name Description
Category

The kind of operation that produced the data

Rep

Where in the chain the data is

dtype

Data Type

Category

Bases: Enum

The kind of operation that produced the data

Rep

Bases: Enum

Where in the chain the data is

dtype

Bases: Enum

Data Type