Skip to content

Air

pysdrlib.air

The air: a medium that devices transmit into and receive from, in one process or across processes on a machine

lab = pysdrlib.air.Air("lab")
tx = pysdrlib.open("sim", air="lab", transmit=True)       # a simulated radio's transmit channels go into the air
rx = pysdrlib.open("sim", air="lab")                      # and its receive channel hears it (here, or in any process)
tx.set_tx_freq(433.92e6); tx.set_tx_sample_rate(1e6); tx.start_tx(); tx.write(x)
rx.initialize(cf=433.9e6, Fs=2e6); rx.start_rx(); y = rx.read(65536)

An Air is a name and its settings (loss_db, capacity, latency, directory); it holds nothing open. What uses it attaches channels:

  • air.tx_channel(Fs, cf, clock) → TxChannel: write(samples, Fs, cf, scale=1.0) places samples in the air at their time. Each one is a shared-memory stream (pysdrlib.shm.ShmStream, named air-<name>.<pid>-<n>, its manifest saying the rate, frequency and time of its samples). A new Fs or cf is a new generation of the stream.
  • air.rx_channel() → RxChannel: receive(first, n, cf, Fs, clock) is what it hears in its samples first..first+n: every transmit channel in the air, shifted by the difference of the frequencies, resampled to its rate, attenuated by the air's loss_db, summed. A transmit channel whose centre is beyond +-Fs/2 of the receiver's is not heard. anchor(t0, first) says when its sample first is.

Whoever makes a channel closes it. A Sim with air= (an Air, or its name) makes one receive channel and a transmit channel for each channel it transmits on, and closes them with itself; it hears its own transmission too, before its gain and ADC (gain_ref, clipping), as its own tones are. Its transmit gain (the "PA" stage) scales what goes into the air.

