Skip to content

Caps

pysdrlib.base.caps

What a device can do: tuning and rate ranges, gain stages, filters, antennas, settings

Device.caps is a Capabilities. Before open() it describes the device class (from the class's CAPS); after, the driver refines it for the unit that is attached (a tuner's real gain steps, the rates its firmware offers...).

caps = sdr.caps
caps.freq                 # [Range(lo, hi)]: tunable ranges
caps.rates                # [Range]: a Range with lo == hi is one discrete rate
caps.gains["rx"]          # {stage name: GainStage}, names as the device calls them
caps.settings             # {name: Setting}: the device's own controls (sdr.set_setting(name, value))

Classes:

Name Description
GainStage

One adjustable gain element of a device (its name is whatever the device calls it), in dB

Range

A closed interval [lo, hi] (lo == hi: one value). step: spacing of the values in it (0: continuous)

Chain

Hardware between a radio and the air that moves frequencies (an LNB, an up/downconverter, a mixer + power amplifier)

Setting

A device-specific control. kind: bool, int, float or str; choices: allowed values (None: any of kind)

Capabilities

See the module docstring. Lists are empty when the device has no such control

Functions:

Name Description
nearest

The value closest to value that one of ranges allows (a step is honoured)

at_least

The smallest value of ranges that is value or more (a step is honoured: the next step up), None when they all stop short of it

from_json

