# AGENTS.md Read this first: it says where everything is. RPPS (RF Parameter Processor Suite) is a Python library (numpy, optional C++ kernels) that generates and processes radio signals: filters, sync, modulation, FEC, framing, and whole standards (DVB-S/S2, 802.11b, 802.15.4, BLE, ADS-B, CCSDS, LTE and 5G NR to SIB1) as JSON profiles, plus blind analysis of unknown signals. It stays **signal agnostic**: a new signal should be new definitions plus existing operators. ## Commands ``` python tools/builder.py -s # pip install -e ".[dev]" python tools/builder.py -c # build the C++ kernels in place (rpps._native) python -m pytest -n auto -m "not slow" # what CI runs RPPS_NO_NATIVE=1 python -m pytest -n auto -m "not slow and not kernels" # the Python loops python tools/builder.py -d # docs: API pages + llms files (tools/gen_docs.py), then zensical build --strict python -m rpps ls [resource] # shipped definitions; also: show, steps, rx, tx, survey, profile, solve, fmt ``` A stale `rpps._native` warns at import: rebuild (`-c`) after touching `csrc/`. ## The model in one screen ``` samples -> symbols -> channel bits -> data bits -> packets signal (conditioning: samples -> samples) sync (estimate + correct, at any representation; never in the data) wave (samples <-> symbols) | symbol (symbols <-> channel bits, LLRs on receive) | code (channel <-> data bits) | link (data bits <-> packets) ``` - Operators: `data * pipe` encodes, `data / pipe` decodes (`Pipe`: symbol, code, link); `data + stage` processes (`Stage`: signal, sync, wave); `pipe * pipe` / `stage + stage` make a `Pipeline`; `data >> sink` writes. - `rp.Data` wraps an array with `Meta` (`Fs`, `sps`, `cf`, absolute position `meta.pos`, the stream). A `Stage` keeps per-stream state in `new_state(meta)`, held by `stream`; a `Pipe` keeps leftovers in `ctx`. Output must not depend on how the input is cut into blocks (any length, including 0). - Form vs representation: `dtype` (SAMPLES, REAL, SYMBOLS, LLR, BITS, BYTES, MSG) and `Rep` (SAMPLES, SYMBOLS, CHANNEL, DATA, PACKETS). Operators check `takes()`; a link refuses channel bits (`rp.code.Uncoded()` between them). - LLRs are log(P0/P1) (positive = 0). Bits are MSB first. `bool` arrays are bits, `uint8`/`bytes` are bytes. - **Where a function goes is decided by what it takes and gives**, not what a standard calls it: estimating an unknown is sync; inserting/removing known structure belongs to the transform where it lives; finding where it starts is sync. - Sync: block estimation over windows at absolute positions, tracked across windows (`sync.track`), is first class; per-sample loops (Costas, M&M, LMS) are second class. - A profile (`config/profile//.json`) lists a signal's steps in receive order; `p.rx()` runs them, `p.tx()` runs the transforms inverted in reverse. Headers drive later steps through `controls` (positions, not time). Full design: the `rpps.base` docstring (model, rule, categories, contracts, grey areas, type tags, streaming rules). ## Where things are | Path | What | |---|---| | `src/rpps//` | one package per category: source, signal, sync, wave, symbol, code, link, grid, profile, parallel, sequence, plan, analysis, base, math, utils, viz | | `src/rpps//__init__.py` | **the package's documentation** (its docstring), rendered in the API reference | | `config//` | JSON definitions: constellation, pulse, filter, sequence, scramble, fec, interleave, crc, frame, header, linktype, table, plan, profile; `tags.json` | | `csrc/rpps_native/` | C++17 kernels (pybind11); the Python loop in the calling stage is the reference | | `docs/` | the site: guides (`docs/guide/`), examples index, contributing, roadmap; `docs/api/` and `docs/llms*.txt` are generated | | `tools/` | `builder.py` (setup, kernels, tests, docs, release), `gen_docs.py` (API pages, llms files), benchmarks (`*_bench.py`, `tpc_ber.py`) | | `examples/` | one self-checking script per recommended usage; the guides embed them and the tests run them | | `tests/unit/` | a folder per package, plus `standards/`, `policy/`, `native/`; helpers in `tests/support/` | | `projects/` | worked receivers on real signals, each with a README | | `private/` | untracked captures and tooling: **never commit or quote it** | Imports run down the chain: nothing in the data path imports `analysis`, `profile` or `parallel` (`test_layering.py`). Nothing under `src/` may import scipy (`test_numpy_only.py`). ## Where to read more | Question | Read | |---|---| | What package X holds, and its rules | `src/rpps/X/__init__.py` docstring (`help(rpps.X)`) | | Sync methods, feedforward rules | `rpps.sync` | | Profile features (bursts, branches, grids, messages, kinds, requires) | `rpps.profile`; header-driven control: `rpps.profile.control` | | Step kinds a profile can name | `rpps.profile.steps`, `python -m rpps steps` | | Definition format, names, `extends`, tags | `docs/guide/definitions.md` | | Which blind tool answers which question | `rpps.analysis` | | Parallel region, batch kernels | `rpps.parallel` | | Effort levels and measured gains | `rpps._effort` | | How to use it for a task | `docs/guide/*.md` | | Setup, test markers, kernel pitfalls, CI, releases | `docs/contributing.md` | | Everything at once | `docs/llms-full.txt` (after `python tools/gen_docs.py`) | ## Conventions - **Operators first:** keep features inside `*`, `/`, `+`, `>>` rather than adding setup calls. - **No aliases:** a rename or move drops the old name and fixes the callers; one name per definition. The one exception is the stable API (`docs/guide/integrating.md`): its old name stays one release, warning, then goes. - **Be explicit:** fix a caller rather than loosen a contract check. - **Python first, then C++:** write the stage in Python with a block-cut test; move hot loops to `csrc/` behind `rpps._accel.native`, keeping the Python loop as the reference the tests compare against. A primitive's kernel goes behind a `rpps.math`/`rpps.signal` wrapper that stages share; one stage's loop stays in that stage until a second caller. - **Decoders return status, never keep it** (`decode(x, status=True)`), so one loaded code serves many threads. - **Read the standard** when a decode does not work, instead of guessing. - **Statistical tests** assert with a margin measured over many seeds. - **Docs live with what they describe:** concepts in the package/module docstring, usage in a guide that embeds an example script. Python blocks in README.md and `docs/` run in the tests (mark untestable ones `# docs: skip`). User-facing changes go in CHANGELOG.md under Unreleased; renames and removals under **Breaking**. - Branch from `dev`; `main` is released. # Package docstrings and public API One section per module: the package's docstring in full, then `name(args): summary` per public class and function. Module docstrings other than packages' are summarized to their first line. ## rpps RPPS: RF Parameter Processor Suite, a generic signal processor/generator library Everything is driven by operators: `*` encodes / modulates / scrambles, `/` undoes it, `+` runs a DSP stage, `>>` writes to a sink. The data carries its sample rate and the state of every stage from block to block. The design (the model, categories, contracts, streaming rules) is in `rpps.base`; how to use it is in the guides of the documentation site (https://anonoei.github.io/RPPS/). ### Where things are Packages follow the categories of `rpps.base`; data goes samples -> symbols -> channel bits -> data bits -> packets. | Package | What is in it | |---|---| | `rpps.source` | files and their formats, WAV, SigMF, sockets, radios through pysdrlib (imported only when used); sinks | | `rpps.signal` | `filters` (FIR, IIR, windows, pulses, fractional delay, polyphase channelizer), `sample` (resampling), `channelize`, `DCBlock`, `Deemphasis`, `Conjugate`, `channel` (the simulated medium); `loops` (the per-sample DCBlock, Deemphasis) | | `rpps.sync` | first class: `time.OerderMeyr`, `phase.MPower`, `phase.DDCarrier`, `equalize.BlockLS`, `CPSync`, tracked by `track`; `FrameSync`, `Delimiter`, `PilotPhase`, `PilotEqualizer`, `Align`, `Puncture`, `Acquire`, `Lock`, `AcquireFEC`, `acquire_code`, `Squelch`, `AGC`, `PeakAGC`, `Burst`, `BurstTx`, `Bursts` (many carriers, a burst time plan), `PlanTx`, `Preamble`, `ToneLock`. Second class: `loops` (`MM` (Gardner), `TLL`, `Costas`, `AGC`, `PeakAGC`, `Squelch`, `pll`, `LMS`, `CMA`) | | `rpps.wave` | `Shape`/`Matched`, `Stagger`, `FM`/`FMDemod`, `OFDMTx`/`OFDMRx`, `AMDemod`, `SSBDemod`, `demod`; `loops` (the per-sample AMDemod) | | `rpps.symbol` | `Constellation` (PSK, QAM, APSK, ASK), `Differential`, `Spread`/`Despread`, `Carriers`, `Header`, `Pilots`, `PhaseScramble` | | `rpps.code` | FEC, interleaving, rate matching (`code.types`), scramblers (`code.scram`), `Line`, `Marker`, `Uncoded` | | `rpps.link` | CRCs, HDLC, `Header` (fields, CRC, payload length) | | `rpps.grid` | resource grids of OFDM systems: LTE and 5G NR cell search, grids, physical channels | | `rpps.profile` | a whole signal from one config file, both directions: loading, steps, header-driven control, runners | | `rpps.parallel` | a profile's frame-parallel region: executors, scheduler, batch kernels | | `rpps.sequence` | recurrences, Gold sequences, chip codes, words: what scramblers, spreaders and searches share | | `rpps.plan` | burst time plans (TDMA, MF-TDMA, hopping, trains): superframes, frames, timeslots, burst types, assignments; from a definition, a forward link's tables (DVB-RCS2) or the bursts themselves | | `rpps.analysis` | outside the data path: spectra, rates, surveys, blind analysis of modulation and FEC; can write definitions | | `rpps.base` | `Data`, `Pipe`, `Stage`, `BitStage`, `Pipeline`, `Stream`, `Tee`, type tags, control, kernels | | `rpps.math`, `rpps.utils`, `rpps.viz` | finite fields and GF(2) algebra; helpers; plots (`pip install rpps[viz]`) | Imports run down this list: nothing in the data path imports `analysis`, `profile` or `parallel` (`tests/unit/policy/test_layering.py`; the one exception is `AcquireFEC`, which imports `analysis.identify` inside the call). `import rpps` loads numpy and RPPS only: no scipy, matplotlib or pysdrlib until something asks for them. Constellations, pulses, filters, sequences, scramblers, codes, headers, tables and profiles are definitions that ship with the package (`python -m rpps ls` lists them; `rp.load("/")` loads any); add your own with `rpps.add_config_path`. How hard decoders and timing work is `rpps.set_effort` (levels and measured gains in `rpps._effort`). The per-sample loops and decoders run in C++ (`rpps._native`) with a Python fallback. ## rpps._effort How hard the receiver works: speed against recovered SNR rp.set_effort("max") # from now on with rp.effort("fast"): # for a block of code out = rx(block) RPPS_EFFORT=max python ... # for a process Levels (looked up when a stage or decoder runs, so a level can change mid-stream): fast the cheapest work that still decodes at good SNR: max-log demapping, half the decoder iterations, half the polar list, one Chase bit less, cubic timing interpolation balanced the default: what each definition says (its iterations, list, Chase bits, demapper, min-sum), timing interpolation that keeps the interpolation error under the pulse's own truncation at 3 samples per symbol and more max the most SNR at more cost: decoders iterate further (up to 4x; each codeword still stops when it converges, so the cost is mostly near the threshold), LDPC by sum-product, 4x the polar list, one Chase bit more, log-MAP turbo decoding, a timing interpolator at the pulse's own floor at 2 samples per symbol A definition's settings stay the base: a level scales them (an LDPC definition with 50 iterations runs 50 balanced, 200 max), and a value set on an operator is that operator's base. `rpps rx --effort` sets it from the shell. | Setting | fast | max | |---|---|---| | LDPC / turbo / TPC iterations (`iters`) | x0.5 | x4, stopping early | | LDPC check update (`check`) | min-sum | sum-product | | Polar list (`list`) | x0.5 | x4 (successive cancellation lists 4) | | TPC Chase-II bits (`chase`) | -1 | +1 | | Max-log or exact (`maxlog`: demapper, BCJR, turbo) | max-log | exact, no extrinsic scaling | | Timing interpolation (`interp_taps`) | cubic | 12-tap windowed sinc (balanced: 8 taps below 4 sps, 12 below 2) | | Blind RS scan by decodes (`rs_decode_scan`) | off: zero syndromes only | on (as balanced): seconds a stream with no RS | | Blind profile retries (`retries`: another constellation, 2x, 1/2 the rate) | none (balanced 2) | 4 | Measured (`tools/effort_bench.py`, FER 1e-1, one thread; Mbit/s at the threshold, where max iterates most): | Chain | Es/N0 dB fast / balanced / max | Mbit/s fast / balanced / max | |---|---|---| | LDPC DVB-S2 64800 1/2, QPSK | 1.08 / 0.94 / 0.75 | 2.2 / 1.2 / 0.96 | | LDPC DVB-S2 16200 3/5, 8PSK | 6.16 / 6.09 / 5.62 | 7.7 / 2.7 / 0.79 | | Turbo LTE K=6144, QPSK | -0.84 / -1.31 / -1.62 | 1.6 / 0.85 / 0.10 | | Turbo LTE K=40, QPSK | -0.34 / -0.41 / -0.49 | 0.47 / 0.24 / 0.073 | | Polar NR DCI (K 63, E 432), QPSK | -4.97 / -5.25 / -5.67 | 0.22 / 0.12 / 0.032 | | Polar NR PBCH, QPSK | -8.50 / -8.85 / -9.32 | 0.19 / 0.097 / 0.029 | | Polar (256,128) + CRC-16, QPSK | 1.29 / 1.13 / 0.90 | 0.92 / 0.38 / 0.098 | | TPC (64,57)^2, BPSK | 2.81 / 2.16 / 1.69 | 0.36 / 0.13 / 0.032 | | Conv K7 1/2 (Viterbi), QPSK | 3.61 / 3.61 / 3.61 | 7.9 / 5.6 / 5.6 | Timing at 2 sps: EVM floor -28.0 / -48.5 / -55.4 dB (pulse truncation -56) at the same speed. Other decoding behaviour worth knowing: - LDPC is layered (checks coloured once per code), about half the iterations of flooding: normalized min-sum, or sum-product at max (phi tabulated, 1.7x min-sum's time an iteration, fewer iterations). - Soft values go as far as something uses them: additive descrambling flips LLR signs, Forney deinterleaving moves LLRs, BCJR hands on a-posteriori LLRs (RS uses them for erasures, keeping two checks spare), differential decoding is the product detector `y conj(y[n-1])`. - A decoder returns its status, it never keeps it (`decode(x, status=True)`). A code step puts the errors on its output (`data.errors`, not carried further) and sets `data.failed` from them (the last code with a verdict decides); later steps carry `failed`, and a link header drops a frame with any failed item whatever its CRC says. The parallel region drops such rows. - Under 4 sps Oerder & Meyr takes its square-law line at 2, 4... times the rate, to 4 samples a symbol (at 2 sps it aliased onto its mirror); it times from 1 sample a symbol. - level(): The effort level in force - set_effort(level): Set the effort level from now on: "fast", "balanced" or "max". Returns the level it replaces - effort(level): The effort level for a `with` block - get(name): A setting at the level in force - interp_taps(sps): Taps of the timing interpolation at the level in force for `sps` samples per symbol: balanced keeps cubic (4) from 4 samples a symbol, where its error (-49 dB) is under the pulse's own truncation, takes 8 under it (cubic: -26 dB at 2), and 12 under 2 samples a symbol (a band-limited signal sampled close to its width: 8 taps lose a few dB there) - scale(name, base): A count at the level in force ("iters", "list"): its own (`base`) scaled, at least 1 - shift(name, base): A count at the level in force ("chase"): its own (`base`) plus the level's step, at least 1 - choice(name, base): A choice at the level in force ("maxlog", "check"): the level's, else the operator's own (`base`) ## rpps.source Signal sources and sinks: files, radios and memory (on pysdrlib), sockets, SigMF recordings, WAV, channels in shared memory (`ShmSink`; received with `Device("shm@...")`); and packets: pcapng for Wireshark, live or in a file (`PcapSink`, read back with `Pcap`), and a Linux TUN/TAP interface both ways (`Tun`) ## rpps.source.formats Sample file formats, as pysdrlib names them: a complex format is named by the bits of its I (or Q) alone, as in SigMF - pysdrlib(): The pysdrlib module, refused (ImportError) when it is older than NEED - ls(): The format names pysdrlib knows - get(fmt): A pysdrlib Formats member from its name (or a member) ## rpps.source.net Samples from the network: raw IQ over UDP or TCP, in any pysdrlib format - Socket(fmt, url, Fs, cf, sps, scale, timeout, chunk): Raw samples from `url`: udp://host:port (bound and listened on) or tcp://host:port (connected to) ## rpps.source.pcap Packets to Wireshark: pcapng written to a file, a FIFO, stdout or a Windows named pipe, live (`PcapSink`); and read back (`Pcap`) - shb(app) - idb(dlt, name, description) - epb(interface, t, data, comment, flags) - rpps_header(p): RPPS's header for a Packet: TLVs (type 1 byte, length 2 bytes big endian), then the packet's bytes - PcapSink(target, rpps, clock): Write packets (rpps.link.capture.Packet) as pcapng: `packets >> sink`, `packet >> sink`, `sink.write(...)` - Record(dlt, data, time, comment, flags, interface): A packet read from a capture: dlt (its link type's number), data, time (seconds), comment, flags, interface - Pcap(source): Packets of a pcapng or pcap capture, in order: `for rec in rp.source.Pcap(path)` (Records). ## rpps.source.shm Channels in shared memory: one process channelizes, others receive their channel (pysdrlib's `shm` streams) - ShmSink(name, namespace, capacity, labels, profile, bw, directory): Publish blocks to shared memory, for other processes: `block >> sink`, `blocks >> sink` ## rpps.source.sigmf SigMF recordings: the samples and what they were recorded with (sigmf.org, the core namespace) - dtype_of(datatype): numpy dtype of the real components, and whether samples are complex, from a SigMF core:datatype - SigMF(path, sps, scale, correct): A SigMF recording (the -meta or -data path, or their stem): Fs, cf and the datatype from its metadata - SigMFSink(path, Fs, cf, datatype, description, annotations, context): Blocks written as a SigMF recording: `path`.sigmf-data as they come, `path`.sigmf-meta when closed ## rpps.source.source Sources and sinks of signal blocks - Blocks(gen): Blocks of a stream. - Source(Fs, cf, sps, ppm, context, correct): Parent of the things that produce blocks. - File(fmt, path, Fs, cf, sps, scale, context, correct): Samples from a file, in blocks (a short last block is delivered, flushing the stream) - Memory(samples, Fs, cf, sps, context, correct): Samples held in memory, in blocks (a short last block flushes the stream): what was captured from a device, for analysis that runs slower than the device does (`Memory.capture`), or an array made some other way - Device(device, cf, Fs, rx_gain, sps, correct, **open_args): Samples from a pysdrlib device (RTL-SDR, HackRF, ..., "sim", or "remote"): blocks until the loop is left. - Sink(fmt, path, scale, append, clip): Write blocks to a file with pysdrlib's FileSink: `block >> sink` or `blocks >> sink` ## rpps.source.transmit Transmitting with a radio: blocks of samples out of a pysdrlib device (`DeviceSink`) - DeviceSink(device, cf, Fs, tx_gain, channel, scale, **open_args): Transmit blocks with a pysdrlib device: `block >> sink`, `blocks >> sink` ## rpps.source.tun A Linux TUN/TAP interface, both ways: decoded packets onto it, packets written to it out to transmit - Tun(name, mode, linktype, up): A TUN or TAP interface (see module). ## rpps.source.wav WAV files in and out (the stdlib `wave` module: no dependency) - write_wav(path, x, rate, peak): Write audio (frames, or (frames, channels)) as a 16-bit WAV at `rate` Hz. - WavSink(path, rate, channels): A 16-bit WAV file written block by block: `block >> sink` or `blocks >> sink`. - Wav(path, iq, cf): A PCM WAV file as a source, scaled to [-1, 1): one channel gives real samples (audio); two give I and Q (`iq=True`: an SDR's IQ recording) or, with iq=False, the first channel. ## rpps.signal Conditioning: samples to samples, without knowing what signal they carry filters FIR/IIR design, windows, frequency shifts, the polyphase channelizer, pulse shaping sample sample-rate changes: decimation, interpolation, rational resampling channelize bring one signal of a wider capture to baseband at a few times its width FFTBank many signals of one capture to baseband at once, each at its own width, from one FFT per hop channel the simulated medium between transmitter and receiver: AWGN, offsets, multipath, fading DCBlock, Deemphasis, Conjugate conditioning: DC removal, FM de-emphasis, spectral inversion loops second class: DCBlock and Deemphasis as per-sample loops (the same output; C++ kernels) ## rpps.signal.channel Channel impairments as stages, to test a receiver against: `signal + rp.signal.channel.AWGN(10) + rp.signal.channel.CFO(300)` - AWGN(snr_db, esn0_db, ebn0_db, bits_per_symbol, power, seed): Additive white gaussian noise at a signal-to-noise ratio - CFO: Carrier frequency offset [Hz]: an oscillator whose phase carries across blocks (the centre frequency is not touched) - PhaseOffset(phase): Constant phase rotation [rad] - Gain(db): Amplitude gain in dB - TimingOffset: Fractional-sample delay (windowed sinc, carried across blocks) - ClockDrift(ppm): Sample clock error [ppm]: the receiver samples slightly fast (positive) or slow. - Multipath(gains, delays): Static multipath: a tap at each delay (in samples, whole numbers) with a complex gain - Fading(doppler_hz, paths, k_db, seed): Flat fading by a sum of sinusoids (Jakes): Rayleigh, or Rician with `k_db` (line of sight over scattered power) ## rpps.signal.channelize - channelize(mid, width, Fs, oversample, max_taps, largest): Filter stages that bring a signal to baseband at about `oversample` times its width - Channelize(freq, width, oversample): `channelize` as one stage: one channel of the capture to baseband, designed from the stream's sample rate when the first block arrives (a profile does not know the capture's rate) - baseband(x, Fs, freq, width, oversample): A channel of a whole capture at baseband, in one call: (samples, Fs_out). ## rpps.signal.condition Conditioning: DC removal, FM de-emphasis, spectral inversion - DCBlock(r): Removes the DC offset (a one pole high pass: y[n] = x[n] - x[n-1] + r*y[n-1]), an `IIR` section - Deemphasis(tau): FM broadcast de-emphasis: a one pole low pass with time constant tau (75 us in the Americas, 50 us elsewhere), an `IIR` section at the stream's rate - Conjugate: Spectral inversion of a complex signal: x -> conj(x), so a capture whose I and Q were swapped (or taken from the lower sideband of a mixer) comes out the right way round. ## rpps.signal.fftbank FFTBank: many channels of one capture, each at its own width and rate, from one FFT per hop - FFTBank(Fs, channels, oversample, guard, transition, min_bins, max_n): Channels (mid, width) [Hz] of a capture at Fs: `step(x)` -> [baseband samples per channel]. Fs_out[k], D[k] ## rpps.signal.loops Conditioning as per-sample loops (second class): the recursions `DCBlock` and `Deemphasis` run sample by sample, in the C++ kernels when they are built (rpps._native: dc_block, one_pole) and a Python loop otherwise - DCBlock(r): Removes the DC offset, a one pole high pass run sample by sample: y[n] = x[n] - x[n-1] + r*y[n-1] - Deemphasis(tau): FM broadcast de-emphasis, a one pole low pass with time constant tau run sample by sample: y += a*(x - y) ## rpps.signal.filters Filters as stages: FIR/IIR design (`low_pass`, `band_pass`, `remez`...), pulse shaping, windows, frequency shifts and a polyphase channelizer: `samples + rp.signal.filters.low_pass(401, 3e6, 100e6)` ## rpps.signal.filters.convert Bring filter coefficients from elsewhere into the config format - read_table(path, fmt, dtype, key): The numbers of a file as a list of 1-D arrays (one per row of text, one for a vector). - fir_def(taps, **fields): Definition of an FIR with these taps (real, or complex: the imaginary parts go in `taps_imag`). - sos_def(sos, **fields): Definition of an IIR from second-order sections, rows [b0 b1 b2 a0 a1 a2] (scipy's `sos`) - ba_def(b, a, convention, **fields): Definition of an IIR from a transfer function. - zpk_def(z, p, k, **fields): Definition of an IIR from zeros, poles and gain (z-plane; complex values are stored as [re, im]) - import_fir(path, fmt, dtype, key, scale, name, dest, overwrite, **fields): The FIR in a file as a config definition (a dict). - import_iir(path, form, fmt, dtype, key, convention, name, dest, overwrite, **fields): The IIR in a file as a config definition. ## rpps.signal.filters.convolve FFT convolution for long filters - fft_pays(nx, nh): Is convolving nx samples with nh taps cheaper by FFT blocks than directly - convolve(x, h, mode): Convolution of the signal `x` with the filter `h` by overlap-add FFT blocks when that is cheaper than `np.convolve` - correlate(x, t): sum_i x[n + i] conj(t[i]) at every n where the template t fits in x (len(x) - len(t) + 1 values, as np.correlate(x, t, "valid")), by FFT blocks when that is cheaper ## rpps.signal.filters.filter - Filter - FIR: Causal FIR that carries its history across blocks: len(out) == len(in) ## rpps.signal.filters.filters - ConvFilter(filt) - low_pass(taps, cutoff, fs, window): Windowed-sinc low pass: `taps` coefficients, cut off at `cutoff` Hz of sample rate `fs` (None: normalised, Nyquist is 1) window: a function of the length, e.g. - high_pass(taps, cutoff, fs, window) - band_pass(taps, cut1, cut2, fs, window) - band_stop(taps, cut1, cut2, fs, window) - kaiser_window(beta): A Kaiser window of shape `beta`, as a function of the length - kaiser_params(atten_db, width): Taps and beta for a Kaiser-window FIR with `atten_db` stopband attenuation and a transition `width` wide (a fraction of the sample rate, e.g. - low_pass_kaiser(cutoff, transition, atten_db, fs): Low pass that meets a specification: stopband `atten_db` down, the transition (Hz) centred on `cutoff` - high_pass_kaiser(cutoff, transition, atten_db, fs) - remez(taps, bands, desired, weight, fs, type): Equiripple (Parks-McClellan) FIR: the smallest possible maximum weighted error for `taps` coefficients ## rpps.signal.filters.iir IIR filters, with numpy only - as_sos(sos): Sections as a float (n, 6) array normalised to a0 = 1 - poles(sos): Every pole of the cascade (a first-order section has one: its unused second pole at the origin is not listed) - sos2zpk(sos): (zeros, poles, gain) of a cascade. - IIR(sos, gain): Cascade of second-order sections `sos` (rows [b0 b1 b2 a0 a1 a2]); `gain` scales the output - zpk2sos(z, p, k): Sections for a filter of zeros z, poles p and gain k (z-plane, conjugates in pairs). - tf2sos(b, a): Sections for the transfer function b(z^-1) / a(z^-1) (coefficients of rising powers of z^-1, as scipy.signal) - design(kind, order, pass_, cutoff, ripple_db, atten_db): Sections of a Butterworth ("butter") or Chebyshev ("cheby1": ripple_db in the pass band, "cheby2": atten_db in the stop band) filter - single_pole(alpha): y[n] = alpha x[n] + (1 - alpha) y[n-1]: a leaky integrator / exponential average (0 < alpha <= 1) - RunningMean(alpha): An exponential average that starts at the first sample: m[0] = x[0], m[n] = m[n-1] + alpha (x[n] - m[n-1]), a `single_pole` IIR whose state is set from the first sample. - biquad(shape, f0, q, gain_db): One RBJ audio-EQ cookbook biquad. ## rpps.signal.filters.pfb - Channelizer(channels, taps_per, window): Polyphase filter bank: splits a wideband signal into `channels` equal bands, each at Fs/channels ## rpps.signal.filters.serial Filter definitions, config/filter///.json (`rp.signal.filters.load("fir/taps/name")`), and pulses, config/pulse//.json (`rp.signal.filters.load("pulse/rrc/0p35")`): two resources - Designed(name, build, fs): A FIR defined by a config entry: the taps are made when the stream starts, from its sample rate and symbol rate - builtin(name): A window function of the code, by name (see `Window.s()`) - window(spec): A window function f(N): a preset ("kaiser/a8"), a built-in ("hann"), inline {"type": "kaiser", "params": {"a": 8}}, or a function - DesignedIIR(name, build, gain, fs): An IIR defined by a config entry: the sections are made when the stream starts (designs in Hz need its sample rate) - ls(path): List the filter and pulse definitions: {"fir/windowed": [names], "pulse/rrc": [...], "window/kaiser": [...]} - load(ref, path, **params): Load a filter, config/filter///.json, or a pulse, config/pulse//.json: `load("fir/taps/moving_average_4")`, `load("pulse/rrc/0p35")`. ## rpps.signal.filters.shaping - rrc_pulse(t, beta): Root-raised-cosine pulse, t in symbols. - ShapingFilter - rc_pulse(t, beta): Raised-cosine pulse, t in symbols. - ShapingRRC(taps, sps, beta, gain) - ShapingRC(taps, sps, beta, gain) - ShapingSinc(taps, sps, gain) - ShapingRect(taps, sps, gain) - ShapingHalfSine(sps, gain) - ShapingGaussian(sps, bt, span, gain) - ShapingMatRRC(N, sps, poff, beta) - ShapingBiphase(gain): Matched filter for biphase (Manchester) symbols: first half +1, second half -1 ## rpps.signal.filters.shift - ShiftFreq(fo): Shift the spectrum by `fo` Hz. - ShiftFreqIdx: Shift by `fo` cycles per sample (fo is normalised to the sample rate) - ShiftTime(delay, taps): Delay by a fraction of a sample (windowed-sinc fractional delay), carrying its history across blocks ## rpps.signal.filters.window - Window(name, N, *args, **kwargs) ## rpps.signal.filters.impl Building blocks behind rpps.signal.filters: `designer` (simple lowpass/highpass prototypes by name: sinc, delta, exponential...), `gaussian` (the Gaussian and its FWHM), `window` (window functions and their properties) ## rpps.signal.filters.impl.designer - lowpass(taps, name) - highpass(taps, name) - designer(taps, cut_off, window, pass_zero, scale, fs) ## rpps.signal.filters.impl.gaussian - sigma2fwhm(sigma) - fwhm2sigma(fwhm) - gaussian(y, sigma) ## rpps.signal.filters.impl.remez Parks-McClellan equiripple FIR design (the Remez exchange), numpy only - remez(taps, bands, desired, weight, fs, type, maxiter, density): Equiripple FIR of `taps` coefficients, optimal in the weighted Chebyshev sense: the maximum error is the smallest possible ## rpps.signal.filters.impl.window Window functions - rect(n) - bartlett(N, Lp) - parzen(N) - welch(N) - welch_2f(N) - hann(N) - hamming(N) - hamming_orig(N) - blackman(N) - blackman_exact(N) - nuttall(N) - blackman_nuttall(N) - blackman_harris(N) - flattop(N) - sine0(N) - sine2(N) - sine4(N) - sine6(N) - sine8(N) - gaussian(N, sigma) - acon_gaussian(N, sigma) - gen_gaussian(N, sigma, p) - tukey(N, a) - planck_taper(N, e) - kaiser(N, a) - exponential(N, D) - get(name) ## rpps.signal.sample Sample-rate changes as stages: `down` (decimation), `up` (interpolation) and `re` (rational resampling), `fractional` (any ratio, with a shift fused in); `resample_poly` and `fractional_resample` resample an array in one call ## rpps.signal.sample.down - Downsample - Decimate(ratio, offset): Keep every `ratio`th sample, starting with sample `offset`. - interpolate_stream(samples, st, step, kind): Read `samples` at positions st.pos, st.pos + step, ... by interpolation, carrying the position and the unread tail in `st` (SimpleNamespace(tail=None, pos=0.0); for "cubic", pos starts at 1.0). - FractionalSpline(ratio, kind) ## rpps.signal.sample.fractional Resampling by any ratio with a windowed-sinc polyphase filter, and an optional frequency shift fused in front of it - design_bank(taps, phases, cutoff, beta): (phases + 1, taps) table of the interpolation filter: row p is the kernel for a read position p/phases of the way past a sample - read_python(buf, table, pos, step, nout): The reference for `native.polyphase_read`: output k is `buf` read at pos + k*step, the nearest of the table's phases. - FractionalPolyphase(ratio, cutoff, taps, phases, beta, shift): Resample by any ratio (output rate over input rate) with a Kaiser-windowed sinc polyphase filter, and optionally move the spectrum first - fractional_resample(x, ratio, Fs, **kw): Resample the array `x` (sample rate `Fs`, which only matters to `cutoff` and `shift`, in Hz) by `ratio`: a one-call `FractionalPolyphase` ## rpps.signal.sample.re - Resample(up, down, taps) - Polyphase: Stateful FIR rational resampler. ## rpps.signal.sample.resample One-shot rational resampling of an array - design(up, down, window): The filter `resample_poly` uses: (taps at the up-sampled rate, gain `up` included, centre index) - resample_poly(x, up, down, window): Resample `x` by the rational factor up/down with a linear-phase FIR low pass and no delay: output m is the input at time m*down/up ## rpps.signal.sample.sample - Sample ## rpps.signal.sample.up - Upsample(ratio) - Interpolate(ratio, filt): Zero stuff by `ratio` and filter with `filt` (an FIR stage, a pulse shape) in one step: the same output as `Zeros(ratio) + filt`, in polyphase form, so the zeros are never multiplied (ratio times less work) - Sinc(ratio, taps): Zero stuff and interpolate with a windowed sinc. - Zeros ## rpps.sync Sync: estimate something unknown about the data and correct or align it, at whatever representation it can be separated Its estimates go to `stream.est[name]`, never into the data. **Block estimation and block-rate tracking are first class; per-sample loops are second class.** ### First class: block estimation, tracked across windows Estimate from a window with block operations (FFTs, correlation, least squares), then a slow loop run **once per window** (`track`: critically damped second order, wide while it pulls in, coasting through gated windows) carries each parameter and its rate across windows and gates outliers; the correction is evaluated per item. | Estimates | Operator | Profile method | |---|---|---| | symbol timing | `time.OerderMeyr`: square-law, cubic interpolation; follows a clock 200 ppm off | `timing: oerder_meyr` (default) | | symbol timing, the matched filter fused in | `time.MatTrack`: the matched filter's energy maximum (MatRRC), read only at the instants; on a GPU too | `timing: mat` | | carrier frequency and phase | `phase.MPower`: M-th power of the phase, FFT acquisition | `carrier: mpower` (default) | | channel | `equalize.BlockLS`: least squares per window against decisions; `blind=True`: constant modulus by least squares until the eye opens | `equalize: ls` (default), `"blind": true` | | OFDM timing and frequency | `CPSync`: from the cyclic prefix | | | carrier phase per frame | `PilotPhase` (pilot blocks), `phase.FFCarrier` (Viterbi & Viterbi) | `carrier: pilots`, `carrier: ff` | | spectral inversion | `Inversion`, `inversion.sense` (known symbols turning backwards) | `inversion` | | frame starts | `FrameSync` (a preamble and the best word of a header code; or named alternatives, Zadoff-Chu sets, a word mid-burst, real levels, what the match says: word, scale, cfo, esn0, modulation), `Delimiter` (a word among bits) | `frame`, `delimit` | | alignment on bits | `Align` (markers, patterns, polarity), `Puncture` (puncture phase) | `align`, `puncture` | | modulation (PSK, QAM, APSK), rate, roll-off, offset | `Acquire` (`detect` once; roll-off: `rate.find_rolloff`), `Lock` (a snapshot: `Lock.find`, `lock.update`; contiguous blocks joined: `lock.follow`); code phase and Doppler: `acquire_code` | | | channel code, bit map, alignment | `AcquireFEC` | | | bursts | `Burst` splits a stream into bursts, `BurstTx` places them; `Bursts` on many carriers, placed in a burst time plan (rpps.plan) whose origin it acquires and tracks, `PlanTx` places them by one; `Preamble` finds each one's preamble (`attach_tx()`: its `PreambleTx`) | `burst`, `preamble` | | a pilot tone | `ToneLock` (FM stereo's 19 kHz, ATSC's pilot) | | Rules for feedforward estimators: 1. **Windows sit at absolute stream positions** (`[k*W, k*W + L)`, history carried between blocks), so output does not depend on how the stream is cut. 2. **Drifting parameters are tracked across windows**, not held per window (a free-running SDR is 10-20 ppm off and wanders), and the correction is evaluated per sample. 3. **Windows are set in time, not symbols**: oscillator phase wanders in time (cycle slips at 8 ms windows, none at 2 ms). 4. **Latency is declared** in `stream.est[name]["latency"]` (seconds), not added to `meta.delay`, the group delay. A profile's sync steps name **what** is estimated (`carrier`, `timing`, `equalize`, `frame`) and get the first-class method; another is chosen by name in `defaults`: `{"timing": {"method": "mat"}}`. A new estimator is registered with `rp.profile.steps.register_sync_method`. ### Second class: per-sample loops `loops` (`rpps.sync.loops`) holds them, for signals and conditions block estimation does not suit, as references and for comparison: `loops.MM` (Mueller & Muller, Gardner), `loops.TLL` (a timing locked loop around a detector from `loops.ted`: `ted="zx"` zero crossing, `"el"` early-late), `loops.Costas` (M-PSK, or any constellation's points), `loops.AGC`, `loops.PeakAGC`, `loops.Squelch`, the adaptive equalizers `loops.LMS` and `loops.CMA`. Profiles reach them by name (`timing: mm`, `gardner`, `timing: {"method": "tll", "ted": "el"}`, `carrier: costas`, `agc: loop`, `equalize: lms`, `cma`). Their loop filter is `loops.pll.PILoop` (gains from a bandwidth: `loops.pll.loop_gains`). ### Known, measured, detected - `time.Known`: timing that is given, not estimated (a loopback, a source whose timing is known); fuses the matched filter before it (`timing: known`). - On a GPU (`rpps._accel.device()`, CUDA or ROCm/HIP; numpy without one), by `"device": true` in a step's sync settings: `time.MatTrack` (`timing: mat`: the held samples filtered and read at the instants on the device, windows measured a group at a time) and `FrameSync` (`frame`: the preamble metric, and the header words ranked in one matrix product). Both agree with their numpy paths to single-precision rounding: the same frames, the same symbols to 1e-4. - `detect`, `Detection`, `rate.find_baud`: the feed-forward estimates `Acquire` runs (rate, timing, modulation, offset, phase); blind analysis uses them too. - `quality`: Es/N0, Eb/N0 and EVM of locked symbols, once (`measure`), over a window (`Track`) or on the stream (`Monitor`, `{"sync": "quality"}`); each symbol's error (`errors`) and an analyser's error summary (`summary`: EVM, MER, magnitude and phase error, IQ offset, gain imbalance, quadrature error). **`AcquireFEC`** does for the code what `Acquire` does for the modulation: on timed, carrier-corrected symbols it finds the configured code, bit map and alignment (`analysis.identify`: convolutional codes, RS behind a Forney interleaver, HDLC, block codes), names the profile that decodes it, then tracks by re-encoding once per window and putting carrier turns and symbol slips right; `est["fec"].rx()` decodes. With `blind=True` the blind tools (`rpps.analysis`) run when no definition fits; what they find is a `Guess`, a definition that decodes once saved. ## rpps.sync.acquire Acquisition: symbol rate, timing, modulation, frequency offset and phase from baseband samples: once (`detect`), as snapshots of separate blocks (`Lock`: a display that seeks, pauses and retunes) and as the stream arrives (`Acquire`) - Detection(**kw): Result of `detect`. - symmetry(points, tol, max_order): Order M of the rotational symmetry of a point set (the M-th power removes the modulation) - candidates(names): Load candidate constellations from config/constellation: {name: unit-rms points}. Each is read once per config search path (a Lock rechecks them every block: finding the files would cost more than scoring them) - turned_candidates(names): Turned candidates. - correct(y, pts, M, pad): Feed-forward frequency + phase correction for a candidate. - drift(y, M, blocks, min_block, sigmas, segments, min_segment, offset): The phase curvature c (radians a symbol^2) a drifting carrier leaves on symbols y. - score(y, pts, iters, esn0): Mean log-likelihood per symbol of unit-rms y under equiprobable points with Gaussian noise: the variance fitted (EM), or, given esn0 (dB), the points scaled to the signal's share of the power and the noise the rest - score_all(ycs, esn0): Scores of {name: (corrected unit-rms symbols, points)} and how they were made: at the caller's esn0 ("given"); each fitting its own variance when the fit's winner reads over FIT_MIN dB ("fit"); else each at its own M2M4 Es/N0 ("moments") - null_score(y): `score` of unit-rms y as Gaussian noise of the same power (complex, unit variance) - track_timing(x, sps, beta, span, rounds): Refine sps from the drift of the best timing between the start and end of x. - detect(x, Fs, names, betas, span, baud, esn0, min_evidence): Find symbol rate, timing, modulation, frequency offset and phase from baseband samples - Lock: A signal's symbols, as a snapshot: found once by a full search (`Lock.find`), then followed block by block (`update`) without searching again. - onset(x, block, level): Where a signal comes on in x. - Acquire(lock, max_wait, history, names, betas, min_samples, baud): Detect as soon as the signal is there, then keep refining as the stream grows ## rpps.sync.acquire_fec AcquireFEC: which code timed symbols carry, found as the stream arrives (the scans are in rpps.analysis.identify) - AcquireFEC(window, skip, max_wait, names, blind, check, relock, name, min_line): Identify the code the symbols carry, then turn them to the map its decoder uses ## rpps.sync.agc Automatic gain control, with no loop over samples - PeakAGC(target, decay, floor): Gain from the peak: |x| is followed instantly upward and decays by `decay` per sample, and the signal is scaled so that peak sits at `target`. - AGC(target, *, window, min_samples, log, min_gain, max_gain, init, name): Gain that brings the signal's level to `target`, by block estimation ## rpps.sync.align - Align(period, markers, pattern, unit, acquire, threshold, misses, polarity, name, start, publish): Align a bit stream on a marker that repeats every `period` units, and resolve its polarity ## rpps.sync.burst Per-burst acquisition: cut a stream of samples into the bursts that rise out of its noise floor - Burst(factor, win, min_s, max_s, percentile, history, settle, quiet): Bursts of a stream of samples, each a block of its own stream (see the module) - BurstTx(Fs, gap_s, ramp_s, hop): The transmit side of Burst: bursts placed on one stream of samples, each where its start puts it ## rpps.sync.code_acquire - acquire_code(x, code, sps, index, Fs, doppler, periods, threshold, pfa): Find where a spreading code starts in a signal, and its frequency offset: the parallel code-phase search - noise_threshold(periods, cells, pfa): The ratio to the mean that the largest of `cells` noise-only powers, each summed over `periods`, exceeds with probability pfa ## rpps.sync.equalize Equalizers: `symbols + rp.sync.equalize.BlockLS(qpsk)` solves the taps per window - BlockLS(constellation, taps, window, min_symbols, iters, blend, gate, name, blind, blind_iters): Equalize symbols by least squares over each window, decision directed, with the taps carried from window to window - symmetry(points, most): (M, E[a^M]) for the smallest M whose moment E[a^M] is not zero: the constellation's rotational symmetry (2 BPSK, 4 QPSK and square QAM, 8 8PSK); (0, 0) when none up to `most` (a constellation with no phase to read) ## rpps.sync.frame Frame sync: where frames start (rpps.sync) - word_errors(n_bits, false_alarm, positions, polarity): The most bit errors a match of an `n_bits` word may have while random bits stay under `false_alarm` matches over `positions` places searched (a frame's bits, when the search restarts every frame): the largest e with positions * P(Binomial(n_bits, 1/2) <= e) (twice that with `polarity`, the inverted word matched too) under it. - FrameSync(preamble, words, threshold, max_length, name, pending, device, before, length, segments, scale, classify, margin, min_symbols, polarity, cfo, count, memory): Find frames by a known preamble among timed symbols, and give them whole and the right way round - Delimiter(word, bits, order, errors, name, length, keep, polarity): Find frames in a bit stream by the word that comes before each one (a start-of-frame delimiter), give the bits after it ## rpps.sync.inversion Spectral inversion (a stream conjugated) found by known symbols turning backwards, and undone (rpps.sync) - handed(known): Whether a sequence turns (a step not 0 or 180 degrees): only then does it tell the senses apart - sense(z, known, threshold, top): Whether symbols z are inverted, by a known sequence in them: True, False, None (not found, or it doesn't turn) - Inversion(known, window, threshold, evidence, hold, name): Spectral inversion of timed symbols by a known sequence that turns; conjugates them back ## rpps.sync.kernels Batch kernels of the sync operators: `PilotLine` of `PilotPhase` - PilotLine(starts, total, length, value, lead, name, left): The carrier phase of each frame from its pilot blocks, taken off: a least-squares line through the phase of every block (and through `lead`, a position where it is known to be 0), per row. ## rpps.sync.ofdm OFDM symbol timing and fractional carrier frequency from the cyclic prefix (van de Beek, Sandell & Borjesson 1997) - CPSync(n_fft, n_cp, window, min_symbols, snr, bw, gate, name): OFDM symbols found by their cyclic prefix: samples in, the same samples out from the start of a symbol (its prefix), whole symbols of n_fft + n_cp, with the fractional carrier frequency offset taken off. ## rpps.sync.pilots - PilotEqualizer(carriers, taps, max_taps): Equalize OFDM carriers from their pilots: n_fft carrier values per OFDM symbol in, the same with the channel removed - PilotPhase(slot, every, length, value, slots, pilots, lead, name, left): Carrier phase over each frame from its pilot blocks: a line through the phases they measure, taken off the frame ## rpps.sync.plan Bursts on many carriers, placed in a burst time plan (rpps.plan): the return link of an MF-TDMA network - Bursts(carriers, plan, origin, gate, tol, lock, margin, oversample, bw, sps, pad, **burst) - PlanTx(plan, origin, cf, Fs, ramp_s): Bursts placed by a plan: each burst's fields name its window (sequence, superframe, frame, slot; or `window`), and it goes where the plan puts it: `at` its burst start, `freq` its carrier, from the plan's time `origin` (clock ticks at the output's first sample) and the output's centre frequency `cf` ## rpps.sync.preamble A preamble at the start of a burst: where it is, and the carrier offset its repetition gives - Preamble(template, repeat, window, search, gate, offset, correct, name, first, pending, span): Find a burst's preamble: a known waveform, or a repeated one (Schmidl & Cox) - PreambleTx(preamble): The transmit side of a Preamble (`Preamble.attach_tx()`): its template put before a stream ## rpps.sync.puncture - Puncture(code, window, name, max_windows, rotations): Find where a punctured convolutional code's puncture pattern starts, and start the stream there ## rpps.sync.quality Signal quality of recovered symbols: Es/N0, Eb/N0, EVM, measured once (`measure`), over a running window (`Track`) or on the stream (`Monitor`, a stage that publishes it); each symbol's error (`errors`) and an analyser's error summary (`summary`: EVM, MER, magnitude and phase error, IQ offset, gain imbalance, quadrature error) - Quality(esn0_db, ebn0_db, snr_db, evm_pct, sigma, bits, rate, n): Es/N0, Eb/N0 and friends of a set of symbols (see `measure`) - measure(y, points, bits, rate, sps): Es/N0, Eb/N0 and EVM of locked symbols `y` around the constellation `points` - SNR(**kw): A signal-to-noise estimate before anything is locked (`from_sequence`, `blind`) - m2m4(y, points): Es/N0 (dB) of symbols y were they of the constellation `points`, from their second and fourth moments alone (Pauluzzi and Beaulieu, 2000): M2 = S + N, M4 = k S^2 + 4 S N + 2 N^2 with k = E|p|^4 of the unit-rms points (1 for any PSK; under 2 for any digital constellation), so S = sqrt((2 M2^2 - M4)/(2 - k)). - from_sequence(y, ref, periodic, guard, sps): SNR of samples `y` carrying the known sequence `ref` (one sample per element, `sps` samples a symbol for esn0) - cyclic(x, sps, nseg, search, step): Es/N0 of samples of one linearly modulated signal (RRC, any roll-off) from its spectral correlation at the symbol rate (see the module). - blind(x, sps, L, max_samples, flat): SNR of oversampled samples of one signal, from the band it leaves empty (see the module). - decide(y, points): The nearest of `points` to each of y - Errors(ideal, vector, evm_pct, mag_pct, phase_deg): Per symbol, against the nearest point (see `errors`): vector = y - ideal; evm_pct = |vector|, mag_pct = |y| - |ideal| (both as a percentage of the constellation's rms, as a vector signal analyser normalises them); phase_deg = the angle from ideal to y [degrees] (0 where the ideal is the origin) - errors(y, points): The error of each symbol of y (locked: corrected and at the constellation's scale) against the nearest of `points`. - Summary(**kw): A vector signal analyser's error summary of locked symbols (see `summary`) - summary(y, points): EVM, MER, magnitude and phase error, IQ offset, gain imbalance and quadrature error of locked symbols y against the nearest of `points` (Summary). - Track(points, bits, rate, history, minimum): Running Es/N0 estimate over the last `history` symbols: `update(block)` returns the current Quality (None until enough) - Monitor(points, bits, rate, history, minimum, name): Es/N0, Eb/N0 and EVM of the locked symbols going by, published to `meta.stream.est[name]` as a `Quality` (None until `minimum` symbols): the symbols pass unchanged. ## rpps.sync.rate Symbol rate estimates: the |x|^2 cyclostationary line on samples (`find_baud`), the rate of symbols (`find_rate`), the pulse's roll-off from the spectrum (`find_rolloff`) - find_baud(x, Fs, lo, hi, pad): Find the symbol rate from IQ samples using the |x|^2 cyclostationary line - find_rate(syms): Find symbol rate (as a fraction of the sample rate) from IQ samples - raised_cosine_psd(f, baud, beta): The power spectrum of RRC-shaped symbols (|RRC|^2, a raised cosine) at frequencies f [Hz], 1 in the flat part - nearest_rolloff(beta): The standard roll-off (ROLLOFFS) nearest a measured one - find_rolloff(x, Fs, baud, cfo, nfft, grid): The roll-off of an RRC-shaped signal from its spectrum: (beta, residual) ## rpps.sync.squelch Squelch: detects that a signal is present, and gates the stream on it - Squelch(threshold_db, hysteresis_db, alpha): Silence the signal while it is quieter than `threshold_db` (power, dB re 1.0), with hysteresis - gate(level, lo, hi, was_open): Hysteresis: open where level > hi, closed where level <= lo, else as at the sample before (`was_open` before the first): each sample takes the last decisive one's state ## rpps.sync.tone A phase-locked tone: the oscillator a pilot sets (FM stereo's 19 kHz, ATSC's pilot), and the signal mixed with it - ToneLock(f0, win, kp, ki, harmonic, min_level, lock_level, lock_err, min_part, history): Lock an oscillator to a steady tone near `f0` Hz, and mix the stream with its `harmonic` ## rpps.sync.track Block-rate tracking (rpps.sync): a slow loop run once per window over the window estimates - new(): A tracker that has seen nothing: `started` False until the first update - wrap(x, period): x wrapped to [-period/2, period/2) - at(tr, t): The tracked value at position t (any position: the correction is evaluated per item, not per window) - line_phasor(phi0, rate, length): exp(-j (phi0 + rate i)) for i in 0 .. length-1: a phase line turned into a phasor with no exponential per item. - line_parts(phi0, rate, length): (starts, local) of `line_phasor`: item i's phasor is starts[i // len(local)]*local[i % len(local)] (a device kernel reads the line this way, the exponentials made on the host in double) - update(tr, measured, t, period, bw, rate): A window's measurement (modulo `period` when given) at position t, its centre. - miss(tr, t): A window gated out: the tracker coasts on its rate - windows(st, x, meta, W): Hold x and give each window ready: (a0, b, seg) for stream positions [a0, b) of [k*W, (k+1)*W). - keep(st, pos): Let go of the items held before stream position pos (at most all of them) ## rpps.sync.loops Second class: per-sample loops (rpps.sync) Each updates its estimate once a sample or a symbol, carrying it from one to the next. Block estimation tracked across windows (rpps.sync's first class) replaces them in the profiles and examples; they stay for signals and conditions it does not suit, as references, and for comparison. Each runs in the C++ kernels when they are built (rpps._native), with its Python loop as the reference. Their loop filter is `pll.PILoop`, its gains from a noise bandwidth (`pll.loop_gains`). | Loop | Estimates | First-class counterpart | |---|---|---| | `MM` | symbol timing: Mueller & Muller (`ted="mm"`, decisions) or Gardner (`"gardner"`), interpolated per symbol | `time.OerderMeyr`, `time.MatTrack` | | `TLL` | symbol timing: a PI loop (`pll.PILoop`) around a detector from `ted` (zero crossing, early-late) | `time.OerderMeyr`, `time.MatTrack` | | `Costas` | carrier phase and frequency, per symbol: M-PSK, or decisions on any constellation's `points` | `phase.MPower`, `phase.DDCarrier` | | `AGC` | the gain, sample by sample (`mu`, linear or in logs) | `rpps.sync.AGC` (the level per window) | | `PeakAGC` | the peak, followed and decayed sample by sample | `rpps.sync.PeakAGC` (closed form, the same output) | | `Squelch` | whether a signal is there, the level followed sample by sample | `rpps.sync.Squelch` (an IIR section, the same output) | | `LMS` | equalizer taps, per symbol: least mean squares against training, then decisions | `equalize.BlockLS` | | `CMA` | equalizer taps, per symbol: constant modulus, blind | `equalize.BlockLS` (`blind=True`) | ## rpps.sync.loops.agc Automatic gain control as per-sample loops - PeakAGC(target, decay, floor): Gain from the peak, followed sample by sample: |x| is followed instantly upward and decays by `decay` per sample, and the signal is scaled so that peak sits at `target` - AGC(target, mu, log, min_gain, max_gain, init): Feedback AGC: `block + rp.sync.loops.AGC(1.0, 0.01)` ## rpps.sync.loops.costas The Costas loop: carrier phase and frequency followed per symbol (rpps.sync.loops) - Costas(alpha, beta, order, offset, points): Costas loop: `symbols + rp.sync.loops.Costas.from_bandwidth(0.02, order=4)`. ## rpps.sync.loops.equalize Adaptive equalizers, updated symbol by symbol (second class): `symbols + rp.sync.loops.CMA(11)`, `rp.sync.loops.LMS` - CMA(taps, mu, sps, modulus): Constant modulus algorithm: blind, for constant-envelope modulations (PSK, FSK) -- it fixes ISI but not rotation - LMS(taps, mu, sps, points, training): Least mean squares against a training sequence for the first symbols, then against the nearest point of `points` (decision directed). ## rpps.sync.loops.mm Mueller & Muller and Gardner timing recovery: a per-symbol loop (rpps.sync.loops) - MM(alpha, est, interp, biphase, ted): Mueller & Muller timing recovery ## rpps.sync.loops.pll Phase Locked Loop helpers - loop_gains(bw, damping, Kd, K0): Proportional and integral gains (alpha, beta) of a second order loop - K_fs(Kd, K0, Df, Bn, Fs): (Kp, Ki) for a loop of noise bandwidth Bn [Hz] running at Fs [Hz] - K_sr(Kd, K0, Df, Bn, sr, sps): (Kp, Ki) for a loop of noise bandwidth Bn [Hz] that updates once per symbol (sr: symbol rate [Hz]) - PILoop(Kp, Ki): Proportional-integral loop filter: eF[n] = Kp*eD[n] + (sum of Ki*eD) ## rpps.sync.loops.squelch Squelch as a per-sample loop: the level and the gate decided sample by sample - Squelch(threshold_db, hysteresis_db, alpha): Silence the signal while it is quieter than `threshold_db` (power, dB re 1.0), with hysteresis ## rpps.sync.loops.ted Timing error detectors: the error a timing loop (rpps.sync.loops.TLL) steers by, from samples around a symbol's instant - zx(early, mid, late): Zero crossing (Gardner): `early` and `late` the instants of two symbols in a row, `mid` the sample half way between - el(before, at, after): Early-late: `at` the symbol's instant, `before` and `after` half a symbol either side (the slope of |z|^2 there) ## rpps.sync.loops.tll Timing locked loop: a per-symbol loop around a timing error detector (rpps.sync.loops.ted) - TLL(sps, bw, damping, name, ted): Symbol timing by a timing locked loop: samples at `sps` in (after their matched filter), one symbol each out ## rpps.sync.phase Carrier frequency and phase, by block estimation (rpps.sync): `MPower` (M-th power: FFT acquisition, then per-window phase, tracked), `DDCarrier` / `decided.follow` (from decisions, any constellation: APSK, QAM), `FFCarrier` (Viterbi & Viterbi, per frame) ## rpps.sync.phase.decided Carrier phase from decisions, by block estimation tracked across windows: any constellation (APSK, QAM, PSK) - decide(y, points): The nearest of `points` to each of y - residual(y, points, iters): The phase of y against its own decisions (its amplitude matched to the points'), refined `iters` times - DDCarrier(points, window, bw, name): Carrier phase and frequency from decisions on any constellation, block estimation tracked across windows - follow(y, points, window, bw): y (symbols, one each, a carrier near 0 already) with the phase its decisions show taken off: `DDCarrier` over the whole array ## rpps.sync.phase.ff - FFCarrier(window): Feed-forward carrier correction for M-fold symmetric (PSK) symbols. ## rpps.sync.phase.mpower - MPower(order, offset, window, min_symbols, bw, gate, relock, name, device, acquire): Carrier frequency and phase of M-fold symmetric symbols by the M-th power, block estimation tracked across windows - offset_of(constellation, order): The angle of a constellation's mean point^M: what MPower takes off as `offset` ## rpps.sync.time Symbol timing: where to sample, by block estimation (rpps.sync). `OerderMeyr` (the square-law line, tracked across windows), `MatTrack` (the matched filter fused in and evaluated only at the instants, timing from its energy maximum, tracked across windows; on a GPU too), `Mat` (matrix matched filter, per block), `Known` when the timing is given ## rpps.sync.time.known Known timing: the symbol instants given, not estimated (a profile's `timing: known`) - Known(sps, anchor): Timing that is known, not estimated (a loopback, a source whose timing is given): one sample per symbol at the pulse peaks, which the group delay so far (meta.delay) places. ## rpps.sync.time.mat - matrix_mf(x, centres, sps, beta, span): Matched filter + symbol sampling as a (banded) matrix: y = W @ x - fits(centres, n, sps, span): Which centres have their whole matched-filter support in n samples (what matrix_mf reads) - centres_in(n, t0, sps, span): Symbol centres t0 + k*sps whose whole support fits in n samples - best_tau(x, sps, beta, span, lo, hi, grid): Symbol timing in [0, sps) maximising the matched-filter output energy, from x[lo:hi] - Mat(beta, span, track): Matrix matched filter and symbol timing ## rpps.sync.time.matrack MatTrack: the matched filter and symbol timing in one, tracked across windows (a profile's `timing: mat`) - MatTrack(sps, window, min_symbols, bw, delta, grid, gate, relock, group, device, name): Matched filter and symbol timing in one: samples at `sps` in (before their matched filter, which a profile fuses in from the step before: `fuse`), one symbol each out. ## rpps.sync.time.om - OerderMeyr(sps, window, min_symbols, bw, gate, name, clock, device): Symbol timing by square-law block estimation (Oerder & Meyr), tracked across windows: samples at `sps` in (after their matched filter), one symbol each out ## rpps.wave Waveform layer: streaming stages between symbols and samples (`data + stage`) Shape symbols to samples, each symbol carrying a pulse (rp.signal.filters.load("pulse/..."): the definitions) Matched the pulse's matched filter Stagger offset one rail by part of a symbol (O-QPSK) FM a shaped level signal to a phase-continuous frequency-modulated one (FSK, GFSK, GMSK, C4FM) FMDemod its quadrature discriminator demod FM, AM or SSB audio from one block, no state, with FM deviation, AM depth and SINAD loops second class: AMDemod with its mean as a per-sample loop (the same output; a C++ kernel) The pulses are definitions (config/pulse: `halfsine`, `gaussian`, `rrc`, `rect`), loaded by rp.signal.filters.load: qpsk = rp.symbol.load("psk/qpsk") wave = bits * qpsk + rp.wave.Shape(8, rp.signal.filters.load("pulse/halfsine/halfsine")) + rp.wave.Stagger() # O-QPSK ### Wave pairs A profile's wave step runs as written on receive and inverted on transmit: | Step | Receive (as written) | Transmit (inverted) | |---|---|---| | `shape`, symbol pulse (rrc, rc, halfsine, rect) | `wave.Matched(pulse)`, unit gain at the instants | `wave.Shape(sps, pulse)`, polyphase | | `shape`, frequency pulse (gaussian, FSK rect) | none (the `fm` discriminator) | `wave.Shape(sps, pulse)` | | `stagger` | `Stagger("i", delay)` | `Stagger("q", delay)` | | `fm` | `FMDemod` + integrate over the symbol | `FM(h, step)` | | `ofdm` | remove CP + FFT | IFFT + CP | Whether a pulse is a symbol or a frequency pulse is the pulse definition's `kind`, not the profile's. ## rpps.wave.analog Analog demodulation, carrier modulation to baseband: AM envelope and SSB as stream stages (FM is `FMDemod`), and `demod`, one block at a time with its measurements (FM deviation, AM depth, SINAD) - AMDemod(alpha): Envelope detector: |x| with the carrier (DC) removed by a slow running mean (alpha: how fast the mean follows, the fraction of the gap closed per sample); `AMDemod(alpha=None)` keeps the envelope as it is (on-off keying, pulse position: the levels themselves carry the bits) - SSBDemod(bw, sideband, taps): Single sideband: keeps `bw` Hz of the upper (or lower) side of the carrier at 0 Hz and returns the audio (real) - Measurements(kind, **kw): What `demod` measured on its block - demod(x, Fs, kind, bw, audio_bw): Demodulate one block of analog signal, centred at 0 Hz, and measure it: for a display that wants each frame on its own (the stream stages `FMDemod`, `AMDemod` and `SSBDemod` carry state and filter delay from block to block instead) ## rpps.wave.fm - FM(h, step, deviation): Frequency modulator: a shaped level signal becomes a constant-envelope signal whose frequency follows it. - discriminate(x, Fs): Instantaneous frequency between samples, arg(x[n] conj(x[n-1])): radians a sample, or Hz given the sample rate Fs. - fm_gain(h, sps, step): The `FMDemod` gain that gives back the levels `FM(h, step)` was fed at `sps` samples per symbol - FMDemod(gain, deviation): Quadrature FM demodulator as a stream stage: the last sample carries across blocks ## rpps.wave.loops Demodulation as per-sample loops (second class): `AMDemod` with its running mean run sample by sample, in the C++ kernel when it is built (rpps._native.am_demod) and a Python loop otherwise - AMDemod(alpha): Envelope detector: |x| with the carrier (DC) removed by a slow running mean (alpha: how fast the mean follows, the fraction of the gap closed per sample), updated sample by sample; `AMDemod(alpha=None)` keeps the envelope ## rpps.wave.ofdm - OFDMTx(n_fft, n_cp): IFFT and cyclic prefix: n_fft carrier values per OFDM symbol in (see `rp.symbol.Carriers`), n_fft + n_cp samples out. - OFDMRx(n_fft, n_cp): Cyclic prefix off, then the FFT: samples starting on an OFDM symbol's prefix in, n_fft carrier values per OFDM symbol out (one value per carrier: symbols). ## rpps.wave.shape Pulse shaping and its matched filter: the wave pair of a symbol pulse (rpps.wave, Wave pairs) - Shape(sps, pulse): Symbols to `sps` samples a symbol, each carrying `pulse` (an FIR stage, a pulse definition) - Matched(pulse, unit): The matched filter of `pulse` (an FIR stage): its taps reversed and conjugated, divided by sum |h|^2 when `unit` (the peak of pulse * matched filter), so a symbol of 1 comes back as 1 ## rpps.wave.stagger - Stagger(rail, delay): Offset one rail of a complex signal by a part of a symbol: the stagger of O-QPSK ## rpps.symbol Modulation: the symbol layer (channel bits <-> symbols, `*` and `/`); the waveform layer is rpps.wave A signal is built from explicit pieces, and a new kind of signal is a new config or a new piece, not a new special case. | Layer | Pieces | Operator | What flows | |---|---|---|---| | **Symbol** (`rp.symbol`; codes from `rp.sequence`) | `Constellation`, `Differential`, `Spread`, `Carriers` | `*` encodes, `/` decodes | bits, symbols, chips (a `Pipe` each; decoding ends in LLRs) | | **Waveform** (`rp.wave`; pulses from `rp.signal.filters.load("pulse/...")`) | `Shape` / `Matched`, `Stagger`, `FM`, `FMDemod` | `+` | symbols and samples (a streaming `Stage` each; any block length) | ### Constellations A constellation is a set of points and the ways of labelling them with bits. PSK, QAM, APSK and ASK are generators (`rp.symbol.PSK(8)`, `rp.symbol.QAM(16)`, `rp.symbol.generate("64QAM")`); anything else is a config file (config/constellation//.json): {"points": [{"mag": 1, "pha": 45}, {"re": 0, "im": 2}, [-1.5, 0]], "maps": [{"map": [0, 1, 3, 2], "comment": "Grey"}]} `maps[i].map[point]` is the value (bits, first bit most significant) the point carries. Points are scaled to unit mean power unless `"normalize": false`. The first map is also turned by every rotation the points allow, with and without spectral inversion (`rp.symbol.load("psk/qpsk", "R090 inverted")`): the maps a receiver has to try when it does not know the carrier phase or the IQ sense. Shapes and definitions are separate: DVB-S2's 16APSK is `rp.symbol.load("apsk/dvbs2_16apsk", rate="3/4")`, not `generate("16APSK")`. ### Differential coding Explicit: `bits * rp.symbol.load("psk/bpsk") * rp.symbol.Differential()` is DBPSK; the constellation's points are then the phase *changes*. 802.11b DQPSK is `psk/qpsk_axes` + `Differential()`; pi/4-DQPSK the ordinary 45 degree `psk/qpsk` + `Differential()`. Bit-level differential coding (NRZ-M, NRZ-I) is `rp.code.Line`. ### Frame structure Known structure among the symbols of a frame (`rpps.symbol.frame`), restarted at each frame start a profile gives it: - `Header`: known symbols then a short code carrying fields (`config/header/physical`, `rp.symbol.load_header("dvbs2_pl")`). Receiving it decodes the fields (every code word tried, soft) and publishes them for the profile; transmitting it builds them. - `Pilots`: a block of pilots after every few slots (DVB-S2: 36 after every 16 slots of 90). - `PhaseScramble`: each symbol turned by a multiple of 90 degrees from a binary sequence (DVB-S2 PL scrambling). ### Recipes Each is exercised in `tests/unit/wave/test_recipes.py` and `tests/unit/wave/test_wave.py`. Shaping needs the symbols' rate, so the bits say theirs: `bits = rp.Data(b, Fs=1e6, sps=1)`. # 802.11b 1 Mb/s: DBPSK, Barker-11, then 11 Mcps shaped as you like chips = bits * rp.symbol.load("psk/bpsk") * rp.symbol.Differential() * rp.symbol.Spread(rp.sequence.load("barker11")) # O-QPSK (half-sine pulses, Q half a symbol late; MSK when the symbols are unit QPSK) halfsine = rp.signal.filters.load("pulse/halfsine/halfsine") wave = bits * rp.symbol.load("psk/qpsk") + rp.wave.Shape(8, halfsine) + rp.wave.Stagger() # 802.15.4 2.4 GHz: 4 bits pick a 32-chip sequence, even chips on I, odd on Q wave = bits * rp.symbol.Spread(rp.sequence.load("ieee802154_2450"), pair=True) + rp.wave.Shape(4, halfsine) + rp.wave.Stagger() # GFSK (Bluetooth LE: BT 0.5, h 0.5): levels from an ASK constellation, a pulse, a frequency modulator c = rp.symbol.ASK(2) wave = bits * c + rp.wave.Shape(8, rp.signal.filters.load("pulse/gaussian/bt0p5")) + rp.wave.FM(0.5, c.min_distance) levels = wave + rp.wave.FMDemod(rp.wave.fm_gain(0.5, 8, c.min_distance)) # then integrate over each symbol and sample ### Notes - BPSK: $P_b = Q(\sqrt{2E_b/N_0}) = \tfrac12 \text{erfc}(\sqrt{E_b/N_0})$; QPSK (Gray) has the same bit error rate per $E_b/N_0$, O-QPSK with matched filters too. - O-QPSK delays Q by half a symbol, so I and Q never change together and the phase moves by at most 90 degrees at a time. With half-sine pulses $p(t) = \sin(\pi t/T)$ on both rails the envelope is constant: it is MSK. ## rpps.symbol.constellation Constellations: a set of points and the bit maps that say which bits each point carries - Constellation(points, maps, mapping, name, normalize): Symbols from bits and back: `bits * c` maps bits to points, `symbols / c` gives one LLR per bit - PSK(M, mapping, offset): M points on the unit circle with a Gray map; offset: the first point's phase [rad], default pi/M (QPSK at 45 degrees), 0 for BPSK (+-1, as `load("psk/bpsk")`) - QAM(M, mapping): Square (4, 16, 64, 256) and cross (32, 128, 512) QAM; square sizes are Gray, cross sizes as close as a cross allows - APSK(M, mapping, rings, ratios): Amplitude-phase keying on rings: `APSK(16)` is 4+12, `APSK(32)` 4+12+16; or give the rings, `APSK(rings=(8, 8))` ratios: radius of the outer rings over the innermost - ASK(M, mapping, bipolar): Amplitude levels on the real axis: `ASK(2)` is on-off keying, `ASK(4)` has four Gray levels; bipolar: symmetric about zero (PAM, the default for M > 2) rather than 0..1 ## rpps.symbol.despread - correlate(x, code, sps): Correlate whole code periods of x (len a multiple of code.length*sps) with every sequence of the code: (periods, code.count). - Despread(code, index, offset, sps): Despread a direct-sequence signal: one value per code period, the correlation with the code ## rpps.symbol.differential - Differential: Differential phase coding of symbols: each one is sent as the phase change from the one before ## rpps.symbol.frame Known structure among the symbols of a frame (rpps.symbol): physical headers, pilot blocks, phase scrambling - turns(n, phase, rotate, cycle, start): exp(j(phase + k*rotate)) in degrees for symbols k = start .. start+n-1, k modulo cycle when given - rotating(bits, constellation, phase, rotate, start, cycle): Symbols of bits on a constellation turned by `phase` degrees, and by `rotate` more each symbol (modulo `cycle` symbols), counting from `start` (pi/2-BPSK: "bpsk", 45, 90, cycle 2) - Header(name, constellation, phase, rotate, known, rows, n, scramble, fields, max_errors, cycle, turn): A physical header at the start of every frame: known symbols, then a code word whose message is the fields - pilot_layout(slots, pilots, slot, every, length): (symbols in the frame, start of each pilot block): `slots` slots of `slot` symbols, a block of `length` pilots after every `every` slots but the last - Pilots(slot, every, length, value, slots, pilots, name): Blocks of known pilot symbols among a frame's data: removed on receive, inserted on transmit - PhaseScramble(sequence, offsets, step, length, name): Every symbol of a frame turned by step * R(i) degrees, R(i) = sum_j 2**(J-1-j) z(i + offsets[j]) for a binary sequence z (rpps.sequence), i counted from the frame start (and from 0 again every `length` symbols when that is set). - Marker(symbols, length, zc, root, shift, name): Known symbols at the start of every frame (a symbol-level sync word: a Zadoff-Chu preamble, a word already mapped) - Puncture(every, at, value, name): Symbols at fixed places of every period of a frame, removed on receive and inserted on transmit: P25's status symbol after every 35 (`every` 36, `at` [35]), counted from the frame start ## rpps.symbol.kernels Batch kernels of the symbol operators: `Demap` of a constellation, `Rotate` of a phase scrambler, `Gather` of a pilot or header remover - Demap(points, labels, maxlog, name, iters, floor): Symbols to per-bit LLRs, as `Constellation.llr`: the noise level of each row (frame) estimated from its own symbols by EM over the points, then log(P(0)/P(1)) per bit (exact, or max-log). - Rotate(phasors, name): Symbols turned by a fixed phasor each position: the batch of a phase scrambler, or any known rotation. - Gather(keep, name): Symbols kept by a fixed selection of positions (pilots and headers removed): `keep(L)` is the boolean mask of a frame of L ## rpps.symbol.mapping Bit maps of a constellation: which value (bits, first bit most significant) each point carries, and the maps a receiver that does not know the carrier phase or the IQ sense has to try (every rotation the constellation allows, with and without spectral inversion) - Mapping(map, comment, turn, tags): Constellation map - symmetries(points): Every (rotation [rad], conjugated) that maps the constellation onto itself, as (angle, flip, permutation) A flip (spectral inversion) is applied first, then the rotation. - bit_rotations(points, labels, bits): A constellation's turns that are bit swaps and inversions. - expand_maps(points, maps): The given maps, then the first one turned by every rotation the constellation allows and spectrally inverted (conjugated) with each. - hard_bits(y, pts, labels): Hard bits of symbols y: the labels (values, first bit most significant) of the nearest points, as uint8 bits ## rpps.symbol.modulation - Modulation(): Modulation parent class ## rpps.symbol.ofdm - Carriers(n_fft, used, pilots): OFDM carrier allocation, the symbol-transform part of OFDM: data symbols <-> the carrier values of each OFDM symbol ## rpps.symbol.serial Constellations: config/constellation/[/].json, loaded with `rp.symbol.load("QPSK")`; physical headers: config/header/physical/.json, `rp.symbol.load_header("dvbs2_pl")` - load_header(name, **params): A physical header definition: `load_header("dvbs2_pl")` (config/header/physical) - ls(blind): List available modulation types: {category: [names]} - load_or_generate(name, mapping): A definition named `name`, else the shape `generate` makes of it: for names that come out of a detector ("8PSK", "16QAM"), where either can turn up. - init(name, obj): Initialize modulation - generate(name): Make a constellation from its name: "16QAM", "QAM64", "8PSK", "16APSK", "4ASK", "OOK"... (no definition file) - load(ref, mapping, **params): Load a constellation definition, config/constellation//.json: `load("psk/qpsk")`, `load("apsk/dvbs2_16apsk", rate="3/4")` (a bare name works while unique). ## rpps.symbol.shapes Constellation generators: points (unit mean power) and the labels that go with them - gray(n): Gray code of integers - psk(M, offset): M points round the unit circle, counter-clockwise from `offset` (default: pi/M, so QPSK sits at 45 degrees; BPSK at 0, on the real axis, as config/constellation/psk/bpsk). - ask(M, bipolar): M amplitudes, evenly spaced, on the real axis (bipolar: -1..1 like PAM, otherwise 0..1 like OOK for M=2). - qam(M): Square (4, 16, 64, 256...) or cross (32, 128, 512...) QAM, labels Gray per axis - apsk(rings, ratios, phases): Amplitude-phase keying on concentric rings ## rpps.symbol.spread - Spread(code, pair): Direct-sequence spreading as an operator: symbols (or bits) to chips and back, one sample per chip (shape and upsample them with the waveform stages) ## rpps.code Code transform: channel bits <-> data bits FEC encoders and decoders, interleaving, rate matching, scrambling (`code.scram`), line codes (`Line`: NRZI, Manchester, inversion), sync markers among channel bits (`Marker`), and `Uncoded` for links with no FEC. Each step takes either channel or data bits, because a code transform is often several steps. ## rpps.code.alist LDPC parity-check matrices in MacKay's alist format (what GNU Radio's gr-fec and most LDPC tools read and write) - read_alist(path): (n, checks): code length and, for each parity check, the bit positions (0-based) it covers - import_alist(path, name, dest, **fields): Definition of the LDPC code in an alist file. ## rpps.code.coding Coding parent classes - Decision: Coding decision type: does the decoder get hard bits or LLRs - Coding(e_impl, d_impl): Coding parent class - puncture_period(code): Channel bits in one period of a convolutional code's puncture pattern (n, the outputs per step, when unpunctured): the alignments a decoder can start at. - mismatch(code, hard): Decode hard channel bits, encode the decision again and compare: (bits that differ, bits compared). - mismatch_batch(code, hard): mismatch() of each row of hard (W, L), decoded together (decode_batch where the decoder has it): (differing bits (W,), bits compared) - cached(ref): A definition loaded once per process and shared (a DVB-S2 LDPC code takes a moment to build): what `control` swaps in, and what the blind tools try: `rp.code.cached("conv/k7_171_133/3_4")` - Block - Convolutional: Parent convolutional coding: separate encoder ("encode") and decoder ("decode") implementations - Interleaver ## rpps.code.factory Codes from their parameters, without a definition file: `rp.code.Hamming(7, 4)`, `rp.code.RS(255, 223)`... - Hamming(n, k, decoder): Hamming code: n = 2**r - 1, k = n - r. - Repetition(count, decoder): Each bit sent `count` times, decoded by majority (or by summing LLRs) - RS(n, k, m, poly, fcr, prim, puncture, decoder): Reed-Solomon over GF(2**m). - Cyclic(n, k, poly, extend, shorten, t, decoder): Binary cyclic code from its generator polynomial (bit i = coefficient of x^i), message first - Golay(n, decoder): Golay (23,12) or extended Golay (24,12), g(x) = 0xC75 - Conv(generators, constraint, puncture, decoder, termination): Rate 1/n convolutional code. ## rpps.code.kernels Batch kernels of the code operators: `BlockDecode` of a block code or interleaver, `XorMask` of an additive scrambler - BlockDecode(coder, block, soft, category, rep, name): A decoder or deinterleaver of whole blocks, over a batch: the frames' blocks go through the coder in one call (a block code's decoder already runs its codewords on several threads, so a batch is more of them at once, not more calls). - XorMask(mask, category, rep, name): Bits XOR a fixed mask repeated from the start of each frame (a scrambler restarted every `len(mask)` bits). - LdpcDecode(coder, block, soft, category, rep, name): `BlockDecode` of a layered min-sum LDPC code that decodes on the device it is given: the batch's codewords in one run of launches, the graph uploaded once. - Identity(category, name): A code or interleaver that a frame's parameters switch off (`control(name=None)`): the items pass as they are, now the code's category, as the operator gives them - Permute(perm, coder, block, soft, category, rep, name): `BlockDecode` of a block interleaver that is a permutation: every block of a row gathered by one index, on whichever `xp` it is given (the index goes to a device once). - permutation_of(coder, block): The index a block deinterleaver gathers with (decoding positions 0 .. block-1), or None when it is not a pure permutation (it changes values, or loses some) - BchDecode(coder, block, soft, category, rep, name): `BlockDecode` of a binary BCH code (`bchgf`) that finds the errors on the device it is given: every codeword's syndromes in one launch; only the words that have errors (few, after an LDPC code) come to the host to be located (Berlekamp-Massey and Chien, as the host decoder), and their bits are flipped on the device. ## rpps.code.line Line codes: bits <-> bits, one step of the code transform, by name - Line(name) ## rpps.code.marker A sync marker among channel bits: a known word before each block of `length` bits (CCSDS ASM before each frame) - Marker(word, bits, length, order) ## rpps.code.serial Code definitions, two resources: config/fec///.json (`rp.code.load("block/rs/204_188")`) and config/interleave//.json (`rp.code.load("interleave/forney/12_17")`) - root(): Directory holding the coding definitions - ls(path, blind): List available FEC definitions by family: {"block/rs": [names], "conv/dvbs": [names], ...} - names(kind, sub, path, blind): References of the definitions of a kind ("block", "conv", "interleave"), as `load(kind, ref)` takes them ("rs/204_188"), across families or just one - init(name, obj, decoder): Initialize coding. - locate(ref, path): (file, kind, name) of a definition: `ref` is "/" ("block/rs/204_188", "interleave/forney/12_17"), or a bare name one definition of any kind has. - mother(generator, constraint): The configured mother code (fec/conv/.json) with these generators, as "k7_171_133", or None: what a found punctured code extends - find(ref, path): File of a definition (see `locate`) - load(ref, path, decoder, **params): Load a code: `load("block/rs/204_188")`, `load("conv/k7_171_133/3_4")`, `load("interleave/forney/12_17")` (config/fec//..., config/interleave/...; or below `path` instead of the shipped config) ## rpps.code.uncoded - Uncoded: No channel code: the channel bits are the data bits. ## rpps.code.scram Scramblers, a step of the code transform: additive (a sequence of rpps.sequence XOR'd in) and self-synchronizing (feedthrough) ## rpps.code.scram.scrambler Scramblers: how a sequence is applied to bits (the `scramble` resource; the sequences are rpps.sequence) - Scram(): Scrambler parent class - Feedthrough(scram_lfsr, descram_lfsr): Feedthrough (self-synchronizing) scrambler: the scrambled bits go through the register, so the keystream depends on the data. - Additive(sequence, frame, period): Additive (synchronous) scrambler: data XOR a sequence that does not depend on the data (rpps.sequence) ## rpps.code.scram.serial Scrambler definitions: config/scramble//.json, loaded with `rp.code.scram.load("dvb_energy")` - ls(blind): The scramblers there are: {type: [names]} - init(name, obj): A scrambler from a definition object - load(name, **params): Load a scrambler by name: `load("dvb_energy")`, `load("ble_whiten", channel=37)`. ## rpps.code.types Code types: the FEC encoders and decoders the definitions in config/fec and config/interleave build A code type subclasses `rpps.code.types._code._code` and defines `_decode(x, ...) -> (output, errors per codeword or None)`, keeping nothing of the call on itself, so one loaded (cached) code decodes on several threads at once. Soft or path outputs are methods that return them too (`app` of BCJR and turbo, `paths` of fsm), never attributes. ### A trellis, worked The rate 1/2, constraint length 3 code with generators 101 and 111 (state = the last two input bits): | State | In | Out | Next | |---|---|---|---| | 00 | 0 | 00 | 00 | | | 1 | 11 | 10 | | 01 | 0 | 11 | 00 | | | 1 | 00 | 10 | | 10 | 0 | 01 | 01 | | | 1 | 10 | 11 | | 11 | 0 | 10 | 01 | | | 1 | 01 | 11 | ```mermaid graph LR S00((00)) -- 0/00 --> T00((00)) S00 -- 1/11 --> T10((10)) S01((01)) -- 0/11 --> T00 S01 -- 1/00 --> T10 S10((10)) -- 0/01 --> T01((01)) S10 -- 1/10 --> T11((11)) S11((11)) -- 0/10 --> T01 S11 -- 1/01 --> T11 ``` `fsm` holds such tables for any code (`output[s][u]`, `next[s][u]`); `viterbi` and `bcjr` decode on them. ## rpps.code.types.bchgf - bchgf(log, n, k, m, poly, t): Binary BCH code over GF(2^m), shortened to (n, k), as in DVB-S2 (m=16, or 14 for short frames) ## rpps.code.types.conv - termination_of(obj): A definition's "termination": "zero" | "tailbiting" | "truncated" (the default) - generators_of(obj): (den, K) generator rows of a definition. - conv(log, num, den, generator, constraint, puncture, termination, invert): Convolutional encoder, rate 1/n. ## rpps.code.types.cyclic - cyclic(log, n, k, poly, extend, shorten, t): Binary cyclic code from its generator polynomial, systematic with the message first: Golay, Hamming, BCH... ## rpps.code.types.expr - codebook(bits, k): Every codeword (2^k, n) of codeword-bit expressions over m0..m{k-1} (and the bits before, c0..), message i's bits MSB first - affine(book, k): (G, offset) when every codeword is offset + m G over GF(2), else None - expr(log, book, t): A small block code whose codeword bits are expressions of the message bits: "k", "bits": one expression per codeword bit over m0..m{k-1} and the bits before it (c0, c1...), with ^ & | ~ and constants ## rpps.code.types.fsm - fsm(log, k, n, next_state, output, start, end, tail, symbols, length): Trellis code given as a finite state machine: P25's 1/2 and 3/4 rate trellis codes, ATSC's 8VSB trellis code ## rpps.code.types.interleave - forney(log, I, M, symbol): Forney convolutional interleaver: I branches, branch j delays by j*M symbols (deinterleaver: (I-1-j)*M) - block_interleaver(log, perm, mapping, symbol): Block interleaver: a fixed permutation of each block of `n` items of `symbol` bits (dibits: symbol=2) - rowcol(length, cols, col_perm, fill, row_perm): `from` permutation of a row-column interleaver: written by rows (dummies first, or last with fill="back"), columns permuted by col_perm (rows by row_perm), read by columns; dummy positions dropped ## rpps.code.types.ira - ira_checks(n, k, table, group): Parity checks of a DVB-S2 style irregular repeat-accumulate LDPC code from its address table - ira_encode(bits, n, k, table, group): Systematic encoder for the same construction: [information | parity] ## rpps.code.types.layout Where a block code's bits go in the word sent, and what is done to them on the way: keys of any block definition - layout_perm(spec, n): `to` map of a layout spec: codeword bit j goes to sent position perm[j], for an n-bit word - xor_mask(spec, n) - arranged(log, inner, layout, xor, extend, dec, append): A block code with check bits appended (`append`, `extend`), its bits placed (`layout`) and masked (`xor`) as sent. ## rpps.code.types.ldpc - gallager(n, wc, wr, seed): Regular (wc, wr) parity-check matrix by Gallager's construction. - qc_checks(base, z): The checks of a quasi-cyclic code: (n, checks) from a base matrix of shifts (an entry s >= 0 is the z x z identity shifted right by s: row r of the block has its 1 at column (r + s) % z; -1 or None is a zero block) - ldpc(log, n, checks, k, systematic_pos, iters, alpha): Linear code defined by sparse parity checks, decoded by belief propagation (normalised min-sum or sum-product) ## rpps.code.types.linear - parity_rows(parity, n, k): The (k, n-k) parity block of parity equations: parity bit j is the XOR of the message bits parity[j] lists - extended(G, H): (G, H) with an overall parity bit after the codeword: each generator row gets its weight's parity, and the check matrix a row of ones over every bit - linear(log, generator, check): Linear block code from its matrices, systematic with the message first. ## rpps.code.types.nr_ldpc 5G NR LDPC code with its rate matching (3GPP TS 38.212 5.2.2, 5.3.2, 5.4.2): one code block, K' bits to E bits - set_of(Z) - lifting(kp, kb): The smallest Z of any set with kb Z >= K' - kb_of(bg, B) - base_graph(A, R): The base graph of a transport block of A bits at code rate R (7.2.2) - segment(B, bg): Code block segmentation (5.2.2) of B bits (the transport block and its CRC): (C blocks, K' bits each with their CRC-24B when C > 1, K bits after the filler, Z) - nr_ldpc(log, bg, graph, kp, e, z, kb, rv, qm, ncb, iters, alpha): One 5G NR LDPC code block (see the module) ## rpps.code.types.nr_polar 5G NR polar code with its rate matching (3GPP TS 38.212 5.3.1, 5.4.1): K bits, CRC included, to E bits - sequence(N): Bit indices below N from least to most reliable (5.3.1.2) - input_pattern(K): Pi(k) of the input interleaver for K bits (5.3.1.1) - code_size(K, E, nmax): n of N = 2^n (5.3.1) - subblock(N): J(n): the coded bit the sub-block interleaver puts at n (5.4.1.1) - triangle(E): The coded-bit interleaver (5.4.1.3): f_k = e_order[k] - nr_polar(log, K, E, nmax, interleave, bil, crc, ones, size, mask): The 5G NR polar code of K bits sent as E (see the module) ## rpps.code.types.polar Polar codes (Arikan): encoding, successive cancellation (SC) and list decoding (SCL), CRC-aided - transform(N): G = F^(x n) for N = 2^n, uint8 - encode_u(u): x = u G for rows u (..., N), by the butterflies (N log N XORs) - pw_order(N): Positions from least to most reliable by polarization weight (sum of 2^(j/4) over the index's set bits j: the beta-expansion 3GPP's NR sequence follows; SNR-independent) - bhattacharyya_order(N, design_db): Positions from least to most reliable by the Bhattacharyya parameter on a BI-AWGN channel at Es/N0 design_db (Z = exp(-Es/N0) a channel, then 2Z - Z^2 / Z^2 down the tree, the index's top bit first) - box(a, b): LLR of the parity of two bits (exact box-plus) - sc(llr, decide): Successive-cancellation decoding of frames (W, N) of LLRs, every frame at once. - scl(llr, frozen, size): List decoding of frames (W, N) of LLRs: the `size` best paths of each frame, best first. - polar(log, n, k, frozen, size, crc): A polar code (see the module): `info` the information positions, `crc` the CRC the last bits of the message carry ## rpps.code.types.product - product(log, rows, cols, reserved, lead, iters, offset, chase): Product code (block product turbo code, BPTC): message in a k2 x k1 matrix, every row encoded with the row code (n1, k1), then every column (parity columns too) with the column code (n2, k2); sent row by row ## rpps.code.types.ratematch - ratematch(log, mode, length, out, rv, ncb): LTE rate matching (3GPP TS 36.212 5.1.4): three coded streams -> E bits through a circular buffer ## rpps.code.types.repeat - repeat(log, count) ## rpps.code.types.rm Reed-Muller codes RM(r, m): the evaluations of every Boolean polynomial of degree at most r in m variables - monomials(r, m): The variable sets of the monomials of degree <= r, in message order - rm(log, r, m) ## rpps.code.types.rs - rs(log, num, den, m, poly, fcr, prim, puncture, basis, beta): Reed-Solomon code over GF(2^m), shortened to (n, k): symbols are bytes for m=8 ## rpps.code.types.syndrome - syndrome(log, G, H, t): Hard decoder of a linear block code by syndrome lookup: corrects every pattern of up to `t` bit errors - min_distance_t(G): (d_min - 1)//2 of the code generated by G, from all its codewords ## rpps.code.types.trellis Trellis (BCJR / MAP) decoding - Trellis(next_state, label): Sections of a trellis - bcjr(tr, llr, start, end, maxlog): Forward-backward over a trellis - bcjr_conv(log, num, den, constraint, generator, puncture, termination, maxlog, hard_llr): BCJR (MAP) decoder for feed-forward convolutional codes: same definition as `viterbi` - trellis(log, H, maxlog, hard_llr): Maximum a-posteriori decoder for a linear block code, on its syndrome trellis ## rpps.code.types.turbo - qpp(K, f1, f2): Quadratic permutation polynomial interleaver: pi(i) = (f1 i + f2 i^2) mod K - rsc(g0, g1, K): Recursive systematic convolutional code: feedback g0 and feedforward g1 over K taps (D^0 first, octal as usual: LTE g0 = 0o13 = 1 + D^2 + D^3, g1 = 0o15 = 1 + D + D^3). - turbo(log, length, g0, g1, constraint, qpp_f, iters, scale, maxlog): Parallel concatenated (turbo) code, LTE layout (3GPP TS 36.212 5.1.3.2) - turbo_mux(log, length, g0, forward, constraint, perm, outputs, iters, scale, maxlog): Parallel concatenated code with its outputs multiplexed bit time by bit time (CCSDS 131.0-B 6): the layout `turbo` takes when a definition gives "outputs" ## rpps.code.types.viterbi - viterbi(log, num, den, constraint, generator, puncture, termination, invert): Viterbi decoder for feed-forward convolutional codes (rate 1/n, any constraint length) ## rpps.link Link transform: data bits <-> packets: framing (HDLC, byte stuffing) and integrity checks (CRC, composite, checksum), defined in config/crc, config/frame and config/header/link. Decoding refuses channel bits: decode them first (or `rp.code.Uncoded()` for no FEC) A link header decodes packets too: a header inside a frame's payload (`{"link": "frame"}` then `{"link": "header"}`, the frame step's `frame` and `frame_bits` driving the header's `frame` and `length`) strips a frame's own header and reads it. Packets that cross frames (`rpps.link.packets`, `{"link": "packets"}`): a stream of packets in fixed frames' data fields, cut back out by a pointer (CCSDS first header pointer, DVB-S2 SYNCD) and each packet's length, per channel. Captures (`rpps.link.capture`): a profile's messages as packets of a link type (config/linktype), for Wireshark and interfaces (rpps.source.PcapSink, rpps.source.Tun), each rule with its inverse for transmitting. ## rpps.link.bytestuff - bytestuff(log, flag, escape, escapes, xor, escaped, fcs, refin, min_bytes): Byte-stuffed framing (SLIP, KISS, asynchronous PPP): a flag byte between frames, and an escape byte before any flag or escape byte inside one, defined by config (see config/frame) ## rpps.link.capture Captures: decoded frames as packets of a link type, for Wireshark (rpps.source.PcapSink) or an interface (rpps.source.Tun) - LinkType(name, dlt, arphrd, proto, dissector, fcs, signature, **kw): A link type (config/linktype): its pcap number (`dlt`), the Linux ARPHRD a TUN takes for it (`arphrd`, `proto`: the EtherType a TUN's packet information says), Wireshark's dissector, what it says of an FCS, and a signature - linktype(name): A link type by name: `linktype("ieee802_15_4")` (config/linktype) - convert(data, src, dst): A packet of link type `src` as one of link type `dst`, where one is the other with transforms (a link type's "from": {other: [transforms]}, as a capture rule's: 802.15.4 with FCS is 802.15.4 without, its FCS appended; AX.25 with its KISS byte is AX.25 with a 0 before). - by_dlt(dlt): The link type of a pcap link type number (None: not one of config/linktype) - linktypes(): Every link type's name - find(data, names, lo, hi, least): (offset, LinkType) where a frame of one of these link types starts in `data`: the best score, the first offset of it, from `lo` to `hi`; (None, None) when none scores `least` - Packet(linktype, data, profile, kind, check, crc_ok, sample, time, freq, quality, fields): One captured frame: its link type and bytes, and what it was (from its message) - exported_pdu(payload, dissector, protocol, info): Wireshark's exported PDU (LINKTYPE_WIRESHARK_UPPER_PDU): tags (dissector, protocol and info columns), the end tag, then the payload. - unexported_pdu(data): (dissector, payload) of an exported PDU - Capture(spec, where, params): One message kind's capture rule (see module): `packet(message)` the Packet (None: dropped), `unpacket(bytes)` the payload bytes and fields to transmit - Captures(spec, where, params): A profile's capture rules, by message kind (`"capture"` in a profile; see module). ## rpps.link.check Composite checks: a check field built from CRCs over transformed views of the message - register(name): Register a byte transform a composite check's parts can name in "input": fn(data uint8 array, **args) -> uint8 array - Part(crc, inputs, outputs, name): One CRC over a transformed view of the message - composite(log, parts, combine, check, name): A check from several CRC parts, concatenated or XORed (see the module docstring) ## rpps.link.checksum Checksums that are not CRCs: sums, ones' complement (Internet), Fletcher, Adler, XOR (LRC) - checksum(log, algorithm, width, word, endian, negate, xorout, refin, order, check, name) ## rpps.link.crc - crc(log, width, poly, init, refin, refout, xorout, check): Parametrised CRC (Rocksoft model: width, poly, init, refin, refout, xorout), any width from 1 to 64 ## rpps.link.encap Encapsulation parent classes - Encap: Parent of framing / integrity-check definitions: the link transform, data bits <-> packets - CRC: CRC defined by config: width, poly, init, refin, refout, xorout (hex strings or ints), check value; or a composite check (type "composite": CRC parts over transformed views of the message, rpps.link.check) - Frame: Framing (HDLC: bit stuffing; bytes: byte stuffing, SLIP / KISS / PPP) defined by config; the FCS is another config, `fcs`, from config/crc ## rpps.link.fields Fields: what a frame's bits say, as a definition (link headers, frame payloads, a profile step's messages) - Short: The bits ended before the schema did - Schema(fields, order, name, groups) - mjd_date(mjd): A Modified Julian Date as an ISO date (EN 300 468 annex C) - mjd_of(date): The Modified Julian Date of an ISO date - dvb_text(data): A DVB string (EN 300 468 annex A): a first byte below 0x20 names its table (latin-1 stands in for ISO 6937, the default); emphasis codes go, 0x8A is a line break - dvb_bytes(text): A DVB string's bytes: as they are when printable ASCII, else UTF-8 after its table byte (0x15) ## rpps.link.gse Generic Stream Encapsulation (ETSI TS 102 606-1): PDUs in the data fields of DVB-S2 BBFRAMEs - pack(pdus, size, frag_ids): Data fields of `size` bytes carrying the PDUs [(protocol type, payload bytes) or (protocol, payload, label bytes)] in GSE packets: whole where they fit, else fragmented (the first fragment as long as the field allows, the rest in the next fields), every field padded with zeros - GSE(protocols, name) ## rpps.link.hdlc - hdlc(log, fcs, flag, stuff, nrzi, min_bytes): HDLC framing: flags, bit stuffing and an FCS, defined by config (see config/frame) ## rpps.link.header Link headers: fields, a CRC, and the payload they announce (rpps.profile.control) - Header(name, fields, order, crc, payload, preamble, framed, fcs, payload_order, payload_fields, groups) ## rpps.link.kernels Batch kernels of the link operators: `HeaderDecode` of a framed header (rpps.parallel) - HeaderDecode(op, length): A framed header (`rpps.link.header.Header`) of fixed size, one frame a row: its fields and CRC read, and the payload they announce given (`payload`, at most the frame's `length` less the header). ## rpps.link.packets Packets that cross frames: a stream of packets carried in the data fields of fixed frames, cut back into packets - Packets(spec, name): Packets cut from frames' data fields (see module) ## rpps.link.serial Link definitions, one resource each: config/crc, config/frame, config/header/link; `rp.link.load("crc/crc32_mpeg2")` - root(): Directory holding the encapsulation definitions - ls(path, blind): List available definitions: {category: [names]} - load(ref, path, **params): Load a link definition by "/": `load("crc/crc32_mpeg2")`, `load("frame/hdlc")`, `load("header/ble_adv")` (config//.json; a link header is config/header/link/.json), or below `path`. ## rpps.grid Resource grids of OFDM systems: cell search, the grid of each subframe with its channel estimates, and the physical channels read off it `grid` steps in a profile take an OFDM system's samples to frames of its resource grid, and its physical channels read them, a branch each (`rpps.profile.branch`). Formula mappings are code here; tables and sequences are definitions. - `lte` (FDD and TDD): `LteCell` (PSS/SSS cell search; `search` lists the cells on a carrier), `LteGrid` (a frame per subframe, with each port's channel), `PBCH` (ports, MIB), `PCFICH` (CFI), `PDCCH` (DCI 1A, 1C), `PDSCH` (SIB1, SI), and `tx`. The profile is `lte/downlink`. - `nr` (FR1, 15 and 30 kHz): `NrCell` (PSS over a LEO pass's offsets, each SS/PBCH block tracked), `NrGrid` (a frame per subframe), `PBCH`, `PDCCH` (CORESET 0), `PDSCH` (LDPC, SIB1), and `tx` (with `leo`). Not every cell applies the per-symbol phase of 38.211 5.4: with `fc` the PDSCH tries both. The profile is `nr/downlink`. ## rpps.grid.lte LTE downlink (FDD and TDD): cell search, the resource grid with its channel estimates, and the physical channels to SIB1 ## rpps.grid.lte.cell LTE cell search and frame timing (3GPP TS 36.211 6.11): a stream of samples to a stream of whole half-frames - pss(u): The PSS of root u: Zadoff-Chu of length 63 without its middle element (it would sit on DC) - bins62(nfft) - pss_time(u, nfft) - sss(n_id1, n_id2, half): The 62 SSS values in subframe 0 (half 0) or 5 (half 1) - sss_table(n_id2): (336, 62): every (N_ID1, half) hypothesis, N_ID1 major - search(x, fs, offset, span, resolution, duplex, acquire, max_cells, gate): The cells on a carrier, strongest first, from the start of x - LteCell(offset, span, resolution, acquire, lose, gate, pci, duplex, name): LTE cell search and half-frame timing (see the module) ## rpps.grid.lte.channels LTE downlink physical channels read off LteGrid's frames: PBCH (MIB), PCFICH (CFI), PDCCH (DCI), PDSCH (transport blocks) - tail_biting(llr, K): K bits (CRC included) from soft bits of the 1/3 tail-biting code, rate matched to len(llr) (positive = 0) - tail_biting_batch(llrs, K): `tail_biting` of each of llrs (soft bits of any lengths): (len(llrs), K) bits, the Viterbi of a length in one batch - crc_bits(bits, name) - PBCH(name): The MIB of every subframe 0 (see the module) - PCFICH(ports, name): The CFI of every subframe, once the port count is known (see the module) - PDCCH(rntis, ports, cfi, phich_ng, phich_duration, name): DCIs in the common search space for the RNTIs given (see the module) - PDSCH(ports, cfi, name): The transport block a DCI allocated in its subframe (see the module) ## rpps.grid.lte.grid The LTE resource grid of each subframe, with every port's channel on every resource element - frame_len(n_rb) - n_rb_of(frame_items): N_RB from the frame length - unpack(frame): (header dict, G (14, 12 N_RB), H (4, 14, 12 N_RB)) of one frame: views, no copies - frames(x, n_rb): The whole frames of a block: (n, frame_len) view - LteGrid(n_rb, cell): Subframes of samples to grid frames (see the module). ## rpps.grid.lte.phy LTE downlink physical layer: numerology, reference signals, resource-element maps, transmit diversity (3GPP TS 36.211) - cp_lengths(nfft): (first symbol's prefix, the others') in samples at this FFT size - subframe_len(nfft) - symbol_starts(nfft): The useful part's first sample of the 14 symbols of a subframe, from the subframe's first sample - sc_bin(k, nfft, n_rb): FFT bin of subcarrier k = 0..12 N_RB - 1 (the DC bin skipped) - grid(x, nfft, n_rb, early): The (14, 12 N_RB) grid of one subframe's samples. - ramp(n, start, step): e^(-j 2 pi (start + step k)) for k = 0..n-1 (cycles): a derotation, complex64. - gold(c_init, n): c(0..n-1) of 7.2 (the rpps definition sequence/recurrence/lte_gold); lengths are taken in steps, so a channel's sequence of any length reuses one made before - sign(c): Bits to the signs a soft bit is multiplied by to descramble it: 0 -> +1, 1 -> -1 - crs_values(pci, ns, l, n_rb): r(m) for m = 0..2 N_RB - 1, of cell `pci`, slot ns (0..19), symbol l of the slot (normal prefix) - crs_shift(port, ns, l): v of 6.10.1.2, before v_shift = PCI mod 6 - crs_mask(pci, n_rb, ports): (14, 12 N_RB) bool: where the reference signals of ports 0..ports-1 are (no data there) - channel(G, pci, n_rb, sf, ports): H (4, 14, 12 N_RB): each port's channel on every resource element of subframe sf's grid G. Least squares at the reference signals, linear in frequency between them (constant past the edges), and a straight line in time through the port's symbols of the subframe (it barely moves in 1 ms). - undo_diversity(G, H, k, l, ports): The symbols sent on resource elements (k, l), in that order, for 1, 2 or 4 transmit ports. - soft_bits(z): QPSK (b(2i) on the real part, b(2i+1) on the imaginary, a 0 positive): soft bits, positive = 0 - qpskness(z): -Re(sum z^4) / sum |z|^4: 1 for QPSK on the diagonals, ~0 for noise or the wrong equalizer - pbch_res(pci, n_rb): (k, l) of the 240 PBCH resource elements of subframe 0: slot 1 symbols 0-3, the 72 central subcarriers, around the reference signals of four ports whatever the cell has - parse_mib(b): The 24 MIB bits (36.331 6.2.2): dl-Bandwidth 3, phich-Config 3, the SFN's 8 MSBs, then 10 bits of later releases - reg_res(k0, l, pci, ports): The four resource elements (k, l) of the REG from subcarrier k0 - pcfich_regs(pci, n_rb) - pcfich_res(pci, n_rb, ports) - short_phich(duplex, sf): TDD subframes 1 and 6: an extended PHICH of two symbols (Table 6.9.3-1) - phich_regs(pci, n_rb, groups, ports, extended, short): The PHICH's REGs (k0, l), three a group (6.9.3) - control_regs(pci, n_rb, symbols, phich_groups, ports, extended, short): The PDCCH's REGs (k0, l) - control_symbols(cfi, n_rb): OFDM symbols of the control region: the CFI, one more at 10 resource blocks or fewer (Table 6.7-1) - phich_groups(ng, n_rb, mi): PHICH groups - control_res(pci, n_rb, symbols, phich_groups_, ports, extended, short): (k, l) of the PDCCH REGs' resource elements in order (control_regs, each REG's four) - subblock_perm(n): The 32-column sub-block interleaver's read-out order of n items (36.212 5.1.4.2.1, dummies left out) - riv_bits(n_rb) - dci_1a_size(n_rb, duplex): Format 1A's payload bits (5.3.3.1.3) - parse_1a(bits, n_rb, duplex): DCI 1A's fields, with an SI-, P- or RA-RNTI - riv_decode(riv, n_rb): (first resource block, count) of a contiguous allocation (36.213 7.1.6.3) - step_1c(n_rb): N_RB^step of format 1C's allocation (36.213 Table 7.1.6.3-1) - dci_1c_size(n_rb): Format 1C's payload bits - parse_1c(bits, n_rb) - gaps(n_rb, second): (N_gap, N_VRB, interleaving unit) of a gap (Table 6.2.3.2-1) - dvrb_map(n_rb, second): (2, N_VRB): each distributed block's physical block, per slot - tbs_table(name): {I_TBS: [TBS, ...]} of a table/lte definition - allocation(d, n_rb): (blocks, TBS) of a DCI, or None - pdsch_res(blocks, symbols, pci, sf, n_rb, ports, duplex): (k, l) of a PDSCH's elements ## rpps.grid.lte.tx An LTE downlink to test the receive side with: cell signals, MIB, CFI, a DCI 1A to the SI-RNTI and its PDSCH - qpsk(bits) - diversity(x, ports): (ports, len(x)): what each port sends on the resource elements of a channel, in order (6.3.4.3) - riv(first, count, n_rb): The resource indication value of a contiguous allocation (36.213 7.1.6.3) - mib(n_rb, sfn, phich_ng, phich_duration) - tail_biting_encode(bits, E) - dci_1a(n_rb, first, count, mcs, rv, tpc, distributed, gap, duplex): DCI 1A's payload bits - dci_1c(n_rb, first, count, mcs, gap): DCI 1C's payload bits - subframe(pci, sf, sfn, n_rb, ports, cfi, phich_ng, dci, sib, rv, rnti, cce, L, fmt, duplex, uldl, extended): (ports, 14, 12 N_RB): what each port sends in a subframe - modulate(X, nfft): (ports, samples): each port's grid (ports, 14 n, 12 N_RB) to samples, a subframe per 14 symbols - downlink(pci, ports, n_rb, frames, sib, mcs, first, count, cfi, phich_ng, sfn0, L, fmt, distributed, gap, rv, duplex, uldl, extended): (ports, samples) of a downlink at the rate of n_rb's FFT - channel(y, gains, cfo, fs, delay, snr_db, seed): The ports' samples (ports, n) through a flat gain each, summed; then a carrier offset [Hz at fs], `delay` samples of noise before, and noise at snr_db (per sample, of the summed signal) ## rpps.grid.nr 5G NR downlink (FR1, 15 and 30 kHz), with LEO non-terrestrial Doppler: SS/PBCH block, MIB, CORESET 0, DCI 1_0, SIB1 ## rpps.grid.nr.cell 5G NR cell search and slot timing through LEO Doppler (38.211 7.4.2-7.4.3, 38.213 4.1): samples to whole slots - pss_time(n_id2, nfft) - NrCell(offset, span, resolution, period, acquire, lose, gate, fc, scs, pattern, name): NR cell search and slot timing, LEO Doppler tracked (see the module) ## rpps.grid.nr.channels NR downlink channels read off NrGrid's frames: PBCH (MIB), PDCCH (DCI 1_0 in CORESET 0), PDSCH (SIB1) - PBCH(name): The MIB of every SS/PBCH block NrGrid marks (see the module) - PDCCH(rntis, min_bw, name): DCI 1_0 in CORESET 0's Type0 occasions (see the module) - PDSCH(fc, min_bw, name): The transport block a DCI 1_0 allocated (see the module) ## rpps.grid.nr.grid The NR resource grid of each subframe: NrCell's slots to a stream of frames, one a millisecond - frame_len(size) - unpack(frame): (header dict, G (slots, 14, nfft), B (4, 240)) of one frame: views, no copies - NrGrid(cell, period): Slots of samples to grid frames (see the module); cell: the name of NrCell's estimates ## rpps.grid.nr.phy 5G NR downlink physical layer at 15 and 30 kHz subcarriers (FR1): SS/PBCH block, PBCH payload, CORESET 0, PDCCH, PDSCH - mu_of(scs): The numerology of a subcarrier spacing [Hz] - cp_lengths(nfft, mu): (the long prefix, the others') in samples - slot_len(nfft): Samples of a slot, at either spacing - symbol_starts(nfft, mu): The useful part's first sample of a slot's 14 symbols - grid(x, nfft, mu, early): The (14, nfft) grid of a slot's samples, lowest frequency first - symbol_phase(fc, nfft, mu, slot): Undoes the upconversion phase - modulate(G, nfft, mu): Samples of slots from their grids (n*14, nfft), as `grid` reads them - pss(n_id2) - sss(n_id1, n_id2) - sss_table(n_id2) - pbch_dmrs(pci, i_ssb_bar): The 144 PBCH DM-RS symbols of block i_SSB-bar (i_SSB + 4 n_hf below 3 GHz) - ssb_map(pci): (k, l) of the block's PBCH (432) and of its DM-RS (144), in mapping order, k 0-239 and l 0-3 within the block - ssb_bins(nfft): Bin of each of the block's 240 subcarriers - ssb_place(pattern, i_ssb): (slot in the half frame, first symbol in it) of candidate block i_SSB - equalize(G, data, dmrs, ref): (Y conj(H), |H|^2) of the data REs of a grid from the DM-RS - read_pbch(B, pci): The PBCH of a block's grid (4, 240), or None where the CRC fails - payload_scramble(pci, sfn_lsb23): The 32 bits XORed onto the interleaved payload (7.1.2): c(j + v M), M = 29, v the SFN's 3rd and 2nd LSBs - payload_encode(mib, sfn, hrf, k_ssb, pci): The 32 PBCH payload bits (before CRC): the 24 MIB bits (SFN's MSBs in them), the timing bits, interleaved, scrambled - payload_decode(bits, pci): (MIB bits 24, sfn, hrf, k_SSB's MSB) from the 32 payload bits after the CRC - parse_mib(mib): The MIB's fields (38.331 6.2.2) by name (SFN's MSBs left to payload_decode) - build_mib(scs_common, k_ssb, dmrs_pos, coreset0, ss0, barred, intra_freq) - pbch_scramble(pci, v, n): PBCH scrambling (38.211 7.3.3.1) - table(name) - coreset0(index, scs, scs_common, min_bw): CORESET 0 (38.213 13) - type0(index) - coreset0_first_bin(nfft, k_ssb, offset, scs, scs_common): CORESET 0's first bin, or None - type0_slots(ss0, i_ssb, coreset_symbols, mu): (slots n0, n0 + 1), frame parity, first symbol of Type0 occasions - cce_regs(n_rb, symbols, pci, L, R): For each CCE, the (symbol, RB) of its 6 REGs (interleaved mapping, bundles of L = 6, R = 2, shift = cell id) - pdcch_dmrs(pci, slot, symbol, n): The PDCCH DM-RS of a symbol: n values (3 a RB) - dci_10_si_size(n_rb) - parse_dci_10_si(bits, n_rb): DCI format 1_0 with the SI-RNTI (38.212 7.3.1.2.1) - riv(first, count, n) - riv_decode(v, n) - vrb_interleaver(n_rb, bundle): VRB-to-PRB (38.211 7.3.1.6) - tdra(row, dmrs_pos) - dmrs_symbols(mapping, s, l, dmrs_pos): PDSCH DM-RS symbols of the slot: single symbol, dmrs-AdditionalPosition pos2 (Table 7.4.1.1.2-3) - pdsch_dmrs(pci, slot, symbol, n) - mcs(index) - tbs(n_re_prb, n_prb, qm, rate, layers): Transport block size (38.214 5.1.3.2) from the REs a PRB carries in the slot - pdsch_res(c0bin, prbs, s, l, mapping, dmrs_pos, blocks): PDSCH data and DM-RS elements - pdcch_res(c0bin, n_rb, symbols, first_symbol, pci, cce, L): (bins, symbols) of a candidate's data REs in mapping order, and of its DM-RS (bins, symbols, sequence index) - ldpc_for(tbs_bits, rate, E, rv, qm): The code block's LDPC code for a transport block of TBS bits (one code block: K' = TBS + its CRC) - qam(bits, qm): Symbols of bits, Qm 2, 4, 6 (Gray, 38.211 5.1.3-5.1.5) - soft_bits(z, qm, noise): Max-log soft bits (positive = 0) of equalized symbols z (unit channel), Qm 2, 4, 6 ## rpps.grid.nr.tx A 5G NR downlink to test the receive side with, and a LEO satellite pass to put it through - dci_10_si(n_rb, first, count, tdra, mcs, rv, sii, vrb) - sib_size(n_rb_alloc, tdra_row, dmrs_pos, mcs): The TBS of an allocation (what a DCI with these fields carries) - downlink(pci, nfft, frames, sib, ssb, coreset0, ss0, k_ssb, dmrs_pos, mcs, first, count, tdra, L, cce, sfn0, fc, scs, scs_common, pattern, lmax, hrf, vrb, min_bw): Samples of a downlink, scs x nfft a second - awgn(x, snr_db, seed, ref) - orbit(t, altitude): Slant range [m] to a satellite in a circular orbit passing overhead, t seconds from closest approach - doppler(t, fc, altitude): The carrier's Doppler shift [Hz] at t (from closest approach) - leo(y, fs, fc, t0, altitude, delay, taps): y's samples received from a LEO pass starting t0 s from closest approach: delayed by the slant range (less its value at the start) and shifted by the carrier's phase over it; `delay` samples of nothing before ## 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//.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": ""`: 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. ## rpps.profile.branch A profile's receive side that fans out: one trunk, then branches that read the same blocks (rpps.profile) - Exit(params): 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). - take_spec(spec, where): (ranges [(start, end or None)], unit) of a branch's `take`: a list of ranges, or {"ranges": [...], "unit": u} - 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) - 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. - BranchChain(slots, name, entries, branch, bus, profile): One branch's runner: it also hands what its headers publish for other branches to the bus, at trunk positions - BranchRunner(trunk, chains, name, bus, order, frame, exit, owner, take, select, step_id, framed): trunk: the runner of the steps before the branch step (None: none), chains: {name: BranchChain} in order ## rpps.profile.burst A profile around a `{"sync": "burst"}` step: per-burst demodulation (BurstRunner), and burst transmission (BurstTxRunner) - BurstRunner(pre, burst, make_post, name, entry): 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. - BurstTxRunner(make_post, burst_tx, pre, name, entry): The transmit side of a profile with a burst step: a call sends one burst ## rpps.profile.catalogue What a profile needs and gives, before it runs: for a program building a menu (rpps.profile.Decoder uses it too) - ProfileInfo(name, comment, ref, tags, params, requires, given): 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) - requirements(req, values, baud, name): A profile's "requires", evaluated over its param values (and `baud`, for a profile whose rate is open). - info(name, baud, **params): A profile described (ProfileInfo), its requires evaluated with these params (the defaults otherwise) and `baud` - fits(name, baud, bw, Fs, seconds, input, 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) - candidates(names, baud, bw, Fs, seconds, input, tol, limit): [(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 - lineage(name): The profiles `name` extends, nearest first (its file's "extends", as written): [] for one that extends none. - variants(name, limit): 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. - catalogue(): Every profile there is, described (with its defaults), by name ## rpps.profile.control Header-driven control: the control path that runs back up a chain - Table(name, key, columns, rows, only): A table resource: rows of named columns, looked up by the key fields - table(name): Load a table resource by name: `rp.profile.table("dvbs2/modcod")` - Entry(header, obj, where): One entry of a profile's `controls`: the fields of one header step and the parameters they drive (see module) - parse(obj, steps, where): The controls section of a profile, checked against its steps: {header step id: Entry} - PosMap(anchors, r0): How a step's input positions become its output positions: anchors (input, output, rate), from which the output advances `rate` items per input item. - rate_of(op, how): Output items per input item of an operator, in the direction it runs (how: "+" stage, "/" decode, "*" encode). ## rpps.profile.decoder A selected signal's samples to a profile's messages, block by block: for a program that shows what a signal carries - Decoder(name, Fs, offset, cf, baud, bw, sync, fill, kinds, **params): A profile's receiver behind a front end that brings a selected signal to it (see module) - requirements_with(desc, params, baud): A ProfileInfo's requires again, the rate now known ## rpps.profile.encoder Packets to samples through a profile's transmitter: what a capture rule gives on receive, sent back out - Encoder(profile, rate, kind, fields, gap, hop, rate_out, linktype, **params): A profile's transmitter, a packet (or a block of bits) at a time (see module) ## rpps.profile.message Decoded messages: what a profile receives, one record a frame, for a program to show or keep (rpps.profile) - Message(profile, kind, fields, payload, bits, crc_ok, sample, time, freq, quality, check, frame, frame_bits, parts): One decoded frame ## rpps.profile.parallel Where a profile's parallel region starts, and whether it can (rpps.parallel) - Region: 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(step, driven): FRAME when every receive operator of the step is frame scoped (given the parameters a control drives), else STREAM - 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} ## rpps.profile.profile Profiles: one config file per signal, both directions (rpps.profile) - Profile(name, obj, sync, params): A signal: its steps in receive order, built from a definition. - load(name, sync, **params): Load a profile: `rp.profile.load("ieee802154/2450", sps=8)`. - ls(blind): The profiles there are: {family: [modes]} ## rpps.profile.runner Profile runners: a profile's operators on a stream of blocks, with header-driven control - Slot(how, op, step, index): One operator of a runner and its stream positions - Change: Field values on their way to the steps they drive - Runner(slots, name, entries, direction, profile): Operators in order, run on a stream of blocks: `out = runner(block)`; transmitting, `runner(block, fields=...)` ## rpps.profile.steps What each step of a profile builds (rpps.profile) A step is one dict with one category key, `{"": "", ...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) ## rpps.parallel Parallel processing of frames: a profile's frame-parallel region Real time needs more than one core, and later a GPU or FPGA. Once frame sync has found a frame and its header has set the parameters, the rest is per-frame work with no state across frames. A profile marks where that region starts (`"parallel": ""`); `rpps.profile.parallel` refuses a region with stream-scoped steps (`SCOPE = STREAM`), a publishing header or a late change. The unit is the **batch**, not the thread: N frames through one program pays on every target. profile.rx(parallel=rp.parallel.Parallel("thread", workers=4)) -> ParallelRunner front the ordinary Runner, stopped at the region; the changes it resolved cut the input at frame starts Scheduler frames -> batches of one key -> Executor (inline, threads by rows, processes, later GPU / FPGA) -> results in order BatchPlan per key (the header's parameters, the frame's shape): the region's kernels, shapes checked, describe() Kernel a pure function over [N, L] arrays, run(xp, batch); LoopKernel runs frame by frame through the operators - An operator gives its kernel with `op.kernel(params, how)`; a step without one runs through `LoopKernel`, which is also the oracle every kernel is checked against (`tests/unit/parallel/`). Kernels: `symbol.kernels` (`Demap`, `Rotate`, `Gather`), `code.kernels` (`BlockDecode`, `LdpcDecode`, `BchDecode`, `Permute` of an interleaver, `Identity` of a code a frame switches off, `XorMask`), `sync.kernels` (`PilotLine`), `link.kernels` (`HeaderDecode` of a framed header); the protocol is `rpps.base.kernel`. - Kernels belong to generic operators, never a protocol; they use only what numpy and cupy share (`xp`), hold their constants, keep shapes fixed per key, and mark a failed row instead of raising. `BatchPlan.describe()` is data, what a device library or HLS generator would build from. - Processes use `fork` where available, else `spawn` (scripts need a `__main__` guard); each builds its region from a picklable `RegionSteps`. - On `dvbs2/normal` the output equals the serial runner's bit for bit, for any block cut, worker count and batch size. Measure with `python tools/parallel_bench.py 64 4`. - A parallel region's kernels decode inside: each frame result is its message (`"frame"`, `crc_ok` False when dropped), without the header fields a serial runner gives. ### Devices (GPUs) Vendor neutral: CUDA and ROCm/HIP alike, through CuPy (built for either, one API); nothing here names a vendor, and no kernel branches on one. `rpps._accel.device()` gives `(xp, "cuda" | "hip")` or `(numpy, None)`; `Parallel("thread", xp=xp)` runs the region's plans on it (inline or thread executors only: a device does not cross a fork). - **Hand-off.** A batch is stacked on the host and the plan moves it: one upload at its start, one download at its end, and a `to:host` / `to:device` pair around each run of kernels that need numpy (`Kernel.where == "host"`: the decoders, a `LoopKernel`). Every crossing is a kernel, so `BatchPlan.describe()` shows the cost; nothing converts implicitly. Constants go to a device once (`Kernel.const`). `bad`, `why`, `notes` and `code_failed` stay on the host. - **Instructions**, each with the numpy run as its oracle: (1) array code over `xp`, which most kernels are and which runs on CuPy unchanged; (2) hand-written device kernels for what array code does badly, in a portable subset of CUDA C that HIP compiles as it is (no warp intrinsics, no wavefront width assumed), compiled at run time by CuPy (NVRTC or hiprtc) through `rpps.base.kernel.device_functions`: the layered min-sum LDPC decoder (`rpps.code.kernels.LdpcDecode`, a launch per layer over every check and codeword, codewords the fastest axis so accesses are contiguous, the batch compacted as codewords converge), BCH syndromes (`BchDecode`: only the words with errors go to the host to be located, their bits flipped on the device) and the soft demapper (`Demap`, a thread a symbol); (3) `describe()`, the export for an FPGA or HLS flow. A header's fields are read on the host from its few bits (`HeaderDecode`); its payload is cut on the device. On `dvbs2/normal` the whole region stays on a device: one upload, one download. - **Getting results back.** The download at the plan's end gives numpy; results are built on the host and the `Scheduler` puts them in order, as for any executor. A dedicated device executor (later) overlaps the next batch's upload with this one's work on device streams, with `Scheduler(eager=False)` so batches fill. - **Checked without a GPU.** `tests/support/fakedevice.py` is numpy behind an array type that refuses what CuPy refuses (no implicit conversion, no numpy array mixed in); every kernel and the DVB-S2 region run on it in the suite. - **Batches pay on a device.** A layer launch needs thousands of (check, codeword) threads to fill a GPU, so a device wins from about 16 frames a batch (`Parallel(max_batch=)`) and is even at one; measure with `tools/device_bench.py`. On an AMD Radeon 860M (an integrated GPU) against 16 CPU threads with the C++ kernels, 16-64 frames a batch, the machine otherwise idle: LDPC 1.9-2.4x, BCH 2.0-3.6x (clean words; 1.0-1.5x with five errors a word), demap 4.2-8.6x; the DVB-S2 region 2.1x, and the receiver end to end (four workers) 1.1x, the serial front now most of its time. - **The front on a device** (`"device": true`): frame sync, `timing: mat` (16% faster end to end on the 860M), Oerder & Meyr and MPower (1.3x slower: each window waits on the device). Per-sample loops stay on the CPU. ## rpps.parallel.executor Executors: where a parallel region runs (rpps.parallel) - Executor: Runs batches of frames. - InlineExecutor: Run each batch right here, in order. - ThreadExecutor(workers, capacity, min_rows): A pool of threads; a batch is split across them (min_rows: frames a run needs at least). - ProcessExecutor(workers, capacity, min_rows, start_method): A pool of worker processes, each with its own copy of the worker (built there from its recipe, so it takes whatever a worker pickles to: a `PlanWorker`, a module level function). - make(executor, **kw): An executor by name: "inline", "thread" (workers=...). ## rpps.parallel.frame The unit of parallel work: one frame in, one result out (rpps.parallel) - Frame: One frame of a parallel region's input - Result: What a frame gave. ## rpps.parallel.kernel Running a step on a batch when its operators give no kernel (the protocol is rpps.base.kernel; rpps.parallel) - LoopKernel(step, live, direction): A step run one frame at a time through its operators (`Data`, a fresh stream per frame): correct for any operator, and the reference the batch kernels are checked against. - kernel_of(step, live, direction): The kernel of a step with these controlled parameters: the operator's own (`op.kernel(params, how)`) when the step is one operator that has one, else a `LoopKernel` ## rpps.parallel.plan Batch plans: a region's kernels for one set of parameters (rpps.parallel) - BatchPlan(kernels, key) - placed(kernels, xp): `kernels` with the transfers a device needs: in from the host, out to it, and around every host kernel (none on numpy) - compile(steps, params, direction, key, xp): The plan of `steps` (built steps, in order) for `params` ({step id: {parameter: value}}). ## rpps.parallel.runner The parallel runner: a serial front, then a region that runs frame by frame (rpps.parallel) - Parallel(executor, max_batch, xp, **kw): How a parallel region runs: executor ("inline", "thread", or an Executor), its keyword arguments, and batching: frames that arrive in one call (up to max_batch, of one key) run as one batch. - ParallelRunner(slots, name, entries, direction, make_steps, region_first, parallel, profile): A Runner whose slots from `region_slot` on run frame by frame on an executor. ## rpps.parallel.scheduler Scheduler: frames in, batches out to an executor, results back in order (rpps.parallel) - Scheduler(executor, worker, max_batch, eager, **kw) ## rpps.parallel.worker The worker of a parallel region: batches of frames through a plan (rpps.parallel) - RegionSteps(name, obj, sync, params, first): The built steps of a profile's parallel region, as a picklable recipe (a worker in another process builds its own) - PlanWorker(make_steps, direction, xp) ## rpps.sequence The sequence resource: bit and chip sequences, config/sequence//.json One engine for every operator that uses a known sequence: a scrambler XORs one in (`rp.code.scram`), a spreader multiplies by one (`rp.symbol.Spread`), a phase scrambler turns symbols by one (`rp.symbol.PhaseScramble`), a code-phase search looks for one (`rp.sync.acquire_code`). rp.sequence.load("lte_gold", c_init=77).bits(100) a Recurrence: 0/1 bits from any position rp.sequence.load("gps_ca", prn=1).chips a Code: (count, length) of +/-1 A config/sequence//.json is one of: {"type": "recurrence", "sequences": [...], "skip": 1600} see rpps.sequence.recurrence {"type": "chips" | "set" | "gold", ...} see rpps.sequence.code {"type": "word", "word": "0x1ACFFC1D", "bits": 32} a fixed word (sync marker, access address): rpps.sequence.word {"type": "zc", "root": 25, "length": 63, "shift": 0} a Zadoff-Chu sequence: `.symbols` (complex) Complex sequences are computed: `rp.sequence.zadoff_chu(u, N, shift)` (rpps.sequence.zc), the CAZAC roots of LTE and NR (PSS, PRACH, SRS, uplink DM-RS); a "zc" definition names one, as a preamble a profile's `sync frame` step finds. Any value can be a load-time parameter ("params", then {"param": ...} / {"expr": ...}). Chip rates are in "rate" (chips/s). - ls(): The sequences there are: {type folder: [names]} - init(name, obj): A sequence from a definition object - load(name, **params): Load a sequence by name: `load("barker11")`, `load("gps_ca", prn=1)`. ## rpps.sequence.code Chip codes: a set of M chip sequences of N chips each, as +/-1 floats (spreading codes) - Code(name, chips, rate): A set of spreading sequences. ## rpps.sequence.lfsr - LFSR(seed) - fibonacci(seed, taps) - Galois(seed, toggle) - galois_left - galois_right ## rpps.sequence.recurrence Binary sequences defined the way standards define them: a linear recurrence or a shift register, optionally XOR'd with a second one (a Gold sequence), from a seed that is often a load-time parameter - Recurrence(name, components, skip): A binary sequence: its components XOR'd, `skip` outputs dropped first. ## rpps.sequence.word A fixed bit word (a sync marker, an access address, a start-of-frame delimiter), as a sequence definition - word_bits(word, bits, order): The bits of a word in transmission order: from an int (or hex string) of `bits` bits, or from a list/array of bits as given - Word(name, word, bits, order): A known bit word. ## rpps.sequence.zc Zadoff-Chu sequences: constant amplitude, zero periodic autocorrelation (CAZAC) - zadoff_chu(u, N, shift): Root u of length N (u coprime to N, 0 < u < N), cyclically advanced by `shift`: x[(n + shift) mod N] - ZadoffChu(name, root, length, shift): A Zadoff-Chu sequence definition: `symbols` (complex, unit magnitude), `fields` ({"root", "shift"}) ## rpps.plan Burst time plans: when, and on which carrier, each burst of a TDMA / MF-TDMA return link is, and what it is A plan is what a network's controller tells its terminals (DVB-RCS2's SCT, FCT2, BCT and TBTP2, ETSI EN 301 545-2 clause 6.2.2; DVB-RCS's SCT/FCT/TCT/TBTP, EN 301 790): RPPS holds it in that model, whatever it came from. sequences superframe sequences: superframe `count` starts at `start` (clock ticks) and each lasts `duration`; a centre frequency; frames at time and frequency offsets from the superframe's, each of a frame type. Frames are numbered from 0 by ascending lowest burst frequency, then start time, then frame type (EN 301 545-2 7.5.1.1) frame_types a grid of bandwidth-time units (BTUs: `btu` duration in ticks, bandwidth, symbol rate) `time_units` long on each carrier (`grid`: the carriers' offsets from the frame's centre); timeslot sections (tx type, repeat) fill the grid in time on the lowest carrier, then the next (7.5.1.3): a slot is as many BTUs as its tx type's `btus`, a tx type 0 one BTU (a slot an assignment gives a type to) tx_types burst formats: `btus`, `offset` (ticks from the slot's start to the burst's), and the `fields` a profile needs to receive it (its preamble word, modulation, code, length...): what controls drive per burst assignments per (sequence, superframe count): per frame, from slot `offset` on, (assignment id, tx type or 0) in slot order; a tx type given to a single-BTU slot takes as many BTUs as it needs (the TBTP2's rule) `Plan.windows(t0, t1)` lists the bursts' places in a span of clock time; `clock` is ticks a second (27e6: the NCR; 1: seconds). Where a plan comes from: - over the air, from the tables a forward link carries: `rp.plan.builder("dvbrcs2/forward")` takes their decoded messages and gives a Plan, updated as new versions and each superframe's assignments come, and the network clock (rpps.plan.air: a builder is a definition too, mapping the tables onto this model) - a definition, `config/plan//.json`, of the same model (a standard's fixed structure, a test, a plan `rp.analysis.burst` learned from detected bursts): `rp.plan.load("demo/mftdma")` Hopping: a sequence's `hop` ({"channels": [Hz, ...], "carrier": "(k*hop + f) % 37", "params": {"hop": 7}}, or "algorithm": "ble_csa1") moves each frame's centre to a channel, superframe by superframe; a train (bursts at a fixed spacing for a while, then a long pause) is a superframe whose frames start where the train's bursts do: a frame's "repeat": n and "every": ticks make n frames that far apart. A receiver places its bursts in the plan (rpps.sync.Burst `plan`), and a transmitter its bursts on it (rpps.sync.PlanTx). The plan's time is the network's: where its clock is in a capture (the origin) is the receiver's to find (from the forward link's clock reference, or from the bursts' preambles). {"clock": 27e6, "tx_types": {"1": {"btus": 2, "offset": 270, "fields": {"word": "demo_uw1", "units": 1}}}, "frame_types": {"1": {"duration": 2700000, "btu": {"duration": 108000, "bw": 600e3, "symbol_rate": 500e3}, "time_units": 25, "grid": [-1e6, 0, 1e6], "sections": [[1, 36]]}}, "sequences": {"0": {"start": 0, "duration": 2700000, "centre": 0, "count": 0, "frames": [{"type": 1, "start": 0, "offset": 0}]}}} - TxType - Slot - FrameType - Frame - Sequence - Hop(channels, carrier, algorithm, params): Frequency hopping: each frame's centre moved to one of `channels` (Hz from the sequence's centre), the channel an expression of the superframe's index `k` (superframes since the sequence's `count`) and the frame number `f` (`"carrier": "(k*hop) % 37"`, the hop's params in scope), or a registered algorithm (`"algorithm": "ble_csa1"`) - hop_algorithm(name): Register a hopping algorithm: fn(k, f, n_channels, **params) -> channel index - Window: Where one burst may be: its superframe sequence and count, frame number, slot number, carrier [Hz, absolute: the sequence's centre + frame + carrier offsets], its slot's start and length and the burst's start [ticks], symbol rate, tx type and the assignment (id, None when the plan has none) - Plan(clock, tx_types, frame_types, sequences, assignments, name): A burst time plan (see the module). - load(name, **params): A plan definition by name: `rp.plan.load("demo/mftdma")` (config/plan//.json) - init(name, obj): A plan from a definition object - ls(): The plans there are, and the builders: {family: [names]} - builder(name, **params): A new builder of plans from a forward link's tables and clock references (rpps.plan.air): `rp.plan.builder("dvbrcs2/forward")` (config/plan/builder//.json) ## rpps.plan.air Plans from what a forward link says: a definition (`"base": "builder"`, config/plan//.json) maps the tables a forward link carries onto the plan model, and its clock reference packets onto the capture - Builder(name, obj): A plan and a clock from a forward link's messages (see the module). ## rpps.analysis Analysis: blind estimation and measurement at any representation, outside the data path. The tree follows what is analysed, the way config/ and the implementation packages do: - spectrum: what is in a capture and at what rate. find (the signals' boxes at a false-alarm rate, the streaming Finder), signal (the survey: find_signals, Survey), psd, cyclic (symbol rate and carrier lines with a calibrated false alarm, the SCF), scf (every cycle frequency, FRESH), pencil (matrix-pencil lines), waveform (tones, OFDM and which system, bursts, envelope), ofdm_pilots (an OFDM grid and its pilots), burst (TDMA bursts on a shared preamble), separate (two co-channel signals), hopping (frequency hopping) - modulation: what carries the symbols (rate, timing, modulation, offset and phase are rp.sync.detect). cumulants (the constellation's family, blind to noise), fsk (FSK / MSK / GMSK), cpm (GMSK and SOQPSK by a per-survivor detector), pm (residual-carrier PM and its subcarriers), quality (a gate on hard decisions; Es/N0 is rp.sync.quality), impairments (compression, IQ imbalance, phase noise, neighbours), cancel (regenerate and subtract: what hides under a signal) - sequence: what was XOR'd in or spread with. recurrence (every recurrence to degree 24, LFSRs, keystreams), scrambler (self-synchronising and additive scramblers), spread (DSSS chip rate and code) - code: which code. conv (puncture: patterns on a known mother code; rsc: turbo constituents and interleaver; tcm: trellis-coded modulation), block (linear: length, alignment and checks by rank, BCH / cyclic, product; ldpc; rs; polar), interleave (block and Forney interleavers) - framing: how the stream is cut. frames (frame period and unique word on symbols), payload (what decoded bits carry), telemetry (PM telemetry end to end), crc (the CRC frames carry: generator, init, xorout, what it covers), fields (what each bit of a header is), marked (frames behind a sync marker, their scrambler and RS code) - code/conv/mother, framing/bits: a convolutional mother code's generators; sync markers, frame length and HDLC on bits - identify: which code a hard-bit stream carries, peeling layers (`identify`, which rp.sync.AcquireFEC runs, `solve`) - result: what the searches return (Hypothesis, Report, Guess) and `pick` - signal_profile: `profile(source)`, every step that processes each signal in a capture, and what is left unsolved - catalogue: measured features to named systems (config/system), with the reasons Results feed the configured stages (`Guess.save` writes a config/fec definition, a found punctured code as a child of its mother code; rp.sync.Detection fills meta.stream.det; `identify.CodeDetection` names the profile that decodes a stream). ### Which tool answers which question Tools for signals no definition covers. Each states its statistic and chance level, so "nothing found" is an answer; each module's docstring has the method, reference and limits. Numpy only, outside the data path (nothing in the data path imports it, except `AcquireFEC` inside the call). Most take baseband at a few times the signal's width (some noise floor beside it), locked symbols, or bits. `identify.solve` peels layers off a decoder's output in turn; structure that holds at every alignment (constant bits, idle words) is not taken for a code. Rank methods need about n + 48 clean words of n bits; strong codes at low SNR are beyond them on channel bits. **What is it, and at what rate** | Question | Tool | How (and limits) | |---|---|---| | symbol rate, carrier order and offset | `spectrum.cyclic.features` | lines of `\|x\|^2`, `x^M` and the discriminator against a median floor, calibrated false alarms; rate by harmonic comb | | every cycle frequency (signals sharing a band) | `spectrum.scf.cycle_frequencies`, `coherence` | FFT-accumulation spectral coherence, conjugate too | | which constellation | `modulation.cumulants.classify` | C40 ... C84 against each constellation's; orders within QAM / ASK need the SNR | | FSK / MSK / GMSK, CPM index | `modulation.fsk.analyze`, `cpm_index` | instantaneous frequency; h from the phase lattice | | GMSK / SOQPSK bits, which pulse | `modulation.cpm.demodulate`, `identify` | per-survivor Viterbi, each survivor its own carrier loop | | OFDM pilot pattern | `spectrum.ofdm_pilots.discover`, `grid` | grid from CP peaks; period from coherent repetition; pilot lattice, boost, empty cells | | TDMA bursts, frame and slots | `burst.demodulate` | each burst on its shared preamble, mid-amble or postamble (`shared_segments`), data-aided carrier and phase; its symbol clock followed; LLRs (`Bursts.llrs`); blind when nothing is shared | | two co-channel signals of equal power | `spectrum.separate.estimate`, `separate` | each one's carrier, timing and phase; joint sequence estimate | | which named system | `catalogue.match`, `features` | measured features against systems from their standards, weighted | | which shipped profile | `profile` | each fixed-rate one's receive on its channel; its checks verify | | PM, residual carrier, subcarriers | `modulation.pm.analyze`, `subcarrier`, `nrz` | carrier tracked, phase around it | | DSSS | `sequence.spread.period`, `chip_rate`, `code`, `despread` | windowed autocorrelation variance; code from eigenvectors | | frequency hopping | `spectrum.hopping.track`, `dehop` | short-time spectrum clustered into channels and dwells | | kind of waveform | `spectrum.waveform.classify` | tones, OFDM numerology against known systems, bursts, envelope kurtosis | | tones in a short record, neighbours | `spectrum.pencil.lines`, `modulation.impairments.neighbours` | matrix pencil; bands split at valleys and level steps | **Is the lock good, and what is left** | Question | Tool | How | |---|---|---| | can hard decisions be trusted | `modulation.quality.gate` | rotation, drift, near-boundary decisions against the measured Es/N0 | | how much is locked; what is underneath | `modulation.cancel.cancel`, `align` | regenerate, subtract, residual against the floor | | amplifier, IQ, phase noise | `modulation.impairments.amplifier`, `iq`, `phase_noise` | ring gains and turns; image ratio; phase error from neighbours | | separate an interferer | `spectrum.scf.fresh` | least-squares FRESH filter trained on a reference (not blind) | **Which code, scrambler, interleaver** | Question | Tool | How | |---|---|---| | convolutional code (rate 1/n, K) | `code.conv.mother.scan_conv`, `scan_defined_conv` | generator-pair parity relation against chance; the configured codes by re-encoding | | puncture of a known mother code | `code.conv.puncture.search` | every rate P/(P+1) pattern through the Viterbi decoder | | Reed-Solomon over GF(256) | `code.block.rs.search` | shared roots by Galois-field Fourier transform at every byte phase | | binary block code | `code.block.linear.solve_block` | length from rank deficiency, checks from the null space; then cyclic / BCH, product or LDPC | | block code from soft values (too noisy for the rank) | `code.block.linear.soft_dual`, `soft_find_length`, `solve_block(llr=, soft_length=)` | subsets of the likeliest clean words; checks kept on the tanh-product syndrome (BCH(63,51) named to 5 dB Eb/N0, hard bits above 6) | | additive scrambler | `sequence.scrambler.additive_search`, `explain`, `search` | Berlekamp-Massey over windows; polynomials factored into known scramblers | | scrambler taps | `sequence.recurrence.search`, `lfsr`, `keystream` | every recurrence to degree 24 at once; any degree by Berlekamp-Massey | | trellis code on PSK labels | `code.conv.tcm.search` | Walsh-Hadamard over label windows, every rotation and labelling | | turbo constituent and interleaver | `code.conv.rsc.constituent`, `turbo_interleaver`, `turbo_interleaver_soft` | 2-bit-label check; permutation from clean or noisy frames | | LDPC (IRA, QC, large) | `code.block.ldpc.staircase`, `qc_staircase`, `qc_dual`, `qc_size`, `progressive` | one GF(2) solve per structure (a DVB-S2 table from k/360 + 12 clean frames) | | cyclic / BCH roots | `code.block.ldpc.roots` | zero counts at every beta^j against chance | | polar frozen bits | `code.block.polar.frozen`, `recognize`, `search` | per-position likelihood over frames (rate 1/2 at -2 dB from 200 frames) | | interleaver | `code.interleave.block_search`, `forney_search`, `column_delays` | rank deficiency for the size; candidates scored by the code coming back | **What the bits are** | Question | Tool | How | |---|---|---| | frame period and unique word on symbols | `framing.frames.find`, `cut`, `bursts` | coherence per position over candidate periods | | sync markers, frame length, HDLC | `framing.bits.find_sync`, `frame_length`, `scan_hdlc` | hits at a period, autocorrelation, flags and FCS against chance | | frames behind a sync marker, their scrambler and code | `framing.marked.layer` | a marker at one period; scramblers restarted per frame; RS words decoding at each depth, against chance | | PM telemetry end to end | `framing.telemetry.analyze` | BPSK per subcarrier, line code, frame period, counters | | what each header bit is | `framing.fields.map` | constants, counters (either bit order, per terminal), ids, length fields, enums, random; a link header definition | | code blocks a burst is made of | `burst.units` | burst lengths as overhead + n units, the unit to a symbol or so | | a burst time plan, and whether one explains the bursts | `burst.learn_plan`, `check_plan` | BTU, frame, slots from the starts; each burst in a slot of its carrier and kind, the plan's origin and clock fitted (`rp.viz.bursts`, `burst_timing`, `plan_evidence` draw them) | | a burst's layout, and how many transmitters | `burst.demodulate` with `rp.viz.burst_stack`, `burst_terminals` | the bursts of a kind lined up on their known symbols (where they agree); a cluster per transmitter in offset and power | | which CRC, over which bits | `framing.crc.search` | GCD of frame differences (RevEng's method on bit streams); init and xorout from two lengths; config/crc names | | framing in decoded bits | `framing.payload.signatures` | E1/T1, ATM, GFP, HDLC, IPv4, CCSDS ASM, MPEG-TS, fixed bits, each against chance | | structured, scrambled or random | `framing.payload.verdict` | signatures, bias, linear complexity, compressibility | | encrypted, or only compressed | `framing.randomness.test` | NIST SP 800-22 frequency, block, runs, serial, approximate entropy, cusum; byte chi-square and entropy | ## rpps.analysis.catalogue A catalogue of radio systems by what the blind tools measure: features in, named systems out, with the reasons - load_system(name, obj): A config/system definition as `match` takes it: {"name": its title, "ref", "id": its reference, "profile", "tags", and each feature} - systems(fresh): Every system in config/system (user layers too), loaded once: [dict], in reference order - family(name): A modulation name from any tool as the catalogue's family name (lower case, aliases folded) - Match(**kw): `match`: name, ref, score (-1..1), agree [(feature, reading)], contradict [(feature, reading)], tied (the names of other systems the features can't tell this one from: the same score and agreement) - match(feats, systems, tolerance, top, prior): Systems ranked by how well measured features fit (see the module): [Match], best first; systems no feature could be compared on are left out. - features(det, fsk, cpm, ofdm, pilots, bursts, spread, frequency, **more): The catalogue's features from rpps.analysis results: det (modulation.Detection), fsk (fsk.FSK), cpm (cpm.CPM or a scheme name), ofdm (waveform.OFDM), pilots (ofdm_pilots.Pilots), bursts (burst.Bursts or waveform.Bursts), spread ((chip rate, code length)), frequency (Hz); more: any feature by name (it wins) ## rpps.analysis.result What the blind code searches return: a Hypothesis (a structure and how far its test sits from chance), a Report of all of them, a Guess (a definition to save), and `pick`, the one that stands out at one alignment only - Hypothesis(kind, name, z, params, coding, guess) - Report(hyps, trials, facts): Ranked hypotheses and a verdict - Guess(kind, definition, evidence): A guessed definition (a code, a scrambler, a CRC). - pick(hyps, z_crit, key, fits): The best hypothesis that stands out, if the code fits these bits at its alignment only ## rpps.analysis.burst TDMA bursts demodulated one by one: each acquired on the preamble the bursts share, as a TDMA receiver must r = rp.analysis.burst.demodulate(x, Fs) # or mod=, baud=, preamble= (symbols) when known print(r) # "12 bursts, qpsk at 100.0 kBd, a 48-symbol preamble; frame 4.615 ms, 8 slots; EVM 6.1% median" b = r.bursts[0] b.symbols, b.bits, b.cfo, b.evm, b.slot, b.frame # carrier-, timing- and phase-corrected symbols, decided bits Every burst comes from another transmitter (or the same one after a gap), with its own carrier offset, phase and symbol timing, and is too short to train loops on: so each is acquired on its own, data-aided, from the preamble. 1. rpps.analysis.framing.frames.bursts gates the bursts (bursts that touch cut apart at a guard time or a power step: frames.split) and acquires each blind (rate, modulation, offset); bursts too short for that keep only their span. The modulation is the bursts' majority, the rate their median (or `mod` / `baud`). 2. The preamble: the leading run of symbols the bursts agree on, as phase steps (rpps.analysis.framing.frames.preamble, or `shared_preamble` for a short one, whichever is longer), or `preamble` given. A network's burst types each carry a unique word of their own: when the bursts share fewer than `min_shared` symbols, they are grouped by length and each group's own preamble found (`burst_kinds`); each burst is acquired on its kind's. Known symbols elsewhere (a mid-amble, a postamble: `shared_segments`) serve the same way, at their offset; with none at all, each burst is returned as acquired blind (`Bursts.blind`: its phase known only to the constellation's symmetry). Its symbols are rebuilt from the steps and turned onto the constellation (one rotation for all bursts: the M-fold phase ambiguity is the same for every burst, so their bits agree with each other). 3. In each burst the preamble is found by correlating its shaped waveform in pieces (the pieces' magnitudes added: a carrier offset costs little), then the fractional timing that best matches the preamble's phase steps (blind to the carrier), then from z_k = y_k conj(p_k) over the preamble: the carrier offset (the mean turn of z_k z*_{k-1}) and the phase and gain (sum z_k with the turn taken out). 4. The burst's symbols, from the preamble to the end of the gate, are taken at that timing and corrected. A burst of several `window`s has its symbol clock followed (`retime`): the matched filter's energy peak in each window (rpps.sync.time.mat.best_tau), a line through them anchored on the preamble (the clock offset, `clock`). A second- phase from decisions on the constellation's points, tracked across 32-symbol windows (rpps.sync.phase.decided), follows what is left of the carrier through the data; decisions give bits, the soft demapper LLRs (`llr`, noise from the burst's own symbols), and the error vector magnitude. 5. The TDMA structure: the period of the bursts' starts (rpps.analysis.spectrum.waveform.on_off, else `frame`) and the slots, clusters of the starts within a frame (to within `slot_tol` symbols): each burst's frame and slot. Limits: the clock is followed as a straight line (a constant offset over the burst), from windows of a few hundred symbols; a burst whose preamble is weaker than the data's noise floor allows is reported with `ok` False and no bits. A network's burst time plan (rpps.plan) from the bursts rp.sync.Bursts detects: `learn_plan` (the BTU, the frame, each carrier's slots and the kinds of burst in them), and whether a plan, learned or told, explains the bursts: `check_plan` (each burst in a slot of its carrier and kind, the plan's origin and clock fitted to them; rp.viz.bursts draws it, folded on the superframe or along the capture). Modules: `preamble` (what the bursts share), `demod` (each burst acquired and demodulated; the frame and slots), `plan` (units, learn_plan, check_plan). Burst code elsewhere: what a receiver runs is in the data path, which may not import this package. - rpps.sync.burst: `Burst` (bursts gated from a stream by energy), `BurstTx` (bursts placed in a stream) - rpps.sync.plan: `Bursts` (bursts cut where a burst time plan puts them), `PlanTx` - rpps.profile.burst: the runners for a profile's `burst` step (receive and transmit) - rpps.plan: burst time plans as definitions; rpps.viz.plots.bursts draws bursts against them ## rpps.analysis.burst.demod Each burst acquired on its preamble and demodulated (`acquire`, `retime`, `demodulate`), and the TDMA frame and slots the bursts' starts show. See rpps.analysis.burst - BurstResult(**kw): One burst: start (sample of its preamble's first symbol, fractional), symbols, bits, llr (per bit, log(P0/P1), the preamble's included, as bits), cfo (Hz), clock (its symbol clock's offset, a fraction: +1e-4 is 100 ppm fast), phase (rad), gain, score (the preamble's correlation 0..1), evm (rms, of the data after the preamble), frame, slot, kind (which of the preambles it was acquired on), known ((first, length): the known symbols in `symbols`), ok - Bursts(**kw): What `demodulate` gives: the bursts and what they share - acquire(x, Fs, pre, baud, beta, search, steps): The preamble `pre` (symbols) in samples x at Fs: (start sample of its first symbol (fractional), score 0..1, cfo (rad a symbol), phase, gain), or None when x is too short. - retime(x, c, sps, beta, anchor, window, skip, offset): Symbol centres c (samples of x, one a symbol) with the symbol clock's offset taken out, and that offset - demodulate(x, Fs, mod, baud, beta, preamble, offset, frame, slot_tol, min_score, min_shared, **kw): Every burst of x, demodulated on its own from its preamble (see the module). ## rpps.analysis.burst.plan A network's burst time plan (rpps.plan) from the bursts rp.sync.Bursts detects: the code blocks a burst is made of (`units`), the plan learned (`learn_plan`), and whether a plan explains the bursts (`check_plan`). See rpps.analysis.burst - Units(**kw): `units`: unit (symbols), err (its standard error: the lengths are known to a few symbols, so a unit is often only known to one either way), overhead (symbols besides the units: preamble, header, tail), counts ({units a burst: bursts}), fit (share of bursts within `tol` of overhead + n*unit) - units(lengths, tol, min_unit, hold): The block a burst's length is made of: lengths (symbols a burst, e.g. - NoPlan: learn_plan found no frame period; `scores`: what it tried (as a Guess's, for rp.viz.plan_evidence) - learn_plan(bursts, quantum, max_btus, clock, purity, tol, carriers): A burst time plan (rpps.plan) from detected bursts, for a network whose forward link is not heard: its BTU, frame period, a frame type per carrier, its slots and their tx types. - PlanCheck(**kw): check_plan's answer: how well a burst time plan explains the bursts detected. - check_plan(plan, bursts, origin, rate, cf, tol, fit, votes): How well a burst time plan (rpps.plan: learned, a definition or from a forward link) explains detected bursts: each burst placed in the slot of its carrier whose burst start is nearest its own, and judged (PlanCheck: "slot", "kind", "long", "none"). ## rpps.analysis.burst.preamble What a TDMA network's bursts share: the preamble (`shared_preamble`, `preamble_symbols`), known symbols elsewhere (`shared_segments`: a mid-amble, a postamble), a word repeated through each burst (`periodic_word`), and burst kinds, each with a word of its own (`burst_kinds`). See rpps.analysis.burst - shared_preamble(burst_list, search, win, agree, max_len): The leading run of symbols the bursts share, as phase steps: (length in steps, steps, where it starts in each burst's symbols), or (0, None, None). - preamble_symbols(steps, points): Symbols of a preamble from its phase steps d[n] = s[n] conj(s[n-1]) (rpps.analysis.framing.frames.preamble), turned so they sit on the constellation `points` (one rotation, chosen from the points' own symmetry) - Segment(steps, offset, agree): `shared_segments`: steps (d[n] = s[n] conj(s[n-1]) the bursts agree on), offset (symbols from the bursts' start to the segment's first symbol; negative: from their end, a postamble), agree (|mean| of the steps over bursts) - shared_segments(burst_list, search, min_len, agree, refs, M, false_alarm): Runs of symbols every burst carries at the same place: a preamble, a mid-amble, a postamble ([Segment], longest first). - periodic_word(burst_list, mod, points, tries, min_frames, max_lag, thr, min_len): (unique word on the constellation, period in symbols) when long bursts hold frames with one unique word, each at its own phase; else None. - burst_kinds(B, sps, pts, min_shared, min_group): (preambles [symbols], member [kind index or None per burst]): one shared by all the bursts, when they share at least `min_shared` symbols; else one per group of bursts of a length (lengths within 16 symbols or 2 %: a network's burst types, each with its own unique word), groups of at least `min_group` with at least `min_shared` symbols in common. ## rpps.analysis.code Which code (see rpps.analysis) ## rpps.analysis.code.interleave Interleavers found blind: a block interleaver's size and shape, a convolutional one's branches and delay, and columns of a grid sent out of step - recurrence_z(bits, max_degree, n): How much linear code structure bits have: the z of their strongest recurrence of degree up to max_degree (0: none) - Shape(**kw): A block interleaver found: size (bits), offset (first block), rows, cols (written by rows, read by columns: the order the bits came in was cols x rows), code (the code length seen once read back), deficiency - block_search(bits, max_size, max_code): A block interleaver's size from the rank deficiency, then the row x column shape whose undoing shows a short code - forney_undo(bits, I, M, symbol): A Forney deinterleaver: symbols of `symbol` bits, branch j (of I, the first symbol on branch 0) delayed by (I - 1 - j) M symbols (rpps.code.types.interleave.forney's decode, without a code object) - forney_search(bits, candidates, score, n): Undo each (I, M, symbol) candidate (default FORNEY) at each start (a branch and a bit within the symbol) and score the result. - column_delays(bits, rows, cols, max_delay, offset, **kw): Each column's shift in rows (positive: sent that many rows late) that makes it a codeword of the column code again. ## rpps.analysis.code.block Block codes: linear / cyclic / BCH / product, LDPC, Reed-Solomon, polar ## rpps.analysis.code.block.ldpc Blind LDPC and algebraic block codes, past what one search finds: staircase (IRA) codes, progressive reconstruction, roots - staircase(words, k, rel, trials, verify, seed, extra): Rows of an IRA code's H from aligned words (W, n) whose first k positions are the information bits and the rest the parity bits in accumulator order. - qc_generator(words, k, z, rel, trials, verify, seed): The generator of a quasi-cyclic code (circulant size z) from aligned words (W, n) with the k information bits first: parity bit o of parity block J is sum over information blocks b and s of u[b, (o - s) % z] V[b, J, s], plus c[J z + o] (zero for a linear code; a coset's constant otherwise). - circulant_size(words, k, sizes, rel, hold, **kw): The circulant size of a quasi-cyclic code: the smallest z (of `sizes`, default every common divisor of k and n - k from 2) whose qc_generator predicts held-out words (every parity block's fraction >= hold), or None. - qc_checks(V, z, max_weight, quads, reps, seed): Sparse parity checks of the quasi-cyclic code qc_generator found: H ((n - k), n) over [information k | parity n - k], full rank when they are found, lightest block rows first. - posterior(H, llr, iters, alpha): A-posteriori LLRs of words (B, n) through the checks H (c, n) by normalized min-sum, flooding (all checks at once): what the checks known so far say about each bit (rpps.code.types.ldpc.flood) - progressive(llr, rounds, iters, max_checks, **kw): Checks of aligned frames (W, n) of LLRs (log P(0)/P(1)), found again and again on frames cleaned by the checks found so far (see the module). - Roots(**kw): Result of `roots`: n, m, roots (exponents j of beta = alpha^((2^m - 1)/n), sorted), zero (fraction of words zero at each root), generator (int, bit i the coefficient of x^i), k (n - degree), designed (BCH designed distance: 1 + the longest run of consecutive roots), clean (estimated share of words without an error) - roots(words, m, z_min, reverse): Roots of a binary cyclic code from aligned words (W, n), position i the coefficient of x^i (reverse: of x^(n-1-i)). - QCStaircase(**kw): Result of `qc_staircase`: table (per information group, the parity addresses x: DVB-S2's address table), checks (positions per check, as rpps.code.types.ira.ira_checks gives), holds (per row class, on held-out frames), Z - qc_staircase(words, k, Z, rel, extra, trials, seed): A DVB-S2-style IRA code (information bits in groups of Z, each adding to parity rows x + m q, parity accumulated) from aligned codewords (W, n), information first: its address table, from about k/Z + `extra` clean words (the most reliable ones, by `rel` |LLR|; `trials` subsets, each row class keeping the solution that holds best) - qc_dual(words, Z, extra, trials, seed): The circulant check blocks of a quasi-cyclic code (every column block of Z, rows and columns cycled alike: 802.11n, 802.16e, 5G NR's lifted base graphs) from aligned clean codewords (W, n), about n/Z + `extra` of them. - qc_size(words, candidates, extra): Circulant sizes Z (dividing n) at which aligned clean codewords (W, n) have checks that stay checks cycled within every block of Z: {Z: how many independent ones}. The code's own Z has them all (n - k); its divisors and multiples some, other sizes none: the largest is the code's ## rpps.analysis.code.block.linear Blind binary block codes: length, alignment, parity checks, and which kind of code it is (cyclic / BCH, product, LDPC) - deficiency(bits, L, offset, segments, extra): L minus the rank of rows of L bits from `offset`, the largest over `segments` stretches of the bits (an error in a row adds to the rank, so the cleanest stretch counts). - alignment(bits, n, extra): (offset, deficiency at each offset): where rows of n bits are shortest of rank - find_length(bits, min_len, max_len, extra): Codeword length of a binary block code: (n, offset, {length: deficiency}) or (None, None, deficiencies) - frame_units(rows, min_len, max_len, extra, trials, seed): The length of a block code whose words lie end to end from where each frame starts: rows are bits that each start at a frame's start (a burst's payload after its preamble, a frame's after its unique word), of any lengths. - to_poly(row): Bits, first the highest power, as a polynomial int - cyclic_generator(words, r): g(x) of a cyclic code from aligned codewords (W, n): the commonest gcd of two words that has degree r (= n - k). - primitive_polys(m): Primitive polynomials of degree m (x is a generator of GF(2^m)) - bch_of(g, n_sent): The narrow-sense BCH definition with generator g, if it is one: {"type": "bch", ...} or None - product(bits, n1, offset, max_n2, extra, per_block): Rows of n1 bits stacked n2 at a time, whose columns are codewords too: (n2, row phase, deficiency) or None. - sparse_checks(words, rel, w_max, trials, verify, seed, k, patience): Low-weight parity checks of aligned words (W, n): (H (c, n) uint8, fraction of words each holds on) - lightest(H): The sparsest description of the checks H span: a basis taken lightest first, then every check no heavier than its heaviest (redundant low-weight checks help a decoder: Gallager's H has more rows than its rank) - trivial_checks(words, nk, hold): When checks of weight 1 and 2 (bits that hold one value, pairs that are equal or opposite, in `hold` of the words) account for all nk independent checks: (fixed positions, equal pairs); else (None, None) - recurrence(bits, n, windows, hold): (degree, taps, fraction holding) when the bits follow one short linear recurrence (shorter than n: what makes every row of n bits short of rank, at every alignment), else None. - solve_block(bits, n, offset, llr, max_len, max_n2, soft_length): Find a binary block code in bits: its length, alignment, checks, and kind. - soft_score(H, llr): z of each check h (rows of H) on words of LLRs (W, n): the sum over words of prod_{j in h} tanh(llr_j/2) (each word's expected parity of h: +1 for a sure 0) over its spread. - soft_dual(llr, n, offset, trials, seed, z_min, size): Parity checks of a linear block code of length n from soft values (LLRs, positive = 0): `recover_dual` for words too noisy for random subsets to be clean. - soft_find_length(llr, min_len, max_len, offset, trials, seed): Codeword length from soft values: the shortest n (rows of n from `offset`) whose soft dual holds a check, or None. - recover_dual(bits, n, offset, trials, seed, z_min): Recover parity checks of an unknown linear block code of length n from (noisy) hard bits ## rpps.analysis.code.block.polar A polar code's frozen positions, blind: which of the u bits are always 0, and which construction froze them - Frozen(**kw): Result of `frozen`: frozen (positions), k (information bits), score (each position's mean tanh(L/2) of u_i: 1 for a frozen position on clean frames, 0 for information), threshold - frozen(llr, threshold): Frozen positions from frames (W, N) of LLRs (log P(0)/P(1)) of aligned polar codewords (see the module). - evidence(L): Per frame, log2 of how much likelier an SC LLR L is with u = 0 than with u uniform: log2(2 / (1 + e^-L)). - Recognition(**kw): Result of `recognize`: frozen (positions), k, evidence (N,): each position's summed evidence (bits; > 0 frozen), construction (the reliability order it fits, with `search`), score - recognize(llr, z, monotone): Frozen positions of aligned polar frames (W, N) of LLRs at low SNR: blind SC (see the module). - search(llr, orders, tolerance, **kw): Which construction (and K) the frozen set of frames (W, N) of LLRs is: `recognize` finds the set blind, then each reliability order (default polarization weight, and Bhattacharyya at -2 / 0 / 2 / 4 dB) is matched by its K whose N - K least reliable positions differ from it in the fewest places. ## rpps.analysis.code.block.rs Blind Reed-Solomon identification: length, field, generator and alignment of an unknown RS code over GF(256) - fit_generator(roots): (fcr, prim) with roots = {prim*(fcr+i) mod 255, i < len(roots)}, prim 1 if it can be, or None - lengths_of(bits, hints): Lengths to try: the hints, then the byte frame periods of the bits, then COMMON - search(bits, lengths, hints, words, depths, polys, exhaustive): Find an RS code over GF(256) in hard bits. ## rpps.analysis.code.conv Convolutional family: the mother code (generators), puncture patterns on it, turbo constituents, TCM ## rpps.analysis.code.conv.mother Mother codes of convolutional codes, blind: the constraint length and generators of a rate 1/n feed-forward code (for generators g_a, g_b, (c_a * g_b) xor (c_b * g_a) = 0 on codewords), a configured code's fit, and the definition a found one is saved as (a child of the configured mother code with these generators, else the generators). Its punctured rates: rpps.analysis.code.conv.puncture - scan_conv(bits, ks, rates, periods, tag, llr): Rate 1/n convolutional code scan on one bit stream. - soft_mismatch_batch(code, llr): The soft re-encoding mismatch of each row of LLRs (W, L): decoded from the LLRs, re-encoded, the share of |LLR| on the bits the code disagrees with (a right code's disagreements fall on unreliable bits, a wrong one's anywhere), and the effective number of bits ((sum |L|)^2 / sum L^2) that share is over. - scan_defined_conv(streams, names, steps, skip, segments, decisive, llrs, screen, cut): Try every convolutional definition in config/fec/conv on every bit mapping and puncture alignment - decode_conv(bits, hyp): Run the config definition behind a conv-config hypothesis on a whole bit stream - guess_conv(hyp): Definition from a conv hypothesis (generators found by the parity relation, plain or with a scrambler) ## rpps.analysis.code.conv.puncture Blind puncture patterns: a known rate 1/2 convolutional code (a "mother code") sent through a puncture pattern that no definition has - patterns(P): Rate P/(P+1) puncture patterns (2, P), one per turn (built once per P; read only) - mothers(): Rate 1/2 mother codes in config: {(K, generators): name}, both output orders - mismatches(K, gen, rows): mismatch() of each (pattern, hard bits) in rows under the mother code (K, gen) with that pattern, decoded together: every pattern of a mother decodes on the mother's trellis with erasures where it punctures (what a punctured decoder does), so the rows go through in one batch per length. - search(streams, periods, steps, confirm, codes): Find a rate 1/2 mother code with a puncture pattern in hard bit streams ({tag: bits}). - best(hyps, trials): The hypothesis that stands out and fits at one offset only, with its Guess (a conv definition), or (None, None) ## rpps.analysis.code.conv.rsc Recursive systematic convolutional codes (turbo constituents) and a turbo code's interleaver, found blind - octal(p): The octal a standard writes (D^0 the most significant bit, 3GPP's 13 = 1 + D^2 + D^3) - Constituent(**kw): g_f (feedforward), g_b (feedback): ints, bit d the coefficient of D^d; memory; holds; z - constituent(s, p, max_memory, pfa): (g_f, g_b) of the code making parity p from s (aligned streams of equal length), or None - encode(u, g_f, g_b): Parity of an RSC encoder from the all-zero state: p = u g_f / g_b (g_b needs a D^0 term) - invert(p, g_f, g_b): The information an RSC encoder (from the all-zero state) made p from: u = p g_b / g_f (g_f needs a D^0 term) - turbo_interleaver(S, P2, g_f, g_b, min_frames): The permutation of a turbo code's second encoder: frames S (F, K) of systematic bits and P2 (F, K) of the second parity (each frame from the all-zero state). - turbo_interleaver_soft(Ls, Lp2, g_f, g_b, beam, expand, repair): The second encoder's permutation from noisy frames: Ls (F, K) LLRs (log P(0)/P(1)) of the systematic bits, Lp2 (F, K) of the second parity (hard bits work as +-large values). ## rpps.analysis.code.conv.tcm Trellis-coded modulation found blind: the parity check a trellis code puts on the constellation's labels - Check(**kw): A parity check found, and how well it holds - decisions(y, M): Nearest of M PSK points at angles 2 pi k / M + offset (the offset taken from the M-th power): k, 0..M-1 - labellings(M, own): {name: label of the point at angle index k} - label_windows(z, m, W): Counts of every W-symbol window of m-bit labels z, as an index whose bit (W-1-d) m + i is z^i at delay d - label_errors(y, M, labs, k, seed): Per label bit, the probability a hard decision gets it wrong at the noise of these symbols: {labelling: array(m)} - search(y, M, max_nu, own, conj, labelling, pfa, top, correlations, soft, shortlist): Parity checks of a trellis code on M-PSK symbols y (locked to within a rotation). - definition(h, m, points): The trellis code of check h as an `fsm` definition (rpps.code.types.fsm): the systematic feedback encoder whose upper m-1 label bits are the input (z^1 the first input bit) and z^0 is solved from sum_i h^i z^i = 0 (h[0] with taps at delay 0 and nu). - encode(bits, h, m): Labels of a systematic feedback trellis encoder for the check h (see `definition`): the upper m-1 label bits are bits (rows of m-1, z^1 first), z^0 is solved from sum_i h^i z^i = 0 ## rpps.analysis.framing How the stream is cut: frames, payloads, telemetry, the CRC frames carry, what each bit of a header is, frames behind a sync marker and the scrambled block code inside them (marked); and whether decoded bits are as random as a cipher's output ## rpps.analysis.framing.bits Frame structure on bits, blind: sync markers, frame length by autocorrelation, HDLC flags and the markers of a framed code - find_sync(bits, markers, period): Bit offset and byte phase at which `markers` repeat every `period` bytes. - frame_length(bits, min_n, top): Candidate frame/block lengths from autocorrelation peaks (sync markers, repeated headers) - scan_hdlc(streams, names, min_frames): HDLC framing (config/frame): many flags, and frames whose FCS checks out - frame_markers(bits, period, offset, column, unit, threshold, lengths): The values that start every `period` units at `column` (units after bit `offset`): a pattern for `sync.Align` ## rpps.analysis.framing.crc Which CRC checks a set of frames, and where it sits: the generator, init and xorout, the bits it covers - CRCFit(**kw): What `search` found: a CRC's parameters and where it sits - search(frames, widths, trials, false_alarm, seed): The CRC the frames (bit arrays as sent; bytes are unpacked MSB first) carry, as a CRCFit, or None. ## rpps.analysis.framing.fields What each bit of a set of frames (or bursts) is: constant, a counter, an id, a length, a few values, or random - Field(start, width, kind, **detail): start (bit), width, kind (constant, counter, id, length, enum, random, varying), detail (dict: value, step, order, values {value: count}, scale, offset, bias) - FieldMap(fields, length, frames): `map`: fields (covering bits 0 .. length - 1 in order), length, frames - map(frames, groups, lengths, length, hold, max_width, max_values): FieldMap of the frames (bit rows, aligned at their first bit). ## rpps.analysis.framing.frames Blind symbol framing: the period a symbol stream repeats with, the unique word that marks it, and the frames cut on it - Frame(**kw): `find`: period (symbols), uw_start (position in the period), uw_length (symbols), coherence (of the unique word, 1 = the same symbols every frame), floor (of the other positions), uw (the unique word's symbols, from the first frame), frames (how many the estimate is over) - comb_lags(za, min_lag, max_lag, top, mean, var): [(lag, z)] the lags in [min_lag, max_lag] a frame structure may repeat at, most significant first - periods(y, max_lag, min_lag, top): [(lag, z)] the lags locked symbols may repeat at with a frame, most significant first (`comb_lags` over their autocorrelation, one FFT) - coherence(y, period): Per position in the period: |mean over frames of y[n] conj(y[n+period])| over their rms, 1 where every frame has the same symbol. - find(y, mod, max_lag, min_frames, threshold, false_alarm, min_coherence): The frame structure of locked symbols y: a Frame, or None (no lag with a unique word standing out) - grid_of(constellation): The turns a constellation is symmetric under. - cut(y, fr, M, grid): Frames x period symbols starting at the unique word, each turned onto the others by its unique word - payload_bits(frames, fr, constellation): Frames x bits of the symbols after each unique word, hard-decided on `constellation` (a name or a Constellation) - repeats(frame_bits, max_period, agree): (period, fraction of frames equal to the one `period` before): the smallest such period, or (None, 0.0). - word_waveform(word, sps, beta, span): The symbols `word` shaped by an RRC pulse at a fractional `sps` samples per symbol - Hit(at, score, baud, sps): `find_word`: at (sample of the word's first symbol), score (0..1, 1 = the word alone, noiseless), baud, sps - find_word(x, Fs, word, bauds, beta, segments, threshold, top): Where a known symbol word (a preamble, a burst's unique word) is in baseband samples x at Fs: [Hit] best first - Burst(start, stop, det, symbols): `bursts`: start, stop (samples), det (rpps.sync.Detection of this burst alone, None if too short), symbols (matched-filtered at det's rate and timing, carrier offset and phase taken off) - split(x, Fs, a, b, win, min_len, min_gap, thr, bw, guards): Where touching bursts meet in x[a:b]: [(start, stop)] - occupied(x, Fs, nfft, share): The bandwidth holding `share` of the power above the noise floor (Hz): about the symbol rate of a shaped signal - gate(x, Fs, smooth, contrast, min_len, hang, touching): [(start, stop)] where the power is on: above the geometric mean of its low and high levels (`contrast` apart at least), bursts closer than `hang` merged, those shorter than `min_len` dropped; each span then cut where bursts touch (`split`: a power step or a guard time), unless `touching` is False. - centroid(x, Fs, nfft): The power-weighted mean frequency (Hz) of the spectrum's bins above twice its 10th-percentile floor: a coarse carrier for a signal cut off-centre - tone_pair(x, Fs, sep, tol, min_snr): The middle (Hz) of the strongest pair of spectral lines `sep` apart (to `tol` of it) in the samples x, or None: a periodic preamble (1100...: tones at the carrier +-baud/4) puts its carrier between two lines, which squaring cannot tell from the lines themselves. - bursts(x, Fs, names, baud, min_symbols, betas, **kw): The bursts of x (`gate`), each acquired on its own: rate (or `baud` for all), modulation, offset, timing (as a TDMA receiver must: every burst comes from another transmitter, with its own clock and carrier). - preamble(burst_list, max_len, agree, search): What the bursts' first symbols share: (length, differential symbols d[n] = s[n] conj(s[n-1]) of it, where it starts in each burst's symbols) or (0, None, None). - coarse_cfo(x, Fs, M, pad): Carrier offset [Hz] from the line of x^M (the modulation's M-fold symmetry taken off) - pilot_frames(x, Fs, uw, baud, period, beta, span, threshold, M, dropout, track, smooth): Frames of symbols synchronized on their unique word as pilots: (frames x period symbols from each word on, the words' sample times) ## rpps.analysis.framing.marked Frames behind a sync marker, the scrambler restarted at each, the block code inside (rpps.analysis.framing.marked) - markers(): {name: bits} of the profiles' sync markers. - chance(code): A random word's chance to decode. - Frames(**kw): A frame layer `layer` found. - layer(bits, min_frames, z): The frame layer in `bits`: a Frames, or None. ## rpps.analysis.framing.payload What decoded bits carry: known framings found at any bit offset, and a verdict on what is left - Found(**kw): A signature found: name, period (bits, or None), offset (first bit), hits, expected (by chance), z, detail; a word found (`fixed_word`): word (hex, first bit sent most significant), bits, mismatches (median, 99%) per frame - e1(bits, z_min, share): G.704 frame alignment: x0011011 every 512 bits (the first bit, Si, is free), in most frames (a framed stream's own fixed fields can hold the word at a period by chance, in some of them) - t1(bits, z_min): A column of the 193-bit grid far from random: its bits repeat with the superframe (12 for SF, 4-bit steps in ESF) - atm(bits, z_min): 53-byte cells: HEC = CRC-8(x^8+x^2+x+1) of the first four header bytes, xor 0x55 (I.432), at some bit offset - gfp(bits, z_min): GFP core headers: PLI (16) + cHEC = CRC-16 of PLI, the four bytes xored with 0xB6AB31E0; frames chained by PLI - hdlc(bits, z_min): HDLC / PPP / LAPD: bit stuffing leaves no run of six ones but a flag's (01111110), where in random bits half of the windows 0111111 go on with a 1 - ipv4(bits, z_min): 20-byte IPv4 headers: 0x45, total length >= 20, ones-complement checksum of the ten words 0xFFFF - ccsds(bits, z_min, periods): The attached sync marker 0x1ACFFC1D at a period (any of `periods`, default every multiple of 8 up to 16384 found from its own hits) - mpeg_ts(bits, z_min): 0x47 every 188 or 204 bytes - fixed_word(bits, max_period, z_min, min_bits, agree, alpha, false_alarm): Bits constant at a period, as a unique word after demodulation: Found with the period, the word (its longest run of constant positions: `word`, a hex string sent first bit first, `bits` long, at `offset`), `hits` (every constant position), and in `mismatches` the bits each frame's copy differs by (median, 99th percentile) - signatures(bits, z_min, tests, max_bits): Every signature that holds on the bits (see the module), strongest first (on the first `max_bits`) - Verdict(**kw): Result of `verdict`: kind ("structured", "scrambled", "random-looking"), why, signatures, bias (|mean - 1/2|*2), byte_chi (z of the byte distribution, the worst of 8 offsets), lc (linear complexity over windows / their length), compress (zlib size / size) - verdict(bits, window, z_min, frame, max_bits): structured (a signature, bias, uneven bytes, or zlib compresses it), scrambled (an LFSR: windows' linear complexity well under half their length), or random-looking (encrypted, compressed, or under something not linear). ## rpps.analysis.framing.randomness Is a bit stream as random as a cipher's output? NIST SP 800-22 tests, and byte-level entropy - frequency(eps): 2.1: the proportion of ones - block_frequency(eps, M): 2.2: the proportion of ones in M-bit blocks (M >= 20, M > n/100, fewer than 100 blocks) - runs(eps): 2.3: the number of runs of identical bits (0 when the frequency prerequisite fails) - serial(eps, m): 2.11: every overlapping m-bit pattern equally often (m < log2 n - 2). - approximate_entropy(eps, m): 2.12: the frequencies of overlapping m- and (m+1)-bit patterns (m < log2 n - 5) - cusum(eps, backward): 2.13: the largest excursion of the random walk of +-1 (mode 0 forward, mode 1 backward) - byte_chi2(eps): Chi-square of the 256 byte values against uniform (255 degrees of freedom) - byte_entropy(eps): Shannon entropy of the bytes [bits a byte] - Result(**kw): `test`: p {test: P-value}, alpha (per test, after the multiple-test correction), passed, failed [test names], entropy (bits a byte), n (bits tested), verdict - test(bits, alpha, max_bits): Every test on (the first `max_bits` of) the bits. ## rpps.analysis.framing.telemetry Residual-carrier PM telemetry (PCM/PSK/PM): the carrier, each subcarrier's data, its line code and its frames - TelemetryFrame(**kw): period (bits), fixed (bits constant over the frames), frames (how many folded), counters [(bit, width, step)] - Subcarrier(**kw): One subcarrier (or the data on the carrier itself: freq 0): freq, baud (symbol rate), quality (|mean|/std of the soft symbols' size), esn0 (dB), manchester, differential, rate (data bits/s), idle (None, or what pattern), bits (data), frame (TelemetryFrame or None), why (when no symbols split) - Telemetry(pm, subcarriers): pm: the rpps.analysis.modulation.pm result; subcarriers: [Subcarrier] - bpsk(z, fs, baud): (soft symbols, quality, Es/N0 dB) of BPSK at complex baseband z: phase from z^2, integrate and dump at the boundary whose symbols split cleanest - doubled(chips, hold): Whether chips come in equal pairs (at one alignment): symbols at twice the real rate - manchester(bits): (fraction of chip pairs opposite, alignment, data bits (the first chip of each pair)) at the better alignment - idle(bits): What idle pattern bits are (alternating, constant), or None - period(bits, min_lag, top): (lag, |r|, fixed fraction) of the frame period: of the autocorrelation peaks past min_lag standing out of the noise (and above FRAME_R) and their divisors, the smallest whose fold leaves nearly the most bits fixed beyond chance (byte or word structure correlates at short lags but fixes nothing; a frame's sync and header do). - counters(F, widths, hold): [(bit, width, step)] of fields in the folded frames F that step by +-1 a frame (in `hold` of the frames: a bit error breaks a step or two), the widest first - frame(bits): TelemetryFrame of the bits, or None when no period shows - line_code(chips): (manchester, differential, data bits) of hard chips: Manchester when nearly every pair is opposite; differential when the XOR of neighbours frames with more bits fixed than the bits themselves - subcarrier(phi, Fs, fsc, half, rates): Subcarrier at fsc (Hz) of the phase phi: its rate, symbols, line code, and frames (see the module) - symmetry(x, Fs, carrier, nfft, band, snr_db): (symmetry, sidebands): how well the spectrum mirrors about the carrier, 0..1 (sum(min)/sum(max) of the power standing clear of the noise, ABOVE times its level per bin, at carrier +-f), and that power's ratio to the carrier's. - analyze(x, Fs, **kw): Telemetry of x (complex baseband, Fs), or None when rpps.analysis.modulation.pm finds no residual carrier ## rpps.analysis.identify Blind FEC identification Takes hard bits (what a demodulator produced, with an unknown bit mapping, rotation and alignment) and asks which code they are most likely carrying. Every test is a parity relation that holds on codewords but is a coin flip on anything else, so a hypothesis is scored by how far its relation sits from 50% (a deviance z-score), then corrected for how many hypotheses were tried. conv: rate 1/n feed-forward convolutional codes. For generators g_a, g_b: (c_a * g_b) xor (c_b * g_a) = 0 block: any linear block code / LDPC given its parity-check matrix H, at every word alignment scramblers: an additive scrambler of period T just adds a fixed pattern to the relation, so folding the relation by T (with `periods`) finds it. Self-synchronising scramblers are undone with `descramblers` first. The tests are about structure, not about being right: a noisy channel weakens them, and the verdict is None when nothing stands out. ## rpps.analysis.modulation What carries the symbols (see rpps.analysis) How low an Es/N0 `cumulants.classify` (and rpps.sync.detect) names each constellation at: tools/modclass_bench.py, its findings in its docstring, kept by tests/unit/analysis/modulation/test_modclass_threshold.py ## rpps.analysis.modulation.cancel How much of a signal we are locked to: regenerate it from its symbols, subtract it, and measure what is left - Cancelled(**kw): Result of `cancel`. - kernel(t, sps, span): Band-limited kernel (|f| < 1/sps cycles a sample, the band of a pulse with roll-off up to 1) of half-symbol spacing, Hann-tapered to +-span symbols: t in samples - regressors(n, symbols, sps, tau, span): The basis signals: column j (of 4 span + 1) is sum_k s_k kernel(n - tau - k sps - j' sps/2), j' = j - 2 span. - decide(y, points): Nearest constellation point of each symbol - cancel(x, Fs, symbols, sps, tau, span, block, widely, cfo, nfft): Regenerate the signal from its symbols and take it off x (see the module). - align(x, symbols, sps, search, span): Where the symbols are in x: tau (samples) of symbol 0, from the cross-correlation of x with the symbols shaped by the basis's centre kernel. ## rpps.analysis.modulation.cpm GMSK and SOQPSK: binary continuous-phase modulation demodulated by a sequence detector, blind to timing and carrier - frequency_pulse(name, sps): The frequency pulse g of a scheme at sps samples a symbol, L*sps samples, sum(g)/sps = 1/2 (q(LT) = 1/2) - phase_table(name, ns): Q (L, ns): 2 pi h q((j + n/ns) T) at sample n of a symbol for the symbol j symbols back (q from g at ns samples: q at the sample's end) - alpha_table(name): atab (2, 8) int8: alpha_k for (k's parity, b_k + 2 b_{k-1} + 4 b_{k-2}) - alphas(bits, name, parity): The CPM symbols of bits (the bits before the first are 0) - modulate(bits, name, sps, parity): Complex baseband of bits at sps samples a symbol (unit amplitude, phase 0 at the start) - mlse(r, name, ns, parity, S, loop): Bits of r: samples at ns a symbol, sample 0 at a symbol's start, carrier near 0. - square_lines(x, Fs, baud, min_ratio, top): The x^2 line pair of an h = 1/2 CPM signal (see the module): (baud, cfo, ratio), ratio the weaker line over the spectrum's median (power); None when there is no pair over min_ratio. - CPM(**kw): Result of `demodulate`: bits, scheme, baud (Hz, clock-corrected), cfo (Hz), tau (s: the first symbol's start), match (0..1), lines (the weaker x^2 line over the spectrum's median; 0 when rate and carrier came from the instantaneous frequency instead) - front(x, Fs, baud): (baud, cfo, lines) of an h = 1/2 CPM signal: the x^2 pair, else fsk.analyze's rate and the median frequency - demodulate(x, Fs, scheme, baud, ns, S, loop, train, clock): Bits of a GMSK / SOQPSK signal x (complex baseband at Fs, a channel around it; see the module). - identify(x, Fs, baud, schemes, n, ns): Which scheme fits x best: [(match, scheme)] best first, each timed on its own over n symbols ## rpps.analysis.modulation.cumulants Higher-order cumulants of symbols: which constellation, blind to Gaussian noise and to the carrier phase - cumulant(M, p, q): C_pq from a moment table: sum over partitions of (-1)^(k-1) (k-1)! prod of the blocks' moments - measure(x, features, power): {name: C_pq / power^(p/2)}: power the signal's (default C21, which counts the noise too) - theory(points, features): The normalized cumulants of equiprobable points (unit power) - Match(**kw): One candidate: name, distance (weighted, of the phase-free cumulants), share (the signal's part of the power that fits best), esn0_db (from the share), values (measured, normalized by the signal power), expected (theory) - candidates(): {name: points} of the constellations to compare with - classify(x, points, esn0_db, shares): Candidates by how well the symbols' cumulants match theirs, best first. ## rpps.analysis.modulation.fsk Frequency-shift keying and continuous-phase modulation from the instantaneous frequency: tones, rate, index, pulse - FSK(**kw): Result of `analyze`. - analyze(x, Fs, lo, hi, pfa, mask, force, max_samples): FSK / CPM parameters of baseband samples x (see the module); lo/hi: symbol rates searched (Hz). - demodulate(x, Fs, r, mask): Tone index (0 = lowest) of every symbol, at the centres `analyze` found (r: its result; the same x, filtered the same way: mask) - cpm_index(x, Fs, baud, tau, h_range, steps, lags): The modulation index h of a full-response CPM (CPFSK, MSK, M-ary), from the phase lattice: between symbol boundaries N apart the phase moves pi h (a sum of N odd levels), whose parity is N's, so exp(j dphi / h) is (-1)^N for every pair at the right h, and averages away at a wrong one. ## rpps.analysis.modulation.impairments What else than noise is in locked symbols: amplifier compression (AM/AM, AM/PM), IQ imbalance, phase noise, neighbours - Amplifier(**kw): Result of `amplifier`: rings (radius of each ring's points), gain_db and phase_deg (each ring's mean symbol against its points, relative to the innermost ring), compression_db (the outermost ring's gain), am_pm (the outermost ring's turn, degrees) - amplifier(y, points, tol): AM/AM and AM/PM from locked symbols y and the constellation's points (rings: points within tol of a radius) - IQ(**kw): Result of `iq`: ratio (nu/mu: the conjugate's part), irr_db (image rejection, |mu/nu|^2 in dB), gain_db (I arm over Q), phase_deg (their angle off 90 degrees), dc (mean / rms), corrected (y with nu s* taken off and the DC) - iq(y): IQ imbalance of symbols (or samples) of a constellation with E[s^2] = 0, blind (see the module) - PhaseNoise(**kw): Result of `phase_noise`: rms_deg (of the phase error), white_deg (what the measured Es/N0 explains), excess_deg (the rest, rms), slow (the share of the phase error's power below a tenth of the symbol rate: much over 0.1 is phase noise slower than the symbols), spectrum (the phase error's, against frequency in symbol rates) - phase_noise(y, points, nfft): The phase of each symbol against its decision, against what white noise at the measured Es/N0 gives - Neighbour(**kw): A band over the floor besides the signal's: lo, hi (Hz), power (relative to the signal's), touching (the spectrum does not reach the floor between it and the signal) - neighbours(x, Fs, nfft, margin_db): Bands over the floor besides the strongest (the signal), from a Welch PSD: whether each reaches the floor between it and the signal (touching: a gap less than `margin_db` over the floor never opens) ## rpps.analysis.modulation.pm Phase modulation with a residual carrier (PCM/PM, telemetry and ranging): carrier, index, the data on the carrier, tones and subcarriers - PM(**kw): Result of `analyze`. - carrier_phase(x, Fs, fc, loop): (phi, z, ref): phi(t) the phase of x around a carrier at fc (Hz); z, x with fc taken off; ref, the carrier as the loop sees it, z smoothed over about 1/loop seconds (a narrow loop: it follows drift and phase noise slower than that, never the data) - share_of(z, ref): The carrier's part of the power: the tracked carrier's power over all of it (a carrier that drifts or wanders over the capture keeps its share; |mean z|^2 would average it away) - analyze(x, Fs, pfa, loop, lo, candidates, max_samples): Residual carrier, index, data rate on the carrier, tones and subcarriers of baseband samples x (see the module) - subcarrier(phi, Fs, fsc, bw): A subcarrier at fsc (Hz) of the phase phi at complex baseband, bw (Hz) wide: rpps.analysis.spectrum.cyclic / detect it - nrz(phi, Fs, rate, tau): Soft symbols of NRZ data on the carrier: phi integrated over each bit (the matched filter of a rectangular pulse), from the boundary tau (samples) - biphase_symbols(phi, Fs, rate, tau): Soft symbols of biphase (Manchester) data on the carrier: the first half-bit's integral less the second's ## rpps.analysis.modulation.quality Whether hard decisions from locked symbols can be trusted for blind tests (`gate`); the Es/N0 it uses is rpps.sync.quality.measure - Gate(**kw): Result of `gate`: whether hard decisions from these symbols can be trusted for blind tests (rank, LFSR, code search), and why not. - gate(y, points, blocks, margin, max_turn, seed): Check locked symbols before their hard decisions go into a blind test (see Gate). ## rpps.analysis.sequence What was XOR'd in or spread with (see rpps.analysis) ## rpps.analysis.sequence.recurrence Every linear recurrence up to a degree, scored at once: the taps of a scrambler (feedthrough or additive), a differential code, or a short code's checks, from hard bits - Recurrence(**kw): A check found: taps (delays, descending, without 0), poly (int: bit j = the coefficient of D^j), degree, weight (taps + 1), holds (fraction of windows it holds on), z (its bias over chance), bias (2 holds - 1, signed) - bit_windows(bits, L): Counts of the (L+1)-bit windows of bits, as an index whose bit j is the bit at delay j (bit 0 the newest) - soft_z(t, taps): The soft statistic of a check over signed reliabilities t = tanh(LLR/2) (s's +-1 expected values): sum over positions of the product over its taps, over its own standard deviation (a check that holds makes it large) - search(bits, max_degree, pfa, top, llr, shortlist): Checks f(D) s = 0 with a constant term, of degree up to max_degree (memory: 2^(max_degree+1) counts), significant at pfa over all of them, multiples of a stronger smaller one dropped: Recurrences, smallest degree first among the strongest. - Keystream(**kw): Result of `keystream`: bits (the LFSR sequence, regenerated over the whole stream), agree (the share of the decoded bits it matches), data (the stream with it taken off), checks (share of the checks holding after decoding) - keystream(bits, poly, data_bias, squarings, iters, alpha): An additive scrambler's keystream from the scrambled stream, its polynomial known (`search` finds it) and the data under it biased (idle fill, mostly-constant fields): the fast correlation attack (Meier & Staffelbach 1989). - lfsr(bits, window, windows, seed): A linear recurrence of any degree up to window/2 that the bits keep (an LFSR scrambler over constant or periodic data: a scrambler of degree d applied twice over an idle word is degree 2d + the word's period, beyond `search`'s transform): Berlekamp-Massey on `windows` windows, the connection polynomial most of them agree on, and how often it holds over the whole stream. ## rpps.analysis.sequence.scrambler Blind scrambler search: self-synchronising (feedthrough) scramblers, and additive ones (and bare LFSR sequences: PRBS) - structure(bits, lags): How far bits are from white, as z-scores: {"bias", "bytes", "autocorr", "score" (the largest)} - polynomials(max_degree, max_taps): Tap sets to try: every 1..max_taps taps up to max_degree (1 + x^a is differential decoding / NRZI at a=1) - search(bits, max_degree, max_taps, top): Find the feedthrough scrambler on hard bits. - explain(taps, max_period): Factor an LFSR recurrence into known scramblers and what is left: (scramblers [(taps, name, times)], the period the data under them repeats with (the least P whose x^P + 1 the rest divides; None if none up to max_period), rest) - lfsr_name(taps): A known name for these taps (or their reciprocal), else the polynomial written out - recurrence_holds(bits, taps): Per bit n >= max(taps): whether s[n] = XOR s[n-t] holds (1) there - additive_search(bits, window, max_len, step): Find an LFSR sequence in hard bits: a bare PRBS, or an additive scrambler showing through constant data. - descramblers(): Self-synchronising descramblers {name: taps}: out[t] = in[t] ^ in[t-k] for each tap - cached_scrambler(ref): A scrambler definition's JSON (its "poly": the taps), read once ## rpps.analysis.sequence.spread Direct-sequence spread spectrum below the noise: the code period, the chip rate, the code, and the data under it - Period(**kw): Result of `period`: lag (samples), fine (the lag between samples, from the peak's shape), seconds, chips (when chip_rate is given), contrast (the peak over the fluctuations' median at other lags: noise alone stays near 1 + a few sigma), significant - fluctuations(x, max_lag, window): Variance over windows of R_w(tau), tau = 0 .. max_lag (R_w the autocorrelation of window w): E|R_w|^2 - |E R_w|^2. - period(x, Fs, max_period, window, chip_rate, min_lag, z_min): The code period of a DSSS signal from autocorrelation fluctuations (see the module). - Code(**kw): Result of `code`: code (+-1 chips, one period), offset (chips: where a symbol starts in the chip stream), chips_rx (the chip-rate samples, from `offset`), gain (leading eigenvalue over the next: how clear) - code(x, Fs, chip_rate, chips, beta): The spreading code (`chips` long) of a DSSS signal at `chip_rate` (see the module). - despread(chips_rx, code_): Symbols: each period of chip samples correlated with the code (the processing gain back; rpps.symbol.despread.correlate) - chip_rate(x, Fs, lag, min_sps, pfa, fluct, fine): The chip rate given the code period (lag, samples, maybe a sample off): |x|^2 of a code repeating every period has lines at multiples of 1/period; the chip rate is the strongest significant one (the pulse's line) near such a multiple, at most Fs / min_sps; without one (far under the noise), from the width of the fluctuation peak (`fluct`, Period.fluct, and `fine`, Period.fine, for the narrow search): a chip. ## rpps.analysis.signal_profile A signal's profile: every step it takes to process it, as far as analysis can tell, and what it might be where it can't profiles = rp.analysis.profile(rp.source.File("ci16t", "capture.cs16", Fs=100e6)) # every signal the survey finds profiles = rp.analysis.profile(src, signals=[0, 3]) # or some of them for p in profiles: print(p) # numbered steps; an unsolved one ends the list with its top candidates p.solved, p.to_dict(), p.rx() # whether every step is known, a JSON-able form, the receiver (when solved) Each signal goes through the chain once: its channel (every signal's from one rp.signal.FFTBank: one FFT of the capture a hop for all of them), Acquire (rate, modulation, offset), the matrix matched filter and feed-forward carrier, then AcquireFEC (the code, its bit map and alignment, with the blind tools when `blind`). When no code is found, shipped profiles that find their own frames (a preamble and a header: DVB-S2) are run on the timed symbols, and named by what their own checks verify (`rank`: a step whose CRC or header code passes; the most general profile when nothing past a shared header tells them apart). A step is "found" (a definition covers it), "guess" (a blind find: a definition once saved, see rpps.analysis.result.Guess) or "unsolved", which ends the profile with what it might be: hypotheses and their weight, a softmax over their z-scores (a clear leader near 100%, close calls shared). ## rpps.analysis.spectrum What is in a capture and at what rate (see rpps.analysis) ## rpps.analysis.spectrum.burst Moved to rpps.analysis.burst. `demodulate` (stable API) stays here for one release with a DeprecationWarning - demodulate(*args, **kwargs): rpps.analysis.burst.demodulate, under its old name: it goes in the next release ## rpps.analysis.spectrum.cyclic Cyclostationary features: the symbol rate and carrier lines a signal has, and how sure each one is - Line(kind, freq, strength, pfa, significant): A spectral line of a nonlinearity of the signal. - Features(**kw): Result of `features`. - lines(z, Fs, lo, hi, pfa, top, pad, width, exclude): Significant spectral lines of the sequence `z` (sampled at Fs) between lo and hi Hz (negative frequencies allowed for a complex z): up to `top` Lines, strongest first, each at least `exclude` Hz from a stronger one (default 4 bins) - spectrum_floor(S, q, stop_db): The noise floor of a power spectrum: its q-th percentile, the bins more than `stop_db` under the median left out (a channelizer's stopband, zeros: not noise, and far under it) - occupied(x, Fs, nfft): (Wiener mask over FFT bins of x's length, occupied bandwidth Hz, (lowest, highest) frequency over the floor Hz): the signal's band estimated from a Welch PSD over its floor (the quietest tenth of the spectrum) - comb_rate(lines, Fs, lo, explain): The symbol rate behind a set of significant lines (cyclic.Line) of a nonlinearity of the signal: every line is a harmonic k R, or one folded about the sample rate, Fs - k R. The rate is the largest R whose harmonics explain explaining the most of the lines' strength (dB over the floor, summed), within (1 - `explain`)/3 of the best: a submultiple of R explains them as well but is smaller, a multiple leaves R's own line unexplained. - symbol_instants(x, Fs, baud, beta, taps): Matched-filtered samples at the symbol instants: an RRC at the baud (roll-off `beta`, a guess: a mismatch only leaves a little ISI), timing from the phase of the |y|^2 line (its cyclic component peaks at the instants). - features(x, Fs, lo, hi, pfa, orders, mask, max_samples): Symbol rate and carrier lines of baseband samples x (see the module). - scf(x, Fs, nfft, frames, hop): Spectral correlation function by the FFT accumulation method (Roberts, Brown & Loomis 1991). - alpha_profile(x, Fs, nfft, frames, bins): Max over frequency of |SCF| against cyclic frequency alpha (alpha = 0 removed): (alpha Hz, profile). ## rpps.analysis.spectrum.find Signals in a capture: centre, width, SNR and when they are on, with a false-alarm rate you set - spectrogram(x, Fs, nfft, overlap): P[t, f] (fftshifted, power per Hz) and the hop - find(x, Fs, cf, nfft, pfa, edge, drop_db, min_bins, min_across, blocks, sys_db): Signals in a capture (see the module): a Survey of Signal sorted by frequency, each with t0/t1 (when it is on, [s from the start]), bursts ([(t0, t1)], None when continuous or too weak a frame to tell; one with bursts is a Burst), score (dB over the threshold that found it) and over (the box it stands on, or None) - FloorFit(floor, a, b, sys, busy): The noise floor fitted to a spectrogram (find's step 2): floor per bin (power per Hz), the usable bins a..b (past the receiver's roll-off), the floor's own error sys (natural log) and busy: the bins clearly signal (left out of the fit, before it was widened) - fit_floor(P, hop, edge, blocks, sys_db): find's step 2 on a spectrogram P[t, f]: the FloorFit - Finder(Fs, nfft, cf, frames, refit, overlap, track, hold, **kw): Signals in a stream, block by block (a live display): find over the last `frames` frames, the floor refitted every `refit` frames [4 x frames: the receiver's passband changes slowly], ids kept from block to block (Survey.match) ## rpps.analysis.spectrum.hopping Frequency hopping: the hops, their dwell, the hop set and its spacing, and the signal de-hopped - Dwell(start, end, freq, power) - Hops(**kw): Result of `track`: dwells (Dwell: start, end s, freq Hz), dwell (s, median of whole dwells), rate (hops/s), channels (Hz, the hop set's frequencies), spacing (Hz), active (share of frames with a signal), hopping (more than one channel visited, dwells shorter than a quarter of the capture, the signal at an instant under half as wide as over the capture) - track(x, Fs, nfft, hop, snr_db, merge, width): Dwells of a frequency-hopping signal (see the module). - dehop(x, Fs, hops, guard): The signal with every dwell mixed to 0 Hz, the dwells joined in order (a `guard` share of each dwell's ends dropped: the synthesizer settling); between dwells nothing. ## rpps.analysis.spectrum.levels The finder's steps 4-6 (rpps.analysis.spectrum.find): a line raised from the floor; a signal comes up and holds its sides - boxes(c, occ, groups, min_snr, state): find's steps 4-6 by levels: the Signals of context c (see find._find_frames), the detector's marks occ. ## rpps.analysis.spectrum.ofdm_pilots OFDM pilot patterns, blind: which cells of the time-frequency grid carry known values, and the lattice they form - Grid(**kw): `grid`: Y (symbols, K) complex cells (kept subcarriers only), k (K,) their FFT bins (0 = the carrier, signed), starts (symbols,) each symbol's start (samples at fs), on (symbols,) bool, N (FFT size), ncp (CP samples at fs), fs (the resampled rate), cfo (Hz: the fractional offset taken out), rho (symbols,) each CP correlation - grid(x, Fs, tu, tcp, floor_db, off_db, max_symbols): The OFDM time-frequency grid of baseband x at Fs (see the module): Grid. - Pilots(**kw): `discover`: period (symbols), mask (period, K) pilot cells, empty (period, K) unused cells, coherence (period, K), scattered [(row, offset, spacing, count)], step (offset change a symbol of the scattered lattice, None), spacing (its subcarrier spacing), continual (kept-subcarrier indices), boost_db, lags [(lag, score)] strongest first, grid (Grid), lattices {row: (spacing, offset, t)}: each row's pilot lattice (spacing 1: the whole symbol known) - discover(x, Fs, o, tu, tcp, max_lag, share, row_coherence, min_t, weak_t, max_spacing, max_symbols): The pilot pattern of an OFDM signal x (see the module). ## rpps.analysis.spectrum.pencil Spectral lines from short records: the matrix pencil (Hua & Sarkar 1990) - lines(x, Fs, K, L, floor, max_samples): Exponentials in x: [(frequency Hz, amplitude (complex), damping 1/s (0 for a steady line))], strongest first. ## rpps.analysis.spectrum.psd - psd(samps, Fs, vbw_hz): Perform Power Spectral Density - vbw_calc(N, Fs, vbw_hz): Convert Hz to gaussian sigma - vbw(samps, smooth): Perform gaussian smoothing ## rpps.analysis.spectrum.scf Spectral coherence over all cycle frequencies (FFT accumulation), the significant ones, and blind FRESH filtering - coherence(x, Fs, nfft, frames, hop, conjugate): Spectral coherence by the FFT accumulation method (as rpps.analysis.spectrum.cyclic.scf): (f Hz, alpha Hz, |coherence|) over the points each channel pair is responsible for. - cycle_frequencies(x, Fs, nfft, conjugate, pfa, merge): Significant cycle frequencies: [(alpha Hz, coherence, conjugate)] best first, non-conjugate a > 0 only (it is symmetric) and a = 0 left out. - fresh(x, Fs, reference, shifts, taps, conj_shifts, train, reg): A frequency-shift filter for the signal `reference` is a stretch of (a known preamble, training, or what rpps.analysis.modulation.cancel regenerates from decisions): the least-squares weights over x's copies shifted by `shifts` (Hz; multiples of the wanted signal's cycle frequencies, e.g. ## rpps.analysis.spectrum.separate Two signals of equal power on one channel, separated: each one's carrier and timing, then both symbol streams - Params(**kw): One signal's: cfo (Hz), tau (s: a symbol centre), gain (complex), line (its x^M line over the spectrum's median) - Separation(**kw): `separate`: symbols [s0, s1] (decided, on each one's grid), soft [s0, s1] (corrected matched-filter outputs with the other signal taken out), params [Params, Params], evm [e0, e1], iterations - estimate(x, Fs, baud, mod, beta, search): Both signals' parameters (see the module): [Params, Params], the lower carrier first. - separate(x, Fs, baud, mod, beta, params, iterations, smooth, taps): Both symbol streams of two overlapping signals (see the module): Separation ## rpps.analysis.spectrum.signal - Signal(mid, width, bottom, height, snr, *, lo, hi, power, peak_freq, duty, resolved, Fs, cf, bin_hz, clipped): A signal found in a spectrum - Burst: A Signal on part of the time - Survey(signals, Fs, cf, nfft, K, freq, db, floor, head): The signals found in a capture (a list of Signal, by frequency), and the spectrum they came from - welch(samps, Fs, nfft, overlap): Averaged periodogram (Hann window), fftshifted. - noise_floor(db, iters, margin, start): Robust noise floor [dB]: median, then median of what is within `margin` dB above it (signals drop out) - measure_band(samps, Fs, freq, bw, cf, nfft, edge): A band given by hand (a channel plan, a band a user typed) measured as find_signals measures what it finds: a Signal with power, SNR, height, peak and duty filled in, so typed and found signals compare alike - find_signals(samps, Fs, nfft, cf, pfa, edge, drop_db, min_bins, min_across, nested, **retired): The signals in a capture: rpps.analysis.spectrum.find.find (how it works is there), as a Survey of Signal sorted by frequency, ids 0, 1... in that order - survey(source, Fs, cf, samples, more, baud, **kw): Look at a source (rp.source.File, Device) or an array, and find the signals in it - reject_spur_bauds(signals, tol, min_count, spread): Drop baud estimates that are really a line in the capture, not the signal's symbol rate ## rpps.analysis.spectrum.waveform What kind of waveform a signal is, when it isn't a single linearly modulated carrier: tones, OFDM, bursts - envelope(x): E|x|^4/E|x|^2^2: 1 constant envelope, about 1.3-1.7 filtered PSK, 2 Gaussian (noise, OFDM, many carriers) - autocorr(x): |sum x(n+L) x*(n)| / sum |x|^2 for every lag L >= 0 (by FFT) - Tones(lines, share, resolution): `tones`: lines [(Hz from the centre, share of the power)], strongest first; share: of all of it, in them - tones(x, Fs, share, max_lines, width_bins): Lines holding `share` of the power, at most `max_lines` of them, each within `width_bins` bins: Tones, or None. - OFDM(**kw): `ofdm`: tu, tcp (s), strength (the correlation at Tu: about tcp/(tu+tcp) at a high SNR), ratio (over other lags), line (the symbol-rate line over its floor), envelope, systems [(name, misfit)] that fit, best first. - ofdm(x, Fs, tu_min, tu_max, min_ratio, min_envelope, max_samples, max_rate_line): OFDM in baseband samples x at Fs: OFDM, or None (no lag stands out, no symbol period, or not Gaussian) - Bursts(duty, period, on): `bursts`: duty (fraction of the time on), period (s, None if the switching isn't periodic), on (s a period) - on_samples(x, Fs, smooth, contrast): The samples of x inside its bursts (a boolean mask): those every window of the smoothed power over them is on, so a filtered signal's dips between symbols stay in and the bursts' edges stay out. - on_off(x, Fs, smooth, contrast, min_off): Whether the power switches on and off: Bursts, or None (steady, or too weak to tell). - Waveform(tones, ofdm, bursts, envelope): `classify`: tones, ofdm, bursts (each None when not), envelope (E|x|^4/E|x|^2^2) - classify(x, Fs): Tones, OFDM, bursts and the envelope of baseband samples x at Fs (see the module): a Waveform ## rpps.base The design: data, operators, categories, contracts and the streaming rules RPPS stays signal agnostic: a new kind of signal should be new definitions plus existing operators. ### The model samples -> symbols -> channel bits -> data bits -> packets / messages Channel bits are what crosses the channel (after FEC, interleaving, scrambling, sync markers); on receive they are LLRs until the code transform decides them. Data bits are what the link layer carries. - **Transforms** turn one representation into the next, as an invertible transmit/receive pair: wave, symbol, code, link. - **Conditioning** (`signal`) changes samples without knowing what they carry. - **Sync** estimates something unknown and corrects or aligns the data with it, at **any** representation: carrier and timing on samples, phase on symbols, codeword boundaries on channel bits, packet starts on data bits. A receiver uses it many times. A **profile** (`rpps.profile`) puts these together for one signal, both directions. Data flows down the chain; **control** flows back up it: a header decoded late can change earlier steps' parameters from a known position onward, without losing lock (`rpps.base.control`, `rpps.profile.control`). ### The rule A function belongs to the category named by **what it takes and what it gives**, not by what a standard calls it. - Changes the representation: the transform for that step. - Estimates an unknown and corrects or aligns with it: sync, at whatever representation. - Changes samples without knowledge of the signal: signal. - Inserting or removing known structure belongs to the transform where the structure lives: pilots and physical headers among symbols (symbol), sync markers among channel bits (code), headers and CRCs among data bits (link). Finding where it starts is sync. Two implementations of one function share a signature, so they land in the same category. ### Categories Receive direction; transmit runs the transforms in reverse, and sync has no transmit side. | Category | Package | Takes → gives | Operator | |---|---|---|---| | Source | `source` | outside world ↔ any representation | `Source(n)`, `block >> sink` | | Conditioning | `signal` | samples → samples | `Stage`, `+` | | Sync | `sync` | any representation → the same, corrected or aligned; timing recovery takes samples to symbols | `Stage`, `+`, one-way | | Wave | `wave` | samples ↔ symbols | `Stage` pairs | | Symbol | `symbol` | symbols ↔ channel bits (LLRs on receive) | `Pipe`, `*` and `/` | | Code | `code` | channel bits ↔ data bits | `Pipe`, `*` and `/` | | Link | `link` | data bits ↔ packets | `Pipe`, `*` and `/` | | Profile | `profile` | one whole signal, both directions | builds the above | | Parallel | `parallel` | a profile's frame-parallel region | `profile.rx(parallel=...)` | "Framing" is two things on opposite sides of the decoder: **sync markers** (CCSDS ASM, DVB-S sync bytes, DVB-S2 SOF, 802.15.4 SHR) live among symbols or channel bits, are found by sync and inserted by symbol or code; **link framing** (HDLC, headers, lengths, CRCs) lives among data bits and belongs to link. A DVB-S2 receiver in order: channelize, decimate (signal) → AGC, coarse frequency (sync) → matched filter (wave) → timing (sync, gives symbols) → SOF, fine frequency and phase from pilots (sync) → PL descrambling, header and pilot removal, demapping (symbol, gives LLRs) → deinterleaving, LDPC, BCH, BB descrambling (code) → BBHEADER, packets (link). DVB-S puts sync between two code steps: Viterbi (code) → byte alignment and polarity from the sync bytes (sync) → Forney deinterleaving, Reed-Solomon, energy dispersal (code). ### Contracts `tests/unit/policy/test_contracts.py` checks these over every registered implementation. - **source**: produces blocks at any representation and says which, and which sync was already applied (for example timed, carrier not removed). Sets the rates it knows (`Fs`, `cf`, symbol rate) and each block's absolute position. Sinks take any representation. - **signal**: `SAMPLES` or `REAL` in, the same out. May change `Fs`, never needs `sps`, same in both directions. Includes `signal.channel`, the simulated medium tests use as the counterpart of sync. - **sync**: any representation in, the same out, corrected or aligned. The one exception is **timing recovery**, the sampler (`SAMPLES` at `sps` > 1 → `SYMBOLS`); the matched filter before it is wave. Estimates (offset, timing, lock, SNR, detection, frame start, polarity) go to `meta.stream`, never into the data. No inverse. - **wave**: transmit takes `SYMBOLS` and raises `sps` (shaping, FM/CPM, stagger, IFFT + CP); receive prepares samples for the sampler (matched filter, discriminator, rail realignment, CP removal + FFT) without choosing the instant. Comes in pairs (`rpps.wave`). - **symbol**: encode takes channel bits, gives symbols. Decode gives `SYMBOLS` (differential, despreading, removing pilots and headers, descrambling) or `LLR` (demapping); the last symbol step always gives soft output. - **code**: encode data bits → channel bits; decode channel bits (LLRs or hard) → data bits, LLRs when it can. FEC, interleaving, rate matching, puncturing, scrambling, line codes, sync markers; all invertible. Needs codeword boundaries known (finding them is sync). - **link**: decode aligned data bits into packets (split at lengths or flags, check CRCs, strip headers and stuffing; status in `ctx`); encode builds them. ### Grey areas Each settled by the rule. | Function | Category | Why | |---|---|---| | Matched filter | wave | prepares samples; does not decide when to sample | | Timing recovery (`OerderMeyr`, `MatTrack`, `Mat`, `Known`) | sync | estimates the instant; the one sync step that changes representation | | Differential coding on symbols / on bits (NRZI) | symbol / code | symbols ↔ symbols / bits ↔ bits | | Manchester as a pulse / as 0 → 01, 1 → 10 | wave / code | symbols ↔ samples / bits ↔ bits | | Spreading at one sample per chip (`Spread`), `Despread` at `sps` with a known code phase | symbol | chips are symbols | | Code-phase and Doppler search, preamble correlation, sync-marker and HDLC-flag search, phase ambiguity | sync | find a start or estimate an unknown | | Attaching a sync marker | code | known structure among channel bits | | Pilots, physical headers, padding, OFDM carrier allocation | symbol | known structure among symbols | | Reading a physical header's fields (DVB-S2 PLS) | symbol | `symbol.Header` decodes its short code into fields | | Equalizer, OFDM pilot equalization, squelch | sync | estimate the channel / presence | | OFDM IFFT/FFT and CP; `FMDemod`, `AMDemod`, `SSBDemod` | wave | symbols ↔ samples, carrier ↔ baseband | | De-emphasis, DC block; channel impairments | signal | samples → samples | | CRC guarding a packet / inside FEC (LTE code-block CRC) | link / code | resources are shared across categories | **Soft information only flows down the receive chain:** symbol gives LLRs, code takes and gives them, link takes hard bits and their reliability, and sync on channel bits passes LLRs through. **Order matters inside sync:** a step sits where what it corrects can still be separated (coarse frequency before the matched filter, fine phase after timing, a staggered signal's carrier before its rails are realigned). ### Type tags Every block carries a **form** (`dtype`: SAMPLES, REAL, SYMBOLS, LLR, BITS, BYTES, MSG; how values are stored) and a **representation** (`Rep`: SAMPLES, SYMBOLS, CHANNEL, DATA, PACKETS; where in the chain). Forms cross representations: LLRs exist before the decoder and after a soft-output one. Each operator declares `takes(encode)` and checks it before working, so a link decoder refuses channel bits and a constellation refuses samples; `CATEGORY` says which category it is. | Category | Accepts | Gives | |---|---|---| | signal | SAMPLES (form SAMPLES or REAL) | the same | | sync | any | the same; timing gives SYMBOLS from SAMPLES | | wave | SYMBOLS (tx), SAMPLES (rx) | SAMPLES | | symbol | CHANNEL (encode), SYMBOLS (decode) | SYMBOLS; SYMBOLS or CHANNEL as LLR | | code | DATA or CHANNEL (both ways) | CHANNEL; DATA as LLR or BITS | | link | PACKETS (encode), DATA (decode) | DATA; PACKETS (BYTES or MSG) | A code transform is often several steps, so code steps take channel and data bits alike; the enforced boundary is the link's. `rp.code.Uncoded()` is the code step of a link with no FEC. `rp.Data(x)` on a complex array is SAMPLES, `rp.Data(x, sps=1)` is SYMBOLS; `BitStage` takes channel or data bits and keeps their form. ### Data and operators **Data** (`base/data.py`) wraps an array with its `Meta`: `Fs`, `sps`, centre frequency, group delay, stream state, and `meta.pos`, the absolute position of its first item (`meta.time_of(k)` gives source time). Samples a source lost (a radio's overrun, a dropped block) are counted in it, and a stage carries a gap in its input into its output positions, so positions stay true to time. Nothing needs setting up or resetting. | Operator | Means | On | |---|---|---| | `data * pipe`, `data / pipe` | encode / decode | `Pipe` (invertible transform) | | `data + stage` | process | `Stage`, `BitStage` | | `pipe * pipe`, `stage + stage` | a reusable `Pipeline` | either | | `data >> sink` | write out | `Sink` | A `Stage` keeps its settings on the object and everything that carries between blocks in `new_state(meta)`, held by the stream; `step(samples, st, meta)` processes a block and sets `meta.op`. `SCOPE` is `STREAM` (state crosses frames) or `FRAME`. `Stream` holds states, estimates (`stream.est[name]`), detections (`det`), control (`stream.control`) and load statistics. `data + rp.Tee(a=..., b=...)` runs each branch in its own stream (FM stereo L+R and L-R). ### Streaming rules Tested by cutting the same input differently (`tests/unit/base/`, per-stage tests): 1. **Any block length, including 0**; never drop or repeat items across blocks. 2. **State lives in the stream state**, so one stage can serve several streams. 3. **Whole blocks** through `rp.base.rpps.align(ctx, key, x, block, pad)`: the leftover waits, a flush pads (encode) or drops and reports (decode). 4. **Positions are absolute**; a stage that drops or inserts items anchors it. 5. **Feedforward estimators** follow the rules in `rpps.sync` (windows at absolute positions, tracked across windows). 6. **Soft information flows down**; sync on channel bits passes LLRs through. ## rpps.base.control The control path, as operators see it (rpps.profile.control) - Control(): The control path of one stream (`stream.control`) - of(stream): The stream's Control, made on first use - publish(meta, op, fields, at, out, span, group): Fields an op decoded (or was given, transmitting), applying from absolute input position `at` onward (see module) - anchor(meta, op, at, out, rate): Absolute input position `at` became item `out` of this call's output (a step that drops or inserts items) - emit(meta, op, kind, fields, bits, ok, at, frame, parts): A decoded frame (see module): kind None takes the profile step's id ## rpps.base.data Data containers - Analog: Analog data - Mod(data, cat, dt, ctx, meta, rep): (De)Modulation data - Digital: Digital data - Data(data, ctx, flush, Fs, sps, cf, stream, delay, t0): Wrapper to get correct Data type, and set PP and DT - expect(op, data, takes, encode): Refuse `data` an operator does not take: `takes` is the set of representations it accepts (None: anything). ## rpps.base.frequency Frequencies as numbers or as people write them - Frequency: A frequency in Hz. ## rpps.base.kernel Kernels: the batch face of an operator, beside the operator it belongs to (rpps.parallel) - Batch: N frames that share a key, as one array. - to_host(a): A numpy array of `a` (a device array's copy back, `a.get()`; a numpy array as it is) - has_device_kernels(xp): True when `xp` compiles and launches kernels of its own (CuPy, on CUDA or HIP); not numpy, not a pretend device - device_functions(xp, source, names): The functions `names` of the device kernel `source` (portable CUDA C: NVRTC or hiprtc compile it as it is), compiled once per process, device and source - Kernel: A batch function. - ToHost: The batch back to the host (before a kernel that needs numpy) - ToDevice: The batch onto the device of `xp` (after a kernel that ran on the host) ## rpps.base.meta Rate information and stream state that travel with data - forward(to, name, doc): A read-only property that reads `name` of the object in attribute `to`: self.Fs is self.state.Fs - Rate(Fs, sps, cf): Sample rate (Fs), samples per symbol (sps) and centre frequency (cf) - Stream(Fs): Everything that follows one source across its blocks, shared by every block (and every data derived from it) - Meta(Fs, sps, cf, delay, stream, pos): The rate information of one block of data, as a stage sees it - timed(stream, op, fn, *args): fn(*args), its time charged to `op` in `stream.busy`: its own time only (an operator timed inside it takes its own off), so nothing is counted twice. ## rpps.base.rpps RPPS parent classes - align(ctx, key, x, block, pad, log): Whole blocks of x for a stage that works on `block` items at a time - failed_of(data): The data's `failed` mask (True where a decoder before could not decode it), or None: nothing known to have failed - Pipe: Parent class for RPPS implementations - Pipeline(*items): Pipes (and stages) applied in order. - Stage: A DSP stage operating on a continuous stream of blocks: `block + stage` - BitStage: A stage on a stream of bits: channel bits or data bits, as LLRs or hard bits (sync on bits: alignment, polarity) - tag_stages(package, category): Give every Stage class defined in `package` (a module or package name, submodules included) the Category `category`, unless the class sets its own. - Tee(**branches): The same blocks through several branches: `data + Tee(name=stage_or_pipeline, ...)` gives {name: data out} ## rpps.base.types Type tags every block of data carries (see rpps.base, Type tags) - Category: The kind of operation that produced the data - Rep: Where in the chain the data is - dtype: Data Type ## rpps.math Shared maths: finite fields, GF(2) linear algebra, cyclic-code decoding, probability, interpolation, rolling percentiles, runs of a mask, least squares, bit tricks Numpy only, no knowledge of the rest of rpps: anything two modules both need and that isn't about signals goes here. ## rpps.math.bits Bit manipulation; on hard bits (one a byte): the Hamming distance to a word at every position (`distance`, `find`) and bit destuffing over many spans (`unstuff`), in C++ when rpps._native is built - entropy(bits): Entropy of a bit stream [bits per bit]: H = -p0 log2 p0 - p1 log2 p1 (0 log 0 = 0) - reflect(v, width): Reverse the order of the low `width` bits of an integer - to_base2(order): Every `order`-bit pattern in counting order: (2^order, order) array of 0/1, most significant bit first - to_base10(arr): Rows of bits (most significant first) -> integers - hamming(a, b): Hamming distance: the number of positions where bit arrays a and b differ - distance(bits, word): The Hamming distance to `word` at every position of `bits` (len(bits) - len(word) + 1 of them, int): 0 where the word starts, len(word) where its inverse does. - find(bits, word, errors): Where `word` starts in `bits` with at most `errors` bits wrong - periodic_scores(bits, span, unit, allowed, periods, polarity): Periodic marker fit. - unstuff(bits, starts, ends, stuff): Bit destuffing (HDLC's: after `stuff` ones a 0 is dropped, `stuff` + 1 ones abort) of the spans [starts[i], ends[i]) of `bits`, each span's bits then packed into bytes least significant bit first. ## rpps.math.cyclic Algebraic decoding of cyclic codes (Reed-Solomon, BCH) from their syndromes - berlekamp_massey(gf, S, nroots, gamma): Error locator sigma (nroots+1 coefficients, lowest degree first) and its degree L from the syndromes - erasure_locator(gf, positions, N, prim): Gamma(x) = prod (1 + X_j x), X_j = alpha^((N-1-pos)*prim): lowest degree first - chien(gf, sigma, L, N, prim): Positions of a word of length N whose locator root is sigma(alpha^(-(N-1-pos)*prim)) = 0 - forney(gf, S, sigma, L, positions, N, nroots, fcr, prim): Error values at `positions`. - correct(gf, S, N, nroots, t, fcr, prim, binary, erasures): Find the errors of one word from its syndromes. ## rpps.math.demap Soft demapping of symbols to bit LLRs, for rows of symbols at once (one frame a row), on any array module `xp` - em_stride(L): Noise stride - mask_matrix(labels): (points, 2*bits) float matrix of the bit values of each point: the zeros first, then the ones. - distances(xp, y, points): Squared distances (rows, L, points) of the symbols (rows, L) from the points, and each symbol's nearest one - noise_variance(xp, d2, dmin, iters, floor, tol): Variance per real dimension of each row (rows,), by EM of one shared variance over equiprobable points: `iters` iterations, fewer when every row has stopped moving (a relative change under `tol`; EM converges geometrically, in about four at the SNR a decoder works at) - llr_rows(xp, y, points, labels, masks, noise_var, maxlog, iters, floor): LLRs log(P(bit=0)/P(bit=1)), positive means 0, of symbols (rows, L): (rows, L*bits) float32, symbol after symbol. ## rpps.math.gf Finite field GF(2^m) arithmetic - GF(m, poly): GF(2^m) with log tables ## rpps.math.gf2 Linear algebra over GF(2), and bit sequences filtered over it - parity_to_gh(n, k, p): Generator and parity-check matrices (G, H) of a systematic linear code from its parity block - gh_to_parity(n, k, G, H): Parity block p (k, n-k) of a systematic code from G = [I | p], or from H = [p^T | I] - to_checks(h): Dense parity-check matrix -> list of variable index arrays (one per check) - pack_rows(B): Rows of bits (r, c) -> (r, words) uint64, column i at word i // 64, bit 63 - i % 64: what `eliminate_packed` takes - unpack_rows(A, c): `pack_rows` undone: (r, c) uint8 - eliminate_packed(A, ncols): Reduced row echelon form in place over GF(2) of packed rows A (`pack_rows`), the first ncols columns as pivots: the pivot columns. - rref(M, pivot_cols): Reduced row echelon form of M over GF(2), bit-packed: (rows (r, n) uint8, pivot columns). - rank(M): Rank of M over GF(2): the pivots of `eliminate_packed` (the C++ kernel), else `_rank_python` - nullspace(M): Basis of {h : M h = 0} over GF(2). - systematic(h): GF(2) elimination of dense H. Returns (G, info) with H @ G.T = 0 and the message in codeword columns `info` - pmod(a, b): a(x) mod b(x) over GF(2), polynomials as Python ints (bit i: the coefficient of x^i) - pdivmod(a, b): (quotient, remainder) of a(x)/b(x) over GF(2) - pmul(a, b): a(x) b(x) over GF(2) - pgcd(*polys): Greatest common divisor over GF(2) of polynomials - porder(g, limit): Smallest N with x^N = 1 mod g(x) (the period of the recurrence g gives, the length of the cyclic code it generates), or None up to `limit` (g of degree >= 1 with g(0) = 1) - berlekamp_massey(bits): The shortest LFSR that makes a bit sequence: (C, L), C its connection polynomial (bit j the coefficient of D^j, bit 0 set: s[n] = XOR of s[n-j] over the j >= 1 where C has bit j) and L its length (the linear complexity). - fwht(a): Walsh-Hadamard transform (unnormalized) of a length-2^B array, a copy: the correlation of a distribution over B-bit words with every parity check (what the blind TCM, recurrence and RSC searches rank checks by) - lfsr_taps(C, L): The delays j (largest first) of a connection polynomial: s[n] = XOR of s[n-j] - rank_ints(vectors): Rank over GF(2) of vectors given as Python ints - fir(x, delays): y[n] = x[n] ^ XOR over d of x[n - d] (0 before the start), as uint8 0/1 - recur(u, delays, chunk): y[n] = u[n] ^ XOR over d of y[n - d] (0 before the start), as uint8 0/1, with no loop over the bits: u is filtered by g(x^(2^i)) for i < k (g = 1 + sum x^d), which leaves the recursion over delays d 2^k, run `chunk` (at least the shortest of them) bits at a time. ## rpps.math.interp Interpolation - parabolic_offset(a, b, c): Vertex offset (-0.5..0.5) of the parabola through three equally spaced samples a, b, c (b in the middle) - peak(spec, circular, log): Index of the largest value of a spectrum, and the sub-bin offset from a parabola through its neighbours - upsampled(x, a, b, base, u): x at a, a + 1/u, a + 2/u, ... up to b - REACH (its positions are absolute: x[0] is position `base`), band limited (the 12-tap windowed sinc at each k/u of a sample: fixed FIRs, one a phase). - fractional_edge(x, t, taps): `fractional` where t may be near either end of x: the samples beyond them are zeros (a stream's start or its flushed end, as a filter's history is) - fractional(x, t, taps): x (complex or real) at the fractional positions t. - interpolate(x, pos, taps, chunk): x at fractional sample positions pos (Kaiser-windowed sinc, `taps` long; x band-limited below Fs/2; outside x is 0), `chunk` positions at a time ## rpps.math.mask Boolean masks along one axis - runs(mask): (starts, stops) of the True runs of a 1-D mask, stops exclusive: two int arrays of the same length ## rpps.math.optimize Nonlinear least squares - least_squares(fun, x0, jac, max_nfev, xtol, ftol): Minimise 0.5 * sum(fun(x)**2) from `x0` (Levenberg-Marquardt with Marquardt scaling) ## rpps.math.prob Probability and statistics helpers - logsumexp(x, axis): log(sum(exp(x))) along an axis, without overflow - z_critical(trials, alpha): z a null hypothesis exceeds with probability alpha/trials (Gaussian tail estimate) - igamc(a, x): Q(a, x) = Gamma(a, x)/Gamma(a), the regularized upper incomplete gamma function (the chi-square tail: a chi-square statistic X with k degrees of freedom has P-value igamc(k/2, X/2)). - log_binom_half_cdf(n, e): log P(Binomial(n, 1/2) <= e) for every e in an array (or one), exactly, in logs (no overflow at any n): the chance a random n-bit window is within e errors of a word. - deviance_z(k, n, p0): Signed z-like score of k events in n trials against probability p0 (binomial deviance) - mixture_variance(d2, iters, floor): Noise variance per real dimension of observations scattered around equiprobable points, by EM ## rpps.math.rolling Rolling statistics of a 1-D array - percentile_filter(x, percentile, size, mode): The `percentile` (0-100) of every window of `size` samples centred on each sample of `x` (a rolling median at 50) ## rpps.utils Generic helpers ## rpps.utils.args argparse argument types - arg_freq(f): Process generic frequency arguments ## rpps.viz Visualization helpers. rpps' figures use `STYLE` (a matplotlib style, default "dark_background"; None: whatever matplotlib is set to); importing this module no longer changes the style of anyone else's figures ## rpps.viz.base Generic viz wrappers - show(): Show plots - styled(): A context in which new figures and axes get `STYLE` (nothing when it is None) - figure(): Create a new figure - subplot(*args, **kwargs): Create/get a subplot - subplots(*args, **kwargs): Create subplots - ion(): Enable interactive mode - ioff(): Disable interactive mode - cla(): Clear axes - pause(interval): Pause - axes(ax, **kw): ax, or the axes of a new figure when it is None (kw: for plt.subplots) - line(ax, x, y, title, left, right, xlabel, ylabel, grid, **style): Plot y against x and return the line. ## rpps.viz.save - FFmpegMP4(fig, fps, path, metadata, dpi): with rp.viz.save.FFmpegMP4(fig, fps, "video.mp4") as writer: ... plt.plot() ... writer.grab_frame() ## rpps.viz.utils - window(samps) - bins(count) - fft(samps) - freq_axis(count, Fs, cf)