Skip to content

Profiles: a known signal

A profile is one JSON file that describes a whole signal in both directions: its steps in receive order (filters, sync, pulse, modulation, codes, framing) and the parameters a header may change along the way. When a signal has a profile, use it instead of chaining operators by hand: the header-driven changes (lengths, rates, modulations) are wired up.

python -m rpps ls profile                 # the shipped profiles
python -m rpps show profile/ble/adv       # one, with its parents applied
python -m rpps steps                      # the step kinds and sync methods a profile can name
python -m rpps rx ble/adv capture.cf32 --fs 4e6 --param channel=38
python -m rpps tx ble/adv out.cf32 --rate 1e6 --random 20 --packet 20 --param channel=38 --field type=2

Transmit and receive

"""A known signal from one definition: a profile transmits and receives it

    python examples/profile_loopback.py
    python -m rpps ls profile          # the shipped profiles
    python -m rpps show profile/ble/adv
    python -m rpps steps               # the step kinds and sync methods a profile can name

A profile is one JSON file with the steps of a signal in receive order. `p.rx()` runs them as written; `p.tx()` runs the
transform steps inverted and in reverse (sync steps are receive only). Header fields go in on transmit (`fields=`) and
come back on receive in `stream.est`. When a signal has a profile, use it instead of chaining operators by hand: the
header-driven changes (lengths, rates, modulations) are wired up for you.

Here: Bluetooth LE advertising packets on channel 38 through a frequency offset and noise. BLE's profile receives packet
by packet: its burst step cuts the samples into packets, and the steps after it run on each packet anew (its preamble
step finds the access address, which places the bit timing and takes off the frequency offset). So a runner gives a list,
one output per packet that ended in the block, each with its own `stream.est`. A runner goes where a stage does,
`source(n) + p.rx()` (blocks flatten the lists), and how the samples are cut doesn't matter: the receive is run in blocks
of two sizes, and once more by hand in uneven blocks (`stream=` passed on, as with any stage).
"""
import numpy as np

import rpps as rp

def main(snr_db=15.0, cfo=20e3):
    rng = np.random.default_rng(11)
    p = rp.profile.load("ble/adv", channel=38)
    print(p, p.params)

    # Transmit three advertising PDUs: a call a burst (its burst step places them, the profile's gap_s apart: 1 ms; a
    # call gives the samples up to its burst's start, flush=True the rest)
    pdus = [bytes(rng.integers(0, 256, n).astype(np.uint8)) for n in (6, 20, 37)]
    tx = p.tx()
    waves = [tx(rp.Data(pdu, Fs=1e6, sps=1), fields={"type": 2, "txadd": 1}).data for pdu in pdus] # the length is worked out
    wave = tx.flush()
    waves.append(wave.data)
    air = (rp.Data(np.concatenate(waves), Fs=wave.Fs)
           + rp.signal.channel.CFO(cfo) + rp.signal.channel.AWGN(snr_db=snr_db, seed=1))
    print(f"transmitted {len(pdus)} packets: {len(air)} samples at {wave.Fs/1e6:g} MS/s, {wave.sps} a bit")

    # Receive: the samples as a source gives them, the runner added like a stage; one output per packet
    def receive(block):
        outs = list(rp.source.Memory(air.data, Fs=wave.Fs, sps=wave.sps)(block) + p.rx())
        return b"".join(bytes.fromhex(o.as_bytes().hex) for o in outs if len(o)), outs
    got, outs = receive(4096)
    for o in outs:
        est = o.stream.est
        print(f"packet at sample {est['aa_wave']['pos']}: header {est['ble_adv']['last']}, offset level {est['aa_wave']['level']:+.3f}")
    assert got == b"".join(pdus)
    assert len(outs) == 3 and all(o.stream.est["ble_adv"]["fcs_failed"] == 0 for o in outs)
    assert outs[-1].stream.est["ble_adv"]["last"]["txadd"] == 1
    assert receive(300)[0] == got

    # By hand, in uneven blocks: the runner called on each, the stream passed on
    rx, stream, parts, at = p.rx(), None, [], 0
    cuts = [333, 1, 700, 5000]
    cuts.append(len(air) - sum(cuts))
    for k, n in enumerate(cuts):
        blk = rp.Data(air.data[at:at + n], Fs=wave.Fs, sps=wave.sps, stream=stream, flush=k == len(cuts) - 1)
        stream, at = blk.stream, at + n
        parts += [bytes.fromhex(o.as_bytes().hex) for o in blk + rx]
    assert b"".join(parts) == got
    print(f"the same {len(got)} bytes in blocks of 4096, of 300, and of {cuts}")

