Skip to content

Sim

pysdrlib.sim

A simulated radio that needs no hardware: pysdrlib.open("sim"), listed by pysdrlib.find(virtual=True).

It runs pysdrlib's real streaming path (the native queue, the stall watchdog, drop reporting, read) over a compiled device with no hardware behind it, so it stands in for a radio in examples, tests and benchmarks. The signal is a tone by default, or tones, noise and QPSK bursts built to order; it can have several channels and accept transmit, and it can drop, stall or disconnect on demand. With air= it transmits into and hears an air that other sims (in this process or another) share (pysdrlib.air). Sim's arguments (pysdrlib.open("sim", channels=2, noise=-60, ...)) are the reference.

Modules:

Name Description
sim

Simulated device.

Functions:

Name Description
find

The simulated device, and one in each air with a transmit channel open (pysdrlib.air.airs: a transmitting sim

find

find()

The simulated device, and one in each air with a transmit channel open (pysdrlib.air.airs: a transmitting sim opens its channel at its first write), listed by pysdrlib.find(virtual=True)

Source code in src/pysdrlib/sim/__init__.py
def find():
    """The simulated device, and one in each air with a transmit channel open (`pysdrlib.air.airs`: a transmitting sim
    opens its channel at its first `write`), listed by pysdrlib.find(virtual=True)"""
    from ..air import airs
    from ..devices import DeviceInfo
    found = [DeviceInfo("sim", "Simulated", None, 0, {}, {"virtual": True})]
    for name, channels in sorted(airs().items()):
        n = len(channels)
        found.append(DeviceInfo("sim", f"Simulated, in the air {name} ({n} transmitter{'s' if n != 1 else ''})", None,
                                None, {"air": name}, {"virtual": True, "air": name}))
    return found

sim

Simulated device.

A real NativeDevice with no hardware. A "streaming thread" hands raw int8 I/Q blocks to a compiled device with no hardware behind it (NullDevice), which converts and queues them as a driver's own thread does, so everything from there (the queue, the stream watchdog, drop reporting, read) is what a radio runs: it can stand in for hardware in tests and benchmarks of pysdrlib's own layers.

sdr = pysdrlib.device("sim")
sdr.open(); sdr.initialize(cf=100e6, Fs=10e6)
sdr.start_rx(); samples = sdr.get_samples()

The signal is a complex tone (see set_tone), phase-continuous across blocks. The raw stream can use any convert.SampleFormat (8-bit, 12-bit, packed, float...) to emulate different hardware.

For testing what reads it, the signal can instead be built from parts, and the stream misbehave on demand:

sdr = Sim(tones=[(100e3, -20), {"freq": 100.5e6, "level": -10}],   # (offset Hz, dBFS), or one fixed in RF
          noise=-60,                                               # dBFS of white noise
          bursts=[{"offset": -200e3, "level": -15, "period": 0.1, "duration": 0.01}],   # QPSK bursts
          gain_ref=32,          # the levels hold at 32 dB of gain; more scales them up, and the ADC clips at full scale
          retune_delay=0.05)    # a new frequency shows 50 ms of samples after set_rx_freq (stale samples in between)
sdr.drop(10_000)                # lose samples, as a radio's overflow: readers see a gap
sdr.stall(2.0); sdr.resume()    # stop delivering (for 2 s, or until resume()); what would have come is lost
sdr.disconnect()                # unplugged: once what is queued is read, read raises err.Lost

Sims can share an air (air="lab", pysdrlib.air): what one transmits, every one in it hears, in this process or another, shifted to its frequency and resampled to its rate. The transmit gain (the "PA" stage, 0-47 dB, full scale at 47) scales what goes into it.

Classes:

Name Description
Sim

Sim

Sim(realtime=True, block_samples=BLOCK_SAMPLES, tone=None, sample_format=convert.INT8, channels=1, transmit=False, *, tones=None, noise=None, bursts=None, gain_ref=None, retune_delay=0.0, seed=None, channel_db=None, air=None)

Bases: NativeDevice

realtime: pace delivery to the sample rate. False delivers as fast as the host allows. block_samples: complex samples per callback. tone: tone frequency in Hz relative to center (default Fs / 8). sample_format: layout of the raw stream the "driver" delivers (convert.SampleFormat). channels: RX (and TX) channels, like a multi-channel radio: channel k is the same tone turned by k*90 degrees transmit: accept start_tx/write; what is written (scaled by the transmit gain) is kept per channel in transmitted (with an air: sent into it instead) tones: instead of the one tone, these: (offset Hz, level dBFS) each, or a dict with "offset" (from the center) or "freq" (fixed in RF: it moves when the radio retunes) and "level" noise: dBFS of complex white noise added (None: none) bursts: QPSK bursts, dicts of "offset" or "freq", "level", "period" and "duration" (seconds), "symbol_rate" (default Fs/16) gain_ref: total receive gain (dB) at which the levels are as given: each dB more scales the signal up one, and the ADC clips at full scale. None: the gain doesn't change the signal retune_delay: seconds of samples after set_rx_freq before the new frequency shows in the signal seed: of the noise and burst symbols channel_db: dB added to the built signal of each channel (a list, one per channel): channels of different strength air: a pysdrlib.air.Air, or its name: transmit into it, and hear it (see pysdrlib.air)

Every argument can also be given to open (so pysdrlib.open("sim", channels=2, realtime=False) and pysdrlib.open("sim", air="lab", transmit=True) work, and a server's --open sim:air=lab,transmit=true)

Methods:

Name Description
configure

Change the signal: any of the constructor's tone, tones, noise, bursts, gain_ref, retune_delay,

set_tone

Tone frequency in Hz relative to center. Rounded so whole cycles fit in a block.

drop

Lose count samples (of every channel), as a radio's overflow: readers see a gap. after: once this many more

stall

Stop delivering, for seconds (None: until resume). The samples the radio would have delivered meanwhile

resume

End a stall

disconnect

As if the radio were unplugged: it stops delivering for good, and once what is queued has been read, read

pump

Deliver blocks blocks synchronously from the calling thread, not paced.

set_tx_pa_gain

TX PA gain [dB], 0-47 in 1 dB steps (default 47: what is written goes out at full scale; each dB less, 1 dB

Attributes:

Name Type Description
dropped

Samples discarded because the consumer fell behind

Source code in src/pysdrlib/sim/sim.py
def __init__(self, realtime=True, block_samples=BLOCK_SAMPLES, tone=None, sample_format=convert.INT8, channels=1,
             transmit=False, *, tones=None, noise=None, bursts=None, gain_ref=None, retune_delay=0.0, seed=None,
             channel_db=None, air=None):
    """
    realtime: pace delivery to the sample rate. False delivers as fast as the host allows.
    block_samples: complex samples per callback.
    tone: tone frequency in Hz relative to center (default Fs / 8).
    sample_format: layout of the raw stream the "driver" delivers (convert.SampleFormat).
    channels: RX (and TX) channels, like a multi-channel radio: channel k is the same tone turned by k*90 degrees
    transmit: accept start_tx/write; what is written (scaled by the transmit gain) is kept per channel in `transmitted`
        (with an `air`: sent into it instead)
    tones: instead of the one tone, these: (offset Hz, level dBFS) each, or a dict with "offset" (from the center) or
        "freq" (fixed in RF: it moves when the radio retunes) and "level"
    noise: dBFS of complex white noise added (None: none)
    bursts: QPSK bursts, dicts of "offset" or "freq", "level", "period" and "duration" (seconds), "symbol_rate" (default Fs/16)
    gain_ref: total receive gain (dB) at which the levels are as given: each dB more scales the signal up one, and the
        ADC clips at full scale. None: the gain doesn't change the signal
    retune_delay: seconds of samples after `set_rx_freq` before the new frequency shows in the signal
    seed: of the noise and burst symbols
    channel_db: dB added to the built signal of each channel (a list, one per channel): channels of different strength
    air: a `pysdrlib.air.Air`, or its name: transmit into it, and hear it (see `pysdrlib.air`)

    Every argument can also be given to `open` (so `pysdrlib.open("sim", channels=2, realtime=False)` and
    `pysdrlib.open("sim", air="lab", transmit=True)` work, and a server's `--open sim:air=lab,transmit=true`)
    """
    self._check_shape(channels, block_samples)
    self.channels = int(channels)
    self.transmit = bool(transmit)
    self.air = self._air(air)
    self._air_rx = None     # the receive channel from the air (while open)
    self._air_tx = {}       # tx channel -> its transmit channel into the air
    self._tx_written = {}   # tx channel -> samples written
    self._tx_gain = {}      # tx channel -> PA gain (dB)
    self.transmitted = {ch: [] for ch in range(self.channels)}
    super().__init__()
    self.SAMPLE_FORMAT = sample_format
    self.realtime = bool(realtime)
    self.block_samples = int(block_samples)
    self.blocks = 0         # blocks delivered since start_rx / reset_stats
    self.max_lag = 0.0      # worst seconds the producer ran behind real time
    self._tone = tone
    self._raw = None
    self._thread = None
    self._stamp = False     # stamp the next block with the time (RxMeta.hw_time)
    self._stop = threading.Event()
    self._gains = [self._default_gains() for _ in range(self.channels)]
    self.channel_db = [0.0] * self.channels
    self.configure(tones=tones, noise=noise, bursts=bursts, gain_ref=gain_ref, retune_delay=retune_delay, seed=seed,
                   channel_db=channel_db)
    self._produced = 0          # samples per channel delivered or lost since open
    self._sim_cf = None         # the frequency the signal is at (None: the device's)
    self._pending_cf = None     # (sample index, frequency): a retune not yet showing
    self._pending_drop = []     # (sample index, count): drops still to happen
    self._deliver_lock = threading.Lock()   # a block's delivery and its count are one step, as `drop` sees them
    self._stall_until = 0.0
    self.disconnected = False
    self._make_block()
dropped property
dropped

Samples discarded because the consumer fell behind

configure
configure(**signal)

Change the signal: any of the constructor's tone, tones, noise, bursts, gain_ref, retune_delay, seed and channel_db (also taken by open, so pysdrlib.open("sim", tones=...) works). Parts beyond +-Fs/2 of the frequency it is tuned to are not received, as a radio's filters would have it

Source code in src/pysdrlib/sim/sim.py
def configure(self, **signal):
    """Change the signal: any of the constructor's `tone`, `tones`, `noise`, `bursts`, `gain_ref`, `retune_delay`,
    `seed` and `channel_db` (also taken by `open`, so `pysdrlib.open("sim", tones=...)` works). Parts beyond
    +-Fs/2 of the frequency it is tuned to are not received, as a radio's filters would have it"""
    unknown = set(signal) - set(self.SIGNAL)
    if unknown:
        raise TypeError(f"Sim has no signal setting {', '.join(sorted(unknown))} (it has {', '.join(self.SIGNAL)})")
    if "tones" in signal:
        self.tones = [self._part(t) for t in (signal["tones"] or ())]
    if "noise" in signal:
        self.noise = signal["noise"]
    if "bursts" in signal:
        self.bursts = [self._part(b) for b in (signal["bursts"] or ())]
    if "gain_ref" in signal:
        self.gain_ref = signal["gain_ref"]
    if "retune_delay" in signal:
        self.retune_delay = float(signal["retune_delay"] or 0.0)
    if "seed" in signal or not hasattr(self, "_rng"):
        self._rng = np.random.default_rng(signal.get("seed"))
    if signal.get("channel_db") is not None:
        if len(signal["channel_db"]) != self.channels:
            raise ValueError(f"channel_db needs one value per channel ({self.channels})")
        self.channel_db = [float(v) for v in signal["channel_db"]]
    if "tone" in signal:
        self.set_tone(signal["tone"])
set_tone
set_tone(freq)

Tone frequency in Hz relative to center. Rounded so whole cycles fit in a block.

Source code in src/pysdrlib/sim/sim.py
def set_tone(self, freq):
    """Tone frequency in Hz relative to center. Rounded so whole cycles fit in a block."""
    self._tone = freq
    self._make_block()
drop
drop(count, after=0)

Lose count samples (of every channel), as a radio's overflow: readers see a gap. after: once this many more samples are delivered (rounded up to a whole block), so a drop can land inside a read

Source code in src/pysdrlib/sim/sim.py
def drop(self, count, after=0):
    """Lose `count` samples (of every channel), as a radio's overflow: readers see a gap. after: once this many more
    samples are delivered (rounded up to a whole block), so a drop can land inside a read"""
    with self._deliver_lock:
        self._pending_drop.append((self._produced + int(after), int(count)))
stall
stall(seconds=None)

Stop delivering, for seconds (None: until resume). The samples the radio would have delivered meanwhile are lost (a gap), as a real one overflows while nobody takes its transfers

Source code in src/pysdrlib/sim/sim.py
def stall(self, seconds=None):
    """Stop delivering, for `seconds` (None: until `resume`). The samples the radio would have delivered meanwhile
    are lost (a gap), as a real one overflows while nobody takes its transfers"""
    self._stall_until = float("inf") if seconds is None else time.monotonic() + float(seconds)
resume
resume()

End a stall

Source code in src/pysdrlib/sim/sim.py
def resume(self):
    """End a `stall`"""
    if not self.disconnected:
        self._stall_until = 0.0
disconnect
disconnect()

As if the radio were unplugged: it stops delivering for good, and once what is queued has been read, read raises err.Lost

Source code in src/pysdrlib/sim/sim.py
def disconnect(self):
    """As if the radio were unplugged: it stops delivering for good, and once what is queued has been read, `read`
    raises err.Lost"""
    self.disconnected = True
    self.stall()
pump
pump(blocks=1)

Deliver blocks blocks synchronously from the calling thread, not paced. For deterministic tests/benchmarks; not allowed while streaming.

Source code in src/pysdrlib/sim/sim.py
def pump(self, blocks=1):
    """Deliver `blocks` blocks synchronously from the calling thread, not paced.
    For deterministic tests/benchmarks; not allowed while streaming."""
    if self.state["rx"]:
        raise RuntimeError("pump() can't be used while streaming")
    self._ensure_open("pump")
    for _ in range(blocks):
        self._deliver()
set_tx_pa_gain
set_tx_pa_gain(gain=None, channel=0)

TX PA gain [dB], 0-47 in 1 dB steps (default 47: what is written goes out at full scale; each dB less, 1 dB down). None: the default. channel: which channel's. Returns the gain set

Source code in src/pysdrlib/sim/sim.py
def set_tx_pa_gain(self, gain=None, channel=0):
    """TX PA gain [dB], 0-47 in 1 dB steps (default 47: what is written goes out at full scale; each dB less, 1 dB
    down). None: the default. `channel`: which channel's. Returns the gain set"""
    self._ensure_open("set_tx_pa_gain")
    self._check_channel("tx", channel)
    return self._set_gain_stage("TX", "PA", gain, self._set_tx_pa_gain, channel)