Skip to content

Plan

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/<family>/<name>.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}]}}}

Modules:

Name Description
air

Plans from what a forward link says: a definition ("base": "builder", config/plan//.json) maps the

Classes:

Name Description
TxType
Slot
FrameType
Frame
Sequence
Hop

Frequency hopping: each frame's centre moved to one of channels (Hz from the sequence's centre), the channel

Window

Where one burst may be: its superframe sequence and count, frame number, slot number, carrier [Hz, absolute: the

Plan

A burst time plan (see the module). clock: ticks a second

Functions:

Name Description
hop_algorithm

Register a hopping algorithm: fn(k, f, n_channels, **params) -> channel index

load

A plan definition by name: rp.plan.load("demo/mftdma") (config/plan//.json)

init

A plan from a definition object

ls

The plans there are, and the builders: {family: [names]}

builder

A new builder of plans from a forward link's tables and clock references (rpps.plan.air):

TxType dataclass

TxType(id: int, btus: int = 1, offset: int = 0, fields: dict = dict())

Slot dataclass

Slot(number: int, carrier: int, freq: float, start: int, btus: int, tx_type: int)

FrameType dataclass

FrameType(id: int, duration: int, btu_duration: int, btu_bw: float, symbol_rate: float, time_units: int, grid: list, sections: list, _slots: list = None)

Methods:

Name Description
slots

The frame's timeslots, numbered from 0: in time on the lowest carrier, then the next (EN 301 545-2 7.5.1.4)

slots

slots(tx_types)

The frame's timeslots, numbered from 0: in time on the lowest carrier, then the next (EN 301 545-2 7.5.1.4)

Source code in src/rpps/plan/__init__.py
def slots(self, tx_types):
    """The frame's timeslots, numbered from 0: in time on the lowest carrier, then the next (EN 301 545-2 7.5.1.4)"""
    if self._slots is not None:
        return self._slots
    grid = sorted(self.grid)
    out, c, t = [], 0, 0
    for tx, repeat in self.sections:
        n = 1 if not tx else tx_types[tx].btus if tx in tx_types else None
        if n is None:
            raise ConfigError(f"frame type {self.id}: tx type {tx} is not in the plan's tx types")
        for _ in range(int(repeat) + 1):
            if t + n > self.time_units:
                c, t = c + 1, 0
            if c >= len(grid):
                raise ConfigError(f"frame type {self.id}: its sections need more than its {len(grid)} carriers x "
                                  f"{self.time_units} BTUs")
            out.append(Slot(len(out), c, float(grid[c]), t, n, int(tx)))
            t += n
    self._slots = out
    return out

Frame dataclass

Frame(type: int, start: int, offset: float)

Sequence dataclass

Sequence(id: int, start: int, duration: int, centre: float, count: int, frames: list, hop: object = None)

Hop

Hop(channels, carrier=None, algorithm=None, params=None)

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")

Source code in src/rpps/plan/__init__.py
def __init__(self, channels, carrier=None, algorithm=None, params=None):
    self.channels = [float(c) for c in channels]
    self.carrier, self.algorithm, self.params = carrier, algorithm, dict(params or {})
    if not self.channels or (carrier is None) == (algorithm is None):
        raise ConfigError("plan hop: channels, and a carrier expression or an algorithm (one of the two)")
    if algorithm is not None and algorithm not in HOPS:
        raise ConfigError(f"plan hop: no algorithm {algorithm!r} (have {sorted(HOPS)})")

Window dataclass

Window(sequence: int, superframe: int, frame: int, slot: int, freq: float, start: int, length: int, burst: int, symbol_rate: float, bw: float, tx_type: int, assignment: object = None)

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)

Methods:

Name Description
fields

The burst's fields: where it is, and its tx type's own (what a profile's controls drive)

fields

fields(plan)

The burst's fields: where it is, and its tx type's own (what a profile's controls drive)

Source code in src/rpps/plan/__init__.py
def fields(self, plan):
    """The burst's fields: where it is, and its tx type's own (what a profile's controls drive)"""
    tx = plan.tx_types.get(self.tx_type)
    return {"sequence": self.sequence, "superframe": self.superframe, "frame": self.frame, "slot": self.slot,
            "freq": self.freq, "tx_type": self.tx_type, "assignment": self.assignment, **(tx.fields if tx else {})}

Plan

Plan(clock=1.0, tx_types=None, frame_types=None, sequences=None, assignments=None, name='plan')

A burst time plan (see the module). clock: ticks a second

Methods:

Name Description
carriers

Every carrier [Hz] a burst of the plan can be on (a hopping sequence's every channel), with its bandwidth and

frames

A sequence's frames in frame-number order: by lowest burst frequency, start, frame type (7.5.1.1)

assign

Assignments of one superframe's frame: [(assignment id, tx type or 0)] in slot order from slot offset

windows

The bursts' places that start in [t0, t1) ticks: every slot of every frame of every superframe there (the

load

From a definition (see the module)

definition

The plan as a definition (what load reads): to save one learned or built

Source code in src/rpps/plan/__init__.py
def __init__(self, clock=1.0, tx_types=None, frame_types=None, sequences=None, assignments=None, name="plan"):
    self.clock, self.name = float(clock), name
    self.tx_types = dict(tx_types or {})
    self.frame_types = dict(frame_types or {})
    self.sequences = dict(sequences or {})
    self.assignments = dict(assignments or {}) # {(sequence, count): {frame: (offset, [(id, tx_type)])}}

carriers

carriers(sequences=None)

Every carrier [Hz] a burst of the plan can be on (a hopping sequence's every channel), with its bandwidth and symbol rate: {freq: (bw, rate)}

Source code in src/rpps/plan/__init__.py
def carriers(self, sequences=None):
    """Every carrier [Hz] a burst of the plan can be on (a hopping sequence's every channel), with its bandwidth and
    symbol rate: {freq: (bw, rate)}"""
    out = {}
    for sid, s in self.sequences.items():
        if sequences is not None and sid not in sequences:
            continue
        hops = [0.0] if s.hop is None else s.hop.channels
        for f in s.frames:
            ft = self.frame_types[f.type]
            for h in hops:
                for g in ft.grid:
                    out.setdefault(s.centre + f.offset + h + g, (ft.btu_bw, ft.symbol_rate))
    return dict(sorted(out.items()))

frames

frames(seq)

A sequence's frames in frame-number order: by lowest burst frequency, start, frame type (7.5.1.1)

Source code in src/rpps/plan/__init__.py
def frames(self, seq):
    """A sequence's frames in frame-number order: by lowest burst frequency, start, frame type (7.5.1.1)"""
    s = self.sequences[seq]
    def low(f):
        ft = self.frame_types[f.type]
        return f.offset + min(ft.grid)
    return sorted(s.frames, key=lambda f: (low(f), f.start, f.type))

assign

assign(sequence, count, frame, assignments, offset=0)

Assignments of one superframe's frame: [(assignment id, tx type or 0)] in slot order from slot offset

Source code in src/rpps/plan/__init__.py
def assign(self, sequence, count, frame, assignments, offset=0):
    """Assignments of one superframe's frame: [(assignment id, tx type or 0)] in slot order from slot `offset`"""
    self.assignments.setdefault((int(sequence), int(count) % COUNT_MOD), {})[int(frame)] = (int(offset), list(assignments))

windows

windows(t0, t1, sequences=None, assigned=False)

The bursts' places that start in [t0, t1) ticks: every slot of every frame of every superframe there (the assignments, where the plan has them, merging single-BTU slots into a tx type's and naming whose slot it is). assigned: only the slots an assignment gives

Source code in src/rpps/plan/__init__.py
def windows(self, t0, t1, sequences=None, assigned=False):
    """The bursts' places that start in [t0, t1) ticks: every slot of every frame of every superframe there (the
    assignments, where the plan has them, merging single-BTU slots into a tx type's and naming whose slot it is).
    assigned: only the slots an assignment gives"""
    out = []
    for sid, s in self.sequences.items():
        if sequences is not None and sid not in sequences:
            continue
        if s.duration <= 0:
            continue
        k0 = int((t0 - s.start)//s.duration) - 1
        k1 = int((t1 - s.start)//s.duration) + 1
        frames = self.frames(sid)
        for k in range(k0, k1 + 1):
            sf0 = s.start + k*s.duration
            count = (s.count + k) % COUNT_MOD
            given = self.assignments.get((sid, count), {})
            for fnum, f in enumerate(frames):
                ft = self.frame_types[f.type]
                f0 = sf0 + f.start
                if s.hop is not None: # (this superframe's channel)
                    f = Frame(f.type, f.start, f.offset + s.hop.offset(k, fnum))
                for w in self._slots(sid, count, fnum, f, ft, f0, s.centre, given.get(fnum), assigned):
                    if t0 <= w.start < t1:
                        out.append(w)
    out.sort(key=lambda w: (w.start, w.freq))
    return out

load staticmethod

load(name, obj)

From a definition (see the module)

Source code in src/rpps/plan/__init__.py
@staticmethod
def load(name, obj):
    """From a definition (see the module)"""
    def num(v, what):
        try:
            return float(v)
        except (TypeError, ValueError):
            raise ConfigError(f"plan {name}: {what} is a number, not {v!r}") from None
    clock = obj.get("clock", 1.0)
    tx = {}
    for k, v in (obj.get("tx_types") or {}).items():
        tx[int(k)] = TxType(int(k), int(v.get("btus", 1)), int(round(num(v.get("offset", 0), f"tx type {k} offset"))),
                            dict(v.get("fields", {})))
    fts = {}
    for k, v in (obj.get("frame_types") or {}).items():
        btu = v.get("btu") or {}
        for need in ("duration", "symbol_rate"):
            if need not in btu:
                raise ConfigError(f"plan {name}: frame type {k} needs btu.{need}")
        fts[int(k)] = FrameType(int(k), int(round(num(v.get("duration", 0), "frame duration"))),
                                int(round(num(btu["duration"], "btu duration"))), num(btu.get("bw", btu["symbol_rate"]), "btu bw"),
                                num(btu["symbol_rate"], "btu symbol_rate"), int(v.get("time_units", 1)),
                                [num(g, "grid offset") for g in (v.get("grid") or [0.0])],
                                [(int(t), int(r)) for t, r in (v.get("sections") or [])])
    seqs = {}
    for k, v in (obj.get("sequences") or {}).items():
        frames = [Frame(int(f["type"]), int(round(num(f.get("start", 0), "frame start") + j*num(f.get("every", 0), "frame every"))),
                        num(f.get("offset", 0), "frame offset"))
                  for f in v.get("frames", []) for j in range(int(f.get("repeat", 1)))] # (repeat, every: a train of frames)
        for f in frames:
            if f.type not in fts:
                raise ConfigError(f"plan {name}: sequence {k} names frame type {f.type}, not one of {sorted(fts)}")
        hop = None
        if v.get("hop"):
            h = v["hop"]
            hop = Hop(h["channels"], h.get("carrier"), h.get("algorithm"), h.get("params"))
        seqs[int(k)] = Sequence(int(k), int(round(num(v.get("start", 0), "start"))), int(round(num(v["duration"], "duration"))),
                                num(v.get("centre", 0), "centre"), int(v.get("count", 0)), frames, hop)
    p = Plan(num(clock, "clock"), tx, fts, seqs, name=name)
    for a in obj.get("assignments") or []:
        p.assign(a["sequence"], a["superframe"], a["frame"], [tuple(x) for x in a["slots"]], a.get("offset", 0))
    for ft in fts.values():
        ft.slots(tx) # (checked now)
    return p

definition

definition(comment='')

The plan as a definition (what load reads): to save one learned or built

Source code in src/rpps/plan/__init__.py
def definition(self, comment=""):
    """The plan as a definition (what `load` reads): to save one learned or built"""
    return {"base": "plan", "comment": comment, "clock": self.clock,
            "tx_types": {str(t.id): {"btus": t.btus, "offset": t.offset, "fields": dict(t.fields)} for t in self.tx_types.values()},
            "frame_types": {str(f.id): {"duration": f.duration, "btu": {"duration": f.btu_duration, "bw": f.btu_bw,
                                                                       "symbol_rate": f.symbol_rate},
                                        "time_units": f.time_units, "grid": list(f.grid),
                                        "sections": [list(s) for s in f.sections]} for f in self.frame_types.values()},
            "sequences": {str(s.id): {"start": s.start, "duration": s.duration, "centre": s.centre, "count": s.count,
                                      "frames": [{"type": f.type, "start": f.start, "offset": f.offset} for f in s.frames],
                                      **({"hop": {"channels": list(s.hop.channels), "carrier": s.hop.carrier,
                                                  "algorithm": s.hop.algorithm, "params": dict(s.hop.params)}}
                                         if s.hop is not None else {})}
                          for s in self.sequences.values()}}

hop_algorithm

hop_algorithm(name)

Register a hopping algorithm: fn(k, f, n_channels, **params) -> channel index

Source code in src/rpps/plan/__init__.py
def hop_algorithm(name):
    """Register a hopping algorithm: fn(k, f, n_channels, **params) -> channel index"""
    def deco(fn):
        HOPS[name] = fn
        return fn
    return deco

load

load(name, **params)

A plan definition by name: rp.plan.load("demo/mftdma") (config/plan//.json)

Source code in src/rpps/plan/__init__.py
def load(name, **params):
    """A plan definition by name: `rp.plan.load("demo/mftdma")` (config/plan/<family>/<name>.json)"""
    if _config.find("plan", name) is None and _config.find("plan", name, "builder") is not None:
        raise ConfigError(f"plan {name} is a plan builder: rp.plan.builder({name!r})")
    p = _config.load("plan", name, params=params)
    if not isinstance(p, Plan):
        raise ConfigError(f"plan {name} is a plan builder: rp.plan.builder({name!r})")
    return p

init

init(name, obj)

A plan from a definition object

Source code in src/rpps/plan/__init__.py
def init(name, obj):
    """A plan from a definition object"""
    return _config.load_obj("plan", name, obj)

ls

ls()

The plans there are, and the builders: {family: [names]}

Source code in src/rpps/plan/__init__.py
def ls():
    """The plans there are, and the builders: {family: [names]}"""
    return _config.ls("plan")

builder

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)

Source code in src/rpps/plan/__init__.py
def 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/<family>/<name>.json)"""
    if _config.find("plan", name, "builder") is None and _config.find("plan", name) is not None:
        raise ConfigError(f"plan {name} is a plan, not a builder: rp.plan.load({name!r})")
    b = _config.load("plan", name, "builder", params=params)
    if not isinstance(b, Builder):
        raise ConfigError(f"plan {name} is a plan, not a builder: rp.plan.load({name!r})")
    return b

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

b = rp.plan.builder("dvbrcs2/forward")
for m in forward.take_messages():   # the forward profile's messages: tables, clock reference packets, frame starts
    b.feed(m)
b.plan                              # rp.plan.Plan, its assignments those of the tables seen
b.clock(t)                          # the network clock at sample t of the forward capture (the packets, fitted)
b.tables(plan, superframes=[...])   # transmit: [(protocol, PDU)] of a plan's tables
b.reference(ncr)                    # transmit: (protocol, PDU) of one clock reference

The definition:

"clock": 27e6                       the plan's ticks a second
"tables": {"header": "rcs2_table",  the header (config/header/link) that reads each table PDU; its messages' `kind`,
           "kind": "table",         the field naming the table and each table's value of it, the protocol the PDUs
           "id": "table_id",        go in on transmit, and the head fields on transmit (expressions over
           "ids": {"sct": 160, ...},network_id and version)
           "protocol": 130,
           "tx": {"interactive_network_id": "network_id", ...}}
"sections": {"tx_types": {...}, "frame_types": {...}, "sequences": {...}, "assignments": {...}}
"reference": {...}                  the clock (below)

A section maps a table onto the plan definition's key of the same name (rpps.plan's model, as rp.plan.load reads it):

{"table": "bct", "each": "tx_types",    the table, and the list in it whose items are the section's entries (none:
 "if": "tx_format_class == 1",          the whole table is one); only the items the expression holds for
 "rx": {"id": "tx_type", "btus": "tx_block_size", "fields": {"bits": "payload_size*8"}},
 "tx": {"tx_type": "id", "tx_block_size": "btus", "payload_size": "bits//8"},
 "defaults": {"bits": 0}}

rx is the entry as a template: a string is an expression over the item's fields (its groups' fields too, by name: a sized group's, a nested group's; the enclosing items' as well), a number itself, a list each of its own, and {"each": "", "rx": template} a list of that list's items. tx_types, frame_types and sequences are keyed by the entry's "id"; an assignments entry is {sequence, superframe, frame, offset, slots: [[id, tx type]]}, and "count_bits" says how many of the superframe count's bits the table carries (counted on from the sequence's count). tx is the reverse: table fields from expressions over the entry (nested keys dotted: btu.duration; a list's element it when not an object), with {"each": "", "tx": {...}} making a list. An enum field is set by name ("modulation_scheme.name": "constellation") and a field the header's tx computes (a loop count) is left out. defaults fill names an entry or item lacks, both ways. On transmit a tx type's word (a sequence name) is there as its bits ([] when it has none).

The clock reference: packets of the network clock, each the clock at a frame start (an event) lag events before the one whose frame carries it:

"reference": {"kind": "gse", "if": "protocol == 129", "protocol": 129, "header": "rcs2_ncr",
              "rx": "base*300 + ext", "tx": {"base": "(value//300) % (1 << 33)", "ext": "value % 300"},
              "wrap": "(1 << 33)*300", "events": "pls", "lag": 2}

The builder pairs each packet (a message of kind the if holds for; its payload read by header, rx its value) with the event (messages of kind events) lag before the last one at or before it, and fits clock = a + b * sample by least squares, the wrap undone.

Classes:

Name Description
Builder

A plan and a clock from a forward link's messages (see the module). plan is None until every keyed section's

Builder

Builder(name, obj)

A plan and a clock from a forward link's messages (see the module). plan is None until every keyed section's table is in

Methods:

Name Description
feed

Take one message of the forward link's: a table, a clock reference packet or an event

value

The clock value of one reference packet's payload

pairs

(sample of the event, clock value) of each reference packet: the event lag before the one carrying it

fit

(a, b): clock = a + b * forward sample, least squares over the pairs (the clock's wrap undone); None with

clock

The clock at a forward capture sample (a time the return capture shares: its first sample's clock is the plan's

definition

The plan definition (rpps.plan's model) of the tables in, without assignments

tables

[(protocol, PDU bytes)] of a plan's tables: each keyed section's, then the assignments' of each (sequence,

reference

(protocol, PDU bytes) of the clock reference packet of a clock value

Source code in src/rpps/plan/air.py
def __init__(self, name, obj):
    self.name = name
    self.ticks = float(obj.get("clock", 1.0))
    t = obj.get("tables") or {}
    for need in ("header", "kind", "id", "ids"):
        if need not in t:
            raise ConfigError(f"plan builder {name}: tables needs {need!r}")
    self.table = t
    self.sections = dict(obj.get("sections") or {})
    bad = set(self.sections) - set(SECTIONS)
    if bad:
        raise ConfigError(f"plan builder {name}: sections are {SECTIONS}, not {sorted(bad)}")
    for k, s in self.sections.items():
        if s.get("table") not in t["ids"]:
            raise ConfigError(f"plan builder {name}: section {k} reads table {s.get('table')!r}, not one of {sorted(t['ids'])}")
        if k != "assignments" and "each" not in s:
            raise ConfigError(f"plan builder {name}: section {k} needs 'each' (the table's list of its entries)")
    self.ref = obj.get("reference")
    self._schema = self._ref_schema = None
    self.tables_in = {}                     # {table: content}, the last of each
    self.assigned = []                      # assignment tables' contents, in order
    self.events, self.packets = [], []      # sample of each event; (sample, clock value) of each packet
    self._plan, self._fit = None, None
feed
feed(m)

Take one message of the forward link's: a table, a clock reference packet or an event

Source code in src/rpps/plan/air.py
def feed(self, m):
    """Take one message of the forward link's: a table, a clock reference packet or an event"""
    f = m.fields
    r = self.ref
    if m.kind == self.table["kind"] and self.table["id"] in f:
        if m.crc_ok is False:
            return
        names = {v: k for k, v in self.table["ids"].items()}
        tab = names.get(f[self.table["id"]])
        content = (f.get("payload") or {}).get(tab)
        if tab is None or content is None:
            return
        if any(s["table"] == tab for k, s in self.sections.items() if k == "assignments"):
            self.assigned.append(content)
            if self._plan is not None:
                self._assign(self._plan, content)
        else:
            self.tables_in[tab], self._plan = content, None
    elif r is not None and m.kind == r.get("events"):
        self.events.append(m.sample)
    elif r is not None and m.kind == r["kind"] and m.payload and m.crc_ok is not False and \
            ("if" not in r or self._eval(r["if"], {k: v for k, v in f.items() if not isinstance(v, (dict, list))}, "reference if")):
        self.packets.append((m.sample, self.value(m.payload)))
        self._fit = None
value
value(payload)

The clock value of one reference packet's payload

Source code in src/rpps/plan/air.py
def value(self, payload):
    """The clock value of one reference packet's payload"""
    b = np.unpackbits(np.frombuffer(bytes(payload), np.uint8)).astype(bool)
    v, _ = self.ref_schema.parse(b)
    return self._eval(self.ref["rx"], _scope(v), "reference rx")
pairs
pairs()

(sample of the event, clock value) of each reference packet: the event lag before the one carrying it

Source code in src/rpps/plan/air.py
def pairs(self):
    """(sample of the event, clock value) of each reference packet: the event `lag` before the one carrying it"""
    ev = np.sort(np.asarray(self.events, dtype=np.float64))
    lag, out = int(self.ref.get("lag", 0)), []
    for s, v in self.packets:
        k = int(np.searchsorted(ev, s, side="right")) - 1 # (the event whose frame carries the packet)
        if k - lag >= 0:
            out.append((ev[k - lag], v))
    return out
fit
fit()

(a, b): clock = a + b * forward sample, least squares over the pairs (the clock's wrap undone); None with fewer than two

Source code in src/rpps/plan/air.py
def fit(self):
    """(a, b): clock = a + b * forward sample, least squares over the pairs (the clock's wrap undone); None with
    fewer than two"""
    if self._fit is None:
        pr = self.pairs()
        if len(pr) < 2:
            return None
        x = np.array([p[0] for p in pr])
        y = np.array([p[1] for p in pr], dtype=np.float64)
        if "wrap" in self.ref:
            y = np.unwrap(y, period=float(self._eval(self.ref["wrap"], {}, "reference wrap")))
        b, a = np.polyfit(x, y, 1)
        self._fit = (a, b)
    return self._fit
clock
clock(sample)

The clock at a forward capture sample (a time the return capture shares: its first sample's clock is the plan's origin there)

Source code in src/rpps/plan/air.py
def clock(self, sample):
    """The clock at a forward capture sample (a time the return capture shares: its first sample's clock is the plan's
    origin there)"""
    fit = self.fit()
    return None if fit is None else fit[0] + fit[1]*sample
definition
definition()

The plan definition (rpps.plan's model) of the tables in, without assignments

Source code in src/rpps/plan/air.py
def definition(self):
    """The plan definition (rpps.plan's model) of the tables in, without assignments"""
    out = {"base": "plan", "clock": self.ticks}
    for key, s in self.sections.items():
        if key == "assignments" or s["table"] not in self.tables_in:
            continue
        out[key] = {}
        for e in self._rx(s, self.tables_in[s["table"]]):
            if "id" not in e:
                raise ConfigError(f"plan builder {self.name}: section {key}'s rx gives no 'id'")
            out[key][str(int(e.pop("id")))] = e
    return out
tables
tables(plan, network_id=1, version=0, superframes=())

[(protocol, PDU bytes)] of a plan's tables: each keyed section's, then the assignments' of each (sequence, superframe count) in superframes that the plan has assignments for

Source code in src/rpps/plan/air.py
def tables(self, plan, network_id=1, version=0, superframes=()):
    """[(protocol, PDU bytes)] of a plan's tables: each keyed section's, then the assignments' of each (sequence,
    superframe count) in `superframes` that the plan has assignments for"""
    d = plan.definition()
    head = {k: self._eval(v, {"network_id": network_id, "version": version}, "tables tx") if isinstance(v, str) else v
            for k, v in (self.table.get("tx") or {}).items()}
    proto = int(self.table.get("protocol", 0))
    contents = {}
    for key, s in self.sections.items():
        if key == "assignments":
            continue
        entries = [{"id": int(k), **v} for k, v in d.get(key, {}).items()]
        if key == "tx_types":
            for e in entries:
                e["word"] = _word(e.get("fields", {}).get("word"))
        contents.setdefault(s["table"], {})[s["each"]] = [self._tx(s["tx"], e, s) for e in entries]
    out = [self._pdu(t, contents[t], head) for t in self.table["ids"] if t in contents]
    s = self.sections.get("assignments")
    for seq, count in superframes if s else ():
        given = plan.assignments.get((int(seq), int(count) % COUNT_MOD))
        if not given:
            continue
        e = {"sequence": int(seq), "superframe": int(count) % COUNT_MOD,
             "frames": [{"frame": f, "offset": off, "slots": [list(x) for x in items]} for f, (off, items) in sorted(given.items())]}
        out.append(self._pdu(s["table"], self._tx(s["tx"], e, s), head))
    return [(proto, pdu) for pdu in out]
reference
reference(value)

(protocol, PDU bytes) of the clock reference packet of a clock value

Source code in src/rpps/plan/air.py
def reference(self, value):
    """(protocol, PDU bytes) of the clock reference packet of a clock value"""
    r = self.ref
    if r is None:
        raise ConfigError(f"plan builder {self.name}: no clock reference")
    v = {k: self._eval(e, {"value": int(round(value))}, "reference tx") if isinstance(e, str) else e
         for k, e in r["tx"].items()}
    return int(r.get("protocol", 0)), _bytes(self.ref_schema.build(v))