if __name__ == "__main__":
    main()

Writing one

A profile lives in config/profile/<family>/<mode>.json (or your own config directory: Definitions). One list of steps, in receive order: a transform step (wave, symbol, code, link) runs as written on receive and inverted, in reverse, on transmit; a sync step is skipped on transmit.

{"comment": "IEEE 802.15.4 2.4 GHz O-QPSK", "ref": "IEEE 802.15.4-2020 12",
 "params": {"sps": {"default": 4}},
 "defaults": {"carrier": {"method": "none"}},
 "steps": [
   {"sync": "carrier"},
   {"wave": "stagger", "delay": 0.5},
   {"wave": "shape", "pulse": "halfsine/halfsine", "sps": {"param": "sps"}},
   {"sync": "timing"},
   {"symbol": "spread", "sequence": "ieee802154_2450", "pair": true}
 ]}

builds rx = carrier + Stagger("i") + halfsine matched + timing + Spread decode and tx = Spread encode + Shape(4, halfsine) + Stagger("q"). The carrier comes before Stagger("i"): a phase offset mixes I into Q while Q is half a symbol late.

  • A step that loads a definition names its kind and reference as the loaders take them: {"code": "conv", "name": "k7_171_133/3_4"}, {"code": "interleave", "name": "forney/12_17"}, {"symbol": "constellation", "name": "psk/qpsk"}.
  • Sync steps name what is estimated (carrier, timing, equalize, frame) and get the first-class method; another is chosen in defaults: {"timing": {"method": "oerder_meyr", "min_symbols": 256, "gate": 0}}.
  • Your own operator is a step by module path, in the category it does: {"signal": "class", "class": "mypkg.Gain", "args": {...}}. A signal or sync class is a Stage run on receive only; a wave class a Stage on receive and "tx_class" the one on transmit; a symbol, code or link class a Pipe, decoding on receive and encoding on transmit. A class whose CATEGORY is another category's is refused.
  • Variants of one signal (QPSK or 16QAM, RRC 0.2 or 0.35, a step only some modes have) are params with "choices" and steps with "when": Definitions.
  • "controls" lets a header's fields drive other steps (DVB-S2's MODCOD, 802.11b's rate): see rpps.profile.control.
  • Bursts, preambles, branches, resource grids and the parallel region are each a step or a key: rpps.profile lists them and where each is documented.

A new signal should need no new operator code. examples/own_definitions.py (Definitions) writes one from scratch in a directory of your own.

A unique word before each frame

A word the modem sends ahead of each block of coded bits (a sync marker, a unique word) is a sequence of type word, of any width: 100 bytes are 200 hex digits.

{"type": "word", "word": "0x1acffc1d...", "bits": 800, "order": "msb"}

There are two places to find it, both after demodulation and before the FEC:

  • Among bits: {"sync": "delimit", "sequence": "<word>", "length": <bits after it>, "keep": true, "polarity": true, "errors": 40} after the symbol mapping, then {"code": "marker", "sequence": "<word>", "length": ...} to strip it. errors is how many of the word's bits may be wrong ({"param": ...} works too), and polarity matches the inverted word too. Use this when the carrier leaves no ambiguity, or only an inversion (BPSK).
  • Among symbols: {"sync": "frame", "sequence": "<word>", "threshold": 0.3} before the symbol mapping. The profile maps the word to symbols through its own steps, and the match measures the word's phase, so a QPSK or 8PSK carrier left a quarter turn off is put right by the word. Its tolerance is the normalised correlation threshold: random data correlates about 1/sqrt(symbols), 0.05 for a 400-symbol word.