Time. A channel is on one of two clocks, and channels on different clocks don't hear each other:

  • "wall": seconds of time.time(). A transmit channel is paced to its rate (write waits, as a radio's queue does) and its samples are placed at the time they go out; written late, after a pause, it starts again at the time it is written (the pause is silence). Processes on one machine share the clock, so a receiver in one hears a transmitter in another, in time. A realtime Sim hears the air latency (0.1 s) late, as a radio's transfers are, so what was just written is there to hear.
  • "samples": each counts its own samples from 0 (a Sim that isn't realtime: receiving from open, transmitting from its first write), so in one process a test is exact and repeatable: write, then pump the receiver.

Within a stream, time is kept relative to its first sample, so a receiver's samples are sample-exact and phase-continuous from block to block on either clock (absolute phase isn't modelled: two receivers at different frequencies see a transmitter at different phases).

Lifetime. A transmit channel's stream lasts until it is closed (on a Sim, stop_tx is silence; close ends it). A receive channel that has seen a stream (it lists the air at every block on the samples clock, every 50 ms on the wall clock) hears it to its end even after its transmitter is closed or its process gone, so one that is behind still hears it all; one that never saw it doesn't. Each stream's ring holds capacity samples (default: a second); a receiver further behind than that misses the oldest.

airs() lists the airs in use on this machine: those with a transmit channel open, which a transmitting Sim makes at its first write (until then, and with only receivers, an air isn't listed). pysdrlib.find(virtual=True) lists a simulated radio in each. Each transmit channel is also a shm stream that pysdrlib.open("shm@air-<name>.<pid>-<n>") receives raw (hidden from find() unless virtual=True).

It is a simulator: resampling is linear (exact when the rates are equal: the nearest sample, on the time grid) and nothing is filtered, so a wideband transmitter heard by a slower receiver aliases into it; there is no multipath and no Doppler. Add noise with the receiving Sim's noise=.

Modules:

Name Description
air

Air: a medium's name and settings, and the transmit channels in it

channel

TxChannel and RxChannel: what a device attaches to an Air to transmit into it, and to receive from it

air

Air: a medium's name and settings, and the transmit channels in it

Classes:

Name Description
Air

A shared medium: a name (letters, digits, _, -), the streams under air-<name>. in the shm directory.

Functions:

Name Description
airs

{name: [manifests of its transmit channels]} of the airs on this machine with a transmit channel open (receivers

Air

Air(name='sim', directory=None, loss_db=0.0, capacity=None, latency=0.1)

A shared medium: a name (letters, digits, _, -), the streams under air-<name>. in the shm directory.

loss_db: attenuation from any transmitter to any receiver. capacity: samples each transmit channel's ring holds (default: a second). latency: seconds a realtime receiver hears the air late (a radio's transfer latency), so what was just written, by a transmitter just made, is there to hear. directory: the shm directory (pysdrlib.shm.stream.stream_dir).

It holds nothing open: two Airs of one name (in one process or two) are the same air.

Methods:

Name Description
channels

The manifests of the transmit channels in this air (fresh=False: a listing up to 50 ms old will do)

tx_channel

A transmit channel into this air, at Fs and cf, on clock ("wall" or "samples"). Close it when done

rx_channel

A receive channel from this air. Close it when done

Source code in src/pysdrlib/air/air.py
def __init__(self, name="sim", directory=None, loss_db=0.0, capacity=None, latency=0.1):
    if not name or not all(c.isalnum() or c in "_-" for c in name):
        raise ValueError(f"{name!r}: an air's name is letters, digits, '_' and '-'")
    self.name, self.directory = name, directory
    self.loss_db, self.capacity, self.latency = float(loss_db), capacity, float(latency)
    self.prefix = f"{PREFIX}{name}."
    self._lock = threading.Lock()
    self._listing, self._listed = [], 0.0
channels
channels(fresh=True) -> list

The manifests of the transmit channels in this air (fresh=False: a listing up to 50 ms old will do)

Source code in src/pysdrlib/air/air.py
def channels(self, fresh=True) -> list:
    """The manifests of the transmit channels in this air (`fresh=False`: a listing up to 50 ms old will do)"""
    with self._lock:
        if fresh or time.monotonic() - self._listed > LIST_SECONDS:
            from ..shm.stream import streams
            self._listing = streams(self.directory, prefix=self.prefix)
            self._listed = time.monotonic()
        return self._listing
tx_channel
tx_channel(Fs, cf, clock='wall')

A transmit channel into this air, at Fs and cf, on clock ("wall" or "samples"). Close it when done

Source code in src/pysdrlib/air/air.py
def tx_channel(self, Fs, cf, clock="wall"):
    """A transmit channel into this air, at `Fs` and `cf`, on `clock` ("wall" or "samples"). Close it when done"""
    from .channel import TxChannel
    return TxChannel(self, Fs, cf, clock)
rx_channel
rx_channel()

A receive channel from this air. Close it when done

Source code in src/pysdrlib/air/air.py
def rx_channel(self):
    """A receive channel from this air. Close it when done"""
    from .channel import RxChannel
    return RxChannel(self)

airs

airs(directory=None) -> dict

{name: [manifests of its transmit channels]} of the airs on this machine with a transmit channel open (receivers alone leave no trace)

Source code in src/pysdrlib/air/air.py
def airs(directory=None) -> dict:
    """{name: [manifests of its transmit channels]} of the airs on this machine with a transmit channel open (receivers
    alone leave no trace)"""
    from ..shm.stream import streams
    found = {}
    for m in streams(directory, prefix=PREFIX):
        name = (m.get("info") or {}).get("air")
        if name:
            found.setdefault(name, []).append(m)
    return found

channel

TxChannel and RxChannel: what a device attaches to an Air to transmit into it, and to receive from it

Classes:

Name Description
TxChannel

One transmit channel's stream in an air: write(samples) places them at their time (see pysdrlib.air)

RxChannel

One receive channel from an air: receive is what it hears in a block of its samples (see pysdrlib.air).

TxChannel

TxChannel(air, Fs, cf, clock='wall')

One transmit channel's stream in an air: write(samples) places them at their time (see pysdrlib.air)

Methods:

Name Description
write

Transmit complex64 samples (full scale +-1) into the air, scaled by scale (linear). A new Fs or cf is a

close

The end of this channel's transmission (receivers that have seen it still hear what was written)

Source code in src/pysdrlib/air/channel.py
def __init__(self, air, Fs, cf, clock="wall"):
    from ..shm.stream import ShmStream
    self.air, self.clock = air, _clock(clock)
    self.Fs, self.cf = float(Fs), float(cf)
    self.stream = ShmStream(f"{air.prefix}{os.getpid()}-{next(_IDS)}", self.Fs, self.cf, capacity=air.capacity,
                            directory=air.directory, clock=clock, air=air.name)
    self.t0 = None if clock == "wall" else 0.0   # the time of index 0 of this generation (wall: at the first write)
    self.index = 0                               # the index of the next sample, in this generation
write
write(samples, Fs=None, cf=None, scale=1.0)

Transmit complex64 samples (full scale +-1) into the air, scaled by scale (linear). A new Fs or cf is a new generation, starting after what was written before. On the wall clock this waits, as a radio's queue does, so no more than ~0.1 s is ahead of now. Returns the count written

Source code in src/pysdrlib/air/channel.py
def write(self, samples, Fs=None, cf=None, scale=1.0):
    """Transmit complex64 `samples` (full scale +-1) into the air, scaled by `scale` (linear). A new `Fs` or `cf` is a
    new generation, starting after what was written before. On the wall clock this waits, as a radio's queue does,
    so no more than ~0.1 s is ahead of now. Returns the count written"""
    x = np.ascontiguousarray(samples, dtype=np.complex64)
    if scale != 1.0:
        x = x * np.float32(scale)
    Fs = self.Fs if Fs is None else float(Fs)
    cf = self.cf if cf is None else float(cf)
    if (Fs, cf) != (self.Fs, self.cf):
        self._retune(Fs, cf)
    if self.clock == "samples":
        self._publish(x)
        return len(x)
    now = time.time()
    if self.t0 is None:
        self.t0 = now
    due = (now - self.t0) * self.Fs
    if self.index < due - 0.01 * self.Fs:   # written late (a pause): it goes out now, the pause was silence
        self.index = int(due)
    step = max(1, min(int(LEAD * self.Fs), self.stream.writer.capacity // 4))
    for i in range(0, len(x), step):   # paced a piece at a time: a long write never laps its own ring
        self._publish(x[i:i + step])
        ahead = self.t0 + self.index / self.Fs - time.time()
        if ahead > LEAD:
            time.sleep(ahead - LEAD)
    return len(x)
close
close()

The end of this channel's transmission (receivers that have seen it still hear what was written)

Source code in src/pysdrlib/air/channel.py
def close(self):
    """The end of this channel's transmission (receivers that have seen it still hear what was written)"""
    self.stream.close()

RxChannel

RxChannel(air)

One receive channel from an air: receive is what it hears in a block of its samples (see pysdrlib.air). Used from one thread

Methods:

Name Description
anchor

Its sample first is at time t0 (seconds on its clock)

receive

What it hears at cf, Fs in its samples first..first+n, on clock ("wall" or "samples"): complex64, before

Source code in src/pysdrlib/air/channel.py
def __init__(self, air):
    self.air = air
    self._streams = {}   # segment -> (manifest, ShmReader): every stream seen, heard to its end
    self._t0 = 0.0       # the time of sample `_first`, on the clock (wall: epoch seconds)
    self._first = 0
    self._off = 0.0      # seconds from _t0 to sample _first, across rate changes since the anchor
    self._Fs = None      # the rate since _first
anchor
anchor(t0, first=0)

Its sample first is at time t0 (seconds on its clock)

Source code in src/pysdrlib/air/channel.py
def anchor(self, t0, first=0):
    """Its sample `first` is at time `t0` (seconds on its clock)"""
    self._t0, self._first, self._off = float(t0), int(first), 0.0
receive
receive(first, n, cf, Fs, clock)

What it hears at cf, Fs in its samples first..first+n, on clock ("wall" or "samples"): complex64, before any gain of its own

Source code in src/pysdrlib/air/channel.py
def receive(self, first, n, cf, Fs, clock):
    """What it hears at `cf`, `Fs` in its samples first..first+n, on `clock` ("wall" or "samples"): complex64, before
    any gain of its own"""
    Fs = float(Fs)
    out = np.zeros(n, np.complex64)
    elapsed = self._elapsed(first, Fs)
    self._discover(_clock(clock))
    gain = np.float32(10 ** (-self.air.loss_db / 20))
    for seg, (m, r) in list(self._streams.items()):
        fs_tx = float(m["Fs"])
        rel = (self._t0 - m["wall_time"]) + elapsed   # seconds from the stream's first sample to our first
        u0 = m["wall_index"] + rel * fs_tx            # the stream's index of our first sample
        step = fs_tx / Fs
        k0 = int(np.floor(u0))
        k1 = int(np.ceil(u0 + (n - 1) * step)) + 2
        try:
            closed = r.closed   # before head: once it is closed, head is the end
            head = r.head
            if k0 >= head and closed:   # heard to its end, and its transmitter is done: forgotten
                self._forget(seg)
                continue
            df = float(m["cf"]) - cf
            if abs(df) >= Fs / 2 or k1 <= m["wall_index"] or k0 >= head:
                continue
            buf = _read(r, k0, k1)
        except ValueError:   # (the ring was let go of)
            self._forget(seg)
            continue
        if step == 1.0:   # the same rate: the nearest sample, on our grid
            off = int(np.floor(u0 - k0 + 0.5))
            piece = buf[off:off + n]
        else:
            u = (u0 - k0) + np.arange(n) * step
            i = np.floor(u).astype(np.int64)
            w = (u - i).astype(np.float32)
            piece = buf[i] * (1 - w) + buf[i + 1] * w
        if df:   # phase-continuous from block to block: from the stream's first sample
            cyc = ((df * rel) % 1.0 + df * np.arange(n) / Fs) % 1.0
            piece = piece * np.exp(np.float32(2 * np.pi) * 1j * cyc.astype(np.float32))
        out += piece * gain
    return out