Skip to content

Profile

rpps.profile

Profiles: a whole signal as one config file, in receive order, both directions

p = rp.profile.load("ieee802154/2450", sps=4)
wave = p.tx()(rp.Data(payload))             # transmit: the transforms inverted, in reverse order
bits = p.rx()(wave)                          # receive: every step as written
bits = p.rx(start=rp.Rep.SYMBOLS)(symbols)   # a source that gives timed symbols: the steps before are skipped

A profile is config/profile/<family>/<mode>.json: operators, order, parameters. Writing one needs no code; the guide "Profiles" walks through one, and python -m rpps steps lists every step kind and sync method.

One list of steps, in receive order

A transform step names a pair, runs as written on receive and inverted, in reverse, on transmit; a sync step is skipped on transmit. Profiles take params like any definition; defaults holds sync methods and loop settings. A step that loads a definition names its kind and reference as the loaders take them: {"code": "conv", "name": "k7_171_133/3_4"}, {"symbol": "constellation", "name": "psk/qpsk"}. The kinds are in rpps.profile.steps; how a wave step pairs on receive and transmit is in rpps.wave.

What else a profile can say

Feature Says Where
Variants a param's "choices" (each a bundle of fields: {"param": "modulation.shape"}), a step's "when" rpps._config.resolve, guide "Definitions"
Header-driven control "controls": a header's fields drive other steps' parameters from a position on, without losing lock rpps.profile.control, rpps.base.control, rpps.profile.runner
Bursts {"sync": "burst"}: the steps after it are built anew for every burst; transmitting places bursts on one stream (gap_s, at=, ramp_s, freq=, hop); carriers: bursts on many carriers, plan: placed in a burst time plan (each burst's fields drive its steps, its messages carry them; transmitting, the plan places them) rpps.profile.burst, rpps.sync.Burst, rpps.sync.BurstTx, rpps.sync.Bursts, rpps.plan
Preambles {"sync": "preamble"} after a burst step: by repetition or a waveform the profile makes from a sequence word; "attach": true sends it on transmit rpps.sync.Preamble
Branches a last {"branch": ...} step fans the chain out; a header in one branch drives the branches after it, frame makes them read whole frames, take only parts of each (a code split around a sync word), select only the frames a trunk step's fields accept rpps.profile.branch
Resource grids grid steps take an OFDM system's samples to frames of its grid; its channels are branches (lte/downlink, nr/downlink) rpps.grid
Parallel region "parallel": "<step id>": the per-frame rest of the chain on threads or processes rpps.parallel, rpps.profile.parallel
Messages every frame is also a Message (kind, fields, payload, crc_ok, where it starts), from runner.take_messages() rpps.profile.message
Only some kinds profile.kinds(), profile.rx(kinds={"pbch"}): hands out only those and builds only the steps they need (profile.needed) rpps.profile.profile
Captures "capture": each message kind as a packet of a link type, for Wireshark (pcapng) and interfaces, and back to transmit (Encoder) rpps.link.capture, rpps.source.pcap, rpps.source.tun, rpps.profile.encoder
Requirements "requires": baud, Fs, bw, min_samples, input, from_cf as expressions, evaluated when asked rpps.profile.catalogue (fits, candidates: what a measured signal can be), rpps.profile.Decoder

Sources that start later in the chain: the runner skips every receive step before what the source gives (Source.REP, APPLIED): timed symbols with the carrier on skip signal, wave and timing; a BBFRAME stream skips everything through code.

Messages come from a step that knows where a frame starts and whether it checked out (rp.base.control.emit(meta, op, kind, fields, bits, ok, at): link headers, failed frames too, the HDLC frame step, the DVB-S2 PL header, the LTE and NR channels). A run of fixed-size frames with no step of their own (TS packets after DVB-S's RS) is cut by the runner from a step's "message": {"kind": "packet", "bits": 1504, "check": true, "fields": [...]}. The runner places each message through the maps of the steps before it and hands it out once; burst and branch runners place their children's in the outer stream.

Only some kinds: a branch none of whose steps is needed is not built, and a chain ends at its last needed step, so the runner's output is that step's (DVB-S2's pls alone: no descrambling, LDPC or BCH). LTE's PDSCH needs the PDCCH, which needs the PCFICH, which needs the PBCH. A kind the profile doesn't give is a ConfigError.

Modules:

Name Description
branch

A profile's receive side that fans out: one trunk, then branches that read the same blocks (rpps.profile)

burst

A profile around a {"sync": "burst"} step: per-burst demodulation (BurstRunner), and burst transmission (BurstTxRunner)

catalogue

What a profile needs and gives, before it runs: for a program building a menu (rpps.profile.Decoder uses it too)

control

Header-driven control: the control path that runs back up a chain

decoder

A selected signal's samples to a profile's messages, block by block: for a program that shows what a signal carries

encoder

Packets to samples through a profile's transmitter: what a capture rule gives on receive, sent back out

message

Decoded messages: what a profile receives, one record a frame, for a program to show or keep (rpps.profile)

parallel

Where a profile's parallel region starts, and whether it can (rpps.parallel)

profile

Profiles: one config file per signal, both directions (rpps.profile)

runner

Profile runners: a profile's operators on a stream of blocks, with header-driven control

branch

A profile's receive side that fans out: one trunk, then branches that read the same blocks (rpps.profile)

"steps": [ ...trunk steps...,
           {"branch": "channels", "order": ["pcfich", "pdcch", "pdsch"],
            "branches": {"pcfich": [...steps...], "pdcch": [...], "pdsch": [...]}}]

The branch step ends the chain. Every block the trunk gives goes through each branch, in order, and the runner gives {branch name: output}. Each branch is a chain of its own (a runner, in a stream of its own, as rp.Tee's branches are), so everything a chain does (header-driven changes at positions, re-runs, restarts) works inside one as it does in a profile.

Controls cross branches: a header in one branch may drive steps in the branches after it. Its fields' position is carried back through its own branch to the trunk's output (the position every branch reads), and the driven branch takes the change there, forward through its steps, before it reads the block. So a branch drives only those after it in order (one before it has read the block already): the PCFICH's control format sets the PDCCH region of the same subframe, a DCI the PDSCH's allocation.

A header publishes once it has read its frame, and the driven branch reads after it only within the block they share. So a branch step names its frame (items of the trunk's output in one: an LTE subframe's resource elements): the branches read whole frames, collected from however the blocks were cut, and every header rules on a frame before the branches after it read that frame. Without one, the branches read each block as it comes, which suits headers whose frames never span two blocks.

With a frame, a branch can read only part of each frame, and only some frames:

{"branch": "burst", "frame": 132,
 "take": {"slot_type": [[49, 54], [78, 83]], "payload": [[0, 49], [83, 132]]},   items of each frame, in order
 "select": {"payload": {"step": "fs", "when": "word == 'bs_data'"}},            frames whose fields say so
 "branches": {...}}

Frames are frame items each, or start wherever a trunk control drives the branch step's own frame (a frame sync's {"<branch step id>": {"frame": "frame"}}): then each runs to the next, of any length. A range's end may be null (to the frame's end), and {"ranges": [...], "unit": 196} keeps only whole groups of that many items (P25's TSBKs, one to three a frame).

take gives a branch the item ranges of each frame, joined (a code split around a sync word); select the frames for which an expression over the fields a trunk step published for that frame holds (the sync word that says voice or data, frame % 2 for one TDMA slot of two). Such a branch counts its own positions (the items it read); changes and messages cross over at the trunk positions they stand for.

A header in the trunk drives steps in the branches too (a DVB-S2 PLS sets the BBFRAME length of every input stream's BBHEADER). The profile ends the trunk on an exit step, EXIT, that the controls drive in their place: the runner carries the change forward through the trunk with the data as it does any, and applies it to the exit at the trunk's output position, which is where every branch takes it.

Classes:

Name Description
Exit

The trunk's last step: passes the data through, and keeps every change applied to it with its position (the trunk's

Taken

Positions of a branch that reads some items of each frame (take) of some frames (select): it counts the items

BranchChain

One branch's runner: it also hands what its headers publish for other branches to the bus, at trunk positions

BranchRunner

trunk: the runner of the steps before the branch step (None: none), chains: {name: BranchChain} in order

Functions:

Name Description
take_spec

(ranges [(start, end or None)], unit) of a branch's take: a list of ranges, or {"ranges": [...], "unit": u}

take_index

Items of a frame of length a branch reads: its ranges in order (an open end: to the frame's end), as many as

Exit

Exit(params)

Bases: Stage

The trunk's last step: passes the data through, and keeps every change applied to it with its position (the trunk's output position from which it holds). Its parameters are "/" of steps in the branches

Source code in src/rpps/profile/branch.py
def __init__(self, params):
    self.CONTROLS = {p: "live" for p in params}
    self.records, self.cursor, self._pending = [], None, []

Taken

Taken(ranges, unit)

Positions of a branch that reads some items of each frame (take) of some frames (select): it counts the items it read. Each frame read is an anchor: its first position in the branch, its start in the trunk's output, its length and the items read

Methods:

Name Description
add

A frame looked at; idx: the items read (None: not read)

to_branch

The branch position of trunk position t: the first item read at or after it

Source code in src/rpps/profile/branch.py
def __init__(self, ranges, unit):
    self.ranges, self.unit = ranges, unit
    self.anchors = [] # (branch position, trunk position of the frame's start, frame length, items read)
    self.count = 0    # branch items so far
    self.covered = None # trunk position up to which every frame has been looked at
add
add(start, length, idx)

A frame looked at; idx: the items read (None: not read)

Source code in src/rpps/profile/branch.py
def add(self, start, length, idx):
    """A frame looked at; idx: the items read (None: not read)"""
    if idx is not None and len(idx):
        self.anchors.append((self.count, int(start), int(length), idx))
        self.count += len(idx)
    self.covered = int(start) + int(length)
to_branch
to_branch(t)

The branch position of trunk position t: the first item read at or after it

Source code in src/rpps/profile/branch.py
def to_branch(self, t):
    """The branch position of trunk position t: the first item read at or after it"""
    import bisect
    k = bisect.bisect_right([a[1] for a in self.anchors], t) - 1
    if k < 0:
        return self.anchors[0][0] if self.anchors else self.count
    bp, tp, n, idx = self.anchors[k]
    off = int(bisect.bisect_left(idx.tolist(), t - tp))
    if off < len(idx) and t - tp < n:
        return bp + off
    return self.anchors[k + 1][0] if k + 1 < len(self.anchors) else bp + len(idx)

BranchChain

BranchChain(slots, name, entries, branch, bus, profile=None)

Bases: Runner

One branch's runner: it also hands what its headers publish for other branches to the bus, at trunk positions

Methods:

Name Description
inject_params

A change from the trunk: step sid's parameters from pos of this branch's input

inject

A change from another branch's header, at pos of this branch's input (a trunk position)

Source code in src/rpps/profile/branch.py
def __init__(self, slots, name, entries, branch, bus, profile=None):
    super().__init__(slots, name, entries, "rx", profile)
    self.branch, self.bus = branch, bus
    self.taken = None # Taken: positions of a branch that reads part of the frames; None: the trunk's own
inject_params
inject_params(sid, params, pos, key)

A change from the trunk: step sid's parameters from pos of this branch's input

Source code in src/rpps/profile/branch.py
def inject_params(self, sid, params, pos, key):
    """A change from the trunk: step sid's parameters from `pos` of this branch's input"""
    if key in self._keys:
        return
    self._keys.add(key)
    pos = self.branch_pos(pos)
    slots = {i: dict(params) for i in self._step_slots.get(sid, [])}
    if not slots:
        return
    ch = Change()
    ch.key, ch.fields, ch.origin, ch.at, ch.params, ch.step = key, dict(params), -1, pos, slots, EXIT
    self._seq += 1
    ch.seq = self._seq
    ch.fwd, ch.hop, ch.pos = set(slots), 0, pos
    ch.group, ch.btargets, ch.back, ch.s0 = (-1, pos), [], {}, None
    self.changes.append(ch)
inject
inject(entry, fields, pos, key)

A change from another branch's header, at pos of this branch's input (a trunk position)

Source code in src/rpps/profile/branch.py
def inject(self, entry, fields, pos, key):
    """A change from another branch's header, at `pos` of this branch's input (a trunk position)"""
    super().inject(entry, fields, self.branch_pos(pos), key)

BranchRunner

BranchRunner(trunk, chains, name, bus, order, frame=None, exit=None, owner=None, take=None, select=None, step_id=None, framed=False)

trunk: the runner of the steps before the branch step (None: none), chains: {name: BranchChain} in order

Methods:

Name Description
pipelined_parts

The runner in two, for Blocks.pipelined to give each a thread: the trunk, then the branches. The branches read

take_messages

The frames the trunk and every branch decoded since the last call, placed in the stream given (a branch's

Source code in src/rpps/profile/branch.py
def __init__(self, trunk, chains, name, bus, order, frame=None, exit=None, owner=None, take=None, select=None,
             step_id=None, framed=False):
    self.trunk, self.chains, self.name, self.bus, self.order = trunk, chains, name, bus, order
    self.exit, self.owner = exit, owner or {} # The trunk's Exit (None: no control of the trunk drives a branch)
    self.frame = None if frame is None else int(frame)
    self.step_id, self.framed = step_id, bool(framed) # framed: frames start where a trunk control drives `frame`
    if self.frame is not None and self.framed:
        raise ConfigError(f"{name}: frames of a fixed `frame` length, or started by a control, not both")
    self.held = None # Trunk output short of a whole frame
    self._tlock, self._block = threading.Lock(), threading.Lock() # The trunk's state, the branches' (pipelined_parts)
    self._starts = [] # Frame starts a control gave (trunk output positions), not yet used
    self._input = (1.0, 0.0, None)
    self.take, self.select = dict(take or {}), dict(select or {})
    self._pending = [] # Trunk changes for branches that read part of the frames, until their frame has been looked at
    if (self.take or self.select) and self.frame is None and not self.framed:
        raise ConfigError(f"{name}: `take` and `select` read parts of frames: the branch step needs `frame`, or a "
                          f"control that drives its `frame`")
    for b in list(self.take) + list(self.select):
        if b not in self.chains:
            raise ConfigError(f"{name}: take / select name branch {b!r}, not one of {list(self.chains)}")
    for b in self.chains:
        if b in self.take or b in self.select:
            ranges, unit = take_spec(self.take.get(b, [[0, None]]), f"{name}: take of {b!r}")
            if self.frame is not None:
                idx = take_index(ranges, unit, self.frame)
                if idx is None or not len(idx):
                    raise ConfigError(f"{name}: take of {b!r}: ranges within a frame of {self.frame}")
            self.chains[b].taken = Taken(ranges, unit)
    for b, rule in self.select.items():
        if not isinstance(rule, dict) or not {"step", "when"} <= set(rule):
            raise ConfigError(f"{name}: select of {b!r} is {{\"step\": <trunk step id>, \"when\": <expression of its fields>}}")
        if trunk is None or rule["step"] not in trunk._step_slots:
            raise ConfigError(f"{name}: select of {b!r}: {rule['step']!r} is not a step of the trunk")
pipelined_parts
pipelined_parts()

The runner in two, for Blocks.pipelined to give each a thread: the trunk, then the branches. The branches read what the trunk carries back (positions, its control log) under its lock, once it is done with a block

Source code in src/rpps/profile/branch.py
def pipelined_parts(self):
    """The runner in two, for Blocks.pipelined to give each a thread: the trunk, then the branches. The branches read
    what the trunk carries back (positions, its control log) under its lock, once it is done with a block"""
    return _Part(self, self._trunk, "trunk"), _Part(self, self._branches, "branches")
take_messages
take_messages()

The frames the trunk and every branch decoded since the last call, placed in the stream given (a branch's positions are the trunk's output, carried back through it)

Source code in src/rpps/profile/branch.py
def take_messages(self):
    """The frames the trunk and every branch decoded since the last call, placed in the stream given (a branch's
    positions are the trunk's output, carried back through it)"""
    with self._block, self._tlock:
        Fs, cf, t0 = self._input
        out = list(self.trunk.take_messages()) if self.trunk is not None else []
        for chain in self.chains.values():
            for m in chain.take_messages():
                at = chain.trunk_pos(m.sample)
                pos = self.trunk.to_input(at) if self.trunk is not None else at
                out.append(m.placed(pos, Fs, cf, t0))
    return sorted((m for m in out if self.kinds is None or m.kind in self.kinds), key=lambda m: m.sample)

take_spec

take_spec(spec, where)

(ranges [(start, end or None)], unit) of a branch's take: a list of ranges, or {"ranges": [...], "unit": u}

Source code in src/rpps/profile/branch.py
def take_spec(spec, where):
    """(ranges [(start, end or None)], unit) of a branch's `take`: a list of ranges, or {"ranges": [...], "unit": u}"""
    unit = 1
    if isinstance(spec, dict):
        if set(spec) - {"ranges", "unit"} or "ranges" not in spec:
            raise ConfigError(f"{where}: take is a list of [start, end] ranges, or {{\"ranges\": [...], \"unit\": items}}")
        unit, spec = int(spec.get("unit", 1)), spec["ranges"]
    ranges = []
    for r in spec:
        if not isinstance(r, (list, tuple)) or len(r) != 2:
            raise ConfigError(f"{where}: a range is [start, end] (end null: to the frame's end), not {r!r}")
        a, e = int(r[0]), None if r[1] is None else int(r[1])
        if a < 0 or (e is not None and e <= a):
            raise ConfigError(f"{where}: range {r} is empty or negative")
        ranges.append((a, e))
    if unit < 1:
        raise ConfigError(f"{where}: unit {unit}: whole groups of at least one item")
    return ranges, unit

take_index

take_index(ranges, unit, length)

Items of a frame of length a branch reads: its ranges in order (an open end: to the frame's end), as many as make whole units; None when a range with an end is past the frame (the frame is not read)

Source code in src/rpps/profile/branch.py
def take_index(ranges, unit, length):
    """Items of a frame of `length` a branch reads: its ranges in order (an open end: to the frame's end), as many as
    make whole units; None when a range with an end is past the frame (the frame is not read)"""
    import numpy as np
    parts = []
    for a, e in ranges:
        if e is None:
            e = length
        elif e > length:
            return None
        parts.append(np.arange(a, max(a, e)))
    idx = np.concatenate(parts) if parts else np.zeros(0, np.int64)
    idx = idx[:len(idx)//unit*unit]
    if len(np.unique(idx)) != len(idx):
        raise ConfigError(f"take ranges {ranges} overlap")
    return idx.astype(np.int64)

burst

A profile around a {"sync": "burst"} step: per-burst demodulation (BurstRunner), and burst transmission (BurstTxRunner)

The steps before the burst step run on the stream, as any profile's do. The burst step cuts the stream into its bursts (rpps.sync.Burst), and every burst runs through the steps after it in a runner of its own, built for it: whatever a stage, a decoder, a marker or a header holds starts over on every burst (each burst is a stream of its own: a packet acquired fresh), and the controls whose header comes after the burst step drive that burst's steps only.

A call gives a list, one output per burst that ended in the block (Blocks flattens it: for pdu in src(n) + p.rx()).

Transmitting is the mirror: every burst through a runner of its own of the steps after the burst step, the bursts placed on one stream (rpps.sync.BurstTx: gaps, start times, ramps, a carrier each), the steps before it on that stream.

The rest of the burst code: rpps.sync.burst, rpps.sync.plan (the stages), rpps.analysis.burst (bursts demodulated blind; plans learned and checked: its docstring maps it all).

Classes:

Name Description
BurstRunner

pre: the runner of the steps before the burst step (None when there are none), burst: the rpps.sync.Burst,

BurstTxRunner

The transmit side of a profile with a burst step: a call sends one burst

BurstRunner

BurstRunner(pre, burst, make_post, name, entry=None)

pre: the runner of the steps before the burst step (None when there are none), burst: the rpps.sync.Burst, make_post(): a new runner of the steps after it. last is the runner of the last burst (its controls, reports)

Methods:

Name Description
take_messages

The frames decoded since the last call, every burst's, placed in the stream given

Attributes:

Name Type Description
ops

[(how, operator)] of every step: those on the stream, the burst step, those of a burst (a runner built to show them)

Source code in src/rpps/profile/burst.py
def __init__(self, pre, burst, make_post, name, entry=None):
    self.pre, self.burst, self.make_post, self.name = pre, burst, make_post, name
    self.entry = entry # The controls entry of the burst step: its fields per burst (rpps.sync.Bursts) drive the burst's steps
    self.last = None
    self.bursts = 0
    self._msgs, self._input = [], (1.0, 0.0, None)
ops property
ops

[(how, operator)] of every step: those on the stream, the burst step, those of a burst (a runner built to show them)

take_messages
take_messages()

The frames decoded since the last call, every burst's, placed in the stream given

Source code in src/rpps/profile/burst.py
def take_messages(self):
    """The frames decoded since the last call, every burst's, placed in the stream given"""
    Fs, cf, t0 = self._input
    out = list(self.pre.take_messages()) if self.pre is not None else []
    for m in self._msgs:
        out.append(m.placed(self.pre.to_input(m.sample) if self.pre is not None else m.sample, Fs, cf, t0))
    self._msgs = []
    return sorted((m for m in out if self.kinds is None or m.kind in self.kinds), key=lambda m: m.sample)

BurstTxRunner

BurstTxRunner(make_post, burst_tx, pre, name, entry=None)

The transmit side of a profile with a burst step: a call sends one burst

tx = p.tx()
out = tx(rp.Data(bits, Fs=1e6, sps=1), fields={"type": 2})       # the samples up to this burst's start
out = tx(rp.Data(bits2, Fs=1e6, sps=1), at=4e-3, freq=2e6, flush=True)  # the rest: the stream ends

Each burst runs through a runner of its own of the steps after the burst step (make_post(): built anew, so every scrambler, header, marker and pulse starts over, and the burst ends whole: its data is sent as a stream of its own, flushed). The burst step's rpps.sync.BurstTx places it on the output stream: at [s from the stream's start], else gap_s after the burst before; freq [Hz from the centre], else the step's hop. The steps before the burst step (pre, None for none) run on that stream. With a plan (rpps.sync.PlanTx) the burst's fields name its window: it goes there, at its symbol rate, and its window's fields (its tx type's) drive the burst's steps. A call gives the samples no later burst can reach any more; flush=True (or flush()) gives the rest and ends the stream. A list of blocks is sent burst by burst (fields, at, freq: one each, or one for all). last is the runner of the last burst, sent the BurstTx's record: (start sample, samples, freq)

Methods:

Name Description
flush

The rest of the stream, ending it

Attributes:

Name Type Description
ops

[(how, operator)] in the order they run: a burst's steps, the burst step's BurstTx, those on the stream

Source code in src/rpps/profile/burst.py
def __init__(self, make_post, burst_tx, pre, name, entry=None):
    self.make_post, self.burst_tx, self.pre, self.name = make_post, burst_tx, pre, name
    self.entry = entry # The controls entry of the burst step: a plan's fields of the burst's window drive its steps
    self.last = None
    self.bursts = 0
    burst_tx.reset()
ops property
ops

[(how, operator)] in the order they run: a burst's steps, the burst step's BurstTx, those on the stream

flush
flush()

The rest of the stream, ending it

Source code in src/rpps/profile/burst.py
def flush(self):
    """The rest of the stream, ending it"""
    return self._take(True)

catalogue

What a profile needs and gives, before it runs: for a program building a menu (rpps.profile.Decoder uses it too)

Each profile's "requires" (config/profile, rpps.profile) says, as expressions over its params and baud:

baud          its symbol rate (chips, subcarrier spacing), or null when the standard leaves it open (DVB-S, CCSDS):
              given to the Decoder, or measured
Fs            the sample rate it receives at
bw            the bandwidth of the channel it takes
min_samples   enough samples for one message
input         "baseband" (complex samples of the channel, default) or "audio" (an FM channel's audio: AX.25)
from_cf       params that follow from the signal's centre frequency `cf` (BLE's advertising channel, NR's fc)

rp.profile.info("dvbs2/normal", baud=27.5e6).requires["Fs"]      # 110e6 at 4 samples a symbol
[i.name for i in rp.profile.catalogue() if i.requires["Fs"] and i.requires["Fs"] <= 20e6]

Any other key is a ConfigError (a misspelt one would otherwise read as "says nothing"), as is an input not listed or a from_cf param the profile doesn't declare.

They narrow a search, too: what a signal was measured to be rules out the profiles it can't be, before any is built. fits says why one can't (None when it may), candidates lists the variants (rp.profile.variants) that may:

rp.profile.fits("ble/adv", baud=250e3)            # "its rate is 1e+06, not 250000"
rp.profile.candidates(baud=27.5e6, bw=36e6)       # [("ccsds/tm_concat", {...}), ..., ("dvbs2/normal", {...}), ...]

baud      the measured symbol rate: a profile whose rate is set takes it within `tol`; an open one takes any
bw        the measured width: no wider than the profile's channel (`tol` over); narrower is fine (a burst, a pulse
          that doesn't fill it)
Fs        the rate of the samples there are: they must hold the profile's channel (what rp.profile.Decoder needs)
seconds   how long the samples there are last: at least a message's worth (min_samples). Worst case: a profile
          whose frames vary (DVB-S2's short frames) can decode from less, so a search that may see those leaves it out
input     "baseband" or "audio"

A measure not given rules nothing out; neither does one a profile can't say (a width before its open rate is known).

Classes:

Name Description
ProfileInfo

A profile, described: name, comment, ref, tags, params ({name: {"default", "comment", and "choices" when it has them}}), requires (evaluated:

Functions:

Name Description
requirements

A profile's "requires", evaluated over its param values (and baud, for a profile whose rate is open). A profile of

info

A profile described (ProfileInfo), its requires evaluated with these params (the defaults otherwise) and baud

fits

Why a signal measured so can't be profile name (with these params): a str, or None when it may be (see module)

candidates

[(name, params)]: each variant (rp.profile.variants) of each profile (names, or every blind one)

lineage

The profiles name extends, nearest first (its file's "extends", as written): [] for one that extends none. Of two

variants

The param values a blind search tries for a profile: every combination of the choices of its params (but those

catalogue

Every profile there is, described (with its defaults), by name

ProfileInfo

ProfileInfo(name, comment, ref, tags, params, requires, given=None)

A profile, described: name, comment, ref, tags, params ({name: {"default", "comment", and "choices" when it has them}}), requires (evaluated: baud, Fs, bw, min_samples, None where they wait for a baud not given; input; from_cf as written; comment), kinds (the message kinds it gives, sorted: what Profile.rx(kinds=...) and the Decoder take; the profile is built, with the params given, when first asked)

Source code in src/rpps/profile/catalogue.py
def __init__(self, name, comment, ref, tags, params, requires, given=None):
    self.name, self.comment, self.ref, self.tags, self.params, self.requires = name, comment, ref, tags, params, requires
    self._given, self._kinds = dict(given or {}), None

requirements

requirements(req, values, baud=None, name='profile')

A profile's "requires", evaluated over its param values (and baud, for a profile whose rate is open). A profile of your own without one says nothing: every value None

Source code in src/rpps/profile/catalogue.py
def requirements(req, values, baud=None, name="profile"):
    """A profile's "requires", evaluated over its param values (and `baud`, for a profile whose rate is open). A profile of
    your own without one says nothing: every value None"""
    unknown = set(req) - set(KEYS) - set(OTHER)
    if unknown:
        raise ConfigError(f"{name}: requires has no {sorted(unknown)} (takes {list(KEYS + OTHER)})")
    if req.get("input", "baseband") not in INPUTS:
        raise ConfigError(f"{name}: requires input {req['input']!r}, not one of {list(INPUTS)}")
    out = {"input": req.get("input", "baseband"), "from_cf": dict(req.get("from_cf") or {}), "comment": req.get("comment")}
    v = dict(values)
    for k in KEYS:
        e = req.get(k)
        if k == "baud" and baud is not None:
            if e is not None and not math.isclose(float(_config.evaluate(e, v, f"{name} requires")), float(baud), rel_tol=1e-3):
                raise ValueError(f"{name}: its rate is set ({e}), not {baud:g}")
            val = float(baud)
        elif e is None:
            val = None
        else:
            try:
                val = _config.evaluate(e, v, f"{name} requires") if isinstance(e, str) else e
            except TypeError: # Waits for a baud not given
                val = None
        if k == "min_samples" and val is not None:
            val = int(math.ceil(val))
        elif val is not None:
            val = float(val)
        out[k] = val
        v[k] = val
    return out

info

info(name, baud=None, **params)

A profile described (ProfileInfo), its requires evaluated with these params (the defaults otherwise) and baud

Source code in src/rpps/profile/catalogue.py
def info(name, baud=None, **params):
    """A profile described (ProfileInfo), its requires evaluated with these params (the defaults otherwise) and `baud`"""
    file = _config.find("profile", name)
    if file is None:
        raise FileNotFoundError(f"profile/{name}: not found, have {_config.ls('profile')}")
    obj = _config.read(file)
    decl = obj.get("params") or {}
    unknown = set(params) - set(decl)
    if unknown:
        raise ConfigError(f"profile/{name}: no params {sorted(unknown)} (has {sorted(decl)})")
    values = {**_config.declared(obj), **params}
    _config.typed(obj, values, f"profile/{name}")
    values = _config.chosen(obj, values, f"profile/{name}")
    req = obj.get("requires") or {}
    stray = set(req.get("from_cf") or {}) - set(decl)
    if stray:
        raise ConfigError(f"profile/{name}: requires from_cf sets {sorted(stray)}, not params (has {sorted(decl)})")
    ps = {k: {"default": v.get("default") if isinstance(v, dict) else v,
              "comment": v.get("comment") if isinstance(v, dict) else None,
              **({"choices": list(v["choices"])} if isinstance(v, dict) and "choices" in v else {})} for k, v in decl.items()}
    return ProfileInfo(name, obj.get("comment", ""), obj.get("ref"), list(obj.get("tags") or []), ps,
                       requirements(req, values, baud, f"profile/{name}"), params)

fits

fits(name, baud=None, bw=None, Fs=None, seconds=None, input=None, tol=TOL, **params)

Why a signal measured so can't be profile name (with these params): a str, or None when it may be (see module)

Source code in src/rpps/profile/catalogue.py
def fits(name, baud=None, bw=None, Fs=None, seconds=None, input=None, tol=TOL, **params):
    """Why a signal measured so can't be profile `name` (with these params): a str, or None when it may be (see module)"""
    r = info(name, **params).requires
    if input is not None and input != r["input"]:
        return f"it takes {r['input']}, not {input}"
    if baud is not None:
        if r["baud"] is not None:
            if not math.isclose(r["baud"], float(baud), rel_tol=tol):
                return f"its rate is {r['baud']:g}, not {float(baud):g}"
        else: # An open rate: what it needs at this one
            r = info(name, baud=baud, **params).requires
    if bw is not None and r["bw"] is not None and float(bw) > r["bw"]*(1 + tol):
        return f"its channel is {r['bw']:g} Hz wide, not {float(bw):g}"
    if Fs is not None and r["bw"] is not None and float(Fs) < r["bw"]:
        return f"it needs {r['bw']:g} Hz of channel, samples at {float(Fs):g} hold less"
    if seconds is not None and r["Fs"] is not None and float(seconds)*r["Fs"] < r["min_samples"]:
        return f"a message takes {r['min_samples']/r['Fs']:g} s, there are {float(seconds):g}"
    return None

candidates

candidates(names=None, baud=None, bw=None, Fs=None, seconds=None, input=None, tol=TOL, limit=64)

[(name, params)]: each variant (rp.profile.variants) of each profile (names, or every blind one) a signal measured so may be (fits), in name order, the defaults of each first

Source code in src/rpps/profile/catalogue.py
def candidates(names=None, baud=None, bw=None, Fs=None, seconds=None, input=None, tol=TOL, limit=64):
    """[(name, params)]: each variant (rp.profile.variants) of each profile (`names`, or every blind one)
    a signal measured so may be (`fits`), in name order, the defaults of each first"""
    if names is None:
        names = [f"{family}/{mode}" for family, modes in sorted(ls(blind=True).items()) for mode in modes] # (no made-up ones; the selected tags)
    return [(n, v) for n in names for v in variants(n, limit)
            if fits(n, baud=baud, bw=bw, Fs=Fs, seconds=seconds, input=input, tol=tol, **v) is None]

lineage

lineage(name)

The profiles name extends, nearest first (its file's "extends", as written): [] for one that extends none. Of two profiles that read a signal alike, the one fewer levels down is the more general name

Source code in src/rpps/profile/catalogue.py
def lineage(name):
    """The profiles `name` extends, nearest first (its file's "extends", as written): [] for one that extends none. Of two
    profiles that read a signal alike, the one fewer levels down is the more general name"""
    out = []
    while name and len(out) < 16:
        try:
            parent = _config._head(_config.find("profile", name)).get("extends")
        except Exception:
            break
        if not parent or parent in out: # (a cycle is the config's error: not followed)
            break
        out.append(parent)
        name = parent
    return out

variants

variants(name, limit=64)

The param values a blind search tries for a profile: every combination of the choices of its params (but those marked "blind": false), the defaults first, at most limit of them; [{}] for a profile without choices. A variant is load(name, **v)

Source code in src/rpps/profile/catalogue.py
def variants(name, limit=64):
    """The param values a blind search tries for a profile: every combination of the choices of its params (but those
    marked "blind": false), the defaults first, at most `limit` of them; [{}] for a profile without choices. A variant
    is `load(name, **v)`"""
    import itertools
    file = _config.find("profile", name)
    if file is None:
        raise FileNotFoundError(f"profile/{name}: not found, have {_config.ls('profile')}")
    decl = _config.read(file).get("params") or {}
    axes = []
    for k, spec in decl.items():
        if isinstance(spec, dict) and spec.get("choices") and spec.get("blind", True):
            keys = list(spec["choices"])
            default = spec.get("default")
            first = next((c for c in keys if c == default or (isinstance(c, str) and c == str(default))), None)
            vals = [default] if first is not None else []
            vals += [c for c in keys if c is not first]
            axes.append((k, vals))
    if not axes:
        return [{}]
    return [dict(zip([k for k, _ in axes], combo)) for combo in itertools.islice(itertools.product(*[v for _, v in axes]), limit)]

catalogue

catalogue()

Every profile there is, described (with its defaults), by name

Source code in src/rpps/profile/catalogue.py
def catalogue():
    """Every profile there is, described (with its defaults), by name"""
    return [info(f"{family}/{mode}") for family, modes in sorted(ls().items()) for mode in modes]

control

Header-driven control: the control path that runs back up a chain

Headers set what follows: DVB-S2 PLS (modulation, LDPC rate, pilots, frame length, per frame), the 802.11b PLCP (payload rate, mid-packet), length fields (802.15.4, BLE, ADS-B), the P25 NID, adaptive links. The change has to land at the right place without losing lock:

  1. Publish with a position. A step calls rp.base.control.publish(meta, op, fields, at=, out=, span=): at is the absolute input position the fields apply from, out where that falls in this call's output, span how long they hold. A frame sync publishes {"frame": k} at each start. A step that drops or inserts items reports rp.base.control.anchor(meta, op, at, out). Everything lands in stream.control (log, fields(step), reports, rerun, buffer).
  2. Map fields to parameters. controls, keyed by the publishing step's id, says which steps take which parameters, usually through a table (below). The loader refuses unknown steps or parameters, ambiguous ids, and parameters a step does not declare.
  3. Change at a position. A live change keeps state (constellation, puncturing, LDPC rate, frame length; taken through control(**params)), a restart rebuilds from the position (interleaver depth, a Viterbi's constraint length, FFT size). QPSK to BPSK changes the constellation and the carrier estimator's power, not the timing. What the last frame left in a step is dropped and reported, never joined to the next.
  4. Positions translate between representations through each step's rate and delay; that is why every block carries its absolute position. A change for a later step travels with the data like a tag.
  5. Late changes re-run. A change for a step before its publisher is carried back through the position maps, and the runner re-runs from a checkpoint (rpps.profile.runner). A change whose data has left the buffer is not applied backwards: the frames are dropped and reported. Standards that announce ahead (DVB-S2) never re-run.

Transmit: each frame's fields come from the caller (fields=, one dict or one per frame), else the entry's schedule, else its defaults; frame gives the items one frame takes. A header step that publishes drives the steps after it (the 802.11b PLCP builder switches the rate where its payload starts).

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 profile's controls maps those fields, through an optional table, to parameters of other steps; a runner changes each parameter at the matching position of that step's input.

What operators call (publish, anchor, both directions) is rpps.base.control.

The profile side ("controls" in a profile, keyed by the header step's id):

"controls": {
  "pls": {"table": "dvbs2/modcod", "key": "modcod",           a table resource: one row per key value
          "default": {"modcod": 4, "pilots": 1},              field values before any header, and after a span
          "schedule": [{"modcod": 4}, {"modcod": 12}],        transmit: the fields of each frame in turn
          "frame": {"calc": "kbch - 80"},                     transmit: items at the first step per frame
          "reach": 64,                                        how far back (header input items) a field can apply
          "on": "tx",                                         this entry drives only when transmitting ("rx", "both": default)
          "drive": {"map": {"name": "constellation"},         step id -> {parameter: source}: a field, a column of
                    "ldpc": {"name": "ldpc"},                   the key's row, or {"calc": ...} over both (with
                                                                "on": "tx" or "rx", in that direction only)
                    "plscram": {"length": {"calc": "slots*90 + pilots*((slots - 1)//16)*36"}}}}}

A "calc" is an expression (as {"expr": ...} takes) worked out when the fields arrive; an "expr" or a "param" in a profile is worked out when it is loaded, from the profile's parameters (a schedule of {"modcod": {"param": "modcod"}}).

A step's parameters are fixed unless controlled. Each step declares how it takes a change, per parameter (Step.controls): LIVE (in place, keeping its state) or RESTART (rebuilt from the position: what was in flight is discarded and reported). A parameter it does not declare cannot be controlled, and the loader refuses a profile that tries. A change applied to a step marks a frame start for it, so frame-scoped steps (a header remover, a pilot remover) restart their frame there.

Classes:

Name Description
Table

A table resource: rows of named columns, looked up by the key fields

Entry

One entry of a profile's controls: the fields of one header step and the parameters they drive (see module)

PosMap

How a step's input positions become its output positions: anchors (input, output, rate), from which the output

Functions:

Name Description
table

Load a table resource by name: rp.profile.table("dvbs2/modcod")

parse

The controls section of a profile, checked against its steps: {header step id: Entry}

rate_of

Output items per input item of an operator, in the direction it runs (how: "+" stage, "/" decode, "*" encode).

Table

Table(name, key, columns, rows, only=None)

A table resource: rows of named columns, looked up by the key fields

{"base": "table", "comment": "...", "key": "modcod",                 or a list of key columns
 "columns": ["modcod", "constellation", "ldpc"],
 "rows": [[4, "psk/qpsk", "ldpc/dvbs2_64800_1_2"], ...]}
{field: value}: the rows apply only where the fields have these values (a field not given counts as its value),

e.g. DVB-S2's MODCODs, and not a DVB-S2X header's (its "s2x" bit set): no row then

Methods:

Name Description
row

The row the fields' key values pick, or None (a key field missing, or no such row)

Source code in src/rpps/profile/control.py
def __init__(self, name, key, columns, rows, only=None):
    self.name = name
    self.only = dict(only or {})
    self.key = [key] if isinstance(key, str) else list(key)
    self.columns = list(columns)
    missing = [k for k in self.key if k not in self.columns]
    if missing:
        raise ConfigError(f"table {name}: key {missing} is not a column of {self.columns}")
    self.rows = {}
    for r in rows:
        if len(r) != len(self.columns):
            raise ConfigError(f"table {name}: row {r} has {len(r)} values for {len(self.columns)} columns")
        d = dict(zip(self.columns, r))
        self.rows[tuple(_norm(d[k]) for k in self.key)] = d
row
row(fields)

The row the fields' key values pick, or None (a key field missing, or no such row)

Source code in src/rpps/profile/control.py
def row(self, fields):
    """The row the fields' key values pick, or None (a key field missing, or no such row)"""
    if any(k not in fields or fields[k] is None for k in self.key):
        return None
    if any(_norm(fields.get(k, v)) != _norm(v) for k, v in self.only.items()):
        return None
    return self.rows.get(tuple(_norm(fields[k]) for k in self.key))

Entry

Entry(header, obj, where)

One entry of a profile's controls: the fields of one header step and the parameters they drive (see module)

Methods:

Name Description
names

Fields and the columns of their row, fields first; and the row (None without a table or a key)

values

{step id: {parameter: value}} these fields set, and the row they picked (None: none). A parameter whose source

frame_items

Transmit: items of the first step one frame takes, from frame (None: one frame per call)

revert

The default values of these fields: what holds after a span

Source code in src/rpps/profile/control.py
def __init__(self, header, obj, where):
    self.header = header
    if not isinstance(obj, dict) or "drive" not in obj:
        raise ConfigError(f"{where}: controls[{header!r}] needs 'drive': {{step id: {{parameter: source}}}}")
    self.table = table(obj["table"]) if obj.get("table") else None
    self.defaults = dict(obj.get("default", {}))
    self.schedule = [dict(f) for f in obj.get("schedule", [])]
    self.frame = obj.get("frame")
    self.reach = obj.get("reach")
    self.on = obj.get("on", "both")
    if self.on not in ("rx", "tx", "both"):
        raise ConfigError(f"{where}: controls[{header!r}] 'on' is rx, tx or both, not {self.on!r}")
    self.drive = {sid: dict(ps) for sid, ps in obj["drive"].items()}
names
names(fields)

Fields and the columns of their row, fields first; and the row (None without a table or a key)

Source code in src/rpps/profile/control.py
def names(self, fields):
    """Fields and the columns of their row, fields first; and the row (None without a table or a key)"""
    row = self.table.row(fields) if self.table is not None else None
    return {**(row or {}), **fields}, row
values
values(fields, direction=None)

{step id: {parameter: value}} these fields set, and the row they picked (None: none). A parameter whose source the fields don't give is left alone, so a change that carries only some fields changes only what they drive; so is one whose source drives only the other direction ({"calc": ..., "on": "tx"})

Source code in src/rpps/profile/control.py
def values(self, fields, direction=None):
    """{step id: {parameter: value}} these fields set, and the row they picked (None: none). A parameter whose source
    the fields don't give is left alone, so a change that carries only some fields changes only what they drive; so is
    one whose source drives only the other direction ({"calc": ..., "on": "tx"})"""
    names, row = self.names(fields)
    out = {}
    for sid, ps in self.drive.items():
        for p, src in ps.items():
            if direction is not None and isinstance(src, dict) and src.get("on", "both") not in ("both", direction):
                continue
            v = self._value(src, names, fields)
            if v is not _NA:
                out.setdefault(sid, {})[p] = v
    return out, row
frame_items
frame_items(fields)

Transmit: items of the first step one frame takes, from frame (None: one frame per call)

Source code in src/rpps/profile/control.py
def frame_items(self, fields):
    """Transmit: items of the first step one frame takes, from `frame` (None: one frame per call)"""
    if self.frame is None:
        return None
    v = self._value(self.frame, self.names(fields)[0], fields)
    if v is _NA or v is None:
        raise ConfigError(f"controls[{self.header!r}]: frame {self.frame} not given by fields {fields}")
    return int(v)
revert
revert(fields)

The default values of these fields: what holds after a span

Source code in src/rpps/profile/control.py
def revert(self, fields):
    """The default values of these fields: what holds after a span"""
    return {k: self.defaults.get(k) for k in fields}

PosMap

PosMap(anchors=None, r0=1.0)

How a step's input positions become its output positions: anchors (input, output, rate), from which the output advances rate items per input item. A step gets one when it first runs, one at every change applied to it (its rate may change), and one wherever it reports that it dropped or inserted items

Methods:

Name Description
cut

Forget the anchors after input position i (they came from a pass that is being re-run)

add

An anchor; one at the same input position is replaced (what a step reports wins over what was worked out). One

fwd

Output position of input position i

back

Input position of output position o

Source code in src/rpps/profile/control.py
def __init__(self, anchors=None, r0=1.0):
    self.a = list(anchors or [])
    self.r0 = float(r0) if r0 else 1.0 # Before any anchor: positions scale by the step's rate from 0, as its first
cut
cut(i)

Forget the anchors after input position i (they came from a pass that is being re-run)

Source code in src/rpps/profile/control.py
def cut(self, i):
    """Forget the anchors after input position i (they came from a pass that is being re-run)"""
    self.a = [x for x in self.a if x[0] <= i]
add
add(i, o, rate)

An anchor; one at the same input position is replaced (what a step reports wins over what was worked out). One on the line already there (a change that kept the rate: every header's) changes nothing and is not kept, so a long stream's map stays as short as its rate changes

Source code in src/rpps/profile/control.py
def add(self, i, o, rate):
    """An anchor; one at the same input position is replaced (what a step reports wins over what was worked out). One
    on the line already there (a change that kept the rate: every header's) changes nothing and is not kept, so a long
    stream's map stays as short as its rate changes"""
    k = bisect.bisect_left(self.a, i, key=_IN)
    if k < len(self.a) and self.a[k][0] == i:
        self.a[k] = [i, o, rate]
        return
    if k and rate == self.a[k - 1][2] and o == self.a[k - 1][1] + (i - self.a[k - 1][0])*rate:
        return
    self.a.insert(k, [i, o, rate])
fwd
fwd(i)

Output position of input position i

Source code in src/rpps/profile/control.py
def fwd(self, i):
    """Output position of input position i"""
    if not self.a:
        return i*self.r0
    k = max(bisect.bisect_right(self.a, i, key=_IN) - 1, 0)
    a = self.a[k]
    return a[1] + (i - a[0])*a[2]
back
back(o)

Input position of output position o

Source code in src/rpps/profile/control.py
def back(self, o):
    """Input position of output position o"""
    if not self.a:
        return o/self.r0
    k = max(bisect.bisect_right(self.a, o, key=_OUT) - 1, 0)
    a = self.a[k]
    return a[0] + (o - a[1])/a[2] if a[2] else a[0]

table cached

table(name)

Load a table resource by name: rp.profile.table("dvbs2/modcod")

Source code in src/rpps/profile/control.py
@functools.lru_cache(maxsize=None)
def table(name):
    """Load a table resource by name: `rp.profile.table("dvbs2/modcod")`"""
    return _config.load("table", name)

parse

parse(obj, steps, where)

The controls section of a profile, checked against its steps: {header step id: Entry}

Every step it names must exist once, and every parameter it drives must be one the step can take, live or restart

Source code in src/rpps/profile/control.py
def parse(obj, steps, where):
    """The controls section of a profile, checked against its steps: {header step id: Entry}

    Every step it names must exist once, and every parameter it drives must be one the step can take, live or restart"""
    if not obj:
        return {}
    by_id = {}
    for st in steps:
        by_id.setdefault(st.id, []).append(st)
    def one(sid, what):
        hits = by_id.get(sid, [])
        if len(hits) != 1:
            raise ConfigError(f"{where}: controls {what} {sid!r}: {'no such step' if not hits else 'several steps have that id'}"
                              f" (step ids: {sorted(by_id)})")
        return hits[0]
    out = {}
    for header, e in obj.items():
        one(header, "header")
        entry = Entry(header, e, where)
        for sid, ps in entry.drive.items():
            st = one(sid, "drives")
            for p in ps:
                how = st.controls.get(p)
                if how not in (LIVE, RESTART):
                    raise ConfigError(f"{where}: controls[{header!r}] drives {sid}.{p}, which {st.category}:{st.kind} cannot "
                                      f"take (it takes {sorted(st.controls) or 'no controlled parameters'})")
        out[header] = entry
    return out

rate_of

rate_of(op, how)

Output items per input item of an operator, in the direction it runs (how: "+" stage, "/" decode, "*" encode). From the operator's pos_rate(decode) when it has one; None when it can't say (the runner measures it)

Source code in src/rpps/profile/control.py
def rate_of(op, how):
    """Output items per input item of an operator, in the direction it runs (how: "+" stage, "/" decode, "*" encode).
    From the operator's `pos_rate(decode)` when it has one; None when it can't say (the runner measures it)"""
    f = getattr(op, "pos_rate", None)
    if f is None:
        return None
    r = f(how != "*")
    return None if r is None else float(r)

decoder

A selected signal's samples to a profile's messages, block by block: for a program that shows what a signal carries

dec = rp.profile.Decoder("adsb/mode_s", Fs=20e6, offset=-3.2e6, cf=1093.2e6)
for start, x, t in blocks:                       # the analyser's blocks: its own sample index, the block's time
    for m in dec.feed(x, start=start, time=t):   # rp.profile.Message, placed in the caller's index and time
        print(m.kind, m.crc_ok, m.fields)
dec.status                                       # {"state": "searching" | "measuring" | "locked" | "lost", "why", ...}

The Decoder brings the signal at offset from the samples' centre to the profile's rate (rp.profile.info: requires): a shift and staged decimation (rp.signal.channelize), then a fractional resampler (FractionalPolyphase) to the exact rate; an FM demodulator between them for a profile that takes an FM channel's audio (AX.25). A profile whose symbol rate the standard leaves open (DVB-S, CCSDS) takes baud, or the Decoder measures it first (rp.sync.Lock.find on the channel, bw wide), holding the samples until it can, and feeds them through once it has.

Blocks need not follow on: start is the caller's index of each block's first sample. An overlap is cut off; a gap up to fill seconds is filled with zeros (the profile's loops coast, frames keep their place, the frames in it are lost); a longer one, or a step back of more than the block, is a seek: the frames the profile holds come out, and its stream starts over (a measured rate is kept). Work is about proportional to the samples fed (and the zeros of a filled gap); status["load"] is the time a feed took over the time its samples span.

One Decoder for one signal; not thread-safe. A retune, a new sample rate or another signal: reset() or a new Decoder.

Classes:

Name Description
Decoder

A profile's receiver behind a front end that brings a selected signal to it (see module)

Functions:

Name Description
requirements_with

A ProfileInfo's requires again, the rate now known

Decoder

Decoder(name, Fs, offset=0.0, cf=None, baud=None, bw=None, sync=None, fill=0.05, kinds=None, **params)

A profile's receiver behind a front end that brings a selected signal to it (see module)

name: the profile; Fs: the rate of the samples fed; offset: the signal's centre from the samples' centre [Hz]; cf: the samples' centre frequency [Hz] (for Message.freq, and the params that follow from it: BLE's channel, NR's fc); baud: the symbol rate, for a profile that leaves it open; bw: the channel's width when there is no rate to work it out from (for measuring one: the selected signal's width); sync: the profile's sync settings; fill: the longest gap filled with zeros [s]; kinds: the message kinds wanted (ProfileInfo.kinds), None for all: only the steps they need run (Profile.rx), and status counts only those; params: the profile's params (those cf would give, given here, win) Raises ValueError when Fs can't hold what the profile needs, ConfigError for a kind it doesn't give.

Methods:

Name Description
reset

Start the profile's stream over (a seek, a pause, a retune): the next block starts a new one. A measured rate

feed

The messages the samples complete (rp.profile.Message, in the caller's index and time).

close

The end of the stream: what the profile holds comes out

Attributes:

Name Type Description
status

{"state": "measuring" (the rate) | "searching" (no good message yet) | "locked" (one lately) | "lost" (none

Source code in src/rpps/profile/decoder.py
def __init__(self, name, Fs, offset=0.0, cf=None, baud=None, bw=None, sync=None, fill=0.05, kinds=None, **params):
    self.name, self.Fs, self.offset, self.cf = name, float(Fs), float(offset), cf
    self.sync, self.fill = sync, float(fill)
    self.kinds = None if kinds is None else frozenset(kinds)
    self._given = dict(params)
    desc = _info(name, baud=baud, **params) # Checks the params and the rate
    self.info = desc
    req = desc.requires
    if cf is not None and req["from_cf"]: # Params the carrier gives, unless given
        from .. import _config
        values = {**{k: v["default"] for k, v in desc.params.items()}, **params, "cf": float(cf) + self.offset}
        for k, e in req["from_cf"].items():
            if k not in params:
                params[k] = _config.evaluate(e, values, f"profile/{name} from_cf")
        desc = _info(name, baud=baud, **params)
    if self.kinds is not None and not self.kinds <= set(desc.kinds): # (before a rate is measured)
        from ..errors import ConfigError
        raise ConfigError(f"profile {name}: no message kinds {sorted(self.kinds - set(desc.kinds))} (gives {desc.kinds})")
    self.params, self.req = params, desc.requires
    self.bw = float(bw) if bw is not None else self.req["bw"]
    if self.bw is not None and self.bw > self.Fs:
        raise ValueError(f"{name} needs {self.bw/1e6:g} MHz of channel; samples at {self.Fs/1e6:g} MS/s hold "
                         f"{self.Fs/1e6:g} MHz")
    if self.req["baud"] is None and self.bw is None:
        self.bw = self.Fs
    self._load = None
    self._counts = {"messages": 0, "good": 0, "failed": 0}
    self.reset()
status property
status

{"state": "measuring" (the rate) | "searching" (no good message yet) | "locked" (one lately) | "lost" (none lately), "why": the reason when there is one, "baud", "Fs": the profile's rate, "load": a feed's time over its samples' time, "messages"/"good"/"failed": counts, "est": the profile's estimates (plain values)}

reset
reset()

Start the profile's stream over (a seek, a pause, a retune): the next block starts a new one. A measured rate is kept; the times blocks were given and the last good message are forgotten. Frames the profile holds are dropped: close() first to have them

Source code in src/rpps/profile/decoder.py
def reset(self):
    """Start the profile's stream over (a seek, a pause, a retune): the next block starts a new one. A measured rate
    is kept; the times blocks were given and the last good message are forgotten. Frames the profile holds are
    dropped: `close()` first to have them"""
    self._anchors, self._last_good = [], None
    self._front = self._rx = self._stream = None
    self._next = None      # The caller's index the next sample should have
    self._seg = None       # The caller's index of the profile stream's first sample
    self._held, self._held_at, self._why = [], None, None
    if self.req["baud"] is not None:
        self._build()
feed
feed(samples, start=None, time=None, flush=False)

The messages the samples complete (rp.profile.Message, in the caller's index and time).

start: the caller's index of samples[0] (None: right after the last block); time: its time [s] (a radio's timestamp, the host clock), so messages carry it; flush: the stream ends here (frames held come out)

Source code in src/rpps/profile/decoder.py
def feed(self, samples, start=None, time=None, flush=False):
    """The messages the samples complete (rp.profile.Message, in the caller's index and time).

    start: the caller's index of samples[0] (None: right after the last block); time: its time [s] (a radio's
    timestamp, the host clock), so messages carry it; flush: the stream ends here (frames held come out)"""
    t_wall = _time.perf_counter()
    x = np.asarray(samples)
    if x.ndim != 1:
        raise ValueError("samples: one channel, a 1-D array")
    if start is None:
        start = self._next if self._next is not None else 0
    start = int(start)
    msgs = []
    if self._next is not None and start != self._next: # Not where the last block ended
        gap = start - self._next
        if gap < 0 and -gap <= len(x): # An overlap: what was fed already is cut off
            x = x[min(-gap, len(x)):]
            start = self._next
        elif 0 < gap <= self.fill*self.Fs and self._rx is not None:
            x = np.concatenate((np.zeros(gap, np.complex64), x.astype(np.complex64)))
            start = self._next
        else: # A long gap, or a seek back
            msgs = self._restart()
    if time is not None:
        self._anchors = (self._anchors + [(start, float(time))])[-64:]
    if self._seg is None:
        self._seg = start
    self._next = start + len(x)
    if self._rx is None: # The rate is not known yet: measure it on what has come
        x = self._measure(x, start)
        if self._rx is None:
            return msgs
        start = self._seg
    msgs += self._run(x, flush)
    span = len(samples)/self.Fs
    if span > 0:
        load = (_time.perf_counter() - t_wall)/span
        self._load = load if self._load is None else 0.8*self._load + 0.2*load
    return msgs
close
close()

The end of the stream: what the profile holds comes out

Source code in src/rpps/profile/decoder.py
def close(self):
    """The end of the stream: what the profile holds comes out"""
    if self._rx is None:
        return []
    return self._run(np.zeros(0, np.complex64), True)

requirements_with

requirements_with(desc, params, baud)

A ProfileInfo's requires again, the rate now known

Source code in src/rpps/profile/decoder.py
def requirements_with(desc, params, baud):
    """A ProfileInfo's requires again, the rate now known"""
    return _info(desc.name, baud=baud, **params).requires

encoder

Packets to samples through a profile's transmitter: what a capture rule gives on receive, sent back out

enc = rp.profile.Encoder("ieee802154/2450", rate=250e3)
for pkt in rp.source.Tun("rpps1", linktype="ieee802_15_4_nofcs").packets():   # what the system sends
    enc.packet(pkt) >> radio                                                   # (rp.source.DeviceSink)
enc.flush() >> radio

A packet is the bytes a profile's capture rule (rpps.link.capture) makes of a message kind: the rule is undone (its transforms in reverse), its included parts split back: a header part read into the fields of the frame (the header's own schema), an FCS part dropped (the transmitter makes it), the payload sent with those fields over the profile's defaults and the Encoder's. Each packet is one frame (a burst profile: one burst, placed by its burst step). bits(...) sends bits as they are (rpps tx does), gap seconds of silence after each.

Classes:

Name Description
Encoder

A profile's transmitter, a packet (or a block of bits) at a time (see module)

Encoder

Encoder(profile, rate, kind=None, fields=None, gap=None, hop=None, rate_out=None, linktype=None, **params)

A profile's transmitter, a packet (or a block of bits) at a time (see module)

profile: a Profile or a name (params: its parameters); rate: the data's rate at the transmitter's first step (bits or symbols a second); kind: the message kind whose capture rule a packet follows (default: the one rule the profile has that captures, else its only kind); fields: the fields of every frame, over the profile's (a packet's own header over these). gap: seconds of silence after each packet or block (a profile without a burst step); hop, rate_out: a burst profile's carrier offsets cycled burst by burst and its output rate. linktype: the packets' link type when it isn't the rule's but one it converts from (802.15.4 without FCS off a Linux interface: the FCS is made). count: packets sent; Fs: the output's rate

Methods:

Name Description
bits

The samples of these bits (bool, MSB first; or bytes) sent as one frame, or burst

flush

A burst profile: the samples of the bursts not given yet (the stream ends); otherwise nothing

rule

(the capture rule a packet follows, the step that emits its kind)

unpacket

(payload bits, fields) of a packet (of linktype: the Encoder's, else the rule's): the capture rule undone,

packet

The samples of one packet (bytes of the capture rule's link type, or of linktype), as one frame or burst

Source code in src/rpps/profile/encoder.py
def __init__(self, profile, rate, kind=None, fields=None, gap=None, hop=None, rate_out=None, linktype=None, **params):
    from .profile import Profile, load
    from .burst import BurstTxRunner
    self.profile = profile if isinstance(profile, Profile) else load(profile, **params)
    self.rate, self.fields, self.gap = float(rate), dict(fields or {}), gap
    self.tx = self.profile.tx()
    self.bursts = isinstance(self.tx, BurstTxRunner)
    if self.bursts:
        bt = self.tx.burst_tx
        if gap is not None:
            bt.gap_s = gap
        if hop:
            bt.hop = [float(f) for f in hop]
        if rate_out:
            bt.Fs = rate_out
        bt.reset()
    elif hop or rate_out:
        raise ConfigError(f"{self.profile.name} has no burst step: hop and rate_out place bursts")
    self.kind, self.linktype = kind, linktype
    self._rule = self._op = None
    self.stream, self.Fs, self.count = None, None, 0
bits
bits(bits, fields=None, last=False)

The samples of these bits (bool, MSB first; or bytes) sent as one frame, or burst

Source code in src/rpps/profile/encoder.py
def bits(self, bits, fields=None, last=False):
    """The samples of these bits (bool, MSB first; or bytes) sent as one frame, or burst"""
    import rpps as rp
    if isinstance(bits, (bytes, bytearray)):
        bits = np.unpackbits(np.frombuffer(bytes(bits), np.uint8)).astype(bool)
    f = {**self.fields, **(fields or {})} or None
    if self.bursts:
        o = self.tx(rp.Data(np.asarray(bits, bool), Fs=self.rate, sps=1), fields=f, flush=last)
        x = np.asarray(o.data, dtype=np.complex64)
    else:
        d = rp.Data(np.asarray(bits, bool), Fs=self.rate, sps=1, stream=self.stream, flush=True)
        self.stream = d.stream
        o = self.tx(d, fields=f)
        x = np.asarray(o.data, dtype=np.complex64)
        if self.gap:
            x = np.concatenate((x, np.zeros(int(round(self.gap*o.Fs)), np.complex64)))
    self.Fs = o.Fs
    self.count += 1
    return rp.Data(x, Fs=o.Fs)
flush
flush()

A burst profile: the samples of the bursts not given yet (the stream ends); otherwise nothing

Source code in src/rpps/profile/encoder.py
def flush(self):
    """A burst profile: the samples of the bursts not given yet (the stream ends); otherwise nothing"""
    import rpps as rp
    if not self.bursts:
        return rp.Data(np.zeros(0, np.complex64), Fs=self.Fs or 1.0)
    o = self.tx.flush()
    return rp.Data(np.asarray(o.data, dtype=np.complex64), Fs=o.Fs)
rule
rule()

(the capture rule a packet follows, the step that emits its kind)

Source code in src/rpps/profile/encoder.py
def rule(self):
    """(the capture rule a packet follows, the step that emits its kind)"""
    if self._rule is None:
        p = self.profile
        kinds = p.kinds()
        kind = self.kind
        if kind is None:
            ruled = [k for k, r in p.capture.rules.items() if r is not False]
            kind = ruled[0] if len(ruled) == 1 else (next(iter(kinds)) if len(kinds) == 1 else None)
            if kind is None:
                raise ConfigError(f"Encoder {p.name}: which kind's packets? kind= one of {sorted(kinds)}")
        if kind not in kinds:
            raise ConfigError(f"Encoder {p.name}: no message kind {kind!r} (gives {sorted(kinds)})")
        r = p.capture.rule(kind)
        if r is False:
            raise ConfigError(f"Encoder {p.name}: kind {kind!r} is not captured (\"capture\": false)")
        sid = kinds[kind]
        st = next(st for st in p.flat(p.steps) if st.id == sid)
        self._rule, self._op, self.kind = r, (st.obj if st.obj is not None else (st.rx[-1][1] if st.rx else None)), kind
    return self._rule, self._op
unpacket
unpacket(data, linktype=None)

(payload bits, fields) of a packet (of linktype: the Encoder's, else the rule's): the capture rule undone, its parts split

Source code in src/rpps/profile/encoder.py
def unpacket(self, data, linktype=None):
    """(payload bits, fields) of a packet (of `linktype`: the Encoder's, else the rule's): the capture rule undone,
    its parts split"""
    rule, op = self.rule()
    lt = linktype if linktype is not None else self.linktype
    if lt is not None and rule.linktype is not None:
        from ..link.capture import convert
        data = convert(data, lt, rule.linktype) # (packets of a link type the rule's is made from)
    body, fields = rule.unpacket(data)
    bits = np.unpackbits(np.frombuffer(body, np.uint8)).astype(bool)
    parts = list(rule.include)
    if "fcs" in parts:
        if parts[-1] != "fcs":
            raise ConfigError(f"Encoder {self.profile.name}: an included FCS is sent last")
        n = _fcs_bits(op)
        bits = bits[:len(bits) - n]
        parts.pop()
    if parts and parts[0] == "header":
        from ..link.header import Header
        if not isinstance(op, Header):
            raise ConfigError(f"Encoder {self.profile.name}: kind {self.kind!r} has no header step to read a header with")
        sent = op._wire(bits, op.order == "lsb") # (its own inverse: as sent)
        n = op.need(sent[:op.header_bits or len(sent)])
        values, ok = op.parse(sent[:n])
        if not ok:
            raise ValueError(f"Encoder {self.profile.name}: the packet's header fails its CRC")
        computed = {f["name"] for f in op.fields if "tx" in f}
        fields.update({k: v for k, v in values.items() if k in op.values and k not in computed})
        bits = bits[n:]
        parts.pop(0)
    if parts != ["payload"]:
        raise ConfigError(f"Encoder {self.profile.name}: a packet of parts {rule.include} can't be split back to its payload")
    return bits, fields
packet
packet(data, fields=None, last=False, linktype=None)

The samples of one packet (bytes of the capture rule's link type, or of linktype), as one frame or burst

Source code in src/rpps/profile/encoder.py
def packet(self, data, fields=None, last=False, linktype=None):
    """The samples of one packet (bytes of the capture rule's link type, or of `linktype`), as one frame or burst"""
    bits, f = self.unpacket(data, linktype)
    return self.bits(bits, {**f, **(fields or {})}, last)

message

Decoded messages: what a profile receives, one record a frame, for a program to show or keep (rpps.profile)

A step that knows where a frame starts and whether it checked out (a link header, an LTE channel) emits it with rp.base.control.emit; the runner places it in the stream it was given and keeps it until runner.take_messages():

rx = rp.profile.load("adsb/mode_s").rx()
for block in src(65536):
    rx(block)
    for m in rx.take_messages():
        print(m.kind, m.crc_ok, m.fields, m.payload.hex() if m.payload else "")

rp.profile.Decoder does this, and brings the samples to the profile's rate first.

Classes:

Name Description
Message

One decoded frame

Message

Message(profile, kind, fields=None, payload=None, bits=0, crc_ok=None, sample=0, time=None, freq=None, quality=None, check=None, frame=None, frame_bits=0, parts=None)

One decoded frame

profile: the profile's name; kind: the step that emitted it (its id: "frame", "pdu", "pbch", "pdsch"...) fields: what the step decoded of the frame (header fields, a MIB, a DCI...) payload: the payload as bytes, most significant bit first (the last byte padded with zeros), None without one; bits: its length in bits crc_ok: whether the frame's check passed (False: shown so, fields as far as they were decoded), None without a check sample: where the frame starts, in samples of the stream the runner was given (a Decoder: of the samples it was fed), counted from the start of that stream time: seconds: the source's time of that sample when it has one (a radio's timestamp), else sample/Fs freq: the signal's centre frequency [Hz] when known (the stream's cf, a Decoder's cf + offset), else None quality: the profile's measure of its symbols when it has one (stream.est["quality"]: Es/N0, EVM), else None check: the definition behind crc_ok ("crc16_x25", a header's "crc24_ble"), None when unknown or without a check frame: the whole frame as received, as bytes (header, payload, FCS), when the step has more of it than the payload; None: the payload is the frame. frame_bits: its length in bits parts: where each part of frame is, {"header" | "payload" | "fcs" | ...: (first bit, bits)}; {} when frame is None

Methods:

Name Description
whole

(bytes, bits, parts) of the frame: frame when the step gave it, else the payload as the one part

payload_of

(bytes, number of bits) of a bit array (bool, 0/1, or soft values: negative is a one), MSB first

to_dict

Plain values, for JSON

placed

A copy placed in an outer stream: at sample there, of rate Fs (time from its t0), cf for freq when unknown

Source code in src/rpps/profile/message.py
def __init__(self, profile, kind, fields=None, payload=None, bits=0, crc_ok=None, sample=0, time=None, freq=None,
             quality=None, check=None, frame=None, frame_bits=0, parts=None):
    self.profile, self.kind, self.fields = profile, kind, dict(fields or {})
    self.payload, self.bits, self.crc_ok = payload, int(bits), crc_ok
    self.sample, self.time, self.freq, self.quality = int(sample), time, freq, quality
    self.check, self.frame, self.frame_bits, self.parts = check, frame, int(frame_bits), dict(parts or {})
whole
whole()

(bytes, bits, parts) of the frame: frame when the step gave it, else the payload as the one part

Source code in src/rpps/profile/message.py
def whole(self):
    """(bytes, bits, parts) of the frame: `frame` when the step gave it, else the payload as the one part"""
    if self.frame is not None:
        return self.frame, self.frame_bits, self.parts
    return (self.payload or b""), self.bits, ({"payload": (0, self.bits)} if self.payload is not None else {})
payload_of staticmethod
payload_of(bits)

(bytes, number of bits) of a bit array (bool, 0/1, or soft values: negative is a one), MSB first

Source code in src/rpps/profile/message.py
@staticmethod
def payload_of(bits):
    """(bytes, number of bits) of a bit array (bool, 0/1, or soft values: negative is a one), MSB first"""
    if bits is None:
        return None, 0
    b = np.asarray(bits)
    if b.dtype.kind == "f":
        b = b < 0
    b = b.astype(bool).ravel()
    return np.packbits(b).tobytes(), len(b)
to_dict
to_dict()

Plain values, for JSON

Source code in src/rpps/profile/message.py
def to_dict(self):
    """Plain values, for JSON"""
    q = self.quality
    if q is not None and not isinstance(q, dict):
        q = {k: getattr(q, k) for k in getattr(q, "__slots__", ()) if isinstance(getattr(q, k), (int, float))}
    return {"profile": self.profile, "kind": self.kind, "fields": {k: _plain(v) for k, v in self.fields.items()},
            "payload": None if self.payload is None else self.payload.hex(), "bits": self.bits,
            "crc_ok": self.crc_ok, "check": self.check, "sample": self.sample, "time": self.time, "freq": self.freq,
            "quality": q, "frame": None if self.frame is None else self.frame.hex(), "frame_bits": self.frame_bits,
            "parts": {k: list(v) for k, v in self.parts.items()}}
placed
placed(sample, Fs, cf=None, t0=None)

A copy placed in an outer stream: at sample there, of rate Fs (time from its t0), cf for freq when unknown

Source code in src/rpps/profile/message.py
def placed(self, sample, Fs, cf=None, t0=None):
    """A copy placed in an outer stream: at `sample` there, of rate Fs (time from its t0), cf for freq when unknown"""
    m = copy.copy(self)
    m.sample = int(round(sample))
    m.time = (t0 or 0.0) + m.sample/Fs
    if m.freq is None and cf:
        m.freq = cf
    return m

parallel

Where a profile's parallel region starts, and whether it can (rpps.parallel)

A profile marks the first step of the region: "parallel": "<step id>". Everything from there on runs frame by frame, and the steps before it (the serial front) find the frames and decide their parameters. The loader refuses a region that could not give the same result as the serial runner:

  • every step in it has frame scope (SCOPE): nothing carried from one frame to the next. An operator that is frame scoped only when a control restarts it (SCOPE_NEEDS, a scrambler's length or frame) needs the profile's controls to drive one of those;
  • no header in it publishes: a publisher in the region would set parameters of frames already being processed, so a header sits in the front and the region takes its resolved fields;
  • no change reaches back across the boundary: a late change (a step driven by a header after it) needs a re-run, which only the serial runner does.

Classes:

Name Description
Region

first: index in the profile's steps of the first parallel step; steps: the region's steps;

Functions:

Name Description
scope_of

FRAME when every receive operator of the step is frame scoped (given the parameters a control drives), else STREAM

plan

The Region for marker (a step id, or None for no region), checked as above; controls is {header id: Entry}

Region dataclass

Region(first: int, steps: list, driven: dict)

first: index in the profile's steps of the first parallel step; steps: the region's steps; driven: {step id: {parameter}} the front resolves for every frame (what controls drive in the region)

scope_of

scope_of(step, driven=())

FRAME when every receive operator of the step is frame scoped (given the parameters a control drives), else STREAM

Source code in src/rpps/profile/parallel.py
def scope_of(step, driven=()):
    """FRAME when every receive operator of the step is frame scoped (given the parameters a control drives), else STREAM"""
    ops = [op for _, op in step.rx]
    why = []
    for op in ops:
        if getattr(op, "SCOPE", None) != FRAME:
            why.append(f"{type(op).__name__} keeps state across frames")
        else:
            needs = list(getattr(op, "SCOPE_NEEDS", ()))
            if needs and not any(p in driven for p in needs):
                why.append(f"{type(op).__name__} restarts at a frame start only when a control drives one of {needs}")
    return ("stream", why) if why else ("frame", [])

plan

plan(marker, steps, controls, where)

The Region for marker (a step id, or None for no region), checked as above; controls is {header id: Entry}

Source code in src/rpps/profile/parallel.py
def plan(marker, steps, controls, where):
    """The Region for `marker` (a step id, or None for no region), checked as above; `controls` is {header id: Entry}"""
    if marker is None:
        return None
    ids = [s.id for s in steps]
    if ids.count(marker) != 1:
        raise ConfigError(f"{where}: parallel starts at {marker!r}: "
                          f"{'no such step' if marker not in ids else 'several steps have that id'} (step ids: {ids})")
    first = ids.index(marker)
    region = steps[first:]
    in_region = {s.id for s in region}
    driven = {}
    for header, entry in controls.items():
        for sid, params in entry.drive.items():
            if sid in in_region:
                driven.setdefault(sid, set()).update(params)
        if header in in_region:
            raise ConfigError(f"{where}: parallel from {marker!r}, but {header!r} publishes fields and is inside it: a "
                              f"header sits in the serial front, the region takes the fields it resolved")
        for sid in entry.drive:
            if sid in ids and ids.index(sid) < ids.index(header) and ids.index(sid) >= first:
                raise ConfigError(f"{where}: {header!r} drives {sid!r} after the fact (a late change, which the serial "
                                  f"runner re-runs): not allowed in a parallel region")
    for st in region:
        s, why = scope_of(st, driven.get(st.id, ()))
        if s != FRAME:
            raise ConfigError(f"{where}: step {st.id!r} ({st.category}:{st.kind}) is in the parallel region from {marker!r} "
                              f"but is not frame scoped: {'; '.join(why)}")
    return Region(first, region, {k: sorted(v) for k, v in driven.items()})

profile

Profiles: one config file per signal, both directions (rpps.profile)

{"base": "profile", "comment": "...", "ref": "...", "params": {"sps": {"default": 4}}, "defaults": {"timing": {"method": "mat"}}, optional: how the receiver estimates what sync steps name "steps": [ {"": "", "id": ..., ...}, ... ]} in receive order (see rpps.profile.steps) "controls": {"

": {...}} optional: header-driven control (see rpps.profile.control) "parallel": "" optional: the first step that runs frame by frame (see rpps.profile.parallel)

Classes:

Name Description
Profile

A signal: its steps in receive order, built from a definition. rx() and tx() give runners

Functions:

Name Description
load

Load a profile: rp.profile.load("ieee802154/2450", sps=8). params: values for its "params".

ls

The profiles there are: {family: [modes]}

Profile

Profile(name, obj, sync=None, params=None)

A signal: its steps in receive order, built from a definition. rx() and tx() give runners

Methods:

Name Description
flat

Every step: the trunk's, then each branch's (a branch step holds its branches' steps)

kinds

{kind: step id} of the messages the receive side gives. parallel: as run with its parallel region, whose kernels

needed

The step ids the messages of kinds need: their emitters, and every header whose fields drive a needed step (and

rx

Receive runner. start: the representation the source gives (a demodulator's timed symbols are SYMBOLS): the steps

tx

Transmit runner: the transform steps inverted, in reverse order (most sync and signal steps have no transmit side).

load

Loader of the profile domain (_config.load_obj): the parameters are already resolved into the steps

Source code in src/rpps/profile/profile.py
def __init__(self, name, obj, sync=None, params=None):
    self.name, self.obj = name, obj
    self.comment, self.ref = obj.get("comment", ""), obj.get("ref", "")
    self.params = dict(params or {})
    self._sync = {k: _config.Keys(dict(v)) for k, v in (sync or {}).items()} # (what reads them is recorded: _check_keys)
    if "steps" not in obj or not obj["steps"]:
        raise ConfigError(f"profile {name}: no steps")
    self.obj = obj = _tracked(obj)
    self.steps = self._build()
    branch = [self.steps[-1]] if self.steps and self.steps[-1].category == "branch" else [] # (its `frame` can be driven)
    self.controls = _control.parse(obj.get("controls"), self.flat(self.steps) + branch, f"profile {name}")
    if self.steps[-1].category == "branch" and obj.get("parallel"):
        raise ConfigError(f"profile {name}: a parallel region and branches together are not supported")
    self.region = _parallel.plan(obj.get("parallel"), self.steps, self.controls, f"profile {name}")
    self.capture = self._captures(obj.get("capture"))
    self._check_keys()
flat staticmethod
flat(steps)

Every step: the trunk's, then each branch's (a branch step holds its branches' steps)

Source code in src/rpps/profile/profile.py
@staticmethod
def flat(steps):
    """Every step: the trunk's, then each branch's (a branch step holds its branches' steps)"""
    if steps and steps[-1].category == "branch":
        return steps[:-1] + [st for chain in steps[-1].obj.values() for st in chain]
    return list(steps)
kinds
kinds(parallel=False)

{kind: step id} of the messages the receive side gives. parallel: as run with its parallel region, whose kernels give one "frame" message a frame in place of what the region's steps would emit

Source code in src/rpps/profile/profile.py
def kinds(self, parallel=False):
    """{kind: step id} of the messages the receive side gives. parallel: as run with its parallel region, whose kernels
    give one `"frame"` message a frame in place of what the region's steps would emit"""
    region = {st.id for st in self.region.steps} if parallel and self.region is not None else set()
    out = {}
    for st in self.flat(self.steps):
        k = self._emits(st)
        if k is not None and st.id not in region:
            out[k] = st.id
    if region:
        out["frame"] = self.region.steps[-1].id
    return out
needed
needed(kinds, parallel=False)

The step ids the messages of kinds need: their emitters, and every header whose fields drive a needed step (and so on). Raises ConfigError for a kind the profile doesn't give

Source code in src/rpps/profile/profile.py
def needed(self, kinds, parallel=False):
    """The step ids the messages of `kinds` need: their emitters, and every header whose fields drive a needed step (and
    so on). Raises ConfigError for a kind the profile doesn't give"""
    have = self.kinds(parallel)
    kinds = set(kinds)
    unknown = kinds - set(have)
    if unknown:
        raise ConfigError(f"profile {self.name}: no message kinds {sorted(unknown)} (gives {sorted(have)})")
    need = {have[k] for k in kinds}
    grew = True
    while grew:
        grew = False
        for e in self.controls.values():
            if e.header not in need and any(sid in need for sid in e.drive):
                need.add(e.header)
                grew = True
    return need
rx
rx(start=Rep.SAMPLES, applied=(), parallel=None, source=None, kinds=None)

Receive runner. start: the representation the source gives (a demodulator's timed symbols are SYMBOLS): the steps before it are skipped. applied: sync kinds the source has done already ({"timing"}): skipped too. source: an rp.source.Source, which says both (its REP and APPLIED). parallel: an rp.parallel.Parallel (where and how the profile's parallel region runs, frame by frame); the profile must have one ("parallel" in its definition) kinds: the message kinds wanted (kinds()), None for all: only those come out of take_messages(), and only the steps they need run (needed): branches none of them needs are not built, a chain ends at its last needed step (the runner's output is that step's). A parallel region runs whole or not at all: not when none of it is needed

Source code in src/rpps/profile/profile.py
def rx(self, start=Rep.SAMPLES, applied=(), parallel=None, source=None, kinds=None):
    """Receive runner. start: the representation the source gives (a demodulator's timed symbols are SYMBOLS): the steps
    before it are skipped. applied: sync kinds the source has done already (`{"timing"}`): skipped too.
    source: an rp.source.Source, which says both (its REP and APPLIED).
    parallel: an `rp.parallel.Parallel` (where and how the profile's parallel region runs, frame by frame); the profile
    must have one (`"parallel"` in its definition)
    kinds: the message kinds wanted (`kinds()`), None for all: only those come out of `take_messages()`, and only the
    steps they need run (`needed`): branches none of them needs are not built, a chain ends at its last needed step
    (the runner's output is that step's). A parallel region runs whole or not at all: not when none of it is needed"""
    if source is not None:
        start, applied = source.REP, source.APPLIED
    if parallel is not None and self.region is None:
        raise ConfigError(f"profile {self.name}: has no parallel region (no \"parallel\" in its definition)")
    keep = lambda st: st.category == "branch" or not (st.takes.value < start.value or (st.category == "sync" and st.kind in applied))
    if kinds is None:
        prune = lambda steps: steps
    else:
        kinds = frozenset(kinds)
        need = self.needed(kinds, parallel is not None)
        if parallel is not None:
            if need & {st.id for st in self.region.steps}:
                need |= {st.id for st in self.region.steps}
            else:
                parallel = None # (nothing of the region is needed: it isn't run)
        prune = lambda steps: self._prune(steps, need)
    steps = prune([st for st in self._build() if keep(st)])
    if not steps:
        raise ConfigError(f"profile {self.name}: no step left to receive {sorted(kinds)} with")
    if steps[-1].category == "branch":
        run = self._branch_rx(steps, parallel)
    elif (k := next((i for i, st in enumerate(steps) if st.category == "sync" and st.kind == "burst"), None)) is not None:
        run = self._burst_rx(steps, k, lambda: prune([st for st in self._build() if keep(st)]), parallel)
    else:
        run = self._chain_rx(steps, parallel)
    run.kinds = kinds
    return run
tx
tx()

Transmit runner: the transform steps inverted, in reverse order (most sync and signal steps have no transmit side). Call it as runner(block, fields=...) to set the fields of the frames that start in the block (see Runner). A profile with a burst step gives a burst transmitter (rpps.profile.burst.BurstTxRunner): a call a burst

Source code in src/rpps/profile/profile.py
def tx(self):
    """Transmit runner: the transform steps inverted, in reverse order (most sync and signal steps have no transmit side).
    Call it as `runner(block, fields=...)` to set the fields of the frames that start in the block (see Runner).
    A profile with a burst step gives a burst transmitter (rpps.profile.burst.BurstTxRunner): a call a burst"""
    built = self._build()
    if built[-1].category == "branch":
        raise ConfigError(f"profile {self.name}: transmitting through branches is not built (receive only)")
    k = [i for i, st in enumerate(built) if st.category == "sync" and st.kind == "burst"]
    if k:
        return self._burst_tx(built, k)
    return Runner(self._tx_slots(built), f"{self.name} tx", self.controls, "tx", profile=self.name)
load staticmethod
load(name, obj)

Loader of the profile domain (_config.load_obj): the parameters are already resolved into the steps

Source code in src/rpps/profile/profile.py
@staticmethod
def load(name, obj):
    """Loader of the profile domain (`_config.load_obj`): the parameters are already resolved into the steps"""
    return Profile(name, obj, params=_config.declared(obj))

load

load(name, sync=None, **params)

Load a profile: rp.profile.load("ieee802154/2450", sps=8). params: values for its "params". sync: per sync kind, the method and its settings, over the profile's defaults: sync={"timing": {"method": "known"}}

Source code in src/rpps/profile/profile.py
def load(name, sync=None, **params):
    """Load a profile: `rp.profile.load("ieee802154/2450", sps=8)`. params: values for its "params".
    sync: per sync kind, the method and its settings, over the profile's defaults: `sync={"timing": {"method": "known"}}`"""
    file = _config.find("profile", name)
    if file is None:
        raise FileNotFoundError(f"profile/{name}: not found, have {_config.ls('profile')}")
    resolved = _config.resolve(_config.read(file), params, f"profile/{name}")
    return Profile(name, resolved, sync=sync, params=_config.declared(resolved))

ls

ls(blind=False)

The profiles there are: {family: [modes]}

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/profile/profile.py
def ls(blind=False):
    """The profiles there are: {family: [modes]}

    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("profile", blind=blind)

runner

Profile runners: a profile's operators on a stream of blocks, with header-driven control

A runner holds one slot per operator. Each slot knows its step, how far it has read its input, and how its input positions map to its output positions (control.PosMap). Changes come from the control path (rpps.profile.control):

  • ahead: the change is for a step after the one that published it (a DVB-S2 PLS sets the constellation of its own payload, which has not been demapped yet). It travels with the data like a tag: before a slot runs, the runner splits the slot's input at the change's position and applies it between the two parts; after the slot ran, the position is carried to its output through the slot's map, and on to the next target.
  • late: the change is for a step before the one that published it (an 802.11b PLCP header sets the rate of the payload the demapper already demapped as DBPSK). Its position is carried back through the maps to that step, and the runner re-runs from the last checkpoint before it: the steps from the earliest such target (the re-run span) run piece by piece, with a checkpoint of their state at the start of every piece and the span's input kept back, sized from the signal (reach in the controls, carried into the span's units through the current rates). A change older than the oldest checkpoint is applied from there instead, and the drop is reported on the stream.

Transmitting, the runner itself publishes each frame's fields at the first step: the caller's, else the profile's schedule, else the defaults. Those drive the steps up to the header step; a header step that publishes in turn (an 802.11b PLCP builder, which knows where its payload starts) drives the steps after it.

Classes:

Name Description
Slot

One operator of a runner and its stream positions

Change

Field values on their way to the steps they drive

Runner

Operators in order, run on a stream of blocks: out = runner(block); transmitting, runner(block, fields=...)

Slot

Slot(how, op, step, index)

One operator of a runner and its stream positions

Source code in src/rpps/profile/runner.py
def __init__(self, how, op, step, index):
    self.how, self.op, self.step, self.index = how, op, step, index
    try:
        r0 = _ctl.rate_of(op, how)
    except Exception: # (an operator that can't say before it runs)
        r0 = None
    self.map = _ctl.PosMap(r0=r0 or 1.0)
    self.in_end = None   # Input position read up to
    self.out_next = None # Pipes: the position of their next output item (stages keep theirs in the stream)
    self.params = {}     # Controlled parameters, as last applied
    self.rate = None     # Output per input item, measured, for an operator that can't say

Change

Field values on their way to the steps they drive

params: {slot: {parameter: value}}. Ahead targets are applied as the tag (hop, pos: a position in slot hop's input) reaches them; late targets have their position in back ({slot: input position}); s0 is the position at the start of the re-run span

Runner

Runner(slots, name='', entries=None, direction='rx', profile=None)

Operators in order, run on a stream of blocks: out = runner(block); transmitting, runner(block, fields=...)

Stages keep their state in the block's stream; encoders and decoders keep theirs in the data's ctx, which the runner carries from one call to the next. So call one runner with consecutive blocks of one stream, and the output is the same whatever the cut. A new stream wants a new runner (profile.rx() / profile.tx()); each has its own operators.

fields (transmit): the fields of the frames that start in this block, over the profile's schedule: one dict for all of them, or a list, one per frame in order (then the schedule)

Receiving, the frames its steps decoded come out of take_messages() (rpps.profile.message), placed in the stream the runner was given. profile: the profile's name, for them

Methods:

Name Description
take_messages

The frames decoded since the last call, by position (each once: a re-run's second decode is not handed out

inject

Fields a step outside this runner published (another branch's header, a burst cutter's labels), driving this

to_input

A position in this runner's output, in its input (the stream it was given)

Source code in src/rpps/profile/runner.py
def __init__(self, slots, name="", entries=None, direction="rx", profile=None):
    self.slots, self.name, self.direction = list(slots), name, direction
    self._schemas = {} # A message step's field schema, by slot
    self.profile = profile if profile is not None else name
    self.messages, self._mseq, self._handed, self._input = [], 0, {}, (1.0, 0.0)
    self.ctx = None
    self.entries = dict(entries or {})
    self._step_slots = {}
    for s in self.slots:
        self._step_slots.setdefault(s.step.id, []).append(s.index)
    self.entries = {h: e for h, e in self.entries.items() if h in self._step_slots and e.on in ("both", direction)}
    self.changes, self._keys, self._logent, self._seq, self._call = [], set(), {}, 0, 0
    self._fresh = []
    self.emitted = None
    self._stream = None
    # Transmit: the entry whose fields the runner publishes, frame by frame
    self.framer = None
    if direction == "tx":
        framers = [e for e in self.entries.values() if e.schedule or e.frame is not None] or list(self.entries.values())
        if len(framers) > 1:
            from ..errors import ConfigError
            raise ConfigError(f"{name}: several controls could frame the transmit side: {[e.header for e in framers]}")
        self.framer = framers[0] if framers else None
    self.next_frame, self._sched, self._queue = None, 0, []
    # Receive: the re-run span, from the earliest step a header drives that comes before the header
    self.span = None
    if direction == "rx":
        for e in self.entries.values():
            h = self._header_slot(e)
            for sid, ps in e.drive.items():
                if all(isinstance(v, dict) and v.get("on", "both") == "tx" for v in ps.values()):
                    continue # (it drives that step only transmitting)
                for i in self._step_slots.get(sid, []):
                    if i < h:
                        self.span = i if self.span is None else min(self.span, i)
    self.ckpts, self.buf = [], []
    self._span_ops = set()
    # Steps whose output is a run of fixed-size frames ({"message": {"bits": n, "kind": k, "check": true, "fields":
    # a schema, rpps.link.fields: [{"name", "from", "bits"}, ...]}} in the profile: TS packets, transfer frames): the runner cuts it into messages, from
    # the step's last op. check: a decoder before it reports failures (an RS), so no failed mask means all good
    self._units = {}
    if direction == "rx":
        for sid, idx in self._step_slots.items():
            spec = self.slots[idx[-1]].step.spec.get("message")
            if spec:
                if self.span is not None and idx[-1] >= self.span:
                    from ..errors import ConfigError
                    raise ConfigError(f"{name}: step {sid!r} cuts messages inside the re-run span")
                self._units[idx[-1]] = [spec, None]
    self.stop = len(self.slots) # Slots this runner runs itself: a parallel runner stops where its region starts
take_messages
take_messages()

The frames decoded since the last call, by position (each once: a re-run's second decode is not handed out again)

Source code in src/rpps/profile/runner.py
def take_messages(self):
    """The frames decoded since the last call, by position (each once: a re-run's second decode is not handed out
    again)"""
    out = []
    for _, _, key, m in self.messages:
        if key not in self._handed:
            self._handed[key] = None
            out.append(m)
    self.messages = []
    while len(self._handed) > self.HANDED:
        self._handed.pop(next(iter(self._handed)))
    return sorted((m for m in out if self.kinds is None or m.kind in self.kinds), key=lambda m: m.sample)
inject
inject(entry, fields, pos, key)

Fields a step outside this runner published (another branch's header, a burst cutter's labels), driving this runner's steps from pos of its input, as its own header's would

Source code in src/rpps/profile/runner.py
def inject(self, entry, fields, pos, key):
    """Fields a step outside this runner published (another branch's header, a burst cutter's labels), driving this
    runner's steps from `pos` of its input, as its own header's would"""
    if key in self._keys:
        return
    self._keys.add(key)
    values, _ = entry.values(fields, self.direction)
    params = {i: dict(ps) for sid, ps in values.items() for i in self._step_slots.get(sid, [])}
    if not params:
        return
    ch = Change()
    ch.key, ch.fields, ch.origin, ch.at, ch.params, ch.step = key, dict(fields), -1, pos, params, entry.header
    self._seq += 1
    ch.seq = self._seq
    ch.fwd, ch.hop, ch.pos = set(params), 0, pos
    ch.group, ch.btargets, ch.back, ch.s0 = (-1, pos), [], {}, None
    self.changes.append(ch)
to_input
to_input(pos)

A position in this runner's output, in its input (the stream it was given)

Source code in src/rpps/profile/runner.py
def to_input(self, pos):
    """A position in this runner's output, in its input (the stream it was given)"""
    return self._back(pos, len(self.slots), 0)

rpps.profile.steps

What each step of a profile builds (rpps.profile)

A step is one dict with one category key, {"<category>": "<kind>", ...its parameters}, in receive order. Building it gives a Step: the operators it runs on receive and on transmit, and the representations it takes and gives on receive.

transform steps (wave, symbol, code, link) build a transmit/receive pair: the receive side as written, the transmit
    side inverted (the profile runs transmit steps in reverse order)
sync and signal steps run on receive only

A step names the resources it uses by their path below the resource ("additive/dvb_energy", "rrc/0p35"), so the profile says what each is.

Sync steps name what is estimated; how is a method, chosen by defaults in the profile or the sync argument of rp.profile.load, else the default here.

Every step has an id ("id", else its kind), by which a profile's controls name it, and says which of its parameters a header may change and how (controls: {parameter: "live" | "restart"}, from its operators' CONTROLS). A parameter it does not list cannot be controlled (see rpps.profile.control).

The kinds (python -m rpps steps lists them with the sync methods):

signal   filter (a definition), lowpass / highpass / bandpass / bandstop (designed in Hz: cutoff + taps, or transition +
         atten_db), decimate, resample (up/down), channelize (freq, width), shift (freq), conjugate (spectral inversion),
         dc_block, deemphasis
every    class: your own operator by module path, in the category it does ("class", "args"; wave: "tx_class")
sync     timing, carrier, equalize, agc (methods), frame (a physical header's preamble, a word or a complex
         sequence, or named alternatives / a Zadoff-Chu set; before, length, segments, scale, polarity, classify), delimit (a word among bits:
         word + bits, a word sequence, or a link header's preamble; length, keep, polarity, errors), align (a repeating
         marker), puncture, pilots, squelch, quality (Es/N0 and EVM to est), ofdm, inversion (by a header's preamble
         or a complex sequence)
wave     shape (a pulse definition; symbol pulses get a matched filter), stagger, fm (h + sps: FSK; deviation: analog),
         am (the envelope; alpha null keeps its mean), ssb (bw, sideband), ofdm (n_fft, n_cp)
symbol   constellation (name, mapping), differential, spread (a chip sequence), carriers, header, pilots, scramble,
         marker (known symbols before each frame: a `sequence` with symbols, or `zc` {length, root, shift}; root,
         shift, sequence controlled per frame), puncture (symbols at `at` of every `every` from the frame start,
         dropped; `value` inserted on transmit: P25's status symbols)
code     fec (type block / conv / interleave, name, args), scramble (name, args; length: frames of that many bits from
         the first), line (invert, nrzi, nrzm, manchester, thomas), marker (a word before each frame: length, or frames by
         control), uncoded
link     crc, frame (HDLC), header (fields, crc, fcs, payload; select: the frames with those field values), gse
         (GSE packets of DVB-S2 data fields: protocols, each PDU a frame)
grid     resource grids (rpps.grid), receive only: lte_cell (offset, span, resolution, acquire, lose, gate, pci, duplex), lte_grid
         (n_rb), and the channels on its frames, lte_pbch, lte_pcfich, lte_pdcch (rntis), lte_pdsch; nr_cell (offset,
         span, resolution, period, acquire, lose, gate, fc, scs, pattern), nr_grid, nr_pbch, nr_pdcch (rntis,
         min_bw), nr_pdsch (fc, min_bw)