How many errors to allow: as many as the word's own bit errors need, but no more than random bits could match. rp.sync.word_errors gives the second bound: the most errors a match may have while random bits stay under a false-alarm rate over the places searched. A long word can tolerate a lot:

import rpps as rp
assert rp.sync.word_errors(800, 1e-9) == 314                  # 100 bytes: 314 wrong bits still can't be chance
assert rp.sync.word_errors(32, 1e-3, positions=8160) == 1     # a 32-bit ASM searched over a CCSDS frame

For an unknown signal, rp.analysis.framing.payload.fixed_word(bits) finds such a word blind among demodulated bits (bit errors and all). It gives the word, its period, and the bits each frame's copy differs by, with an errors to start from. rp.analysis.framing.frames.find(symbols) does the same among symbols.

A preamble that says what follows

A frame sync can look for several words at once and say which it found. Each alternative is named, and the one that matched is published with the frame as word, with its own fields, so controls drive the steps after it from a table, the same way a header's fields do:

  • "sequences": {"bs_voice": "dmr_bs_voice", ...}: words given as bits, mapped to symbols by the profile's own steps (DMR's eight sync patterns: voice or data, base station or mobile).
  • "zc": {"roots": [25, 29, 34], "length": 63, "shifts": [0]}: a set of Zadoff-Chu sequences, published with root and shift. One complex sequence alone is a definition of type zc named by "sequence".
  • "before": 54, "length": 132: the frame starts that many symbols ahead of its word (a sync word in the middle of a burst) and is that long; length can be driven by a control too.
  • Real levels (an FM discriminator's) stay real, and the match's phase is a polarity. "scale": true puts the levels back where the word's are; "polarity": false matches in phase only, for a discriminator whose sense is known, and is needed when alternatives are each other inverted (DMR's voice and data patterns).
  • Every frame also publishes what its preamble measured: scale, phase, cfo (cycles a symbol, from the phase between the word's halves), esn0 (the frame's symbols over the noise left after the word). "cfo": true takes that frequency off the frame; "segments": 4 correlates the word in parts so a carrier that turns across a long word doesn't hide it. Offsets past about 1/L cycles a symbol are for a carrier step before.
  • "classify": ["psk/qpsk", "psk/8psk"]: when the word does not say the modulation, each frame's symbols are scored against the candidates and the best published as modulation.

