Skip to content

Real time

# docs: skip
blocks = rp.source.Device("hackrf", cf=915e6, Fs=10e6)(65536).threaded(drop=True)  # the radio is read in a thread of its own
for out in blocks.pipelined(rx):     # and every stage of rx runs in its own thread
    ...
print(out.stream.load())             # each operator's time as a fraction of real time (over 1.0: too slow)
print(out.stream.realtime(window=2)) # one number, over the last 2 s of signal: the busiest thread (<= 1.0 keeps up)
  • Load. stream.load() is each operator's own time over the signal's: stages (+) and pipes (/, *, the decoders) alike, and a parallel region's workers. 1.0 is exactly real time. load(window=s) measures over the last s seconds of signal, so a stage that slows down shows at once. stream.realtime() adds the loads up per thread and gives the busiest: serial work is the sum, pipelined work the slowest stage, a parallel region its workers' time over their number.

  • Profiles that branch. blocks.pipelined(profile.rx()) gives a branching profile's trunk one thread and its branches another (BranchRunner.pipelined_parts), with the same output and messages as one thread. Python holds both to one core between numpy and kernel calls, so they gain less than two threads would: lte/downlink at 15.36 MS/s is 1.1x real time in one thread and 1.0x pipelined in blocks of 65536, 0.95x pipelined in 262144 (python tools/lte_bench.py). Longer blocks cost less per sample, at a block's latency.

  • Native kernels. The per-sample loops (AGC, Costas, timing recovery, equalizers, IIR, demodulators) and the decoders (Viterbi, trellis, BCJR / turbo, LDPC, Reed-Solomon, BCH, polar) run in C++ (rpps._native, built with the package) and release the GIL, so threads run them in parallel; batches of codewords are spread over the cores (RPPS_THREADS sets how many). Without a compiler RPPS uses its Python loops, the reference (RPPS_NO_NATIVE=1 forces them). Compare with python tools/bench_stages.py.
  • Frame-parallel profiles. After frame sync and the header, a profile's per-frame work can run on threads or processes in batches: Profiles, rpps.parallel.
  • Effort. rp.set_effort("fast" | "balanced" | "max"), with rp.effort(...), RPPS_EFFORT or rpps rx --effort trade speed for recovered SNR: decoder iterations, exact or max-log demapping, the timing interpolator. The levels and their measured gains are in rpps.
  • Gaps. Samples the radio lost (an overrun) and blocks threaded(drop=True) discarded are counted in meta.pos, at the source and through every stage, so positions and meta.time_of(k) stay true to time across a gap; out.stream.dropped is how many source samples were lost. Device dates the stream from the radio's clock where it timestamps its samples (else the host's).
  • GPUs. A frame-parallel region's kernels run on any array module: xp, _ = rpps._accel.device() gives CuPy (built for CUDA or ROCm/HIP; nothing in RPPS names a vendor) or numpy without a GPU, and Parallel("thread", xp=xp) runs the region on it, one upload and one download a batch. How the hand-off works: rpps.parallel.
  • Only what you need. profile.rx(kinds={...}) builds only the steps the wanted messages need.

The pipelined threads and their load are shown end to end in streaming_io.py.

More than one signal

When one process is not enough (stream.realtime() over 1.0), there are three ways to split the work:

  1. A process per signal, each reading the radio. On a pysdrlib server's machine every RPPS process opens Device("remote"). The server shares its samples in memory, so each process reads at its own pace, and each does its own wideband downconversion.
  2. One channelizer, a process per channel. The wideband work is done once: one process publishes each channel as a pysdrlib shared-memory stream (rp.source.ShmSink), and each demodulator receives its channel like a radio, rp.source.Device("shm@rpps.<name>"). Positions stay true to time, a retune starts the receivers over, the publisher stopping ends their blocks, and a live view (pyspecan) or pysdrlib.find() sees the same channels.
  3. One process, a thread per channel, for a few channels: Channelizer, then each channel's stages.
"""Several signals at once: one process channelizes, the others each receive a channel from shared memory

    python examples/channel_shm.py

The wideband work (here a polyphase channelizer) is done once, and each channel is published as a pysdrlib shared-memory
stream (`rp.source.ShmSink`). A demodulator receives its channel like a radio, `rp.source.Device("shm@rpps.ch1")`, in a
process of its own (`python my_rx.py ch1`); here threads stand in for those processes. Positions are true to time, a
retune starts a receiver over, the publisher stopping ends its blocks, and a live view (pyspecan) or `pysdrlib.find()`
sees the same channels.

Here: two tones in a 400 kS/s capture, channelized into 4 channels of 100 kS/s; each receiver finds its tone and says
where it is in absolute frequency, from the channel's own centre. `stream.realtime()` says how much of real time a
receiver used: under 1.0 it keeps up.
"""
import os
import tempfile
import threading
import time

import numpy as np

import rpps as rp

def main():
    os.environ.setdefault("PYSDRLIB_SHM_DIR", tempfile.mkdtemp(prefix="rpps-shm-")) # (a directory of its own, for the example)
    Fs, cf, M = 400e3, 100e6, 4
    n = 200_000
    t = np.arange(n)/Fs
    tones = {"ch1": 100e3 + 7e3, "ch3": -100e3 - 12e3} # inside channels 1 and 3 (channel 3 is -100 kHz)
    x = sum(np.exp(2j*np.pi*f*t) for f in tones.values()).astype(np.complex64)
    names = [f"ch{k}" for k in range(M)]

    found = {}
    def receiver(name):
        src = rp.source.Device(f"shm@rpps.{name}")
        y = np.concatenate([np.asarray(b.data) for b in src(4000) + rp.signal.DCBlock()]) # (a demodulator would go here)
        f = np.fft.fftfreq(len(y), 1/src.Fs)[np.argmax(np.abs(np.fft.fft(y)))]
        found[name] = (src.cf + f, src.stream.realtime())

    wide = iter(rp.source.Memory(x, Fs=Fs, cf=cf)(20_000) + rp.signal.filters.Channelizer(M))
    with rp.source.ShmSink(names, labels={"ch1": "tone A", "ch3": "tone B"}) as sink:
        next(wide) >> sink # The channels exist from the first block: receivers can open them
        threads = [threading.Thread(target=receiver, args=(nm,)) for nm in tones]
        for th in threads:
            th.start()
        time.sleep(0.3) # (a receiver gets what is published once it is receiving)
        for blk in wide: # The channelizer process: wideband blocks in, one stream per channel out
            blk >> sink
    for th in threads: # Closing the sink ended the streams, and with them the receivers' blocks
        th.join()

    for name, f in tones.items():
        got, load = found[name]
        print(f"{name}: tone at {got/1e6:.4f} MHz (sent {(cf + f)/1e6:.4f}), load {load:.3f}")
        assert abs(got - (cf + f)) < 100, (name, got, cf + f)

if __name__ == "__main__":
    main()