The inverse of Capabilities.json() (a remote device's capabilities)

for_class

A fresh copy of the capabilities a device class declares in CAPS (what is known before opening one)

GainStage dataclass

GainStage(step: float, min: float, max: float, default: Optional[float] = None, values: Optional[tuple] = None)

One adjustable gain element of a device (its name is whatever the device calls it), in dB

step: spacing of its values (0: continuous). values: the gains it really has, when they are uneven steps (a tuner's table); set gains snap to the nearest. default: what set_rx_gain() with no value sets.

Range dataclass

Range(lo: float, hi: float, step: float = 0)

A closed interval [lo, hi] (lo == hi: one value). step: spacing of the values in it (0: continuous)

Chain dataclass

Chain(direction: str = 'rx', port: Optional[str] = None, antenna: Optional[str] = None, lo: float = 0.0, invert: bool = False, lo_accuracy: Optional[float] = None, usable: list = list(), optimal: list = list(), name: str = '', channel: Optional[int] = None, polarization: Optional[str] = None, info: dict = dict())

Hardware between a radio and the air that moves frequencies (an LNB, an up/downconverter, a mixer + power amplifier) and the antenna on it. Frequencies a program asks for are over the air ("RF"); the radio tunes "IF".

direction: "rx" or "tx" (a radio can have a chain of each). port: the radio's antenna port it sits behind (None: the one for any port that has no chain of its own). channel: the radio's channel it is on (None: any), for a radio whose channels' ports share names (a B210's RX2 on channels 0 and 1, a dual-feed LNB's two outputs on them). lo: Hz of the external LO (0: none, RF == IF); a measured one where it has been measured. lo_accuracy: how well lo is known, a standard error [Hz] (None: not known; an LNB's LO is off by tens of kHz to a MHz unless measured or locked). invert: the LO is above the signal, RF = lo - IF and the spectrum arrives mirrored (RF = IF + lo otherwise). antenna: the standard of antenna fitted to it (see pysdrlib.base.antennas). usable: [Range] of RF Hz it works at at all (empty: the antenna's, else whatever the radio's tuning gives). optimal: [Range] of RF Hz it is best at (empty: the antenna's). polarization: what the feed takes in, one of POLARIZATIONS ("H", "V", "RHCP", "LHCP"; None: not said). It describes the feed, not the signal.

Methods:

Name Description
to_if

The radio frequency for an over-the-air one

to_rf

The over-the-air frequency for one the radio tunes

rf_ranges

ranges (what the radio tunes) as the over-the-air ranges they give through this chain, held to what it is usable at

describe

What is known about the antenna on it (pysdrlib.base.antennas.Antenna.describe), None when it names none: from the

to_if

to_if(rf)

The radio frequency for an over-the-air one

Source code in src/pysdrlib/base/caps.py
def to_if(self, rf):
    """The radio frequency for an over-the-air one"""
    return self.lo - rf if self.invert else rf - self.lo

to_rf

to_rf(if_)

The over-the-air frequency for one the radio tunes

Source code in src/pysdrlib/base/caps.py
def to_rf(self, if_):
    """The over-the-air frequency for one the radio tunes"""
    return self.lo - if_ if self.invert else if_ + self.lo

rf_ranges

rf_ranges(ranges)

ranges (what the radio tunes) as the over-the-air ranges they give through this chain, held to what it is usable at

Source code in src/pysdrlib/base/caps.py
def rf_ranges(self, ranges):
    """`ranges` (what the radio tunes) as the over-the-air ranges they give through this chain, held to what it is usable at"""
    out = []
    for r in ranges:
        lo, hi = self.span_to_rf(r.lo, r.hi)
        out.append(Range(lo, hi, r.step))
    use = self.usable_ranges()
    if not use:
        return out
    return [Range(max(a.lo, u.lo), min(a.hi, u.hi)) for a in out for u in use if max(a.lo, u.lo) <= min(a.hi, u.hi)]

describe

describe()

What is known about the antenna on it (pysdrlib.base.antennas.Antenna.describe), None when it names none: from the registry where it has it, else what the server said

Source code in src/pysdrlib/base/caps.py
def describe(self):
    """What is known about the antenna on it (`pysdrlib.base.antennas.Antenna.describe`), None when it names none: from the
    registry where it has it, else what the server said"""
    if not self.antenna:
        return None
    from . import antennas
    found = antennas.find(self.antenna)
    return found.describe() if found else (dict(self.info) or {"name": self.antenna})

Setting dataclass

Setting(kind: type, doc: str, method: str, choices: Optional[tuple] = None, getter: Optional[str] = None, default: Any = None, per_channel: bool = False)

A device-specific control. kind: bool, int, float or str; choices: allowed values (None: any of kind)

method: the device method that applies it (called with the value). getter: one that reads it back, if any. per_channel: those methods also take channel= (the setting is per channel).

Capabilities dataclass

Capabilities(driver: str, channels: dict = (lambda: {'rx': 1, 'tx': 0})(), shared: dict = (lambda: {'freq': 'device', 'rate': 'device', 'gain': 'channel', 'bandwidth': 'channel', 'antenna': 'channel'})(), freq: list = list(), rates: list = list(), default_freq: Optional[float] = None, default_rate: Optional[float] = None, bandwidths: dict = (lambda: {'rx': [], 'tx': []})(), gains: dict = (lambda: {'rx': {}, 'tx': {}})(), gain_modes: dict = (lambda: {'rx': ['manual'], 'tx': ['manual']})(), antennas: dict = (lambda: {'rx': [], 'tx': []})(), clock_sources: list = list(), settings: dict = dict(), chains: list = list(), retune_settle: float = 0.0, retune_samples: int = 0, info: dict = dict())

See the module docstring. Lists are empty when the device has no such control

Methods:

Name Description
stage

The named gain stage of a direction, or None if the device has no such stage

gain_range

Range of the total gain across a direction's stages

json

Plain types only (for the remote protocol, logs, UIs)

stage

stage(direction, name) -> Optional[GainStage]

The named gain stage of a direction, or None if the device has no such stage

Source code in src/pysdrlib/base/caps.py
def stage(self, direction, name) -> Optional[GainStage]:
    """The named gain stage of a direction, or None if the device has no such stage"""
    return self.gains[direction.lower()].get(str(name).upper())

gain_range

gain_range(direction='rx')

Range of the total gain across a direction's stages

Source code in src/pysdrlib/base/caps.py
def gain_range(self, direction="rx"):
    """Range of the total gain across a direction's stages"""
    stages = self.gains[direction].values()
    return Range(sum(s.min for s in stages), sum(s.max for s in stages))

json

json()

Plain types only (for the remote protocol, logs, UIs)

Source code in src/pysdrlib/base/caps.py
def json(self):
    """Plain types only (for the remote protocol, logs, UIs)"""
    def ranges(rs):
        return [[r.lo, r.hi, r.step] for r in rs]
    return {
        "driver": self.driver,
        "channels": dict(self.channels),
        "shared": dict(self.shared),
        "freq": ranges(self.freq),
        "rates": ranges(self.rates),
        "default_freq": self.default_freq,
        "default_rate": self.default_rate,
        "bandwidths": {d: ranges(v) for d, v in self.bandwidths.items()},
        "gains": {d: {n: asdict(s) for n, s in st.items()} for d, st in self.gains.items()},
        "gain_modes": {d: list(v) for d, v in self.gain_modes.items()},
        "antennas": {d: list(v) for d, v in self.antennas.items()},
        "clock_sources": list(self.clock_sources),
        "settings": {n: {"kind": s.kind.__name__, "doc": s.doc, "choices": s.choices, "default": s.default,
                     "per_channel": s.per_channel}
                     for n, s in self.settings.items()},
        "chains": [c.json() for c in self.chains],
        "retune_settle": self.retune_settle,
        "retune_samples": self.retune_samples,
        "info": dict(self.info),
    }

nearest

nearest(ranges, value)

The value closest to value that one of ranges allows (a step is honoured)

Source code in src/pysdrlib/base/caps.py
def nearest(ranges, value):
    """The value closest to `value` that one of `ranges` allows (a step is honoured)"""
    best, best_d = None, None
    for r in ranges:
        v = r.clip(value)
        if r.step:
            v = r.lo + round((v - r.lo) / r.step) * r.step
            v = r.clip(v)
        d = abs(v - value)
        if best_d is None or d < best_d:
            best, best_d = v, d
    return value if best is None else best

at_least

at_least(ranges, value)

The smallest value of ranges that is value or more (a step is honoured: the next step up), None when they all stop short of it

Source code in src/pysdrlib/base/caps.py
def at_least(ranges, value):
    """The smallest value of `ranges` that is `value` or more (a step is honoured: the next step up), None when they all stop short of it"""
    best = None
    for r in ranges:
        if value > r.hi:
            continue
        v = max(value, r.lo)
        if r.step:
            v = r.lo + math.ceil((v - r.lo) / r.step - 1e-9) * r.step
            if v > r.hi:
                continue
        if best is None or v < best:
            best = v
    return best

from_json

from_json(obj) -> Capabilities

The inverse of Capabilities.json() (a remote device's capabilities)

Source code in src/pysdrlib/base/caps.py
def from_json(obj) -> Capabilities:
    """The inverse of Capabilities.json() (a remote device's capabilities)"""
    def ranges(rs):
        return [Range(*r) for r in rs]
    return Capabilities(
        driver=obj["driver"],
        channels=dict(obj["channels"]),
        shared=dict(obj.get("shared", {})) or Capabilities(driver="").shared,
        freq=ranges(obj["freq"]),
        rates=ranges(obj["rates"]),
        default_freq=obj.get("default_freq"),
        default_rate=obj.get("default_rate"),
        bandwidths={d: ranges(v) for d, v in obj["bandwidths"].items()},
        gains={d: {n: GainStage(**{**s, "values": tuple(s["values"]) if s.get("values") else None}) for n, s in st.items()}
               for d, st in obj["gains"].items()},
        gain_modes={d: list(v) for d, v in obj["gain_modes"].items()},
        antennas={d: list(v) for d, v in obj["antennas"].items()},
        clock_sources=list(obj["clock_sources"]),
        settings={n: Setting(_KINDS.get(s["kind"], str), s["doc"], "set_setting",
                             tuple(s["choices"]) if s.get("choices") else None, default=s.get("default"),
                             per_channel=s.get("per_channel", False))
                  for n, s in obj["settings"].items()},
        chains=[chain_from_json(c) for c in obj.get("chains", [])],
        retune_settle=obj.get("retune_settle", 0.0),
        retune_samples=obj.get("retune_samples", 0),
        info=dict(obj.get("info", {})),
    )

for_class

for_class(cls) -> Capabilities

A fresh copy of the capabilities a device class declares in CAPS (what is known before opening one)

Source code in src/pysdrlib/base/caps.py
def for_class(cls) -> Capabilities:
    """A fresh copy of the capabilities a device class declares in `CAPS` (what is known before opening one)"""
    caps = copy.deepcopy(cls.CAPS) if cls.CAPS is not None else Capabilities(driver="")
    caps.driver = cls.NAME
    if cls.CAN_TRANSMIT and not caps.channels.get("tx"):
        caps.channels["tx"] = 1
    if not cls.CAN_TRANSMIT:
        caps.gains["tx"] = {}
    if cls.DUPLEX:   # separate receive and transmit synthesizers
        caps.shared.update(freq="direction", rate="direction")
    caps.retune_settle = getattr(cls, "RETUNE_SETTLE", 0.0)
    caps.retune_samples = getattr(cls, "RETUNE_SAMPLES", 0)
    return caps

pysdrlib.base.antennas

Standards of antenna, by name: the band each works at and the band it is best at

A Chain (see pysdrlib.base.caps) names the antenna fitted to a radio instead of repeating its ranges, and selection (pysdrlib.remote.choose) prefers a radio whose antenna is optimal at the frequency a program wants.

from pysdrlib.base import antennas
antennas.get("ANT500").optimal      # [Range(75e6, 1e9)]
antennas.register(antennas.Antenna("MYDISH", kind="dish", size=(0.6, 0.6), impedance=50, optimal=[Range(10e9, 12e9)]))
antennas.find_kind("lpda").measures # "boom length"
antennas.format_antenna(antennas.get("ANT500").describe())   # "ANT500 (Whip / monopole, length 20-88 cm, 50 ohm)"

Classes:

Name Description
Kind

A type of antenna. key: its short id. name: how it is shown. measures: what an antenna's size is for this type

Antenna

name: how a chain refers to it. usable: [Range] of Hz it works at at all (empty: no limit known).

Functions:

Name Description
register_kind

Make kind known (by its key and its name, case ignored). Raises ValueError for a key that is taken, unless replace

find_kind

The Kind whose key or name is text (case ignored), or None

register

Make antenna known by its name (case ignored). Raises ValueError for a name that is taken, unless replace

find

The antenna called name, or None

get

The antenna called name. Raises ValueError listing the known ones when there is none

format_antenna

One antenna as text, e.g. ANT500 (Whip / monopole, length 20-88 cm, 50 ohm); info is Antenna.describe()

Kind dataclass

Kind(key: str, name: str, measures: str = 'size')

A type of antenna. key: its short id. name: how it is shown. measures: what an antenna's size is for this type

Antenna dataclass

Antenna(name: str, usable: list = list(), optimal: list = list(), doc: str = '', kind: Optional[str] = None, size: Optional[tuple] = None, impedance: Optional[float] = None)

name: how a chain refers to it. usable: [Range] of Hz it works at at all (empty: no limit known). optimal: [Range] of Hz it is best at (empty: none declared, so it is never preferred or avoided). kind: what type it is: a key or name from KINDS, or any text for one that is not there. size: (smallest, largest) in metres of what that type measures (length of a whip, diameter of a dish; Kind.measures), the same twice for a fixed one. impedance: ohms

Methods:

Name Description
describe

Plain types only: what is known about the antenna, for clients and list

describe

describe() -> dict

Plain types only: what is known about the antenna, for clients and list

Source code in src/pysdrlib/base/antennas.py
def describe(self) -> dict:
    """Plain types only: what is known about the antenna, for clients and `list`"""
    kind = find_kind(self.kind)
    return {"name": self.name, "kind": kind.key if kind else self.kind, "kind_name": kind.name if kind else self.kind,
            "size": list(self.size) if self.size else None, "measures": kind.measures if kind else "size",
            "impedance": self.impedance, "doc": self.doc}

register_kind

register_kind(kind, replace=False)

Make kind known (by its key and its name, case ignored). Raises ValueError for a key that is taken, unless replace

Source code in src/pysdrlib/base/antennas.py
def register_kind(kind, replace=False):
    """Make `kind` known (by its key and its name, case ignored). Raises ValueError for a key that is taken, unless `replace`"""
    key = kind.key.strip().lower()
    if not key:
        raise ValueError("a kind of antenna needs a key")
    if key in KINDS and not replace:
        raise ValueError(f"kind of antenna {kind.key!r} is already registered")
    KINDS[key] = kind
    return kind

find_kind

find_kind(text)

The Kind whose key or name is text (case ignored), or None

Source code in src/pysdrlib/base/antennas.py
def find_kind(text):
    """The `Kind` whose key or name is `text` (case ignored), or None"""
    if text is None:
        return None
    text = " ".join(str(text).lower().split())
    text = _KIND_ALIASES.get(text, text)
    if text in KINDS:
        return KINDS[text]
    return next((k for k in KINDS.values() if k.name.lower() == text), None)

register

register(antenna, replace=False)

Make antenna known by its name (case ignored). Raises ValueError for a name that is taken, unless replace

Source code in src/pysdrlib/base/antennas.py
def register(antenna, replace=False):
    """Make `antenna` known by its name (case ignored). Raises ValueError for a name that is taken, unless `replace`"""
    key = _key(antenna.name)
    if not key:
        raise ValueError("an antenna needs a name")
    if key in ANTENNAS and not replace:
        raise ValueError(f"antenna {antenna.name!r} is already registered")
    ANTENNAS[key] = antenna
    return antenna

find

find(name)

The antenna called name, or None

Source code in src/pysdrlib/base/antennas.py
def find(name):
    """The antenna called `name`, or None"""
    return ANTENNAS.get(_key(name))

get

get(name)

The antenna called name. Raises ValueError listing the known ones when there is none

Source code in src/pysdrlib/base/antennas.py
def get(name):
    """The antenna called `name`. Raises ValueError listing the known ones when there is none"""
    found = find(name)
    if found is None:
        raise ValueError(f"no antenna {name!r} (known: {', '.join(a.name for a in ANTENNAS.values()) or 'none'})")
    return found

format_antenna

format_antenna(info)

One antenna as text, e.g. ANT500 (Whip / monopole, length 20-88 cm, 50 ohm); info is Antenna.describe()

Source code in src/pysdrlib/base/antennas.py
def format_antenna(info):
    """One antenna as text, e.g. `ANT500 (Whip / monopole, length 20-88 cm, 50 ohm)`; `info` is `Antenna.describe()`"""
    if not info:
        return "none"
    parts = []
    if info.get("kind_name"):
        parts.append(info["kind_name"])
    size = info.get("size")
    if size:
        lo, hi = (f"{v * 100:g}" for v in size)
        parts.append(f"{info.get('measures') or 'size'} {lo} cm" if lo == hi else f"{info.get('measures') or 'size'} {lo}-{hi} cm")
    if info.get("impedance"):
        parts.append(f"{info['impedance']:g} ohm")
    return info["name"] + (f" ({', '.join(parts)})" if parts else "")