On transmit, {"symbol": "marker", "zc": {"length": 63, "root": 25}} puts known symbols before each frame (its root, shift or sequence set per frame by a control), and strips them on receive. {"symbol": "puncture", "every": 36, "at": [35]} drops a symbol at those places of every period (P25's status symbols) and puts value there on transmit.

"""A preamble that says what follows: Zadoff-Chu roots pick each frame's modulation and code

    python examples/zc_modes.py

The transmitter starts every frame with a Zadoff-Chu sequence of length 63 whose root names the frame's mode, from a
table: root 25 QPSK with Hamming (7,4), root 29 8PSK with Hamming (7,4), root 34 16APSK uncoded. The receiver's frame
sync correlates all three roots, and the one it finds is published with the frame (`word`, `root`, `shift`, and what
the preamble measured: `cfo`, `esn0`, `scale`), so `controls` drive the constellation and the code from the same table,
frame by frame. The `symbol marker` step puts the root's symbols before each frame on transmit and strips them on
receive. All of it is definitions: a table, a profile.
"""
import json
import pathlib
import tempfile

import numpy as np

import rpps as rp

N, SYMBOLS = 63, 420 # Preamble length; symbols of a frame after it (a whole number of Hamming words in every mode)
MODES = [[25, "psk/qpsk", None, "hamming/7_4", SYMBOLS*2*4//7],
         [29, "psk/8psk", None, "hamming/7_4", SYMBOLS*3*4//7],
         [34, "apsk/dvbs2_16apsk", {"rate": "3/4"}, None, SYMBOLS*4]]

DEFINITIONS = {
    "table/demo/zc_modes": {
        "comment": "Zadoff-Chu root -> the frame's constellation, code and data bits",
        "key": "root", "columns": ["root", "constellation", "params", "code", "bits"], "rows": MODES},
    "profile/demo/zc_modes": {
        "comment": "Demo: frames of 420 symbols, each after a 63-symbol Zadoff-Chu preamble whose root says its "
                   "modulation and code (table demo/zc_modes). The input is symbols, one a sample",
        "steps": [
            {"sync": "frame", "id": "fs", "zc": {"roots": [25, 29, 34], "length": N}, "length": N + SYMBOLS,
             "segments": 2, "cfo": True, "threshold": 0.5},
            {"symbol": "marker", "id": "pre", "zc": {"length": N, "root": 25}},
            {"symbol": "constellation", "id": "map", "name": "psk/qpsk"},
            {"code": "block", "id": "fec", "name": "hamming/7_4"}],
        "controls": {
            "fs": {"table": "demo/zc_modes", "key": "root",
                   "drive": {"pre": {"frame": "frame"}, "map": {"name": "constellation", "params": "params"}, "fec": {"name": "code"}}},
            "pre": {"on": "tx", "table": "demo/zc_modes", "key": "root", "frame": "bits",
                    "schedule": [{"root": 25}, {"root": 29}, {"root": 34}],
                    "drive": {"pre": {"root": "root"}, "map": {"name": "constellation", "params": "params"}, "fec": {"name": "code"}}}}},
}

def main():
    d = pathlib.Path(tempfile.mkdtemp())
    for ref, obj in DEFINITIONS.items():
        f = d/f"{ref}.json"
        f.parent.mkdir(parents=True, exist_ok=True)
        f.write_text(json.dumps(obj, indent=1))
    rp.add_config_path(d)

    p = rp.profile.load("demo/zc_modes")
    rng = np.random.default_rng(0)
    per = [m[4] for m in MODES]*3 # nine frames: the schedule three times over
    data = rng.integers(0, 2, sum(per)).astype(bool)
    sym = np.asarray(p.tx()(rp.Data(data, sps=1, flush=True)).data)
    assert len(sym) == 9*(N + SYMBOLS)

    # The channel: a carrier offset and phase, noise at 26 dB Es/N0 (the 16APSK frames are uncoded), some noise before the first frame
    n = np.arange(len(sym))
    y = sym*np.exp(2j*np.pi*0.001*n + 1.1j)
    y = np.concatenate(((rng.normal(size=300) + 1j*rng.normal(size=300))*0.05, y))
    y = (y + (rng.normal(size=len(y)) + 1j*rng.normal(size=len(y)))*np.sqrt(10**(-26/10)/2)).astype(np.complex64)

    rx = p.rx()
    out, stream = [], None
    for blk in rp.source.Memory(y, Fs=1.0, sps=1)(1000):
        r = blk + rx
        stream = r.meta.stream
        out.append(np.asarray(r.bits()) if len(r) else np.zeros(0, bool))
    found = [f for _, f, _ in stream.control.fields("fs")]
    got = np.concatenate(out)[:len(data)]
    roots = [f["root"] for f in found]
    print(f"{len(found)} frames, roots {roots}, cfo {np.median([f['cfo'] for f in found]):.4f} cycles a symbol (0.001 sent), "
          f"Es/N0 {np.median([f['esn0'] for f in found]):.1f} dB (26 sent); {np.count_nonzero(got != data)} bit errors")
    assert roots == [25, 29, 34]*3
    assert np.array_equal(got, data)

if __name__ == "__main__":
    main()

One frame can hold several codes: a branch step can give each branch only its take (item ranges of every frame, joined) and only the frames its select expression accepts, over the fields a trunk step published for that frame. Frames are a fixed frame length, or start where a trunk control drives the branch step's frame (a frame sync's {"tsdu": {"frame": "frame"}}) and run to the next. A range's end can be null (to the frame's end), and {"ranges": [[64, null]], "unit": 196} keeps whole groups only: profile/p25/tsdu reads one to three TSBKs a frame that way. profile/dmr/burst reads every burst's slot type (Golay (20,8), split around the sync word) and only the data bursts' BPTC payload:

{"branch": "burst", "frame": 264,
 "take": {"slot": [[98, 108], [156, 166]], "data": [[0, 98], [166, 264]]},
 "select": {"data": {"step": "fs", "when": "word == 'bs_data' or word == 'ms_data'"}},
 "branches": {"slot": [...], "data": [...]}}

Burst time plans

A TDMA or MF-TDMA network's terminals send bursts in timeslots of a repeating plan: superframes of frames, each frame a grid of carriers and timeslots, each slot a burst type, and which terminal has which slot. A burst step that knows the carriers cuts each burst on its own carrier, and with a plan names its place:

  • {"sync": "burst", "carriers": [{"freq", "width", "rate"}, ...], "sps": 4}: bursts on many carriers of one wideband capture, each carrier brought to baseband at sps samples a symbol (rp.sync.Bursts). Each burst's fields (carrier, freq, start) reach the steps after it; its type comes from its unique word (a frame sync with sequences), its length and code from a table keyed on the word.
  • "plan": "<name>" (or control(plan=...)): each burst is placed in the plan (superframe, frame, slot, tx_type, assignment), and its decoded messages carry those under fields["burst"]. The plan's time in the capture (its origin) is given, or found: the bursts vote for it, and their unique words keep it there (the clock is tracked). "gate": "plan" cuts every slot the plan gives, whether its energy shows or not.
  • Transmitting, the plan places each burst: tx(data, fields={"superframe", "frame", "slot"}).

A plan (rpps.plan) comes from where the network keeps it:

  • Over the air. DVB-RCS2's hub broadcasts it in its forward link: SCT, FCT2, BCT and TBTP2 tables in GSE packets, and the network clock (NCR). profile/dvbrcs2/forward reads them and rp.plan.builder("dvbrcs2/forward") makes the plan and the clock of its messages. The builder is a definition too (config/plan/builder/dvbrcs2/forward.json): which tables, how their fields map onto the plan model both ways, and how the clock references pair with frame starts.
  • A definition, config/plan/<family>/<name>.json, in the same model: a standard's fixed structure, a test. A sequence's hop moves its frames from channel to channel (an expression, or an algorithm by name: ble_csa1); a frame's repeat and every make a train of bursts.
  • Learned from the bursts, when the forward link is not heard: rp.analysis.burst.learn_plan(bursts) finds the BTU, the frame and the slots, and saves a definition (.save(name)).

Whether a plan, from anywhere, explains the bursts: rp.analysis.burst.check_plan(plan, bursts) fits its origin and clock to them and puts each in a slot of its carrier (in a slot of its kind, another kind's, overrunning it, or in none), and rp.viz.bursts(None, check, fold=True) draws a raster of superframes, one a row: a right plan keeps the bursts inside its slots' columns, a wrong frame slants them, a wrong BTU puts them across the columns' edges. rp.viz.burst_timing draws each burst's start error against time, and rp.viz.plan_evidence what learn_plan chose its BTU and frame on (or, from the NoPlan it raises, why every period was passed over).

"""An MF-TDMA network whose burst time plan comes over the air (DVB-RCS2's way), and the same bursts without it

    python examples/mftdma.py

The hub's forward link (DVB-S2) carries the plan as tables in GSE packets (SCT: superframes and their frames, FCT2: each
frame's carriers and timeslots, BCT: each burst type, TBTP2: which terminal has which slot) and the network clock (NCR
packets, each the time of an earlier PL frame's start). The terminals' bursts (profile/demo/mftdma: three carriers, two
symbol rates, three burst types each with its unique word, LDPC units, CRC) go where the plan says.

The receiver reads the forward link (profile/dvbrcs2/forward), builds the plan and the clock from its messages
(rp.plan.builder("dvbrcs2/forward"), a definition), and gives both to the return link's burst step: every burst is cut on its carrier, decoded,
and named by its superframe, frame, timeslot, burst type and terminal. The return path's delay is not told: the bursts'
own unique words pull the clock onto it. Without the forward link, a plan learned from the bursts themselves
(rp.analysis.burst.learn_plan) places them as well, under its own names, and check_plan says how well it
explains them.
"""
import numpy as np

import rpps as rp
from rpps.link import gse

N0, DELAY = 10**9, 1e-4 # The NCR when both captures start; the return path's delay, unknown to the receiver [s]

def network(rng, superframes=3, per=5, frames=6):
    """(forward link samples at 4 MS/s, return link samples at 8 MS/s, what was sent)"""
    plan = rp.plan.load("demo/mftdma")
    s = plan.sequences[0]
    s.start, s.count = N0 + 27000, 100
    sent = []
    for k in range(superframes): # A few bursts each superframe, each slot assigned to its terminal in that superframe's TBTP2
        ws = plan.windows(s.start + k*s.duration, s.start + (k + 1)*s.duration)
        slots = {}
        for i in sorted(rng.choice(len(ws), per, replace=False)):
            w, term = ws[i], int(rng.integers(1, 250))
            sent.append((w, {"superframe": w.superframe, "frame": w.frame, "slot": w.slot, "terminal": term, "seq": len(sent)},
                         rng.integers(0, 2, plan.tx_types[w.tx_type].fields["bits"] - 32).astype(bool)))
            slots.setdefault(w.frame, {})[w.slot] = term
        for fr, sl in slots.items():
            lo, hi = min(sl), max(sl)
            plan.assign(0, ws[0].superframe, fr, [(sl.get(j, 0), 0) for j in range(lo, hi + 1)], offset=lo)
    # The forward link: the tables in every frame, frame k's NCR packet the NCR of frame k-2's start
    dfl = rp.profile.table("dvbs2/modcod").row({"modcod": 4, "short": 0, "pilots": 1})["kbch"] - 80
    hub = rp.plan.builder("dvbrcs2/forward") # (its definition both ways: the tables and NCR packets sent)
    tables = hub.tables(plan, network_id=7, superframes=[(0, s.count + k) for k in range(superframes)])
    fwd = rp.profile.load("dvbs2/normal")
    def send(sof):
        fields = []
        for k in range(frames):
            pdus = ([hub.reference(N0 + 27e6*sof[k - 2]/4e6)] if k >= 2 else []) + tables
            fields.append(np.unpackbits(np.frombuffer(gse.pack(pdus, dfl//8)[0], np.uint8)).astype(bool))
        return fwd.tx()(rp.Data(np.concatenate(fields), Fs=1e6, sps=1, flush=True), fields=[{"modcod": 4, "pilots": 1}]*frames)
    o = send([0]*frames)
    sof = [o.meta.delay*4e6 + k*(90 + 360*90 + 22*36)*4 for k in range(frames)] # (QPSK, pilots: a frame's samples)
    xf = np.asarray(send(sof).data)
    xf = (xf*np.exp(0.7j) + 0.05*(rng.normal(size=len(xf)) + 1j*rng.normal(size=len(xf)))).astype(np.complex64)
    # The return link: each terminal's burst on its slot, the path's delay late
    tx = rp.profile.load("demo/mftdma").tx()
    tx.burst_tx.plan, tx.burst_tx.origin = plan, N0 - DELAY*27e6
    sent.sort(key=lambda t: t[0].burst)
    xr = np.concatenate([np.asarray(tx(rp.Data(p, sps=1), fields=f).data) for _, f, p in sent] + [np.asarray(tx.flush().data)])
    xr = np.concatenate((xr, np.zeros(4000)))
    xr = (xr + 0.02*(rng.normal(size=len(xr)) + 1j*rng.normal(size=len(xr)))).astype(np.complex64)
    return xf, xr, sent

def decode(xr, plan=None, origin=None, **params):
    rx = rp.profile.load("demo/mftdma", **params).rx()
    if plan is not None:
        rx.burst.control(plan=plan, origin=origin)
    got = {}
    for blk in rp.source.Memory(xr, Fs=8e6)(1 << 15):
        blk + rx
        for m in rx.take_messages():
            if m.kind == "hdr" and m.crc_ok:
                got[(m.fields["terminal"], m.fields["seq"])] = m.fields["burst"]
    return got

def main():
    rng = np.random.default_rng(1)
    xf, xr, sent = network(rng)

    fwd, b = rp.profile.load("dvbrcs2/forward").rx(), rp.plan.builder("dvbrcs2/forward")
    for blk in rp.source.Memory(xf, Fs=4e6, sps=4)(1 << 16):
        blk + fwd
        for m in fwd.take_messages():
            b.feed(m)
    print(f"forward link: {b.plan}; NCR at t=0 {b.clock(0) - N0:+.0f} ticks from the hub's (its filters' delay)")

    got = decode(xr, b.plan, b.clock(0))
    for w, f, _ in sent:
        g = got[(f["terminal"], f["seq"])]
        assert (g["superframe"], g["frame"], g["slot"], g["tx_type"], g["assignment"]) == (w.superframe, w.frame, w.slot, w.tx_type, f["terminal"])
    print(f"return link, plan from the air: {len(got)} of {len(sent)} bursts, each in its slot, named by its terminal")

    C = [{"freq": -2e6, "width": 337.5e3, "rate": 250e3}, {"freq": -1.5e6, "width": 337.5e3, "rate": 250e3},
         {"freq": 1.5e6, "width": 675e3, "rate": 500e3}]
    bursts = rp.Data(xr, Fs=8e6, flush=True) + rp.sync.Bursts(carriers=C, sps=4, factor=4, win=16, min_s=0.5e-3)
    learned = rp.analysis.burst.learn_plan(bursts, carriers=C)
    got = decode(xr, learned.plan)
    assert len(got) == len(sent)
    print(f"return link, plan learned from its own bursts: {learned}; {len(got)} of {len(sent)} bursts")

    # Whether a plan explains the bursts: each in a slot of its kind, the plan's origin and clock fitted to them
    # (rp.viz.bursts(None, check, fold=True) draws it: the bursts stacked on the superframe's slots)
    check = rp.analysis.burst.check_plan(learned.plan, bursts)
    assert check.explained == 1.0
    print(f"the learned plan against the bursts: {check}")

if __name__ == "__main__":
    main()

Decoded messages, and only some of them

Every frame a profile receives is also a record, rp.profile.Message: its kind, the fields it decoded, its payload, crc_ok, and where it starts in the stream (sample, time, freq). What a payload says goes in fields["payload"] when its header or frame definition has "payload_fields" (AX.25 addresses, BLE AD structures), and a step's "message" fields are a schema too (DVB-S's TS adaptation field and PCR): see Definitions.

# docs: skip
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 "")

profile.kinds() lists what a profile gives; profile.rx(kinds={"pbch"}) (also Decoder(..., kinds=), rpps rx --kinds pbch,pcfich) hands out only those and builds only the steps they need.

What a profile needs

"requires" says, as expressions over the params and baud, what a profile needs: baud, Fs, bw, min_samples, input ("audio" for an FM channel's audio), from_cf (params the carrier gives). rp.profile.info(name, baud=...) and rp.profile.catalogue() evaluate them, for a program building a menu. rp.profile.Decoder uses them to bring a selected signal to the profile: shift and decimation, an FM demodulator for audio, a resampler to Fs, a rate measured when the standard leaves it open.

They also narrow a blind search. rp.profile.fits(name, baud=..., bw=..., Fs=..., seconds=..., input=...) says why a signal measured so can't be a profile, and rp.profile.candidates(...) lists the variants that may be. A profile whose rate is set elsewhere, whose channel is narrower than the signal, or which takes audio, is never built:

import rpps as rp
print(rp.profile.fits("ble/adv", baud=250e3))                     # its rate is 1e+06, not 250000
print(sorted({n for n, _ in rp.profile.candidates(baud=27.5e6)})) # the open-rate profiles: CCSDS, DVB-S, DVB-S2

More than one core

A profile marks where its frame-parallel region starts; p.rx(parallel=rp.parallel.Parallel(kind, workers=n)) runs it in batches (rpps.parallel).

"""Use more than one core: a profile's frame-parallel region

    python examples/parallel_rx.py [frames] [workers]

Once frame sync has found a frame and its header has set the parameters, the rest of the work on that frame (demap,
deinterleave, LDPC, BCH, descramble) has no state shared with the next one. A profile marks where that region starts,
and `p.rx(parallel=rp.parallel.Parallel(kind, workers=n))` runs it on frames in batches: "inline" (one thread, batched),
"thread" (the C++ kernels release the GIL) or "process". Everything before the region runs as usual. The output is
the serial runner's, bit for bit, for any block cut, worker count and batch size.

Here: DVB-S2 normal frames (QPSK 1/2 and 8PSK 3/4 alternating, pilots on, each frame's own MODCOD from its header),
received serially and in parallel. Each runner is run once to warm up the shared tables and the second run is timed,
as tools/parallel_bench.py does in more detail. The `__main__` guard is needed: process workers import this file.
"""
import sys
import time

import numpy as np

import rpps as rp

def main(frames=8, workers=4):
    # Timing known: the transmitter's. The carrier and frame sync still run (rpps.parallel)
    p = rp.profile.load("dvbs2/normal", sync={"timing": {"method": "known"}})
    table = rp.profile.table("dvbs2/modcod")
    fields = [{"modcod": (4, 12)[i % 2], "pilots": 1} for i in range(frames)] # one header per frame
    sizes = [table.row({**f, "short": 0})["kbch"] - 80 for f in fields] # data bits each frame carries
    data = np.random.default_rng(1).integers(0, 2, sum(sizes)).astype(bool)
    wave = p.tx()(rp.Data(data, Fs=1e6, sps=1, flush=True), fields=fields)
    x = (np.concatenate((wave.data, np.zeros(200, np.complex64)))*np.exp(0.7j)).astype(np.complex64) # a phase offset

    def receive(rx):
        t = time.perf_counter()
        out = rx(rp.Data(x, Fs=wave.Fs, sps=wave.sps, delay=wave.delay, flush=True))
        return np.asarray(out.data).astype(bool), time.perf_counter() - t

    def timed(make):
        receive(make()) # warm up
        rx = make()
        try:
            got, dt = receive(rx)
        finally:
            if hasattr(rx, "close"): # a parallel runner owns its workers
                rx.close()
        assert np.array_equal(got, data), "the output differs from what was sent"
        return dt

    print(f"{frames} DVB-S2 normal frames, {len(data)} data bits, native kernels: {rp._accel.available()}")
    base = timed(p.rx)
    print(f"  serial        {base:6.2f} s")
    for kind in ("thread", "process"):
        dt = timed(lambda: p.rx(parallel=rp.parallel.Parallel(kind, workers=workers)))
        print(f"  {kind:7s} x{workers}    {dt:6.2f} s  ({base/dt:.1f}x)")

if __name__ == "__main__":
    main(*(int(a) for a in sys.argv[1:3]))