Skip to content

Analysis

rpps.analysis

Analysis: blind estimation and measurement at any representation, outside the data path. The tree follows what is analysed, the way config/ and the implementation packages do:

  • spectrum: what is in a capture and at what rate. find (the signals' boxes at a false-alarm rate, the streaming Finder), signal (the survey: find_signals, Survey), psd, cyclic (symbol rate and carrier lines with a calibrated false alarm, the SCF), scf (every cycle frequency, FRESH), pencil (matrix-pencil lines), waveform (tones, OFDM and which system, bursts, envelope), ofdm_pilots (an OFDM grid and its pilots), burst (TDMA bursts on a shared preamble), separate (two co-channel signals), hopping (frequency hopping)
  • modulation: what carries the symbols (rate, timing, modulation, offset and phase are rp.sync.detect). cumulants (the constellation's family, blind to noise), fsk (FSK / MSK / GMSK), cpm (GMSK and SOQPSK by a per-survivor detector), pm (residual-carrier PM and its subcarriers), quality (a gate on hard decisions; Es/N0 is rp.sync.quality), impairments (compression, IQ imbalance, phase noise, neighbours), cancel (regenerate and subtract: what hides under a signal)
  • sequence: what was XOR'd in or spread with. recurrence (every recurrence to degree 24, LFSRs, keystreams), scrambler (self-synchronising and additive scramblers), spread (DSSS chip rate and code)
  • code: which code. conv (puncture: patterns on a known mother code; rsc: turbo constituents and interleaver; tcm: trellis-coded modulation), block (linear: length, alignment and checks by rank, BCH / cyclic, product; ldpc; rs; polar), interleave (block and Forney interleavers)
  • framing: how the stream is cut. frames (frame period and unique word on symbols), payload (what decoded bits carry), telemetry (PM telemetry end to end), crc (the CRC frames carry: generator, init, xorout, what it covers), fields (what each bit of a header is), marked (frames behind a sync marker, their scrambler and RS code)
  • code/conv/mother, framing/bits: a convolutional mother code's generators; sync markers, frame length and HDLC on bits
  • identify: which code a hard-bit stream carries, peeling layers (identify, which rp.sync.AcquireFEC runs, solve)
  • result: what the searches return (Hypothesis, Report, Guess) and pick
  • signal_profile: profile(source), every step that processes each signal in a capture, and what is left unsolved
  • catalogue: measured features to named systems (config/system), with the reasons Results feed the configured stages (Guess.save writes a config/fec definition, a found punctured code as a child of its mother code; rp.sync.Detection fills meta.stream.det; identify.CodeDetection names the profile that decodes a stream).

Which tool answers which question

Tools for signals no definition covers. Each states its statistic and chance level, so "nothing found" is an answer; each module's docstring has the method, reference and limits. Numpy only, outside the data path (nothing in the data path imports it, except AcquireFEC inside the call). Most take baseband at a few times the signal's width (some noise floor beside it), locked symbols, or bits. identify.solve peels layers off a decoder's output in turn; structure that holds at every alignment (constant bits, idle words) is not taken for a code. Rank methods need about n + 48 clean words of n bits; strong codes at low SNR are beyond them on channel bits.

What is it, and at what rate

Question Tool How (and limits)
symbol rate, carrier order and offset spectrum.cyclic.features lines of \|x\|^2, x^M and the discriminator against a median floor, calibrated false alarms; rate by harmonic comb
every cycle frequency (signals sharing a band) spectrum.scf.cycle_frequencies, coherence FFT-accumulation spectral coherence, conjugate too
which constellation modulation.cumulants.classify C40 ... C84 against each constellation's; orders within QAM / ASK need the SNR
FSK / MSK / GMSK, CPM index modulation.fsk.analyze, cpm_index instantaneous frequency; h from the phase lattice
GMSK / SOQPSK bits, which pulse modulation.cpm.demodulate, identify per-survivor Viterbi, each survivor its own carrier loop
OFDM pilot pattern spectrum.ofdm_pilots.discover, grid grid from CP peaks; period from coherent repetition; pilot lattice, boost, empty cells
TDMA bursts, frame and slots burst.demodulate each burst on its shared preamble, mid-amble or postamble (shared_segments), data-aided carrier and phase; its symbol clock followed; LLRs (Bursts.llrs); blind when nothing is shared
two co-channel signals of equal power spectrum.separate.estimate, separate each one's carrier, timing and phase; joint sequence estimate
which named system catalogue.match, features measured features against systems from their standards, weighted
which shipped profile profile each fixed-rate one's receive on its channel; its checks verify
PM, residual carrier, subcarriers modulation.pm.analyze, subcarrier, nrz carrier tracked, phase around it
DSSS sequence.spread.period, chip_rate, code, despread windowed autocorrelation variance; code from eigenvectors
frequency hopping spectrum.hopping.track, dehop short-time spectrum clustered into channels and dwells
kind of waveform spectrum.waveform.classify tones, OFDM numerology against known systems, bursts, envelope kurtosis
tones in a short record, neighbours spectrum.pencil.lines, modulation.impairments.neighbours matrix pencil; bands split at valleys and level steps

Is the lock good, and what is left

Question Tool How
can hard decisions be trusted modulation.quality.gate rotation, drift, near-boundary decisions against the measured Es/N0
how much is locked; what is underneath modulation.cancel.cancel, align regenerate, subtract, residual against the floor
amplifier, IQ, phase noise modulation.impairments.amplifier, iq, phase_noise ring gains and turns; image ratio; phase error from neighbours
separate an interferer spectrum.scf.fresh least-squares FRESH filter trained on a reference (not blind)

Which code, scrambler, interleaver

Question Tool How
convolutional code (rate 1/n, K) code.conv.mother.scan_conv, scan_defined_conv generator-pair parity relation against chance; the configured codes by re-encoding
puncture of a known mother code code.conv.puncture.search every rate P/(P+1) pattern through the Viterbi decoder
Reed-Solomon over GF(256) code.block.rs.search shared roots by Galois-field Fourier transform at every byte phase
binary block code code.block.linear.solve_block length from rank deficiency, checks from the null space; then cyclic / BCH, product or LDPC
block code from soft values (too noisy for the rank) code.block.linear.soft_dual, soft_find_length, solve_block(llr=, soft_length=) subsets of the likeliest clean words; checks kept on the tanh-product syndrome (BCH(63,51) named to 5 dB Eb/N0, hard bits above 6)
additive scrambler sequence.scrambler.additive_search, explain, search Berlekamp-Massey over windows; polynomials factored into known scramblers
scrambler taps sequence.recurrence.search, lfsr, keystream every recurrence to degree 24 at once; any degree by Berlekamp-Massey
trellis code on PSK labels code.conv.tcm.search Walsh-Hadamard over label windows, every rotation and labelling
turbo constituent and interleaver code.conv.rsc.constituent, turbo_interleaver, turbo_interleaver_soft 2-bit-label check; permutation from clean or noisy frames
LDPC (IRA, QC, large) code.block.ldpc.staircase, qc_staircase, qc_dual, qc_size, progressive one GF(2) solve per structure (a DVB-S2 table from k/360 + 12 clean frames)
cyclic / BCH roots code.block.ldpc.roots zero counts at every beta^j against chance
polar frozen bits code.block.polar.frozen, recognize, search per-position likelihood over frames (rate 1/2 at -2 dB from 200 frames)
interleaver code.interleave.block_search, forney_search, column_delays rank deficiency for the size; candidates scored by the code coming back

What the bits are

Question Tool How
frame period and unique word on symbols framing.frames.find, cut, bursts coherence per position over candidate periods
sync markers, frame length, HDLC framing.bits.find_sync, frame_length, scan_hdlc hits at a period, autocorrelation, flags and FCS against chance
frames behind a sync marker, their scrambler and code framing.marked.layer a marker at one period; scramblers restarted per frame; RS words decoding at each depth, against chance
PM telemetry end to end framing.telemetry.analyze BPSK per subcarrier, line code, frame period, counters
what each header bit is framing.fields.map constants, counters (either bit order, per terminal), ids, length fields, enums, random; a link header definition
code blocks a burst is made of burst.units burst lengths as overhead + n units, the unit to a symbol or so
a burst time plan, and whether one explains the bursts burst.learn_plan, check_plan BTU, frame, slots from the starts; each burst in a slot of its carrier and kind, the plan's origin and clock fitted (rp.viz.bursts, burst_timing, plan_evidence draw them)
a burst's layout, and how many transmitters burst.demodulate with rp.viz.burst_stack, burst_terminals the bursts of a kind lined up on their known symbols (where they agree); a cluster per transmitter in offset and power
which CRC, over which bits framing.crc.search GCD of frame differences (RevEng's method on bit streams); init and xorout from two lengths; config/crc names
framing in decoded bits framing.payload.signatures E1/T1, ATM, GFP, HDLC, IPv4, CCSDS ASM, MPEG-TS, fixed bits, each against chance
structured, scrambled or random framing.payload.verdict signatures, bias, linear complexity, compressibility
encrypted, or only compressed framing.randomness.test NIST SP 800-22 frequency, block, runs, serial, approximate entropy, cusum; byte chi-square and entropy

Modules:

Name Description
catalogue

A catalogue of radio systems by what the blind tools measure: features in, named systems out, with the reasons

result

What the blind code searches return: a Hypothesis (a structure and how far its test sits from chance), a Report

catalogue

A catalogue of radio systems by what the blind tools measure: features in, named systems out, with the reasons

f = rp.analysis.catalogue.features(fsk=r, frequency=935.2e6)       # from tool results (or a dict by hand)
for m in rp.analysis.catalogue.match(f)[:3]:
    print(m)        # "GSM (3GPP TS 45.004/45.002): 0.93 - modulation gmsk, baud 270833 ~ 270833, frame ..."

Features (any subset; a tool result fills the ones it measures, features maps them): modulation a family name: gmsk msk gfsk 2fsk 4fsk bpsk qpsk oqpsk 8psk pi4dqpsk 16qam 16apsk 32apsk soqpsk ofdm ppm css 8vsb pm fm am (rpps.analysis tools' own names are mapped: Detection.mod, FSK.name, cpm schemes) baud symbol rate (Hz); chip_rate and code_length for spread signals bt, h a Gaussian pulse's bandwidth-time, a CPM / FSK index beta a root-raised-cosine roll-off scs, cp OFDM subcarrier spacing (Hz) and cyclic prefix (s); pilot_spacing, pilot_step, pilot_period (symbols) frame, slots a TDMA / TDD frame (s) and its slots bandwidth occupied (Hz); frequency (Hz: the carrier, a weak hint: allocations differ by region) burst True for bursts (TDMA, MF-TDMA, packets), False for a continuous carrier sync the synchronisation signal seen: pss_sss (LTE), ssb (NR); ssb_period (s) an NR SSB burst period subcarrier, subcarrier_baud a PM telemetry subcarrier (Hz) and its symbol rate (rp.analysis.framing.telemetry) profile the shipped profile that decoded it (rp.analysis.profile's profile_name): strong evidence modulation cw: an unmodulated carrier or a beacon (the waveform step's tones)

Each system lists values (a number, a list of allowed numbers, a (lo, hi) range, or a set of names) with a relative tolerance. A feature both sides have scores +weight when it agrees and -weight when it contradicts; the score is the sum over the most it could have been plus prior (so a fit on one feature ranks below a fit on several: 1 is approached as more agrees; below 0 more contradicts than agrees), and the reasons say which. Nothing measured that a system lacks counts either way. A positive score needs two agreeing features that are not weak (frequency, bandwidth), or one strong one (baud, chip_rate, scs, code_length, profile, subcarrier): a carrier's frequency alone, or a modulation alone, names nothing. Systems the features can't tell apart are reported tied, not ordered. A blind tool reads some modulations as others (pi/4-DQPSK as 8PSK, GMSK as MSK or 2-FSK, C4FM as 4-FSK): systems list what they are seen as too.

Classes:

Name Description
Match

match: name, ref, score (-1..1), agree [(feature, reading)], contradict [(feature, reading)], tied (the names

Functions:

Name Description
load_system

A config/system definition as match takes it: {"name": its title, "ref", "id": its reference, "profile",

systems

Every system in config/system (user layers too), loaded once: [dict], in reference order

family

A modulation name from any tool as the catalogue's family name (lower case, aliases folded)

match

Systems ranked by how well measured features fit (see the module): [Match], best first; systems no feature

features

The catalogue's features from rpps.analysis results: det (modulation.Detection), fsk (fsk.FSK), cpm (cpm.CPM or a

Match

Match(**kw)

match: name, ref, score (-1..1), agree [(feature, reading)], contradict [(feature, reading)], tied (the names of other systems the features can't tell this one from: the same score and agreement)

Source code in src/rpps/analysis/catalogue.py
def __init__(self, **kw):
    for k_ in self.__slots__:
        setattr(self, k_, kw.get(k_))

load_system

load_system(name, obj)

A config/system definition as match takes it: {"name": its title, "ref", "id": its reference, "profile", "tags", and each feature}

Source code in src/rpps/analysis/catalogue.py
def load_system(name, obj):
    """A config/system definition as `match` takes it: {"name": its title, "ref", "id": its reference, "profile",
    "tags", and each feature}"""
    unknown = set(obj.get("features") or {}) - set(WEIGHTS)
    if unknown:
        raise ConfigError(f"system/{name}: no features {sorted(unknown)} (has {sorted(WEIGHTS)})")
    return {"name": obj.get("title", name), "ref": obj.get("ref"), "id": name, "profile": obj.get("profile"),
            "tags": list(obj.get("tags") or []),
            **{k_: _value(k_, v) for k_, v in (obj.get("features") or {}).items()}}

systems

systems(fresh=False)

Every system in config/system (user layers too), loaded once: [dict], in reference order

Source code in src/rpps/analysis/catalogue.py
def systems(fresh=False):
    """Every system in config/system (user layers too), loaded once: [dict], in reference order"""
    key = _config.state()
    if fresh or key not in _SYSTEMS:
        _SYSTEMS.clear()
        _SYSTEMS[key] = [_config.load("system", f"{cat}/{n}") for cat, names in _config.ls("system", blind=True).items()
                         for n in names]
    return _SYSTEMS[key]

family

family(name)

A modulation name from any tool as the catalogue's family name (lower case, aliases folded)

Source code in src/rpps/analysis/catalogue.py
def family(name):
    """A modulation name from any tool as the catalogue's family name (lower case, aliases folded)"""
    n = str(name).strip().lower()
    return ALIASES.get(n, n)

match

match(feats, systems=None, tolerance=None, top=None, prior=2.0)

Systems ranked by how well measured features fit (see the module): [Match], best first; systems no feature could be compared on are left out. tolerance: {feature: relative tolerance} over the defaults (a coarse measurement deserves a wider one)

Source code in src/rpps/analysis/catalogue.py
def match(feats, systems=None, tolerance=None, top=None, prior=2.0):
    """Systems ranked by how well measured features fit (see the module): [Match], best first; systems no feature
    could be compared on are left out. tolerance: {feature: relative tolerance} over the defaults (a coarse measurement
    deserves a wider one)"""
    tol = {k_: t for k_, (_, t) in WEIGHTS.items()}
    tol.update(tolerance or {})
    feats = {k_: v for k_, v in feats.items() if v is not None}
    out = []
    for s in systems if systems is not None else _configured():
        got = most = 0.0
        agree, against = [], []
        for key, val in feats.items():
            if s.get(key) is None or key not in WEIGHTS:
                continue
            w = WEIGHTS[key][0]
            ok, how = _agrees(key, s[key], val, tol[key] or 0.0)
            most += w
            if ok:
                got += w
                agree.append((key, how))
            else:
                got -= w
                against.append((key, how))
        if most:
            score = got/(most + prior)
            # Weak evidence is no match: two features that aren't weak must agree, or one strong one
            firm = [f for f, _ in agree if f not in WEAK]
            alone = family(feats.get("modulation", "")) == "cw" # A carrier alone is what it is
            if score > 0 and len(firm) < 2 and not any(f in STRONG for f in firm) and not alone:
                score = 0.0
            out.append(Match(name=s["name"], ref=s["ref"], score=score, agree=agree, contradict=against, tied=[]))
    out.sort(key=lambda m: (-m.score, -len(m.agree), m.name))
    for m in out: # The same score on the same features: say so rather than let the name order decide
        if m.score > 0:
            m.tied = [o.name for o in out if o is not m and abs(o.score - m.score) < 1e-9 and
                      sorted(f for f, _ in o.agree) == sorted(f for f, _ in m.agree)]
    return out[:top] if top else out

features

features(det=None, fsk=None, cpm=None, ofdm=None, pilots=None, bursts=None, spread=None, frequency=None, **more)

The catalogue's features from rpps.analysis results: det (modulation.Detection), fsk (fsk.FSK), cpm (cpm.CPM or a scheme name), ofdm (waveform.OFDM), pilots (ofdm_pilots.Pilots), bursts (burst.Bursts or waveform.Bursts), spread ((chip rate, code length)), frequency (Hz); more: any feature by name (it wins)

Source code in src/rpps/analysis/catalogue.py
def features(det=None, fsk=None, cpm=None, ofdm=None, pilots=None, bursts=None, spread=None, frequency=None, **more):
    """The catalogue's features from rpps.analysis results: det (modulation.Detection), fsk (fsk.FSK), cpm (cpm.CPM or a
    scheme name), ofdm (waveform.OFDM), pilots (ofdm_pilots.Pilots), bursts (burst.Bursts or waveform.Bursts), spread
    ((chip rate, code length)), frequency (Hz); more: any feature by name (it wins)"""
    f = {}
    if det is not None:
        f.update(modulation=det.mod, baud=det.baud, beta=det.beta)
    if fsk is not None and fsk.M is not None:
        f.update(baud=fsk.baud, h=fsk.h, modulation=("gmsk" if fsk.M == 2 and abs(fsk.h - 0.5) < 0.06 and fsk.gaussian
                 else "msk" if fsk.M == 2 and abs(fsk.h - 0.5) < 0.06 else "gfsk" if fsk.M == 2 and fsk.gaussian
                 else f"{fsk.M}fsk"))
    if cpm is not None:
        name = cpm if isinstance(cpm, str) else cpm.scheme
        f["modulation"] = family(name)
        if not isinstance(cpm, str):
            f["baud"] = cpm.baud
        if "gmsk" in name:
            f["bt"] = float(name.rsplit("_", 1)[1])
        f["h"] = 0.5
    if ofdm is not None:
        f["modulation"] = "ofdm"
        if ofdm.comb:
            f["scs"] = 1/(ofdm.comb*ofdm.tu)
        else:
            f.update(scs=1/ofdm.tu, cp=ofdm.tcp)
    if pilots is not None and pilots.period:
        f["pilot_period"] = pilots.period
        if pilots.spacing:
            f["pilot_spacing"] = pilots.spacing
        if pilots.step:
            f["pilot_step"] = pilots.step
        g = pilots.grid
        f.setdefault("scs", g.fs/g.N)
        f.setdefault("cp", g.ncp/g.fs)
    if bursts is not None and not isinstance(bursts, bool):
        f["burst"] = True
        fr = getattr(bursts, "frame", None) or getattr(bursts, "period", None)
        if fr:
            f["frame"] = fr
        sl = getattr(bursts, "slots", None)
        if sl:
            f["slots"] = len(sl)
        if getattr(bursts, "mod", None):
            f.setdefault("modulation", bursts.mod)
            f.setdefault("baud", bursts.baud)
    if isinstance(bursts, bool): # Measured as bursty, or as continuous
        f["burst"] = bursts
    if spread is not None:
        f["chip_rate"], f["code_length"] = spread
    if frequency is not None:
        f["frequency"] = frequency
    f.update(more)
    return f

result

What the blind code searches return: a Hypothesis (a structure and how far its test sits from chance), a Report of all of them, a Guess (a definition to save), and pick, the one that stands out at one alignment only

Classes:

Name Description
Hypothesis
Report

Ranked hypotheses and a verdict

Guess

A guessed definition (a code, a scrambler, a CRC). Decoding only happens from a saved config: save it, then load

Functions:

Name Description
pick

The best hypothesis that stands out, if the code fits these bits at its alignment only

Hypothesis

Hypothesis(kind, name, z, params=None, coding=None, guess=None)

Attributes:

Name Type Description
p

The chance of a z this high from chance alone (one-sided Gaussian tail)

Source code in src/rpps/analysis/result.py
def __init__(self, kind, name, z, params=None, coding=None, guess=None):
    self.kind = kind
    self.name = name
    self.z = z
    self.params = params or {}
    self.coding = coding # (folder, config name) when it is in config/fec
    self.guess = guess # The Guess (definition to save) a blind find comes with
p property
p

The chance of a z this high from chance alone (one-sided Gaussian tail)

Report

Report(hyps, trials, facts)

Ranked hypotheses and a verdict

Methods:

Name Description
p

h's p-value (the best's by default) over every hypothesis tried (Bonferroni: its own times trials, at

Attributes:

Name Type Description
verdict

The best hypothesis if it stands out from chance, else None

Source code in src/rpps/analysis/result.py
def __init__(self, hyps, trials, facts):
    self.hyps = sorted(hyps, key=lambda h: -h.z)
    self.trials = trials
    self.z_crit = z_critical(trials)
    self.facts = facts
verdict property
verdict

The best hypothesis if it stands out from chance, else None

p
p(h=None)

h's p-value (the best's by default) over every hypothesis tried (Bonferroni: its own times trials, at most 1): what the z_crit threshold tests at 0.01

Source code in src/rpps/analysis/result.py
def p(self, h=None):
    """h's p-value (the best's by default) over every hypothesis tried (Bonferroni: its own times `trials`, at
    most 1): what the z_crit threshold tests at 0.01"""
    h = self.best if h is None else h
    return None if h is None else min(1.0, h.p*max(1, self.trials))

Guess

Guess(kind, definition, evidence=None)

A guessed definition (a code, a scrambler, a CRC). Decoding only happens from a saved config: save it, then load it (rp.code.load("block/guess/"), rp.code.scram.load("feedthrough/guess/"), rp.link.load("crc/guess/"))

Methods:

Name Description
save

Write config///guess/.json (or //guess/.json). Returns the file

Source code in src/rpps/analysis/result.py
def __init__(self, kind, definition, evidence=None):
    self.kind = kind
    self.definition = definition
    self.evidence = evidence or {}
    self.plan = None # (a plan's guess: the Plan itself)
    self.scores = None # (a plan's guess: the curves it was chosen on, rp.viz.plan_evidence)
save
save(name, path=None)

Write config///guess/.json (or //guess/.json). Returns the file

Source code in src/rpps/analysis/result.py
def save(self, name, path=None):
    """Write config/<domain>/<folder>/guess/<name>.json (or <path>/<folder>/guess/<name>.json). Returns the file"""
    import json
    from pathlib import Path
    from .. import _config
    domain, sub = self.FOLDER[self.kind]
    base = Path(path) if path else _config.find_config(domain)
    folder = base / sub / "guess"
    folder.mkdir(parents=True, exist_ok=True)
    f = folder / f"{name.lower()}.json"
    obj = _config.file_obj(domain, (*([sub] if sub else []), "guess", f.stem), self.definition) # (no "base": the folder says it)
    f.write_text(json.dumps({**obj, "guess": self.evidence}, indent=1, default=lambda o: o.item() if hasattr(o, "item") else list(o)))
    return f

pick

pick(hyps, z_crit, key, fits)

The best hypothesis that stands out, if the code fits these bits at its alignment only

A code fits its own bits at one alignment (puncture phase, codeword start). Bits that fit at several did not come from it: constant bits (an unmodulated carrier) are a codeword of every linear code at every alignment, and bits repeated by a symbol rate locked too high fit a repetition code at all but a few. fits(h, other): other is as good

Source code in src/rpps/analysis/result.py
def pick(hyps, z_crit, key, fits):
    """The best hypothesis that stands out, if the code fits these bits at its alignment only

    A code fits its own bits at one alignment (puncture phase, codeword start). Bits that fit at several did not come
    from it: constant bits (an unmodulated carrier) are a codeword of every linear code at every alignment, and bits
    repeated by a symbol rate locked too high fit a repetition code at all but a few. fits(h, other): other is as good"""
    good = [h for h in hyps if h.z > z_crit]
    if not good:
        return None
    best = min(good, key=lambda h: (key(h), -h.z))
    same = [h for h in good if h.coding == best.coding and h.params["stream"] == best.params["stream"]
            and h.params.get("segment") == best.params.get("segment") # (a slip between segments moves the offset)
            and h.params["offset"] != best.params["offset"] and fits(best, h)]
    return None if same else best

rpps.analysis.burst

TDMA bursts demodulated one by one: each acquired on the preamble the bursts share, as a TDMA receiver must

r = rp.analysis.burst.demodulate(x, Fs)                       # or mod=, baud=, preamble= (symbols) when known
print(r)       # "12 bursts, qpsk at 100.0 kBd, a 48-symbol preamble; frame 4.615 ms, 8 slots; EVM 6.1% median"
b = r.bursts[0]
b.symbols, b.bits, b.cfo, b.evm, b.slot, b.frame   # carrier-, timing- and phase-corrected symbols, decided bits

Every burst comes from another transmitter (or the same one after a gap), with its own carrier offset, phase and symbol timing, and is too short to train loops on: so each is acquired on its own, data-aided, from the preamble.

  1. rpps.analysis.framing.frames.bursts gates the bursts (bursts that touch cut apart at a guard time or a power step: frames.split) and acquires each blind (rate, modulation, offset); bursts too short for that keep only their span. The modulation is the bursts' majority, the rate their median (or mod / baud).
  2. The preamble: the leading run of symbols the bursts agree on, as phase steps (rpps.analysis.framing.frames.preamble, or shared_preamble for a short one, whichever is longer), or preamble given. A network's burst types each carry a unique word of their own: when the bursts share fewer than min_shared symbols, they are grouped by length and each group's own preamble found (burst_kinds); each burst is acquired on its kind's. Known symbols elsewhere (a mid-amble, a postamble: shared_segments) serve the same way, at their offset; with none at all, each burst is returned as acquired blind (Bursts.blind: its phase known only to the constellation's symmetry). Its symbols are rebuilt from the steps and turned onto the constellation (one rotation for all bursts: the M-fold phase ambiguity is the same for every burst, so their bits agree with each other).
  3. In each burst the preamble is found by correlating its shaped waveform in pieces (the pieces' magnitudes added: a carrier offset costs little), then the fractional timing that best matches the preamble's phase steps (blind to the carrier), then from z_k = y_k conj(p_k) over the preamble: the carrier offset (the mean turn of z_k z*_{k-1}) and the phase and gain (sum z_k with the turn taken out).
  4. The burst's symbols, from the preamble to the end of the gate, are taken at that timing and corrected. A burst of several windows has its symbol clock followed (retime): the matched filter's energy peak in each window (rpps.sync.time.mat.best_tau), a line through them anchored on the preamble (the clock offset, clock). A second- phase from decisions on the constellation's points, tracked across 32-symbol windows (rpps.sync.phase.decided), follows what is left of the carrier through the data; decisions give bits, the soft demapper LLRs (llr, noise from the burst's own symbols), and the error vector magnitude.
  5. The TDMA structure: the period of the bursts' starts (rpps.analysis.spectrum.waveform.on_off, else frame) and the slots, clusters of the starts within a frame (to within slot_tol symbols): each burst's frame and slot. Limits: the clock is followed as a straight line (a constant offset over the burst), from windows of a few hundred symbols; a burst whose preamble is weaker than the data's noise floor allows is reported with ok False and no bits.

A network's burst time plan (rpps.plan) from the bursts rp.sync.Bursts detects: learn_plan (the BTU, the frame, each carrier's slots and the kinds of burst in them), and whether a plan, learned or told, explains the bursts: check_plan (each burst in a slot of its carrier and kind, the plan's origin and clock fitted to them; rp.viz.bursts draws it, folded on the superframe or along the capture).

Modules: preamble (what the bursts share), demod (each burst acquired and demodulated; the frame and slots), plan (units, learn_plan, check_plan).

what a receiver runs is in the data path, which may not import this package.
  • rpps.sync.burst: Burst (bursts gated from a stream by energy), BurstTx (bursts placed in a stream)
  • rpps.sync.plan: Bursts (bursts cut where a burst time plan puts them), PlanTx
  • rpps.profile.burst: the runners for a profile's burst step (receive and transmit)
  • rpps.plan: burst time plans as definitions; rpps.viz.plots.bursts draws bursts against them

Modules:

Name Description
demod

Each burst acquired on its preamble and demodulated (acquire, retime, demodulate), and the TDMA frame and slots

plan

A network's burst time plan (rpps.plan) from the bursts rp.sync.Bursts detects: the code blocks a burst is made of

preamble

What a TDMA network's bursts share: the preamble (shared_preamble, preamble_symbols), known symbols elsewhere

demod

Each burst acquired on its preamble and demodulated (acquire, retime, demodulate), and the TDMA frame and slots the bursts' starts show. See rpps.analysis.burst

Classes:

Name Description
BurstResult

One burst: start (sample of its preamble's first symbol, fractional), symbols, bits, llr (per bit, log(P0/P1), the

Bursts

What demodulate gives: the bursts and what they share

Functions:

Name Description
acquire

The preamble pre (symbols) in samples x at Fs: (start sample of its first symbol (fractional), score 0..1,

retime

Symbol centres c (samples of x, one a symbol) with the symbol clock's offset taken out, and that offset

demodulate

Every burst of x, demodulated on its own from its preamble (see the module). Bursts of several kinds, each with a

BurstResult

BurstResult(**kw)

One burst: start (sample of its preamble's first symbol, fractional), symbols, bits, llr (per bit, log(P0/P1), the preamble's included, as bits), cfo (Hz), clock (its symbol clock's offset, a fraction: +1e-4 is 100 ppm fast), phase (rad), gain, score (the preamble's correlation 0..1), evm (rms, of the data after the preamble), frame, slot, kind (which of the preambles it was acquired on), known ((first, length): the known symbols in symbols), ok

Attributes:

Name Type Description
payload

The symbols without the known ones

Source code in src/rpps/analysis/burst/demod.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))
payload property
payload

The symbols without the known ones

Bursts

Bursts(**kw)

What demodulate gives: the bursts and what they share

bursts [BurstResult], mod, baud, beta, preamble (symbols: the most common kind's), preambles (every kind's), offsets (each kind's known symbols from the bursts' start; negative: from their end), frame (s, None), slots (offsets within the frame, s), blind (no known symbols: each burst's phase only to the constellation's symmetry), period (symbols: a unique word repeating that often within each burst, at its own phase (offsets [None]); a burst's known is its first), frame (s: the period the bursts' pattern repeats at, every slot in the same frames of it; None when the starts fall on no slot grid), plan_frame (s: the burst time plan's frame, learn_plan's: half or less of frame where terminals get slots in alternate frames of it; None when not found or not fitting the starts)

Methods:

Name Description
llrs

Each demodulated burst's LLRs (of kind only, when given), without its known symbols' unless preamble: a

Source code in src/rpps/analysis/burst/demod.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))
llrs
llrs(kind=None, preamble=False)

Each demodulated burst's LLRs (of kind only, when given), without its known symbols' unless preamble: a list, the bursts' lengths differing

Source code in src/rpps/analysis/burst/demod.py
def llrs(self, kind=None, preamble=False):
    """Each demodulated burst's LLRs (of `kind` only, when given), without its known symbols' unless `preamble`: a
    list, the bursts' lengths differing"""
    out = []
    for b in self.bursts:
        if b.ok and b.llr is not None and (kind is None or b.kind == kind):
            m = len(b.llr)//len(b.symbols)
            a, n = b.known if b.known else (0, 0)
            out.append(b.llr if preamble else np.concatenate((b.llr[:a*m], b.llr[(a + n)*m:])))
    return out

acquire

acquire(x, Fs, pre, baud, beta=0.35, search=None, steps=16)

The preamble pre (symbols) in samples x at Fs: (start sample of its first symbol (fractional), score 0..1, cfo (rad a symbol), phase, gain), or None when x is too short. search: (lo, hi) samples where the first symbol may be (default: anywhere)

Source code in src/rpps/analysis/burst/demod.py
def acquire(x, Fs, pre, baud, beta=0.35, search=None, steps=16):
    """The preamble `pre` (symbols) in samples x at Fs: (start sample of its first symbol (fractional), score 0..1,
    cfo (rad a symbol), phase, gain), or None when x is too short. search: (lo, hi) samples where the first symbol may be
    (default: anywhere)"""
    x = np.asarray(x, dtype=np.complex128)
    sps = Fs/baud
    n = len(pre)
    span = 8
    hits = frames.find_word(x, Fs, pre, [baud], beta=beta, threshold=0.0, top=4)
    if search is not None:
        hits = [h for h in hits if search[0] <= h.at <= search[1]] or hits
    if not hits:
        return None
    at = hits[0].at
    dp = pre[1:]*np.conj(pre[:-1])
    best = None
    for f in np.arange(-steps//2, steps//2 + 1)/steps:
        t0 = at + f*sps
        c = t0 + sps*np.arange(n)
        if c[0] - span*sps < 0 or c[-1] + span*sps + 2 >= len(x):
            continue
        y = _mf(x, c, sps, beta)
        m = np.abs(np.sum(y[1:]*np.conj(y[:-1])*np.conj(dp)))/(np.sum(np.abs(y)**2) + 1e-30)
        if best is None or m > best[0]:
            best = (m, t0, y)
    if best is None:
        return None
    _, t0, y = best
    z = y*np.conj(pre)
    w = float(np.angle(np.sum(z[1:]*np.conj(z[:-1])))) # rad a symbol
    zz = z*np.exp(-1j*w*np.arange(n))
    c = np.sum(zz)
    phase = float(np.angle(c))
    gain = float(np.abs(c)/np.sum(np.abs(pre)**2))
    score = float(np.abs(c)/np.sqrt(np.sum(np.abs(y)**2)*np.sum(np.abs(pre)**2)))
    return t0, score, w, phase, gain

retime

retime(x, c, sps, beta, anchor=0, window=256, skip=None, offset=False)

Symbol centres c (samples of x, one a symbol) with the symbol clock's offset taken out, and that offset

The offset is the symbol rate's, a fraction: positive when the symbols come faster than sps. It is the matched filter's energy peak (best_tau) in each window of window symbols but those over the known symbols skip ((first, stop): a repeating pattern's energy can peak between its symbols), unwrapped, a line through them (Theil-Sen: the median slope between windows) turned about symbol anchor (where the preamble set the timing; with offset, the timing there from the windows too, for an acquisition on a short word). c and 0 when fewer than three windows

Source code in src/rpps/analysis/burst/demod.py
def retime(x, c, sps, beta, anchor=0, window=256, skip=None, offset=False):
    """Symbol centres c (samples of x, one a symbol) with the symbol clock's offset taken out, and that offset

    The offset is the symbol rate's, a fraction: positive when the symbols come faster than sps. It is the matched
    filter's energy peak (best_tau) in each window of `window` symbols but those over the known symbols `skip` ((first, stop): a repeating
    pattern's energy can peak between its symbols), unwrapped, a line through them (Theil-Sen: the median slope between
    windows) turned about symbol `anchor` (where the preamble set the timing; with `offset`, the timing there from the
    windows too, for an acquisition on a short word). c and 0 when fewer than three windows"""
    from ...sync.time.mat import best_tau
    nw = len(c)//window
    if nw < 3:
        return c, 0.0
    mids, offs = [], []
    for i in range(nw):
        a, b = i*window, (i + 1)*window - 1
        if skip is not None and a < skip[1] and skip[0] <= b: # known symbols (a 1100 preamble's energy peaks between symbols)
            continue
        lo, hi = max(0, int(c[a] - sps)), min(len(x), int(np.ceil(c[b] + sps)) + 1)
        tau, _ = best_tau(x, sps, beta, lo=lo, hi=hi)
        m = (a + b)/2
        cm = c[0] + a*sps # (a lattice point: tau is a phase of the lattice, the window's middle may fall between)
        offs.append(2*np.pi*((tau - cm) % sps)/sps)
        mids.append(m)
    if len(offs) < 3:
        return c, 0.0
    d = np.unwrap(np.array(offs))*sps/(2*np.pi)
    d = d - np.round(np.median(d)/sps)*sps # the lattice is periodic in sps: the nearest copy
    mids = np.array(mids)
    i, j = np.triu_indices(len(mids), 1) # Theil-Sen: the median of the slopes between windows (one odd window can't tilt it)
    slope = float(np.median((d[j] - d[i])/(mids[j] - mids[i])))
    k = np.arange(len(c))
    if offset: # the windows' timing at the anchor too, not the acquisition's (a short word's can be half a symbol out)
        at = float(np.median(d - slope*(mids - anchor)))
        at -= np.round(at/sps)*sps
        return c + at + slope*(k - anchor), float(-slope/sps)
    return c + slope*(k - anchor), float(-slope/sps) # sps (1 + e) samples a symbol: a rate 1/(1 + e), about 1 - e

demodulate

demodulate(x, Fs, mod=None, baud=None, beta=None, preamble=None, offset=0, frame=None, slot_tol=16, min_score=0.5, min_shared=16, **kw)

Every burst of x, demodulated on its own from its preamble (see the module). Bursts of several kinds, each with a preamble of its own (burst_kinds: by length, when they share fewer than min_shared symbols), are each acquired on their kind's. With no preamble they share, known symbols elsewhere (shared_segments: a mid-amble, a postamble); with none at all, each burst blind (Bursts.blind). preamble: known symbols given, offset symbols after the burst's start (negative: before its end). kw: frames.gate's

Source code in src/rpps/analysis/burst/demod.py
def demodulate(x, Fs, mod=None, baud=None, beta=None, preamble=None, offset=0, frame=None, slot_tol=16, min_score=0.5,
               min_shared=16, **kw):
    """Every burst of x, demodulated on its own from its preamble (see the module). Bursts of several kinds, each with a
    preamble of its own (burst_kinds: by length, when they share fewer than `min_shared` symbols), are each acquired on
    their kind's. With no preamble they share, known symbols elsewhere (`shared_segments`: a mid-amble, a postamble);
    with none at all, each burst blind (`Bursts.blind`). preamble: known symbols given, `offset` symbols after the
    burst's start (negative: before its end). kw: frames.gate's"""
    from ... import symbol as rsym
    x = np.asarray(x, dtype=np.complex128)
    B = frames.bursts(x, Fs, names=None if mod is None else [mod], baud=baud,
                      betas=(0.2, 0.25, 0.35) if beta is None else (beta,), **kw) # what is known isn't searched for
    acq = [b for b in B if b.det is not None]
    if mod is None:
        if not acq:
            raise ValueError("no burst long enough to tell the modulation: give mod")
        mods = [b.det.mod for b in acq]
        mod = max(set(mods), key=mods.count)
    if baud is None:
        if not acq:
            raise ValueError("no burst long enough to measure the rate: give baud")
        baud = float(np.median([b.det.baud for b in acq]))
    if beta is None:
        beta = float(np.median([b.det.beta for b in acq])) if acq else 0.35
    con = rsym.load(mod)
    pts = np.asarray(con.points, dtype=np.complex128)
    sps = Fs/baud
    offsets, period = None, None
    if preamble is None:
        kinds, member = burst_kinds(B, sps, pts, min_shared)
        if len(kinds) <= 1: # one kind, or none: where the known symbols sit (a "preamble" may be a mid-amble)
            from ...sync.acquire import symmetry
            segs = shared_segments(B, min_len=max(8, min_shared - 1), M=max(2, symmetry(pts)))
            top = segs[0] if segs else None
            if top is not None and (not kinds or len(top.steps) + 1 > len(kinds[0])
                                    or (len(top.steps) + 1 >= len(kinds[0]) - 2 and not 0 <= top.offset <= 8)):
                o = 0 if 0 <= top.offset <= 8 else top.offset # (within the gate's slack of the start: a preamble)
                kinds, member, offsets = [preamble_symbols(top.steps, pts)], [0]*len(B), [o]
        if not kinds or len(kinds[0]) < 8: # long bursts of frames: the unique word each repeats, at its own phase
            pw = periodic_word(B, mod, pts)
            if pw is not None:
                kinds, member, offsets, period = [pw[0]], [0]*len(B), [None], pw[1]
        if not kinds or len(kinds[0]) < 8: # a symbol or two in common is chance: each burst blind
            return _blind(B, mod, baud, beta, con, pts, frame, slot_tol, x, Fs)
    else:
        kinds, member = [np.asarray(preamble, dtype=np.complex128)], [0]*len(B)
        offsets = [int(offset)]
    offsets = offsets or [0]*len(kinds)
    out = []
    for b, m in zip(B, member):
        tries = [m] if m is not None else range(len(kinds)) # A burst of no group: every kind's preamble, the best kept
        best = None
        for kind in tries:
            p, o = kinds[kind], offsets[kind]
            pad = int(np.ceil(16*sps)) + len(p)
            a2, b2 = max(0, b.start - pad), min(len(x), b.stop + pad)
            # The burst's own blind carrier offset off first: the preamble search correlates in pieces, which a carrier
            # tens of kHz out (a large share of a turn a symbol) turns past finding
            f0 = float(getattr(b.det, "cfo", 0.0) or 0.0) if b.det is not None else 0.0
            seg = x[a2:b2]*np.exp(-2j*np.pi*f0/Fs*np.arange(b2 - a2)) if f0 else x[a2:b2]
            if o == 0:
                search = (0, b.start - a2 + 4*len(p)*sps)
            elif o is None: # a word every `period`: its first, within a period of the gate's opening
                search = (max(0, b.start - a2 - 8*sps), b.start - a2 + (period + len(p))*sps)
            else: # where the known run should be, from the gate's start (or its end: a postamble)
                e = (b.start - a2 if o > 0 else b.stop - a2) + o*sps
                margin = max(16, len(p))*sps
                search = (e - margin, e + margin)
            r = acquire(seg, Fs, p, baud, beta, search=search)
            if r is not None and (best is None or r[1] > best[0][1]):
                best = (r, kind, a2, seg, f0)
        if best is None:
            out.append(BurstResult(start=float(b.start), score=0.0, ok=False))
            continue
        r, kind, a2, seg, f0 = best
        pre, o = kinds[kind], offsets[kind]
        t0, score, w, phase, gain = r
        if score < min_score:
            out.append(BurstResult(start=a2 + t0, score=score, kind=kind, ok=False))
            continue
        # The burst's first symbol: `o` before the known run, or (a postamble) wherever the gate opened
        oe = o if o is not None and o >= 0 else max(0, int(round((t0 - (b.start - a2))/sps)))
        oe = min(oe, int((t0 - 8*sps - 5)//sps)) # (the matched filter's span before it)
        from ...sync.time.mat import centres_in
        c = centres_in(len(seg), t0 - oe*sps, sps, 8)
        c = c[c <= b.stop - a2 + sps] # to the end of the gate
        n = len(pre)
        c, clock = retime(seg, c, sps, beta, anchor=oe + n/2, skip=(oe, oe + n), offset=o is None)
        y = _mf(seg, c, sps, beta)
        k = np.arange(len(y)) - oe
        if o is None and period: # a word every period: the carrier from all of them, not from the first alone
            from ...sync.acquire import symmetry
            y, w, phase, gain, oe = _word_carrier(y, pre, oe, period, symmetry(pts))
        else:
            y = y*np.exp(-1j*(w*k + phase))/max(gain, 1e-12)
        if len(y) > oe + n: # the carrier loop from the known run out, both ways
            y = np.concatenate((_follow(y[:oe][::-1], pts)[::-1], y[oe:oe + n], _follow(y[oe + n:], pts)))
        idx = np.argmin(np.abs(y[:, None] - pts[None, :]), axis=1)
        dec = pts[idx]
        data = np.ones(len(y), bool)
        data[oe:oe + n] = False
        evm = float(np.sqrt(np.mean(np.abs(y[data] - dec[data])**2)/np.mean(np.abs(pts)**2))) if data.any() else 0.0
        out.append(BurstResult(start=a2 + c[0], symbols=y, bits=_bits(idx, con), llr=con.llr(y), cfo=f0 + w*baud/(2*np.pi),
                               clock=clock, phase=phase, gain=gain, score=score, evm=evm, kind=kind, known=(oe, n), ok=True))
    frame, slots, plan = _structure(out, x, Fs, baud, frame, slot_tol)
    return Bursts(bursts=out, mod=mod, baud=baud, beta=beta, preamble=kinds[0], preambles=kinds, offsets=offsets, frame=frame,
                  slots=slots, blind=False, period=period, plan_frame=plan)

plan

A network's burst time plan (rpps.plan) from the bursts rp.sync.Bursts detects: the code blocks a burst is made of (units), the plan learned (learn_plan), and whether a plan explains the bursts (check_plan). See rpps.analysis.burst

Classes:

Name Description
Units

units: unit (symbols), err (its standard error: the lengths are known to a few symbols, so a unit is often

NoPlan

learn_plan found no frame period; scores: what it tried (as a Guess's, for rp.viz.plan_evidence)

PlanCheck

check_plan's answer: how well a burst time plan explains the bursts detected.

Functions:

Name Description
units

The block a burst's length is made of: lengths (symbols a burst, e.g. len(b.symbols) of a kind's bursts) as

learn_plan

A burst time plan (rpps.plan) from detected bursts, for a network whose forward link is not heard: its BTU, frame

check_plan

How well a burst time plan (rpps.plan: learned, a definition or from a forward link) explains detected bursts:

Units

Units(**kw)

units: unit (symbols), err (its standard error: the lengths are known to a few symbols, so a unit is often only known to one either way), overhead (symbols besides the units: preamble, header, tail), counts ({units a burst: bursts}), fit (share of bursts within tol of overhead + n*unit)

Source code in src/rpps/analysis/burst/plan.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

NoPlan

Bases: ValueError

learn_plan found no frame period; scores: what it tried (as a Guess's, for rp.viz.plan_evidence)

PlanCheck

PlanCheck(**kw)

check_plan's answer: how well a burst time plan explains the bursts detected.

plan; origin (plan clock ticks at the capture's first sample) and rate (the network clock's offset from the capture's, a fraction): a capture time t [s] is plan tick origin + tclock(1 + rate); cf (the capture's centre in the plan's frequencies); bursts (the bursts as records: freq, start, length, kind); per burst its status: "slot" in a slot of its carrier (its start to tol of the slot's burst start), of its kind, and fitting it "kind" in a slot whose tx type is another kind's (its unique word, kind or word in the tx type's fields) "long" in a slot, but running past the slot's end by more than tol "none" no slot of its carrier starts near it: the plan does not explain it its window (rpps.plan.Window; None where "none") and error (s: its start minus its window's burst start, nan where "none"); windows, every window starting within the bursts' span, and filled, how many bursts each holds

Methods:

Name Description
tick

The plan's clock at capture time t [s]

time

The capture time [s] of plan tick tick

Attributes:

Name Type Description
explained

The fraction of the bursts in a slot of their own kind that they fit

rms

The rms start error [s] of the bursts in slots

Source code in src/rpps/analysis/burst/plan.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))
explained property
explained

The fraction of the bursts in a slot of their own kind that they fit

rms property
rms

The rms start error [s] of the bursts in slots

tick
tick(t)

The plan's clock at capture time t [s]

Source code in src/rpps/analysis/burst/plan.py
def tick(self, t):
    """The plan's clock at capture time t [s]"""
    return self.origin + np.asarray(t)*self.plan.clock*(1 + self.rate)
time
time(tick)

The capture time [s] of plan tick tick

Source code in src/rpps/analysis/burst/plan.py
def time(self, tick):
    """The capture time [s] of plan tick `tick`"""
    return (np.asarray(tick) - self.origin)/(self.plan.clock*(1 + self.rate))

units

units(lengths, tol=3, min_unit=16, hold=0.9)

The block a burst's length is made of: lengths (symbols a burst, e.g. len(b.symbols) of a kind's bursts) as overhead + n*unit, n the units in that burst (1, 2, 3...: MF-TDMA slots of one, two, three code blocks), or None. Lengths are known to within the gate's slack (tol symbols), so the unit is the largest one their differences are all near multiples of (in hold of the pairs), with at least two different multiples among them (a unit longer than every difference fits trivially), then unit and overhead refitted by least squares. What lengths cannot tell: the overhead is the least that fits (100 symbols and 84-symbol units read as 16 and one unit more), and a unit whose bursts all hold an even number of it reads as twice the size

Source code in src/rpps/analysis/burst/plan.py
def units(lengths, tol=3, min_unit=16, hold=0.9):
    """The block a burst's length is made of: lengths (symbols a burst, e.g. len(b.symbols) of a kind's bursts) as
    overhead + n*unit, n the units in that burst (1, 2, 3...: MF-TDMA slots of one, two, three code blocks), or None.
    Lengths are known to within the gate's slack (`tol` symbols), so the unit is the largest one their differences are
    all near multiples of (in `hold` of the pairs), with at least two different multiples among them (a unit longer
    than every difference fits trivially), then unit and overhead refitted by least squares. What lengths cannot tell:
    the overhead is the least that fits (100 symbols and 84-symbol units read as 16 and one unit more), and a unit
    whose bursts all hold an even number of it reads as twice the size"""
    Ls = np.sort(np.asarray(lengths, dtype=np.float64))
    if len(Ls) < 3:
        return None
    d = np.abs(Ls[:, None] - Ls[None, :])[np.triu_indices(len(Ls), 1)]
    big = d[d > 2*tol]
    if len(big) < 2:
        return None
    for u in range(int(big.max()), min_unit - 1, -1):
        m = np.round(d/u)
        near = np.abs(d - m*u) <= 2*tol
        if np.mean(near) < hold or not np.any(m >= 1):
            continue
        n0 = np.floor((Ls - Ls[0])/u + 0.5) # units beyond the shortest burst's
        if len(np.unique(n0)) < 2:
            continue
        # the shortest burst's own units: as many as fit beside a non-negative overhead
        base = int(np.floor((Ls[0] + tol)/u))
        best = None
        for b0 in range(base, 0, -1):
            n = n0 + b0
            over = np.median(Ls - n*u)
            fit = float(np.mean(np.abs(Ls - n*u - over) <= tol))
            if over >= -tol and (best is None or fit > best[2]):
                best = (n, over, fit)
                break
        if best is None:
            continue
        n, over, fit = best
        if fit < hold:
            continue
        # unit and overhead refitted by least squares on the bursts that fit (the search steps a symbol at a time, and
        # the largest unit within tolerance runs high)
        uf, of = float(u), float(over)
        for _ in range(4):
            ok = np.abs(Ls - n*uf - of) <= tol
            if ok.sum() < 3:
                break
            (uf, of), *_ = np.linalg.lstsq(np.vstack((n[ok], np.ones(ok.sum()))).T, Ls[ok], rcond=None)
        ok = np.abs(Ls - n*uf - of) <= tol
        r = Ls[ok] - n[ok]*uf - of
        sn = np.sum((n[ok] - n[ok].mean())**2)
        err = float(np.sqrt(np.sum(r**2)/max(ok.sum() - 2, 1)/sn)) if sn > 0 else float("inf")
        u, over = int(round(uf)), int(round(of))
        fit = float(np.mean(np.abs(Ls - n*u - over) <= tol))
        vals, cnt = np.unique(n.astype(int), return_counts=True)
        return Units(unit=u, err=err, overhead=over, counts={int(v): int(c) for v, c in zip(vals, cnt)}, fit=fit)
    return None

learn_plan

learn_plan(bursts, quantum=None, max_btus=4096, clock=27000000.0, purity=0.95, tol=0.1, carriers=None)

A burst time plan (rpps.plan) from detected bursts, for a network whose forward link is not heard: its BTU, frame period, a frame type per carrier, its slots and their tx types. Returns a Guess to save (config/plan/guess/) and load as a plan (rp.plan.load("guess/<name>")), whose plan is the Plan itself and scores what it was chosen on (each BTU's score, each frame period's purity and why it was passed over: rp.viz.plan_evidence draws them).

bursts: rp.sync.Bursts' output (each its ctx["burst"]: carrier freq, start; its length) or dicts {freq, start, length [s], kind (a burst type: its unique word), rate}. quantum: the BTU [s] when known. carriers: [{freq, width, rate}] the bursts were detected on (rp.sync.Bursts'): each frame type's bandwidth and symbol rate.

  1. The BTU: the quantum of the bursts' start differences (every slot starts on the grid of its frame): the largest q whose multiples the differences sit on, to tol of q, made exact over the whole capture (each start's count of BTUs, over a span doubling from the first burst: the slope of a line through them), and taken only where 90% of the starts sit on its grid (a mean of differences passes near a q they only nearly fit).
  2. The frame: the shortest period of M BTUs at which every (carrier, BTU in the frame) holds one kind of burst (purity of them; length clusters stand for kinds not given), with bursts at two or more places of it.
  3. A frame type per carrier: its slots where bursts were seen (as many BTUs as the longest burst of the kind needs), single-BTU slots between; a tx type per kind (kind in its fields, and word when the kind is a word's name), its offset the bursts' median offset from the slot's start. The superframe starts at the first burst's frame start. Only what the bursts show is learned: slots never used are single BTUs, carriers never used are not in it.
Source code in src/rpps/analysis/burst/plan.py
def learn_plan(bursts, quantum=None, max_btus=4096, clock=27e6, purity=0.95, tol=0.1, carriers=None):
    """A burst time plan (rpps.plan) from detected bursts, for a network whose forward link is not heard: its BTU, frame
    period, a frame type per carrier, its slots and their tx types. Returns a Guess to `save` (config/plan/guess/<name>)
    and load as a plan (`rp.plan.load("guess/<name>")`), whose `plan` is the Plan itself and `scores` what it was chosen
    on (each BTU's score, each frame period's purity and why it was passed over: rp.viz.plan_evidence draws them).

    bursts: rp.sync.Bursts' output (each its ctx["burst"]: carrier freq, start; its length) or dicts {freq, start, length
    [s], kind (a burst type: its unique word), rate}. quantum: the BTU [s] when known. carriers: [{freq, width, rate}]
    the bursts were detected on (rp.sync.Bursts'): each frame type's bandwidth and symbol rate.

      1. The BTU: the quantum of the bursts' start differences (every slot starts on the grid of its frame): the largest q
         whose multiples the differences sit on, to `tol` of q, made exact over the whole capture (each start's count of
         BTUs, over a span doubling from the first burst: the slope of a line through them), and taken only where 90% of
         the starts sit on its grid (a mean of differences passes near a q they only nearly fit).
      2. The frame: the shortest period of M BTUs at which every (carrier, BTU in the frame) holds one kind of burst
         (`purity` of them; length clusters stand for kinds not given), with bursts at two or more places of it.
      3. A frame type per carrier: its slots where bursts were seen (as many BTUs as the longest burst of the kind needs),
         single-BTU slots between; a tx type per kind (`kind` in its fields, and `word` when the kind is a word's name), its offset the bursts' median offset from
         the slot's start. The superframe starts at the first burst's frame start.
    Only what the bursts show is learned: slots never used are single BTUs, carriers never used are not in it."""
    from ..result import Guess
    from ...plan import Plan, TxType, FrameType, Sequence, Frame
    rec = _records(bursts)
    if len(rec) < 4:
        raise ValueError("learn_plan: a few bursts at least")
    starts = np.array([r["start"] for r in rec])
    # Kinds: given, else clusters of length per carrier (a new one where the sorted lengths jump by more than 10%)
    for fr in {r["freq"] for r in rec if r["kind"] is None}:
        mine = sorted((r for r in rec if r["freq"] == fr and r["kind"] is None), key=lambda r: r["length"])
        c, last = 0, None
        for r in mine:
            if last is not None and r["length"] > 1.1*last:
                c += 1
            r["kind"], r["auto"], last = f"{fr:g}/{c}", True, r["length"]
    curve = None
    if quantum:
        q = float(quantum)
    else:
        q, curve = _quantum(starts, tol)
    t0 = float(starts.min())
    k = np.round((starts - t0)/q).astype(np.int64)
    off = (starts - t0) - k*q
    need = {}
    for r in rec: # BTUs each kind's longest burst takes
        need[str(r["kind"])] = max(need.get(str(r["kind"]), 1), int(np.ceil(r["length"]/q - 1e-9)))
    best, tried = None, [] # tried: (M, purity, why not: "" taken, "purity", "repeats", "short", "overlap")
    for M in range(2, max_btus + 1):
        cells = {}
        for r, kk in zip(rec, k):
            cells.setdefault((r["freq"], int(kk % M)), []).append(r["kind"])
        major = sum(max(np.unique([str(x) for x in v], return_counts=True)[1]) for v in cells.values())
        repeated = sum(len(v) > 1 for v in cells.values())
        why = ("purity" if major < purity*len(rec) else "repeats" if repeated < 2 else
               "short" if M*q < max(r["length"] for r in rec) else "overlap" if _overlap(cells, need, M) else "")
        tried.append((M, major/len(rec), why)) # (the overlap check only where the rest pass: it costs most)
        if why:
            continue
        best = (M, cells)
        break
    if best is None:
        e = NoPlan("learn_plan: no frame period found (too few bursts, or no plan): rp.viz.plan_evidence(None, error) "
                   "shows why each was passed over")
        e.scores = {"quantum": curve, "btu": q, "tol": tol, "purity": purity, "frames": [(M_*q, pur, why) for M_, pur, why in tried],
                    "frame": None}
        raise e
    M, cells = best
    # The frame's start: where no carrier's slot crosses from one frame into the next (the first burst need not be first)
    slots = [(b, need[max(set(str(x) for x in v), key=[str(x) for x in v].count)]) for (f, b), v in cells.items()]
    shift = next((r for r in range(M) if all((b - r) % M + n <= M for b, n in slots)), 0)
    t0 += shift*q
    k = np.round((starts - t0)/q).astype(np.int64)
    off = (starts - t0) - k*q
    cells = {}
    for r, kk in zip(rec, k):
        cells.setdefault((r["freq"], int(kk % M)), []).append(r["kind"])
    kinds = sorted({str(r["kind"]) for r in rec})
    tx_id = {kd: 128 + i for i, kd in enumerate(kinds)}
    longest = {kd: max(r["length"] for r in rec if str(r["kind"]) == kd) for kd in kinds}
    btus = {kd: max(1, int(np.ceil(longest[kd]/q - 1e-9))) for kd in kinds}
    offs = {kd: float(np.median([o for r, o in zip(rec, off) if str(r["kind"]) == kd])) for kd in kinds}
    T = lambda s: int(round(s*clock))
    word = {str(r["kind"]): r["kind"] for r in rec if isinstance(r["kind"], str) and not r.get("auto")} # (a word's name)
    txs = {tx_id[kd]: TxType(tx_id[kd], btus[kd], max(T(offs[kd]), 0), {"kind": kd, **({"word": word[kd]} if kd in word else {})})
           for kd in kinds}
    fts, frames = {}, []
    for ci, fr in enumerate(sorted({r["freq"] for r in rec})):
        here = sorted((b_, max(set(v), key=v.count)) for (f_, b_), v in cells.items() if f_ == fr)
        sections, t = [], 0
        for b_, kd in here:
            kd = str(kd)
            if b_ < t:
                continue # (a slot inside the one before: the purity let it through)
            if b_ > t:
                sections.append([0, b_ - t - 1])
            sections.append([tx_id[kd], 0])
            t = b_ + btus[kd]
        if t < M:
            sections.append([0, M - t - 1])
        c = next((c for c in (carriers or []) if abs(float(c["freq"]) - fr) < 1.0), {})
        rate = c.get("rate") or next((r["rate"] for r in rec if r["freq"] == fr and r["rate"]), None) or 1.0/q
        fts[ci + 1] = FrameType(ci + 1, T(M*q), T(q), float(c.get("width") or rate), float(rate), M, [0.0],
                                [tuple(s) for s in sections if s[1] >= 0])
        frames.append(Frame(ci + 1, 0, fr))
    seq = Sequence(0, T(t0), T(M*q), 0.0, 0, frames)
    plan = Plan(clock, txs, fts, {0: seq}, name="learned")
    for ft in fts.values():
        ft.slots(txs) # (checked: the sections fill the frame)
    g = Guess("plan", plan.definition("burst time plan learned from detected bursts (rpps.analysis.burst.learn_plan)"),
              {"btu": q, "frame": M*q, "bursts": len(rec), "carriers": len(fts), "kinds": len(kinds)})
    g.plan = plan
    g.scores = {"quantum": curve, "btu": q, "tol": tol, "purity": purity,
                "frames": [(M_*q, pur, why) for M_, pur, why in tried], "frame": M*q}
    return g

check_plan

check_plan(plan, bursts, origin=None, rate=0.0, cf=0.0, tol=None, fit=True, votes=48)

How well a burst time plan (rpps.plan: learned, a definition or from a forward link) explains detected bursts: each burst placed in the slot of its carrier whose burst start is nearest its own, and judged (PlanCheck: "slot", "kind", "long", "none"). A right plan puts every burst in a slot of its kind; a wrong BTU or frame leaves bursts in none, or drifting through their slots (error growing with time); a wrong slot layout puts them in other kinds'.

bursts: rp.sync.Bursts' output or dicts {freq [Hz from the capture's centre], start [s], length [s], kind}, as learn_plan takes. origin: plan ticks at the capture's first sample (a forward link's clock reference); None: voted for (known only to a whole superframe: the one nearest the capture's start is taken), as rp.sync.Bursts acquires it (each of votes bursts spread over the capture votes for the origins that put it on a slot of its carrier, of its kind when both are known; the most voted wins). rate: the network clock's offset. fit: refine the origin and rate on the bursts placed (a line through their start errors, its slope taken where it is over three standard errors), placing them again. cf: the capture's centre in the plan's frequencies. tol: how far [s] a burst's start may be from its slot's (None: half the shortest BTU). Plans whose sequences have different superframe durations are voted on the longest.

Source code in src/rpps/analysis/burst/plan.py
def check_plan(plan, bursts, origin=None, rate=0.0, cf=0.0, tol=None, fit=True, votes=48):
    """How well a burst time plan (rpps.plan: learned, a definition or from a forward link) explains detected bursts:
    each burst placed in the slot of its carrier whose burst start is nearest its own, and judged (PlanCheck: "slot",
    "kind", "long", "none"). A right plan puts every burst in a slot of its kind; a wrong BTU or frame leaves bursts in
    none, or drifting through their slots (`error` growing with time); a wrong slot layout puts them in other kinds'.

    bursts: rp.sync.Bursts' output or dicts {freq [Hz from the capture's centre], start [s], length [s], kind}, as
    learn_plan takes. origin: plan ticks at the capture's first sample (a forward link's clock reference); None: voted
    for (known only to a whole superframe: the one nearest the capture's start is taken), as rp.sync.Bursts acquires it (each of `votes` bursts spread over the capture votes for the origins that put it
    on a slot of its carrier, of its kind when both are known; the most voted wins). rate: the network clock's offset.
    fit: refine the origin and rate on the bursts placed (a line through their start errors, its slope taken where it is
    over three standard errors), placing them again.
    cf: the capture's centre in the plan's frequencies. tol: how far [s] a burst's start may be from its slot's (None:
    half the shortest BTU). Plans whose sequences have different superframe durations are voted on the longest."""
    from ...sync import track
    rec = _records(bursts)
    if not rec:
        raise ValueError("check_plan: no bursts")
    clock = plan.clock
    if tol is None:
        tol = 0.5*min(ft.btu_duration for ft in plan.frame_types.values())/clock
    rate = float(rate)
    if origin is None:
        origin = _vote_origin(plan, rec, cf, tol, votes, track)
    if origin is None: # (no slot on any burst's carrier)
        nan = float("nan")
        return PlanCheck(plan=plan, origin=nan, rate=rate, cf=cf, tol=tol, bursts=rec, status=[NONE]*len(rec),
                         window=[None]*len(rec), error=np.full(len(rec), nan), windows=[], filled=np.zeros(0, int))
    origin = float(origin)
    for it in range(3 if fit else 1):
        out = _place(plan, rec, origin, rate, cf, tol)
        if not fit or it == 2:
            break
        ok = [(r["start"], e) for r, s, e in zip(rec, out[0], out[2]) if s != NONE]
        if not ok:
            break
        t, e = np.asarray(ok).T
        a, b = float(np.mean(e)), 0.0
        if len(t) >= 8 and np.ptp(t) > 0: # (the rate only where the start errors lean beyond their scatter)
            (b1, a1), cov = np.polyfit(t, e, 1, cov=True)
            if abs(b1) > 3*np.sqrt(cov[0, 0]):
                a, b = a1, b1
        # e = (tick(t) - window)/clock = a + b t: the window's tick is origin - a clock + t clock (1 + rate - b)
        origin, rate = origin - a*clock, rate - b
    status, window, error, windows, filled = out
    return PlanCheck(plan=plan, origin=origin, rate=rate, cf=cf, tol=tol, bursts=rec, status=status, window=window,
                     error=error, windows=windows, filled=filled)

preamble

What a TDMA network's bursts share: the preamble (shared_preamble, preamble_symbols), known symbols elsewhere (shared_segments: a mid-amble, a postamble), a word repeated through each burst (periodic_word), and burst kinds, each with a word of its own (burst_kinds). See rpps.analysis.burst

Classes:

Name Description
Segment

shared_segments: steps (d[n] = s[n] conj(s[n-1]) the bursts agree on), offset (symbols from the bursts' start

Functions:

Name Description
shared_preamble

The leading run of symbols the bursts share, as phase steps: (length in steps, steps, where it starts in each

preamble_symbols

Symbols of a preamble from its phase steps d[n] = s[n] conj(s[n-1]) (rpps.analysis.framing.frames.preamble), turned so

shared_segments

Runs of symbols every burst carries at the same place: a preamble, a mid-amble, a postamble ([Segment], longest

periodic_word

(unique word on the constellation, period in symbols) when long bursts hold frames with one unique word, each at

burst_kinds

(preambles [symbols], member [kind index or None per burst]): one shared by all the bursts, when they share at least

Segment

Segment(steps, offset, agree)

shared_segments: steps (d[n] = s[n] conj(s[n-1]) the bursts agree on), offset (symbols from the bursts' start to the segment's first symbol; negative: from their end, a postamble), agree (|mean| of the steps over bursts)

Source code in src/rpps/analysis/burst/preamble.py
def __init__(self, steps, offset, agree):
    self.steps, self.offset, self.agree = steps, offset, agree

shared_preamble

shared_preamble(burst_list, search=8, win=12, agree=0.8, max_len=512)

The leading run of symbols the bursts share, as phase steps: (length in steps, steps, where it starts in each burst's symbols), or (0, None, None). Like rpps.analysis.framing.frames.preamble, but aligned on a short window (win steps near the start, so a preamble shorter than framing's 64-step window aligns too), each burst against a dozen others' starts (the longest, the first, some spread over the list), the reference being the burst the others agree with most

Source code in src/rpps/analysis/burst/preamble.py
def shared_preamble(burst_list, search=8, win=12, agree=0.8, max_len=512):
    """The leading run of symbols the bursts share, as phase steps: (length in steps, steps, where it starts in each
    burst's symbols), or (0, None, None). Like rpps.analysis.framing.frames.preamble, but aligned on a short window (`win` steps
    near the start, so a preamble shorter than framing's 64-step window aligns too), each burst against a dozen others'
    starts (the longest, the first, some spread over the list), the reference being the burst the others agree with
    most"""
    S = [b.symbols for b in burst_list if b.symbols is not None and len(b.symbols) > 2*search + win + 4]
    if len(S) < 3:
        return 0, None, None
    D = [v[1:]*np.conj(v[:-1])/(np.abs(v[1:]*v[:-1]) + 1e-12) for v in S]
    def align(ref):
        offs, score = [], 0.0
        for d in D:
            sc = [np.abs(np.vdot(ref, d[k:k + win])) for k in range(2*search + 1) if k + win <= len(d)]
            offs.append(int(np.argmax(sc)) - search)
            score += max(sc)
        return offs, score
    best = None # References: the longest bursts (their gate opened earliest: the preamble whole), the first, and some
    # spread over the rest (a gate opening late cuts a burst's preamble short: no reference among those)
    longest = sorted(range(len(D)), key=lambda i: -len(D[i]))[:4]
    refs = list(dict.fromkeys(longest + list(range(min(len(D), 4))) + list(np.linspace(0, len(D) - 1, 4).astype(int))))
    for i in refs:
        offs, score = align(D[i][search:search + win])
        if best is None or score > best[1]:
            best = (offs, score)
    offs = best[0]
    c = max(0, -min(offs))
    L = min(max_len, min(len(d) - o - c for d, o in zip(D, offs)))
    rows = np.array([d[o + c:o + c + L] for d, o in zip(D, offs)])
    m = np.abs(np.mean(rows, axis=0))
    s0 = next((i for i in range(min(len(m), 2*search + 2)) if m[i] > agree), None)
    if s0 is None:
        return 0, None, None
    n = 0
    while s0 + n < len(m) and m[s0 + n] > agree:
        n += 1
    return n, np.mean(rows, axis=0)[s0:s0 + n], [o + c + s0 for o in offs]

preamble_symbols

preamble_symbols(steps, points)

Symbols of a preamble from its phase steps d[n] = s[n] conj(s[n-1]) (rpps.analysis.framing.frames.preamble), turned so they sit on the constellation points (one rotation, chosen from the points' own symmetry)

Source code in src/rpps/analysis/burst/preamble.py
def preamble_symbols(steps, points):
    """Symbols of a preamble from its phase steps d[n] = s[n] conj(s[n-1]) (rpps.analysis.framing.frames.preamble), turned so
    they sit on the constellation `points` (one rotation, chosen from the points' own symmetry)"""
    d = np.asarray(steps, dtype=np.complex128)
    d = d/np.maximum(np.abs(d), 1e-12)
    s = np.concatenate(([1.0 + 0j], np.cumprod(d)))
    pts = np.asarray(points, dtype=np.complex128)
    r = np.sqrt(np.mean(np.abs(pts)**2))
    best = None
    for th in np.linspace(0, 2*np.pi, 720, endpoint=False):
        q = s*r*np.exp(1j*th)
        e = np.min(np.abs(q[:, None] - pts[None, :]), axis=1).mean()
        if best is None or e < best[0]:
            best = (e, q)
    q = best[1]
    return pts[np.argmin(np.abs(q[:, None] - pts[None, :]), axis=1)]

shared_segments

shared_segments(burst_list, search=24, min_len=12, agree=0.8, refs=6, M=4, false_alarm=0.001)

Runs of symbols every burst carries at the same place: a preamble, a mid-amble, a postamble ([Segment], longest first). Phase steps, so each burst's own carrier phase drops out. Each burst is aligned on a reference by a lag within search symbols: the one with the best window of min_len steps (a known run of that length adds up to its length, random steps to its square root), once from the start and once from the end (bursts of several lengths sharing a postamble); the reference is the burst the others agree with most (of the first refs). A run is where the bursts' steps lie within 45 degrees of their mean: all of 3, all but one of 4 or more (up to agree: a weak burst's decision error), gaps of a step or two where a majority still agrees bridged; at least min_len steps, and longer where chance would make one (M: the steps' alphabet, M-PSK; false_alarm over every position)

Source code in src/rpps/analysis/burst/preamble.py
def shared_segments(burst_list, search=24, min_len=12, agree=0.8, refs=6, M=4, false_alarm=1e-3):
    """Runs of symbols every burst carries at the same place: a preamble, a mid-amble, a postamble ([Segment], longest
    first). Phase steps, so each burst's own carrier phase drops out. Each burst is aligned on a reference by a lag
    within `search` symbols: the one with the best window of `min_len` steps (a known run of that length adds up to its
    length, random steps to its square root), once from the start and once from the end (bursts of several lengths
    sharing a postamble); the reference is the burst the others agree with most (of the first `refs`). A run is where
    the bursts' steps lie within 45 degrees of their mean: all of 3, all but one of 4 or more (up to `agree`: a weak
    burst's decision error), gaps of a step or two where a majority still agrees bridged; at least `min_len` steps, and
    longer where chance would make one (M: the steps' alphabet, M-PSK; `false_alarm` over every position)"""
    S = [b.symbols for b in burst_list if b.symbols is not None and len(b.symbols) > 2*search + min_len + 2]
    if len(S) < 3:
        return []
    # How many must agree: all of 3, all but one of 4 or more (a weak burst's decision error), at most `agree`; and so
    # how long a run chance would not make: M-PSK steps of random data agree that well at a position with probability
    # about M P(Binomial(K, 1/M) >= need), over every position of two alignments
    from math import comb, ceil, log
    K = len(S)
    need = K if K < 4 else max(int(np.ceil(agree*K)), K - 1) if agree*K <= K - 1 else K - 1
    need = min(need, K)
    share = need/K - 1e-9
    pc = min(1.0, M*sum(comb(K, j)*(1/M)**j*(1 - 1/M)**(K - j) for j in range(need, K + 1)))
    positions = 2*max(len(v) for v in S)*(2*search + 1) # (every position of both alignments, each lag tried)
    if 0 < pc < 1: # (0: underflowed, many bursts: chance agreeing that well is nothing, no longer run needed)
        min_len = max(min_len, int(ceil(log(false_alarm/positions)/log(pc))))
    out = []
    for end in (False, True):
        D = [_unit_steps(v[::-1] if end else v) for v in S]
        best = None
        for r in range(min(refs, len(D))):
            ref = D[r]
            lags = []
            for d in D:
                c = []
                for l in range(-search, search + 1): # d[k + l] against ref[k], over all they overlap (a run at the very
                    r0, d0 = max(0, -l), max(0, l) #   start, a postamble's in the reversed pass, counts too)
                    n = min(len(ref) - r0, len(d) - d0)
                    if n <= min_len:
                        c.append(0.0)
                        continue
                    pr = np.conj(ref[r0:r0 + n])*d[d0:d0 + n]
                    cs = np.concatenate(([0], np.cumsum(pr)))
                    c.append(np.real(cs[min_len:] - cs[:-min_len]).max()) # the best window of min_len steps (real:
                    # steps drop each burst's phase, so a true alignment adds up positive; a periodic preamble one symbol
                    # off adds up as large, negative)
                lags.append(int(np.argmax(c)) - search)
            lo = max(0, -min(lags))
            L = min(len(d) - l - lo for d, l in zip(D, lags))
            if L <= min_len:
                continue
            rows = np.array([d[l + lo:l + lo + L] for d, l in zip(D, lags)])
            mean = rows.mean(axis=0)
            m = np.mean(np.abs(np.angle(rows*np.conj(mean)[None, :])) < np.pi/4, axis=0) # share near the mean step
            m[np.abs(mean) < 0.3] = 0 # (no direction to be near)
            if best is None or np.sum(m >= share) > best[0]:
                best = (int(np.sum(m >= share)), m, mean, lo)
        if best is None:
            continue
        _, m, mean, lo = best
        ok = m >= share
        gap = ~ok & (m >= 0.5) # a step or two where a weak burst slipped, between agreeing ones: bridged
        for g in (1, 2):
            fill = np.zeros_like(ok)
            for i in range(1, len(ok) - g):
                if ok[i - 1] and ok[i + g] and gap[i:i + g].all():
                    fill[i:i + g] = True
            ok |= fill
        for a, b in zip(*runs(ok)):
            if b - a < min_len:
                continue
            steps = mean[a:b]
            if end: # reversed: steps of the reversed run are the conjugates, in reverse order
                steps = np.conj(steps[::-1])
                offset = -(a + lo + (b - a) + 1) # its first symbol, counted back from the last
            else:
                offset = a + lo
            out.append(Segment(steps, int(offset), float(np.mean(m[a:b]))))
    # The same run seen from both ends (bursts of one length): the start-anchored one
    starts = [g for g in out if g.offset >= 0]
    keep = starts + [g for g in out if g.offset < 0 and all(abs(len(g.steps) - len(k.steps)) > 8 for k in starts)]
    return sorted(keep, key=lambda g: -len(g.steps))

periodic_word

periodic_word(burst_list, mod, points, tries=4, min_frames=6, max_lag=20000, thr=0.8, min_len=4)

(unique word on the constellation, period in symbols) when long bursts hold frames with one unique word, each at its own phase; else None. Every lag from 16 to a min_frames-th of the shortest of the tries longest bursts is folded (_fold_coherence: O(n) a lag); at a lag, each burst's longest circular run of positions coherent from frame to frame above thr (over 8 frames a position passes 0.8 by chance one time in 170, so a run of min_len over every position and lag is rare, where a unique word's sit near 1). The first lag where two bursts hold such a run, of the same length and phase steps, is the period (its multiples pass too); the word is that run's symbols averaged over one burst's frames. A word of U symbols every P adds only U/P to an autocorrelation, which a comb over it finds about half the time on bursts of 8 frames; the fold finds it every time

Source code in src/rpps/analysis/burst/preamble.py
def periodic_word(burst_list, mod, points, tries=4, min_frames=6, max_lag=20000, thr=0.8, min_len=4):
    """(unique word on the constellation, period in symbols) when long bursts hold frames with one unique word, each at
    its own phase; else None. Every lag from 16 to a `min_frames`-th of the shortest of the `tries` longest bursts is
    folded (`_fold_coherence`: O(n) a lag); at a lag, each burst's longest circular run of positions coherent from
    frame to frame above `thr` (over 8 frames a position passes 0.8 by chance one time in 170, so a run of `min_len`
    over every position and lag is rare, where a unique word's sit near 1). The first lag where two bursts hold such a
    run, of the same length and phase steps, is the period (its multiples pass too); the word is that run's symbols
    averaged over one burst's frames. A word of U symbols every P adds only U/P to an autocorrelation, which a comb
    over it finds about half the time on bursts of 8 frames; the fold finds it every time"""
    L = sorted((b for b in burst_list if b.symbols is not None), key=lambda b: -len(b.symbols))[:tries]
    if len(L) < 2:
        return None
    from ..framing.frames import _normalized
    n = len(L[-1].symbols)
    Y = [_normalized(b.symbols[:n]) for b in L]
    pts = np.asarray(points, dtype=np.complex128)
    for lag in range(16, min(max_lag, n//min_frames) + 1):
        runs = []
        for y in Y:
            st, ln = _run(_fold_coherence(y, lag), thr)
            if ln >= min_len:
                F = len(y)//lag
                fr = np.array([np.roll(y[f*lag:(f + 1)*lag], -st)[:ln] for f in range(F)])
                rot = np.exp(-1j*np.angle(np.sum(fr*np.conj(fr[0])[None, :], axis=1)))
                runs.append(np.mean(fr*rot[:, None], axis=0))
        for w in runs:
            same = [v for v in runs if abs(len(v) - len(w)) <= 2 and
                    abs(np.mean(_unit_steps(v[:min(len(v), len(w))])*np.conj(_unit_steps(w[:min(len(v), len(w))])))) > 0.8]
            if len(same) >= 2:
                uw = w/np.sqrt(np.mean(np.abs(w)**2))*np.sqrt(np.mean(np.abs(pts)**2))
                return pts[np.argmin(np.abs(uw[:, None] - pts[None, :]), axis=1)], int(lag)
    return None

burst_kinds

burst_kinds(B, sps, pts, min_shared=16, min_group=3)

(preambles [symbols], member [kind index or None per burst]): one shared by all the bursts, when they share at least min_shared symbols; else one per group of bursts of a length (lengths within 16 symbols or 2 %: a network's burst types, each with its own unique word), groups of at least min_group with at least min_shared symbols in common. Most bursts first. A burst in no group has None (it is tried on every kind's)

Source code in src/rpps/analysis/burst/preamble.py
def burst_kinds(B, sps, pts, min_shared=16, min_group=3):
    """(preambles [symbols], member [kind index or None per burst]): one shared by all the bursts, when they share at least
    `min_shared` symbols; else one per group of bursts of a length (lengths within 16 symbols or 2 %: a network's burst
    types, each with its own unique word), groups of at least `min_group` with at least `min_shared` symbols in common.
    Most bursts first. A burst in no group has None (it is tried on every kind's)"""
    def shared(g):
        # The gate opens within a few symbols of a short burst's start, but a long burst's (thousands of symbols) can be
        # tens of symbols out: each search a near one, then a wider one, the longest kept
        best = (0, None)
        for search in (8, 32):
            for n, d, _ in (frames.preamble(g, search=search), shared_preamble(g, search=search)):
                if n > best[0]:
                    best = (n, d)
        return best
    n, d = shared(B)
    if n >= min_shared or len(B) < 2*min_group:
        return ([preamble_symbols(d, pts)], [0]*len(B)) if n else ([], [None]*len(B))
    L = np.array([(b.stop - b.start)/sps for b in B])
    order = np.argsort(L)
    groups, cur = [], [order[0]]
    for i, j in zip(order[:-1], order[1:]):
        if L[j] - L[i] > max(16, 0.02*L[i]):
            groups.append(cur); cur = []
        cur.append(j)
    groups.append(cur)
    kinds, member = [], [None]*len(B)
    for g in sorted((g for g in groups if len(g) >= min_group), key=len, reverse=True):
        n, d = shared([B[i] for i in g])
        if n >= min_shared:
            for i in g:
                member[i] = len(kinds)
            kinds.append(preamble_symbols(d, pts))
    if not kinds and n: # (no group of its own: what they all share, however short)
        n, d = shared(B)
        if n and np.all(np.isfinite(d)):
            return [preamble_symbols(d, pts)], [0]*len(B)
        return [], [None]*len(B)
    return kinds, member

rpps.analysis.code

Which code (see rpps.analysis)

Modules:

Name Description
interleave

Interleavers found blind: a block interleaver's size and shape, a convolutional one's branches and delay, and columns

interleave

Interleavers found blind: a block interleaver's size and shape, a convolutional one's branches and delay, and columns of a grid sent out of step

r = rp.analysis.code.interleave.block_search(bits)                     # size N (rank), then rows x columns
r = rp.analysis.code.interleave.forney_search(bits, [(12, 17, 8), ...]) # which (I, M, symbol) gives code structure back
d = rp.analysis.code.interleave.column_delays(bits, rows, cols)         # each column's shift in rows (a product code's
                                                                    #  parity column sent a row late)

A block interleaver keeps whole codewords inside each block of N bits, so the stream's rank deficiency first shows at L = N (Sicot, Houcke & Barbier 2009) as it would at a code's length: rpps.analysis.code.block.linear.find_length finds N. Read back in the order written (each factorization N = rows x columns, either way), the code's own length shows again, short.

A convolutional (Forney) interleaver has no block: its branches delay by multiples of M symbols. Each candidate (from the standards, or a grid) is undone, and the stream is scored by the code structure that comes back: by default the strongest linear recurrence (rpps.analysis.sequence.recurrence), which a convolutional code's parity check is.

column_delays: bits are rows of cols bits, rows to a frame, and each column of a frame is a codeword of a column code (a product code). A column sent d rows late is not; its checks hold again when it is read d rows back. The column code's checks are found from all the columns (most are right), then each column's shift is the one they hold best at.

Classes:

Name Description
Shape

A block interleaver found: size (bits), offset (first block), rows, cols (written by rows, read by columns: the

Functions:

Name Description
recurrence_z

How much linear code structure bits have: the z of their strongest recurrence of degree up to max_degree (0: none)

block_search

A block interleaver's size from the rank deficiency, then the row x column shape whose undoing shows a short code

forney_undo

A Forney deinterleaver: symbols of symbol bits, branch j (of I, the first symbol on branch 0) delayed by

forney_search

Undo each (I, M, symbol) candidate (default FORNEY) at each start (a branch and a bit within the symbol) and score

column_delays

Each column's shift in rows (positive: sent that many rows late) that makes it a codeword of the column code again.

Shape

Shape(**kw)

A block interleaver found: size (bits), offset (first block), rows, cols (written by rows, read by columns: the order the bits came in was cols x rows), code (the code length seen once read back), deficiency

Source code in src/rpps/analysis/code/interleave.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

recurrence_z

recurrence_z(bits, max_degree=14, n=200000)

How much linear code structure bits have: the z of their strongest recurrence of degree up to max_degree (0: none)

Source code in src/rpps/analysis/code/interleave.py
def recurrence_z(bits, max_degree=14, n=200000):
    """How much linear code structure bits have: the z of their strongest recurrence of degree up to max_degree (0: none)"""
    found = recurrence.search(np.asarray(bits, dtype=np.uint8)[:n], max_degree)
    return found[0].z if found else 0.0
block_search(bits, max_size=None, max_code=None)

A block interleaver's size from the rank deficiency, then the row x column shape whose undoing shows a short code

Source code in src/rpps/analysis/code/interleave.py
def block_search(bits, max_size=None, max_code=None):
    """A block interleaver's size from the rank deficiency, then the row x column shape whose undoing shows a short code"""
    b = np.asarray(bits, dtype=np.uint8)
    N, off, _ = find_length(b, max_len=max_size)
    if N is None:
        return None
    b = b[off:]
    blocks = b[:len(b)//N*N].reshape(-1, N)
    best = None
    for rows in range(2, N//2 + 1):
        if N % rows:
            continue
        cols = N//rows
        perm = rowcol(N, cols) # out[i] = in[perm[i]]: the order the interleaver read
        inv = np.argsort(perm)
        back = blocks[:, inv].reshape(-1)
        n, o, defs = find_length(back, max_len=max_code or min(N - 1, 512))
        if n is not None and n < N and (best is None or n < best.code):
            best = Shape(size=N, offset=off, rows=rows, cols=cols, code=n, deficiency=defs.get(n))
    return best or Shape(size=N, offset=off)

forney_undo

forney_undo(bits, I, M, symbol=8)

A Forney deinterleaver: symbols of symbol bits, branch j (of I, the first symbol on branch 0) delayed by (I - 1 - j) M symbols (rpps.code.types.interleave.forney's decode, without a code object)

Source code in src/rpps/analysis/code/interleave.py
def forney_undo(bits, I, M, symbol=8):
    """A Forney deinterleaver: symbols of `symbol` bits, branch j (of I, the first symbol on branch 0) delayed by
    (I - 1 - j) M symbols (rpps.code.types.interleave.forney's decode, without a code object)"""
    b = np.asarray(bits, dtype=np.uint8)
    b = b[:len(b)//(I*symbol)*(I*symbol)]
    sym = b.reshape(-1, symbol)
    out = np.zeros_like(sym)
    for j in range(I):
        x = sym[j::I]
        d = (I - 1 - j)*M
        out[j::I] = np.concatenate((np.zeros((d, symbol), np.uint8), x))[:len(x)]
    return out.reshape(-1)
forney_search(bits, candidates=None, score=recurrence_z, n=200000)

Undo each (I, M, symbol) candidate (default FORNEY) at each start (a branch and a bit within the symbol) and score the result. Returns [(score, (I, M, symbol), start bit)], best first

Source code in src/rpps/analysis/code/interleave.py
def forney_search(bits, candidates=None, score=recurrence_z, n=200000):
    """Undo each (I, M, symbol) candidate (default FORNEY) at each start (a branch and a bit within the symbol) and score
    the result. Returns [(score, (I, M, symbol), start bit)], best first"""
    b = np.asarray(bits, dtype=np.uint8)[:n]
    cands = list(FORNEY.values()) if candidates is None else list(candidates)
    out = []
    for I, M, sym in cands:
        delay = (I - 1)*I*M*sym # start-up bits of the deinterleaver
        for start in range(I*sym):
            x = b[start:]
            x = x[:len(x)//(I*sym)*(I*sym)]
            if len(x) <= delay + 4096:
                continue
            y = forney_undo(x, I, M, sym)[delay:]
            out.append((float(score(y)), (I, M, sym), start))
    return sorted(out, key=lambda t: -t[0])

column_delays

column_delays(bits, rows, cols, max_delay=2, offset=0, **kw)

Each column's shift in rows (positive: sent that many rows late) that makes it a codeword of the column code again. bits: frames of rows x cols bits, row by row, from offset. kw: rpps.analysis.code.block.linear.sparse_checks's. Returns (delays (cols,), fraction of frames the column's checks hold on at that delay (cols,), checks H)

Source code in src/rpps/analysis/code/interleave.py
def column_delays(bits, rows, cols, max_delay=2, offset=0, **kw):
    """Each column's shift in rows (positive: sent that many rows late) that makes it a codeword of the column code again.
    bits: frames of rows x cols bits, row by row, from `offset`. kw: rpps.analysis.code.block.linear.sparse_checks's.
    Returns (delays (cols,), fraction of frames the column's checks hold on at that delay (cols,), checks H)"""
    b = np.asarray(bits, dtype=np.uint8)[offset:]
    F = len(b)//(rows*cols)
    R = b[:F*rows*cols].reshape(F*rows, cols) # every row of every frame, in order
    frames = R.reshape(F, rows, cols)
    vecs = frames.transpose(0, 2, 1).reshape(-1, rows) # every column of every frame
    kw.setdefault("w_max", rows) # a short column code's checks can be heavy (Hamming (15, 11): all weight 8)
    H, _ = sparse_checks(vecs, **kw)
    if not len(H):
        raise ValueError("no checks over the columns: not a column code at this rows x cols")
    delays = np.zeros(cols, dtype=int)
    held = np.zeros(cols)
    fs = np.arange(1, F - 1) # frames whose rows +- max_delay are all held
    if len(fs) < 4:
        raise ValueError("too few frames")
    for c in range(cols):
        best = (-1.0, 0)
        for d in range(-max_delay, max_delay + 1):
            # sent d rows late: frame f's row r arrived as row f rows + r + d of the stream
            idx = fs[:, None]*rows + np.arange(rows)[None, :] + d
            vv = R[idx, c]
            h = 1.0 - ((vv.astype(np.int32) @ H.T.astype(np.int32)) % 2).mean()
            if h > best[0] + 1e-9:
                best = (h, d)
        held[c], delays[c] = best
    return delays, held, H

rpps.analysis.code.block

Block codes: linear / cyclic / BCH / product, LDPC, Reed-Solomon, polar

Modules:

Name Description
ldpc

Blind LDPC and algebraic block codes, past what one search finds: staircase (IRA) codes, progressive reconstruction, roots

linear

Blind binary block codes: length, alignment, parity checks, and which kind of code it is (cyclic / BCH, product, LDPC)

polar

A polar code's frozen positions, blind: which of the u bits are always 0, and which construction froze them

rs

Blind Reed-Solomon identification: length, field, generator and alignment of an unknown RS code over GF(256)

ldpc

Blind LDPC and algebraic block codes, past what one search finds: staircase (IRA) codes, progressive reconstruction, roots

H, holds = rp.analysis.code.block.ldpc.staircase(words, k)          # dual-diagonal parity (DVB-S2, 802.11n, 802.16e, 5G NR)
H, holds, rounds = rp.analysis.code.block.ldpc.progressive(llr)     # checks found, frames cleaned with them, more found, ...
r = rp.analysis.code.block.ldpc.roots(words)                        # a binary cyclic code's roots: BCH and its distance
z = rp.analysis.code.block.ldpc.circulant_size(words, k)            # quasi-cyclic: the circulant size
V, c, holds = rp.analysis.code.block.ldpc.qc_generator(words, k, z) # its generator, (k/z) x ((n-k)/z) circulants
H, rank = rp.analysis.code.block.ldpc.qc_checks(V, z)               # and sparse checks from it

staircase: an IRA code's parity part is dual-diagonal: parity bit j is parity bit j-1 plus a sum of information bits, the row of A in H = [A | staircase]. With k information bits first, d_j = p_j + p_{j-1} is a linear function of them, the same for every word: over k + some words, one GF(2) elimination of the information bits solves every row at once (no search for sparse dual words: Valembois, Cluzeau, Canteaut-Chabaud would look for each). Noisy bits: the most reliable words are used, several subsets, and each row is kept by its vote and checked on words it was not solved from.

progressive: the checks one search finds (rpps.analysis.code.block.linear.sparse_checks: information sets) decode the frames (min-sum on the partial H), the decoded frames have fewer errors, and the next search finds checks the first could not, until no new ones come (Cluzeau 2006, block code reconstruction with iterative decoding; the ISIT 2024 progressive QC-LDPC reconstruction reaches ~100x the bit error rate of one search).

quasi-cyclic (qc_generator, qc_checks): a QC code's generator is circulants, so each word gives z equations at once and a few dozen words solve it (k/z + 9 of them, where a dense search for dual words needs over k); the sparse checks are then found in the generator itself, as sums of a few shifted parity blocks whose information dependences nearly cancel (an LDPC code's dense generator hides them from a word-level search unless words are many).

roots: a binary cyclic code of length n | 2^m - 1 is its generator's roots: every codeword c has c(beta^j) = 0 at them (the Vandermonde parity checks). Evaluated at every beta^j, words of the code are zero at the roots and a fraction 2^-m elsewhere; a word with an error is not zero there either, so the zero fraction is the clean words' share, which stands far over 2^-m at a few percent of clean words. Consecutive roots give a BCH code's designed distance.

Classes:

Name Description
Roots

Result of roots: n, m, roots (exponents j of beta = alpha^((2^m - 1)/n), sorted), zero (fraction of words zero at

QCStaircase

Result of qc_staircase: table (per information group, the parity addresses x: DVB-S2's address table), checks

Functions:

Name Description
staircase

Rows of an IRA code's H from aligned words (W, n) whose first k positions are the information bits and the rest

qc_generator

The generator of a quasi-cyclic code (circulant size z) from aligned words (W, n) with the k information bits

circulant_size

The circulant size of a quasi-cyclic code: the smallest z (of sizes, default every common divisor of k and n - k

qc_checks

Sparse parity checks of the quasi-cyclic code qc_generator found: H ((n - k), n) over [information k | parity

posterior

A-posteriori LLRs of words (B, n) through the checks H (c, n) by normalized min-sum, flooding (all checks at once):

progressive

Checks of aligned frames (W, n) of LLRs (log P(0)/P(1)), found again and again on frames cleaned by the checks

roots

Roots of a binary cyclic code from aligned words (W, n), position i the coefficient of x^i (reverse: of

qc_staircase

A DVB-S2-style IRA code (information bits in groups of Z, each adding to parity rows x + m q, parity accumulated)

qc_dual

The circulant check blocks of a quasi-cyclic code (every column block of Z, rows and columns cycled alike: 802.11n,

qc_size

Circulant sizes Z (dividing n) at which aligned clean codewords (W, n) have checks that stay checks cycled within

Roots

Roots(**kw)

Result of roots: n, m, roots (exponents j of beta = alpha^((2^m - 1)/n), sorted), zero (fraction of words zero at each root), generator (int, bit i the coefficient of x^i), k (n - degree), designed (BCH designed distance: 1 + the longest run of consecutive roots), clean (estimated share of words without an error)

Source code in src/rpps/analysis/code/block/ldpc.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

QCStaircase

QCStaircase(**kw)

Result of qc_staircase: table (per information group, the parity addresses x: DVB-S2's address table), checks (positions per check, as rpps.code.types.ira.ira_checks gives), holds (per row class, on held-out frames), Z

Source code in src/rpps/analysis/code/block/ldpc.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

staircase

staircase(words, k, rel=None, trials=16, verify=256, seed=0, extra=())

Rows of an IRA code's H from aligned words (W, n) whose first k positions are the information bits and the rest the parity bits in accumulator order. extra: parity positions (indices into the parity part) that some rows also involve (802.11n's first parity column is weight 3): they join the information bits as regressors. Returns (H (n-k, n) uint8, fraction of held-out words each row holds on)

Source code in src/rpps/analysis/code/block/ldpc.py
def staircase(words, k, rel=None, trials=16, verify=256, seed=0, extra=()):
    """Rows of an IRA code's H from aligned words (W, n) whose first k positions are the information bits and the rest
    the parity bits in accumulator order. extra: parity positions (indices into the parity part) that some rows also
    involve (802.11n's first parity column is weight 3): they join the information bits as regressors.
    Returns (H (n-k, n) uint8, fraction of held-out words each row holds on)"""
    words = np.asarray(words, dtype=np.uint8)
    W, n = words.shape
    m = n - k
    P = words[:, k:]
    D = P.copy()
    D[:, 1:] ^= P[:, :-1] # d_j = p_j + p_{j-1}
    cols = list(range(k)) + [k + e for e in extra]
    U = words[:, cols]
    order = np.argsort(_expected_errors(rel), kind="stable") if rel is not None else np.arange(W)
    use = len(cols) + 24
    if W < use + 32:
        raise ValueError(f"need about {use + 32} words for k = {k}, have {W}")
    pool, test = order[:max(use, W - verify)], order[max(use, W - verify):]
    rng = np.random.default_rng(seed)
    # Each trial solves every row; per row, the solution holding on the most held-out words is kept (an error in a word
    # used spoils a trial's rows, not all trials')
    T = test[:verify]
    best = np.full(m, -1.0)
    X = np.zeros((len(cols), m), np.uint8)
    for t in range(trials):
        sub = pool[:use] if t == 0 else rng.choice(pool[:min(len(pool), 3*use)], use, replace=False)
        Xt, ok = _solve(U[sub], D[sub])
        if not ok:
            continue
        held = 1.0 - ((U[T].astype(np.int32) @ Xt.astype(np.int32) + D[T]) % 2).mean(axis=0)
        better = held > best
        X[:, better], best[better] = Xt[:, better], held[better]
    if np.all(best < 0):
        raise ValueError("the information bits do not have full rank over the words: not k information bits first")
    H = np.zeros((m, n), np.uint8)
    for j in range(m):
        H[j, np.array(cols)[X[:, j] == 1]] ^= 1
        H[j, k + j] ^= 1
        if j:
            H[j, k + j - 1] ^= 1
    holds = 1.0 - ((words[test].astype(np.int32) @ H.T.astype(np.int32)) % 2).mean(axis=0)
    return H, holds

qc_generator

qc_generator(words, k, z, rel=None, trials=8, verify=256, seed=0)

The generator of a quasi-cyclic code (circulant size z) from aligned words (W, n) with the k information bits first: parity bit o of parity block J is sum over information blocks b and s of u[b, (o - s) % z] V[b, J, s], plus c[J z + o] (zero for a linear code; a coset's constant otherwise). A shift of every information block by one shifts every parity block by one, so the k x (n - k) generator is (k/z) x ((n - k)/z) circulants, each one row of z bits: each word gives z equations in the k + z unknowns of a parity block, and the coefficients are the same for every parity block, so one elimination over about k/z + 9 words solves them all. Noisy bits: the most reliable words, several subsets, each parity block's solution kept by how many held-out equations it satisfies. Information bits that never vary (a header's constants) leave the system short of rank: their share falls to the constant, which the held-out words, having the same constants, still bear out. Returns (V (k/z, (n-k)/z, z) uint8, c (n - k,) uint8, holds ((n-k)/z,): the fraction of held-out parity bits each block's solution predicts)

Source code in src/rpps/analysis/code/block/ldpc.py
def qc_generator(words, k, z, rel=None, trials=8, verify=256, seed=0):
    """The generator of a quasi-cyclic code (circulant size z) from aligned words (W, n) with the k information bits
    first: parity bit o of parity block J is sum over information blocks b and s of u[b, (o - s) % z] V[b, J, s], plus
    c[J z + o] (zero for a linear code; a coset's constant otherwise). A shift of every information block by one shifts
    every parity block by one, so the k x (n - k) generator is (k/z) x ((n - k)/z) circulants, each one row of z bits:
    each word gives z equations in the k + z unknowns of a parity block, and the coefficients are the same for every
    parity block, so one elimination over about k/z + 9 words solves them all. Noisy bits: the most reliable words, several
    subsets, each parity block's solution kept by how many held-out equations it satisfies. Information bits that never
    vary (a header's constants) leave the system short of rank: their share falls to the constant, which the held-out
    words, having the same constants, still bear out.
    Returns (V (k/z, (n-k)/z, z) uint8, c (n - k,) uint8, holds ((n-k)/z,): the fraction of held-out parity bits each
    block's solution predicts)"""
    words = np.asarray(words, dtype=np.uint8)
    W, n = words.shape
    if k % z or (n - k) % z:
        raise ValueError(f"k = {k} and n - k = {n - k} are not multiples of z = {z}")
    kb, mb = k//z, (n - k)//z
    order = np.argsort(_expected_errors(rel), kind="stable") if rel is not None else np.arange(W)
    use = kb + 9
    if W < use + 8:
        raise ValueError(f"need about {use + 8} words for k = {k}, z = {z}, have {W}")
    pool, test = order[:max(use, W - verify)], order[max(use, W - verify):]
    U = words[:, :k].reshape(W, kb, z)
    Y = words[:, k:].reshape(W, mb, z).transpose(0, 2, 1).reshape(W*z, mb) # row (w, o), column J
    rng = np.random.default_rng(seed)
    At = _qc_system(U[test], z)
    Yt = Y.reshape(W, z, mb)[test].reshape(-1, mb)
    best = np.full(mb, -1.0)
    X = np.zeros((k + z, mb), np.uint8)
    for t in range(trials):
        sub = pool[:use] if t == 0 else rng.choice(pool[:min(len(pool), 3*use)], use, replace=False)
        Xt, rk = _solve_partial(_qc_system(U[sub], z), Y.reshape(W, z, mb)[sub].reshape(-1, mb))
        held = 1.0 - ((At.astype(np.int32) @ Xt.astype(np.int32) + Yt) % 2).mean(axis=0)
        better = held > best
        X[:, better], best[better] = Xt[:, better], held[better]
    V = X[:k].reshape(kb, z, mb).transpose(0, 2, 1).copy()
    c = X[k:].T.reshape(-1).copy()
    return V, c, best

circulant_size

circulant_size(words, k, sizes=None, rel=None, hold=0.95, **kw)

The circulant size of a quasi-cyclic code: the smallest z (of sizes, default every common divisor of k and n - k from 2) whose qc_generator predicts held-out words (every parity block's fraction >= hold), or None. kw: its

Source code in src/rpps/analysis/code/block/ldpc.py
def circulant_size(words, k, sizes=None, rel=None, hold=0.95, **kw):
    """The circulant size of a quasi-cyclic code: the smallest z (of `sizes`, default every common divisor of k and n - k
    from 2) whose qc_generator predicts held-out words (every parity block's fraction >= hold), or None. kw: its"""
    n = np.asarray(words).shape[1]
    if sizes is None:
        g = np.gcd(k, n - k)
        sizes = [z for z in range(2, g + 1) if g % z == 0]
    for z in sizes:
        try:
            _, _, holds = qc_generator(words, k, z, rel=rel, **kw)
        except ValueError:
            continue
        if np.all(holds >= hold):
            return z
    return None

qc_checks

qc_checks(V, z, max_weight=8, quads=True, reps=12, seed=0)

Sparse parity checks of the quasi-cyclic code qc_generator found: H ((n - k), n) over [information k | parity n - k], full rank when they are found, lightest block rows first.

A block row of checks is a sum of shifted parity blocks whose information dependences cancel but for a few bits: x^a p_J1 + x^b p_J2 (+ x^c p_J3 (+ x^d p_J4)) = a sparse sum of information bits, for every shift together (z checks). LDPC codes have them with few terms (the generator, H_p^-1 H_u, is dense: a search for sparse dual words in the words themselves needs many), so: every pair and triple of parity blocks over all shifts, and quadruples by meeting in the middle (pairs whose dependences nearly agree: locality-sensitive hashing on reps random 40-bit projections), each kept when its information part has at most max_weight bits and it adds rank. Returns (H, rank)

Source code in src/rpps/analysis/code/block/ldpc.py
def qc_checks(V, z, max_weight=8, quads=True, reps=12, seed=0):
    """Sparse parity checks of the quasi-cyclic code qc_generator found: H ((n - k), n) over [information k | parity
    n - k], full rank when they are found, lightest block rows first.

    A block row of checks is a sum of shifted parity blocks whose information dependences cancel but for a few bits:
    x^a p_J1 + x^b p_J2 (+ x^c p_J3 (+ x^d p_J4)) = a sparse sum of information bits, for every shift together (z checks).
    LDPC codes have them with few terms (the generator, H_p^-1 H_u, is dense: a search for sparse dual words in the words
    themselves needs many), so: every pair and triple of parity blocks over all shifts, and quadruples by meeting in the
    middle (pairs whose dependences nearly agree: locality-sensitive hashing on `reps` random 40-bit projections), each
    kept when its information part has at most `max_weight` bits and it adds rank. Returns (H, rank)"""
    V = np.asarray(V, dtype=np.uint8)
    kb, mb, _ = V.shape
    k, m = kb*z, mb*z
    D = _qc_dependence(V, z)
    pad = (-k) % 64
    Dp = np.packbits(np.concatenate((D, np.zeros((mb, z, pad), np.uint8)), axis=2), axis=2).view(np.uint64)
    def weight(x):
        return np.unpackbits(np.ascontiguousarray(x).view(np.uint8), axis=-1).sum(axis=-1)
    rels = [] # (weight, ((J, shift), ...))
    for J1 in range(mb):
        for J2 in range(J1 + 1, mb):
            w = weight(Dp[J1, 0][None] ^ Dp[J2])
            for o in np.flatnonzero(w <= max_weight):
                rels.append((int(w[o]), ((J1, 0), (J2, int(o)))))
    for J3 in range(mb):
        for J1 in range(mb):
            for J2 in range(J1 + 1, mb):
                if J3 in (J1, J2):
                    continue
                w = weight(Dp[J3, 0][None, None] ^ Dp[J1][:, None] ^ Dp[J2][None, :])
                for a, b in zip(*np.nonzero(w <= max_weight)):
                    rels.append((int(w[a, b]), ((J3, 0), (J1, int(a)), (J2, int(b)))))
    if quads and mb >= 4:
        rng = np.random.default_rng(seed)
        seen = set()
        for _ in range(reps):
            proj = rng.choice(k, min(40, k), replace=False)
            P = D[:, :, proj] # (mb, z, 40)
            buckets = {}
            for J1 in range(mb):
                for J2 in range(J1 + 1, mb):
                    keys = np.packbits(P[J1][:, None, :] ^ P[J2][None, :, :], axis=2)
                    for a in range(z):
                        for b in range(z):
                            buckets.setdefault(keys[a, b].tobytes(), []).append((J1, a, J2, b))
            for lst in buckets.values():
                if len(lst) < 2 or len(lst) > 64:
                    continue
                for i in range(len(lst)):
                    for j in range(i + 1, len(lst)):
                        p, q = lst[i], lst[j]
                        if len({p[0], p[2], q[0], q[2]}) < 4:
                            continue
                        terms = tuple(sorted(((p[0], p[1]), (p[2], p[3]), (q[0], q[1]), (q[2], q[3]))))
                        base = tuple((J, (s - terms[0][1]) % z) for J, s in terms) # one per block row
                        if base in seen:
                            continue
                        seen.add(base)
                        w = int(weight(Dp[p[0], p[1]] ^ Dp[p[2], p[3]] ^ Dp[q[0], q[1]] ^ Dp[q[2], q[3]]))
                        if w <= max_weight:
                            rels.append((w, base))
    rels.sort(key=lambda r: (r[0] + len(r[1]), r[1]))
    basis, rows = {}, []
    for _, terms in rels:
        for kk in range(z):
            h = np.zeros(k + m, np.uint8)
            v = np.zeros(k, np.uint8)
            for J, s in terms:
                o = (s + kk) % z
                h[k + J*z + o] ^= 1
                v ^= D[J, o]
            h[:k] = v
            x = int.from_bytes(np.packbits(h).tobytes(), "big") # a new direction? (elimination on leading bits)
            while x:
                lead = x.bit_length()
                if lead not in basis:
                    basis[lead] = x
                    rows.append(h)
                    break
                x ^= basis[lead]
        if len(rows) >= m:
            break
    H = np.array(rows, dtype=np.uint8) if rows else np.zeros((0, k + m), np.uint8)
    return H, len(rows)

posterior

posterior(H, llr, iters=20, alpha=0.8)

A-posteriori LLRs of words (B, n) through the checks H (c, n) by normalized min-sum, flooding (all checks at once): what the checks known so far say about each bit (rpps.code.types.ldpc.flood)

Source code in src/rpps/analysis/code/block/ldpc.py
def posterior(H, llr, iters=20, alpha=0.8):
    """A-posteriori LLRs of words (B, n) through the checks H (c, n) by normalized min-sum, flooding (all checks at once):
    what the checks known so far say about each bit (rpps.code.types.ldpc.flood)"""
    H = np.asarray(H, dtype=bool)
    code = _ldpc(Logger(), H.shape[1], to_checks(H), k=0, systematic_pos=[], iters=int(iters), alpha=float(alpha))
    return code.flood(llr)

progressive

progressive(llr, rounds=8, iters=20, max_checks=None, **kw)

Checks of aligned frames (W, n) of LLRs (log P(0)/P(1)), found again and again on frames cleaned by the checks found so far (see the module). kw: rpps.analysis.code.block.linear.sparse_checks's. Stops when a round adds no rank. Returns (H (c, n): a basis of the checks found, lightest first, then more light ones; holds on the original hard bits; [rank after each round])

Source code in src/rpps/analysis/code/block/ldpc.py
def progressive(llr, rounds=8, iters=20, max_checks=None, **kw):
    """Checks of aligned frames (W, n) of LLRs (log P(0)/P(1)), found again and again on frames cleaned by the checks
    found so far (see the module). kw: rpps.analysis.code.block.linear.sparse_checks's. Stops when a round adds no rank.
    Returns (H (c, n): a basis of the checks found, lightest first, then more light ones; holds on the original hard
    bits; [rank after each round])"""
    llr = np.asarray(llr, dtype=np.float64)
    n = llr.shape[1]
    max_checks = max_checks or 2*n
    kw.setdefault("trials", 60)
    words0 = (llr < 0).astype(np.uint8)
    H = np.zeros((0, n), np.uint8)
    history = []
    cur = llr
    for r in range(rounds):
        new, _ = sparse_checks((cur < 0).astype(np.uint8), rel=np.abs(cur), seed=r, **kw)
        if len(new):
            H, rk = _keep(np.concatenate((H, new)), max_checks)
        else:
            rk = history[-1] if history else 0
        grew = not history or rk > history[-1]
        history.append(rk)
        if not len(H) or (not grew and r > 0):
            break
        cur = posterior(H, llr, iters) # always from the channel's LLRs: the checks only add what they know
    holds = 1.0 - ((words0.astype(np.int32) @ H.T.astype(np.int32)) % 2).mean(axis=0) if len(H) else np.zeros(0)
    return H, holds, history

roots

roots(words, m=None, z_min=8.0, reverse=False)

Roots of a binary cyclic code from aligned words (W, n), position i the coefficient of x^i (reverse: of x^(n-1-i)). m: the field (default the smallest with n | 2^m - 1)

Source code in src/rpps/analysis/code/block/ldpc.py
def roots(words, m=None, z_min=8.0, reverse=False):
    """Roots of a binary cyclic code from aligned words (W, n), position i the coefficient of x^i (reverse: of
    x^(n-1-i)). m: the field (default the smallest with n | 2^m - 1)"""
    words = np.asarray(words, dtype=np.int64)
    if reverse:
        words = words[:, ::-1]
    W, n = words.shape
    if m is None:
        m = next((mm for mm in range(2, 17) if (2**mm - 1) % n == 0), None)
        if m is None:
            raise ValueError(f"no GF(2^m), m <= 16, has an n = {n}th root of unity")
    gf = GF(m, PRIMITIVE[m])
    N = 2**m - 1
    step = N//n
    i = np.arange(n)
    zero = np.zeros(n)
    for j in range(n):
        zero[j] = np.mean(gf.evaluate(words, i*j*step) == 0)
    # c(beta^j) of a random word lies in the subfield its conjugates span, GF(2^|coset|): zero 2^-|coset| of the time
    base = np.array([2.0**-len(_minimal(gf, j*step, N)[1]) for j in range(n)])
    z = (zero - base)/np.sqrt(base*(1 - base)/W)
    found = [j for j in range(n) if z[j] > z_min]
    # A code's roots come in cyclotomic cosets: keep only whole cosets
    keep = set()
    for j in found:
        _, coset = _minimal(gf, j*step, N)
        js = {c//step for c in coset}
        if js <= set(found):
            keep |= js
    rts = sorted(keep)
    g = 1
    done = set()
    for j in rts:
        if j in done:
            continue
        p, coset = _minimal(gf, j*step, N)
        done |= {c//step for c in coset}
        out = 0 # g * p over GF(2)
        a, b = g, p
        while b:
            if b & 1:
                out ^= a
            a <<= 1
            b >>= 1
        g = out
    run = best = 0
    for j in range(1, n + 1):
        run = run + 1 if (j % n) in keep else 0
        best = max(best, run)
    clean = float(np.median(zero[rts] - base[rts])) if rts else 0.0
    return Roots(n=n, m=m, roots=rts, zero=zero, generator=g if rts else 0, k=n - (g.bit_length() - 1) if rts else n,
                 designed=best + 1, clean=clean)

qc_staircase

qc_staircase(words, k, Z=360, rel=None, extra=12, trials=3, seed=0)

A DVB-S2-style IRA code (information bits in groups of Z, each adding to parity rows x + m q, parity accumulated) from aligned codewords (W, n), information first: its address table, from about k/Z + extra clean words (the most reliable ones, by rel |LLR|; trials subsets, each row class keeping the solution that holds best)

Source code in src/rpps/analysis/code/block/ldpc.py
def qc_staircase(words, k, Z=360, rel=None, extra=12, trials=3, seed=0):
    """A DVB-S2-style IRA code (information bits in groups of Z, each adding to parity rows x + m q, parity accumulated)
    from aligned codewords (W, n), information first: its address table, from about k/Z + `extra` clean words (the most
    reliable ones, by `rel` |LLR|; `trials` subsets, each row class keeping the solution that holds best)"""
    words = np.asarray(words, dtype=np.uint8)
    W, n = words.shape
    m = n - k
    if m % Z or k % Z:
        raise ValueError(f"n - k = {m} and k = {k} are not multiples of Z = {Z}")
    q, G = m//Z, k//Z
    use = G + extra
    if W < use + 8:
        raise ValueError(f"need about {use + 8} words, have {W}")
    P = words[:, k:]
    D = P.copy()
    D[:, 1:] ^= P[:, :-1] # d_r = p_r + p_{r-1}
    order = np.argsort(_expected_errors(rel), kind="stable") if rel is not None else np.arange(W)
    held_out = order[use + max(0, (trials - 1)*4):][:256]
    rng = np.random.default_rng(seed)
    best_A, best_h = None, np.full(q, -1.0)
    rows_r = (np.arange(q)[:, None] + q*np.arange(Z)[None, :]) # row r of class c, offset j
    for t in range(trials):
        pool = order[:use + (trials - 1)*4]
        sub = pool[:use] if t == 0 else rng.choice(pool, use, replace=False)
        M = np.concatenate([_qc_rows(words[w, :k], Z, G) for w in sub]) # (use Z, k)
        R = np.concatenate([D[w][rows_r].T for w in sub]) # (use Z, q): class c's right side at (frame, j)
        E, piv = rref(np.concatenate((M, R), axis=1), pivot_cols=k)
        if len(piv) < k:
            continue # the frames do not span: more frames, or not this k / Z
        X = E[:k, k:] # (k, q): row of pivot column = that unknown
        sol = np.zeros((k, q), np.uint8)
        sol[piv] = X
        # each class's rows on held-out frames
        h = np.zeros(q)
        for c in range(q):
            nz = np.flatnonzero(sol[:, c])
            g, t0 = nz//Z, nz % Z
            ok = []
            for w in held_out[:64]:
                u = words[w, :k].reshape(G, Z)
                lhs = np.zeros(Z, np.uint8)
                for gg, tt in zip(g, t0):
                    lhs ^= np.roll(u[gg], tt) # u[g, (j - t) mod Z] over j
                ok.append(np.mean(lhs == D[w][rows_r[c]]))
            h[c] = np.mean(ok) if ok else 0.0
        better = h > best_h
        if best_A is None:
            best_A = sol.copy()
        best_A[:, better] = sol[:, better]
        best_h[better] = h[better]
    if best_A is None:
        raise ValueError("no subset of frames spans the information bits: not an IRA code with this k and Z")
    table = [[] for _ in range(G)]
    for c in range(q):
        for v in np.flatnonzero(best_A[:, c]):
            g, j0 = divmod(int(v), Z)
            table[g].append(c + q*j0)
    table = [sorted(t) for t in table]
    from ....code.types.ira import ira_checks
    return QCStaircase(table=table, checks=ira_checks(n, k, table, Z), holds=best_h, Z=Z, n=n, k=k)

qc_dual

qc_dual(words, Z, extra=8, trials=200, seed=0)

The circulant check blocks of a quasi-cyclic code (every column block of Z, rows and columns cycled alike: 802.11n, 802.16e, 5G NR's lifted base graphs) from aligned clean codewords (W, n), about n/Z + extra of them. The circulant system's null space holds every check row (a base row's shifts are base rows too); its sparse vectors, found by information sets over it, are the blocks' rows. Returns base rows (b, n) uint8, one per circulant block, lightest first: row j of a block is its base row with every block of Z cycled by j

Source code in src/rpps/analysis/code/block/ldpc.py
def qc_dual(words, Z, extra=8, trials=200, seed=0):
    """The circulant check blocks of a quasi-cyclic code (every column block of Z, rows and columns cycled alike: 802.11n,
    802.16e, 5G NR's lifted base graphs) from aligned clean codewords (W, n), about n/Z + `extra` of them. The circulant
    system's null space holds every check row (a base row's shifts are base rows too); its sparse vectors, found by
    information sets over it, are the blocks' rows. Returns base rows (b, n) uint8, one per circulant block, lightest
    first: row j of a block is its base row with every block of Z cycled by j"""
    words = np.asarray(words, dtype=np.uint8)
    W, n = words.shape
    if n % Z:
        raise ValueError(f"n = {n} is not a multiple of Z = {Z}")
    G = n//Z
    use = min(W, G + extra)
    M = np.concatenate([_qc_rows(words[w], Z, G) for w in range(use)])
    R, piv = rref(M)
    pset = set(piv)
    free = [c for c in range(n) if c not in pset]
    if not free:
        return np.zeros((0, n), np.uint8)
    B = np.zeros((len(free), n), np.uint8)
    for i, f in enumerate(free): # null vector: x_f = 1, the pivots from their rows
        B[i, f] = 1
        B[i, piv] = R[:, f]
    # (column (g, t) of the system is the check's position Z g + (j - t) mod Z at row j: row 0 has it at (g, -t))
    g, t = np.divmod(np.arange(n), Z)
    B0 = np.zeros_like(B)
    B0[:, Z*g + (-t) % Z] = B
    # sparse vectors of the null space: information sets (random column orders, reduced: rows one free column each)
    rng = np.random.default_rng(seed)
    found = {}
    for _ in range(trials):
        perm = rng.permutation(n)
        rows, _ = rref(B0[:, perm])
        rows_full = np.zeros_like(rows)
        rows_full[:, perm] = rows
        for r_ in rows_full:
            wgt = int(r_.sum())
            if wgt and wgt <= 2*G:
                key = min(tuple(np.flatnonzero(sh)) for sh in _shifts(r_, Z, G)) # one per shift class
                found.setdefault(key, r_)
    cand = sorted(found.values(), key=lambda v: int(v.sum()))
    out, span = [], np.zeros((0, n), np.uint8)
    target = rank(B0)
    for v in cand:
        S = np.concatenate((span, _shifts(v, Z, G)))
        if rank(S) > rank(span) if len(span) else True:
            out.append(v)
            span = S
            if rank(span) >= target:
                break
    return np.array(out, dtype=np.uint8) if out else np.zeros((0, n), np.uint8)

qc_size

qc_size(words, candidates=None, extra=8)

Circulant sizes Z (dividing n) at which aligned clean codewords (W, n) have checks that stay checks cycled within every block of Z: {Z: how many independent ones}. The code's own Z has them all (n - k); its divisors and multiples some, other sizes none: the largest is the code's

Source code in src/rpps/analysis/code/block/ldpc.py
def qc_size(words, candidates=None, extra=8):
    """Circulant sizes Z (dividing n) at which aligned clean codewords (W, n) have checks that stay checks cycled within
    every block of Z: {Z: how many independent ones}. The code's own Z has them all (n - k); its divisors and multiples
    some, other sizes none: the largest is the code's"""
    words = np.asarray(words, dtype=np.uint8)
    W, n = words.shape
    cands = candidates or [z for z in range(8, n//4 + 1) if n % z == 0]
    out = {}
    for Z in cands:
        G = n//Z
        if W < G + extra:
            continue
        M = np.concatenate([_qc_rows(words[w], Z, G) for w in range(G + extra)])
        nul = n - rank(M)
        if nul:
            out[Z] = nul
    return out

linear

Blind binary block codes: length, alignment, parity checks, and which kind of code it is (cyclic / BCH, product, LDPC)

Rows of L bits from a stream of codewords of length n: when L is a multiple of n (and for most alignments when L = n), every row holds whole codewords at the same place, so the rows satisfy the code's parity checks and the matrix of rows is short of full rank. Random bits, or rows of any other length, are not (with EXTRA more rows than columns, a random matrix is short 2^-EXTRA of the time). That finds the length; the alignment is where rows of n bits are shortest of rank; the checks are the null space of the rows (recover_dual, which tolerates some words with errors).

Then what kind of code

cyclic (BCH, cyclic Hamming and Golay, shortened ones too): every codeword is a multiple of the generator g(x), so g is the greatest common divisor of codewords. Its full length is the order of x modulo g; a narrow-sense BCH code is the one whose generator is the product of the minimal polynomials of alpha, alpha^3, ..., alpha^(2t-1) in some GF(2^m). product (turbo product codes): rows are codewords of one code and, stacked n2 at a time, columns of another. LDPC: the checks found have low weight (sparse_checks, which takes soft values to pick the cleanest words).

The rank methods need about n + EXTRA rows of n bits with few errors: lengths up to roughly sqrt(len(bits)), at a bit error rate well below 1/n^2 (after a decoder, or a strong signal). What they find is a Guess: decoded once saved.

Functions:

Name Description
deficiency

L minus the rank of rows of L bits from offset, the largest over segments stretches of the bits (an error in a row

alignment

(offset, deficiency at each offset): where rows of n bits are shortest of rank

find_length

Codeword length of a binary block code: (n, offset, {length: deficiency}) or (None, None, deficiencies)

frame_units

The length of a block code whose words lie end to end from where each frame starts: rows are bits that each start

to_poly

Bits, first the highest power, as a polynomial int

cyclic_generator

g(x) of a cyclic code from aligned codewords (W, n): the commonest gcd of two words that has degree r (= n - k). With

primitive_polys

Primitive polynomials of degree m (x is a generator of GF(2^m))

bch_of

The narrow-sense BCH definition with generator g, if it is one: {"type": "bch", ...} or None

product

Rows of n1 bits stacked n2 at a time, whose columns are codewords too: (n2, row phase, deficiency) or None.

sparse_checks

Low-weight parity checks of aligned words (W, n): (H (c, n) uint8, fraction of words each holds on)

lightest

The sparsest description of the checks H span: a basis taken lightest first, then every check no heavier than its

trivial_checks

When checks of weight 1 and 2 (bits that hold one value, pairs that are equal or opposite, in hold of the words)

recurrence

(degree, taps, fraction holding) when the bits follow one short linear recurrence (shorter than n: what makes every

solve_block

Find a binary block code in bits: its length, alignment, checks, and kind. Returns [(Hypothesis, Guess or None)]

soft_score

z of each check h (rows of H) on words of LLRs (W, n): the sum over words of prod_{j in h} tanh(llr_j/2) (each

soft_dual

Parity checks of a linear block code of length n from soft values (LLRs, positive = 0): recover_dual for words

soft_find_length

Codeword length from soft values: the shortest n (rows of n from offset) whose soft dual holds a check, or None.

recover_dual

Recover parity checks of an unknown linear block code of length n from (noisy) hard bits

deficiency

deficiency(bits, L, offset=0, segments=3, extra=EXTRA)

L minus the rank of rows of L bits from offset, the largest over segments stretches of the bits (an error in a row adds to the rank, so the cleanest stretch counts). 0 for random bits; the number of independent checks for a code. None when there are fewer than L + extra rows

Source code in src/rpps/analysis/code/block/linear.py
def deficiency(bits, L, offset=0, segments=3, extra=EXTRA):
    """L minus the rank of rows of L bits from `offset`, the largest over `segments` stretches of the bits (an error in a row
    adds to the rank, so the cleanest stretch counts). 0 for random bits; the number of independent checks for a code. None
    when there are fewer than L + extra rows"""
    b = np.asarray(bits, dtype=np.uint8)[offset:]
    W = L + extra
    total = len(b)//L
    if total < W:
        return None
    starts = sorted(set(np.linspace(0, total - W, segments).astype(int))) if segments > 1 else [0]
    return max(L - rank(b[s*L:(s + W)*L].reshape(W, L)) for s in starts)

alignment

alignment(bits, n, extra=EXTRA)

(offset, deficiency at each offset): where rows of n bits are shortest of rank

Source code in src/rpps/analysis/code/block/linear.py
def alignment(bits, n, extra=EXTRA):
    """(offset, deficiency at each offset): where rows of n bits are shortest of rank"""
    d = np.array([deficiency(bits, n, o, segments=2, extra=extra) or 0 for o in range(n)])
    return int(np.argmax(d)), d

find_length

find_length(bits, min_len=4, max_len=None, extra=EXTRA)

Codeword length of a binary block code: (n, offset, {length: deficiency}) or (None, None, deficiencies)

The rank deficiency shows at multiples of n (and at n itself for most alignments): n is the smallest divisor of the first deficient length at which some alignment is deficient. Structure at most lengths (constant bits, a repetition) is not a block code.

Source code in src/rpps/analysis/code/block/linear.py
def find_length(bits, min_len=4, max_len=None, extra=EXTRA):
    """Codeword length of a binary block code: (n, offset, {length: deficiency}) or (None, None, deficiencies)

    The rank deficiency shows at multiples of n (and at n itself for most alignments): n is the smallest divisor of the
    first deficient length at which some alignment is deficient. Structure at most lengths (constant bits, a repetition)
    is not a block code."""
    b = np.asarray(bits, dtype=np.uint8)
    max_len = max_len or int(np.sqrt(len(b)/1.2)) - extra
    defs = {}
    for L in range(min_len, max_len + 1):
        d = deficiency(b, L, extra=extra)
        if d is None:
            break
        defs[L] = d
    hits = [L for L, d in defs.items() if d > 0]
    if not hits or len(hits) > 0.5*len(defs):
        return None, None, defs
    first = hits[0]
    for n in [d for d in range(min_len, first + 1) if first % d == 0]:
        off, prof = alignment(b, n, extra)
        # Most deficient at one alignment, above the others (a sparse code keeps some checks at any alignment; constant
        # bits are as deficient everywhere)
        if prof[off] > 0 and prof[off] > np.median(prof):
            return _longer(b, n, off, max_len, extra) + (defs,)
    return None, None, defs

frame_units

frame_units(rows, min_len=4, max_len=None, extra=EXTRA, trials=6, seed=0)

The length of a block code whose words lie end to end from where each frame starts: rows are bits that each start at a frame's start (a burst's payload after its preamble, a frame's after its unique word), of any lengths. For each n the words at 0, n, 2n... of every row are stacked: a code of length n leaves them short of rank. Returns (n, deficiency) for the shortest that is, or (None, 0). Rows are many short frames where find_length wants one long stream: a code laid out per frame breaks at every frame's end there, here it doesn't. As for find_length, n + extra words at a time (a word with a bit error adds to the rank: fewer words, fewer of them), the best of trials draws

Source code in src/rpps/analysis/code/block/linear.py
def frame_units(rows, min_len=4, max_len=None, extra=EXTRA, trials=6, seed=0):
    """The length of a block code whose words lie end to end from where each frame starts: rows are bits that each start
    at a frame's start (a burst's payload after its preamble, a frame's after its unique word), of any lengths. For each
    n the words at 0, n, 2n... of every row are stacked: a code of length n leaves them short of rank. Returns (n,
    deficiency) for the shortest that is, or (None, 0). Rows are many short frames where `find_length` wants one long
    stream: a code laid out per frame breaks at every frame's end there, here it doesn't. As for `find_length`, n + extra
    words at a time (a word with a bit error adds to the rank: fewer words, fewer of them), the best of `trials` draws"""
    rows = [np.asarray(r, dtype=np.uint8) for r in rows if len(r)]
    if not rows:
        return None, 0
    rng = np.random.default_rng(seed)
    L = max(len(r) for r in rows)
    for n in range(min_len, (max_len or L) + 1):
        W = np.array([r[o:o + n] for r in rows for o in range(0, len(r) - n + 1, n)], dtype=np.uint8)
        if len(W) < n + extra: # Too few words for the rank to say anything (and fewer still for longer n)
            break
        m = n + extra
        draws = [W] if len(W) <= m else [W[rng.choice(len(W), m, replace=False)] for _ in range(trials)]
        d = max(n - rank(w) for w in draws)
        if d > 0:
            return n, d
    return None, 0

to_poly

to_poly(row)

Bits, first the highest power, as a polynomial int

Source code in src/rpps/analysis/code/block/linear.py
def to_poly(row):
    """Bits, first the highest power, as a polynomial int"""
    row = np.asarray(row, dtype=np.uint8)
    pad = (-len(row)) % 8
    return int.from_bytes(np.packbits(row).tobytes(), "big") >> pad

cyclic_generator

cyclic_generator(words, r)

g(x) of a cyclic code from aligned codewords (W, n): the commonest gcd of two words that has degree r (= n - k). With errors in some words their gcds differ; codewords' share g. Returns (g, fraction of words g divides) or (None, 0)

Source code in src/rpps/analysis/code/block/linear.py
def cyclic_generator(words, r):
    """g(x) of a cyclic code from aligned codewords (W, n): the commonest gcd of two words that has degree r (= n - k). With
    errors in some words their gcds differ; codewords' share g. Returns (g, fraction of words g divides) or (None, 0)"""
    polys = [to_poly(w) for w in words]
    cnt = Counter()
    for a, b in zip(polys[0::2], polys[1::2]):
        if a and b:
            g = pgcd(a, b)
            if g.bit_length() - 1 == r:
                cnt[g] += 1
    if not cnt:
        return None, 0.0
    g = cnt.most_common(1)[0][0]
    return g, float(np.mean([pmod(p, g) == 0 for p in polys]))

primitive_polys

primitive_polys(m)

Primitive polynomials of degree m (x is a generator of GF(2^m))

Source code in src/rpps/analysis/code/block/linear.py
def primitive_polys(m):
    """Primitive polynomials of degree m (x is a generator of GF(2^m))"""
    N = (1 << m) - 1
    return [p for p in range((1 << m) + 1, 1 << (m + 1), 2) if porder(p, N) == N]

bch_of

bch_of(g, n_sent)

The narrow-sense BCH definition with generator g, if it is one: {"type": "bch", ...} or None

Source code in src/rpps/analysis/code/block/linear.py
def bch_of(g, n_sent):
    """The narrow-sense BCH definition with generator g, if it is one: {"type": "bch", ...} or None"""
    from ....logger import Logger
    from ....code.types.bchgf import bchgf
    N = porder(g)
    r = g.bit_length() - 1
    if N is None:
        return None
    m = next((m for m in range(2, 17) if ((1 << m) - 1) % N == 0), None)
    if m is None or N != (1 << m) - 1 or r % m:
        return None
    for p in primitive_polys(m) if m <= 16 else []:
        if pmod(g, p):
            continue
        try:
            gen = bchgf(Logger().Child("blind-bch", 0), n_sent, n_sent - r, m, p, r//m).gen
        except ValueError:
            continue
        if to_poly(gen) == g:
            return {"base": "block", "type": "bch", "n": int(n_sent), "k": int(n_sent - r), "m": m, "poly": hex(p), "t": r//m}
    return None

product

product(bits, n1, offset, max_n2=128, extra=24, per_block=4)

Rows of n1 bits stacked n2 at a time, whose columns are codewords too: (n2, row phase, deficiency) or None. Columns from n2 + extra blocks, one each; with fewer blocks, up to per_block from each (spread across the columns)

Source code in src/rpps/analysis/code/block/linear.py
def product(bits, n1, offset, max_n2=128, extra=24, per_block=4):
    """Rows of n1 bits stacked n2 at a time, whose columns are codewords too: (n2, row phase, deficiency) or None.
    Columns from n2 + extra blocks, one each; with fewer blocks, up to `per_block` from each (spread across the columns)"""
    b = np.asarray(bits, dtype=np.uint8)[offset:]
    rows = b[:len(b)//n1*n1].reshape(-1, n1)
    best = None
    for n2 in range(3, max_n2 + 1):
        d = []
        for ph in range(n2):
            B = (len(rows) - ph)//n2
            per = -(-(n2 + extra)//max(B, 1)) # Columns a block gives
            if per > min(per_block, n1):
                break
            # Columns from many blocks: a few blocks can agree with a wrong n2 by chance; each block's spread over its row
            blk = rows[ph:ph + B*n2].reshape(B, n2, n1).transpose(0, 2, 1)
            pick = (np.arange(B)[:, None] + np.arange(per)[None, :]*(n1//per)) % n1
            cols = blk[np.arange(B)[:, None], pick].reshape(-1, n2)
            d.append(n2 - rank(cols[:n2 + extra]))
        if len(d) < n2:
            break
        d = np.array(d)
        ph = int(np.argmax(d))
        if d[ph] > 0 and (d == d[ph]).sum() == 1 and (best is None or d[ph] > best[2]):
            best = (n2, ph, int(d[ph]))
            if (d > 0).sum() == 1: # One phase only: the column length (a multiple would come later, and weaker per row)
                return best
    return best

sparse_checks

sparse_checks(words, rel=None, w_max=None, trials=150, verify=400, seed=0, k=None, patience=20)

Low-weight parity checks of aligned words (W, n): (H (c, n) uint8, fraction of words each holds on)

Each trial puts the columns in a random order and takes the null space of up to k + 16 words: its basis vectors are each one free position plus pivots, and a sparse check comes out as one of them whenever all but one of its positions are pivots. Those of weight <= w_max that hold on far more than half of verify words are kept. rel: reliabilities (|LLR|) of the bits: the words with the fewest expected errors (sum of 1/(1 + e^|LLR|)) are the ones used. k: the code's dimension if known: k + 16 words span it, and the fewer words the likelier they are all clean.

Source code in src/rpps/analysis/code/block/linear.py
def sparse_checks(words, rel=None, w_max=None, trials=150, verify=400, seed=0, k=None, patience=20):
    """Low-weight parity checks of aligned words (W, n): (H (c, n) uint8, fraction of words each holds on)

    Each trial puts the columns in a random order and takes the null space of up to k + 16 words: its basis vectors are each
    one free position plus pivots, and a sparse check comes out as one of them whenever all but one of its positions are
    pivots. Those of weight <= w_max that hold on far more than half of `verify` words are kept. rel: reliabilities
    (|LLR|) of the bits: the words with the fewest expected errors (sum of 1/(1 + e^|LLR|)) are the ones used. k: the code's
    dimension if known: k + 16 words span it, and the fewer words the likelier they are all clean."""
    words = np.asarray(words, dtype=np.uint8)
    W, n = words.shape
    w_max = w_max or max(6, min(40, n//4))
    # Checks are verified on words they were not computed from (a null space vector holds on those by construction): those
    # are kept aside first, even when that leaves fewer than k + 16 to solve from (sparse checks still come out)
    hold = min(64, max(32, W//5))
    R = min(W - hold, (k if k is not None else n) + 16)
    if R < 4:
        return np.zeros((0, n), np.uint8), np.zeros(0)
    order = (np.argsort((1.0/(1.0 + np.exp(np.minimum(np.asarray(rel, dtype=float), 50.0)))).sum(axis=1), kind="stable")
             if rel is not None else np.arange(W))
    npool = min(4*R, W - hold)
    pool = words[order[:npool]]
    rest = order[npool:]
    if len(rest) < 32:
        return np.zeros((0, n), np.uint8), np.zeros(0)
    test = words[np.random.default_rng(seed + 1).choice(rest, min(len(rest), verify), replace=False)].astype(np.int32)
    crit = z_critical(max(1, trials*n))
    # (trials: the most; it stops once `patience` trials in a row find nothing new)
    rng = np.random.default_rng(seed)
    found = {}
    quiet = 0
    for t in range(trials):
        if quiet >= patience: # Nothing new for a while: what can be found has been
            break
        before = len(found)
        # The cleanest words first; then random subsets of the reliable ones, some smaller than k (likelier all clean: their
        # null space holds junk too, which fails verification, and the sparse checks still come out as basis vectors)
        if t == 0:
            sub = pool[:R]
        else:
            size = int(rng.integers(max(4, R//2), R + 1))
            sub = pool[rng.choice(len(pool), min(size, len(pool)), replace=False)]
        perm = rng.permutation(n)
        N = nullspace(sub[:, perm])
        if not len(N):
            quiet += 1
            continue
        h = np.zeros_like(N)
        h[:, perm] = N
        h = h[h.sum(axis=1) <= w_max]
        if not len(h):
            quiet += 1
            continue
        sat = 1.0 - ((test @ h.T.astype(np.int32)) % 2).mean(axis=0)
        z = (sat - 0.5)*2*np.sqrt(len(test))
        for v, s in zip(h[z > crit], sat[z > crit]):
            found.setdefault(v.tobytes(), (v, float(s)))
        quiet = 0 if len(found) > before else quiet + 1
    if not found:
        return np.zeros((0, n), np.uint8), np.zeros(0)
    H = np.array([v for v, s in found.values()])
    return H, np.array([s for v, s in found.values()])

lightest

lightest(H)

The sparsest description of the checks H span: a basis taken lightest first, then every check no heavier than its heaviest (redundant low-weight checks help a decoder: Gallager's H has more rows than its rank)

Source code in src/rpps/analysis/code/block/linear.py
def lightest(H):
    """The sparsest description of the checks H span: a basis taken lightest first, then every check no heavier than its
    heaviest (redundant low-weight checks help a decoder: Gallager's H has more rows than its rank)"""
    H = np.asarray(H, dtype=np.uint8)
    if not len(H):
        return H
    H = H[np.argsort(H.sum(axis=1), kind="stable")]
    basis, r = [], 0
    for row in H:
        if rank(np.array(basis + [row])) > r:
            basis.append(row)
            r += 1
    w = max(int(b.sum()) for b in basis)
    return H[H.sum(axis=1) <= w]

trivial_checks

trivial_checks(words, nk, hold=0.97)

When checks of weight 1 and 2 (bits that hold one value, pairs that are equal or opposite, in hold of the words) account for all nk independent checks: (fixed positions, equal pairs); else (None, None)

Source code in src/rpps/analysis/code/block/linear.py
def trivial_checks(words, nk, hold=0.97):
    """When checks of weight 1 and 2 (bits that hold one value, pairs that are equal or opposite, in `hold` of the words)
    account for all nk independent checks: (fixed positions, equal pairs); else (None, None)"""
    W = np.asarray(words[:400], dtype=np.int8)
    n = W.shape[1]
    m = W.mean(axis=0)
    fixed = [int(j) for j in np.nonzero((m <= 1 - hold) | (m >= hold))[0]]
    rows = []
    for j in fixed:
        r = np.zeros(n, dtype=np.uint8)
        r[j] = 1
        rows.append(r)
    rest = [j for j in range(n) if j not in set(fixed)]
    same = []
    if 1 < len(rest) <= 512:
        X = 2*W[:, rest].astype(np.float32) - 1
        C = np.abs(X.T @ X)/len(W)
        for a, c in zip(*np.nonzero(np.triu(C >= 2*hold - 1, 1))):
            r = np.zeros(n, dtype=np.uint8)
            r[rest[a]] = r[rest[c]] = 1
            rows.append(r)
            same.append((int(rest[a]), int(rest[c])))
    if not rows or rank(np.array(rows)) < nk:
        return None, None
    return fixed, same

recurrence

recurrence(bits, n, windows=4, hold=0.9)

(degree, taps, fraction holding) when the bits follow one short linear recurrence (shorter than n: what makes every row of n bits short of rank, at every alignment), else None. Berlekamp-Massey on a few clean-looking stretches of 3n bits; the shortest recurrence found must hold over the whole stream

Source code in src/rpps/analysis/code/block/linear.py
def recurrence(bits, n, windows=4, hold=0.9):
    """(degree, taps, fraction holding) when the bits follow one short linear recurrence (shorter than n: what makes every
    row of n bits short of rank, at every alignment), else None. Berlekamp-Massey on a few clean-looking stretches of
    3n bits; the shortest recurrence found must hold over the whole stream"""
    from ...sequence.scrambler import recurrence_holds
    b = np.asarray(bits, dtype=np.uint8)
    span = 3*n
    if len(b) < 2*span:
        return None
    best = None
    for s in np.linspace(0, len(b) - span, windows).astype(int):
        C, L = berlekamp_massey(b[s:s + span])
        taps = lfsr_taps(C, L)
        if 0 < L < n and taps and (best is None or L < best[0]):
            best = (L, tuple(taps))
    if best is None:
        return None
    h = float(np.mean(recurrence_holds(b, best[1])))
    return (best[0], best[1], h) if h >= hold else None

solve_block

solve_block(bits, n=None, offset=None, llr=None, max_len=None, max_n2=128, soft_length=False)

Find a binary block code in bits: its length, alignment, checks, and kind. Returns [(Hypothesis, Guess or None)]

n / offset: when known (a frame length, a hint); else found by rank (lengths up to max_len, by default what the bits allow). llr: soft values of the bits (positive = 0), to pick the cleanest words for the sparse checks, and for the checks when the bits are too noisy for the rank (soft_dual, about a second); soft_length: the length too (soft_find_length: seconds a length tried, so only when asked)

Source code in src/rpps/analysis/code/block/linear.py
def solve_block(bits, n=None, offset=None, llr=None, max_len=None, max_n2=128, soft_length=False):
    """Find a binary block code in bits: its length, alignment, checks, and kind. Returns [(Hypothesis, Guess or None)]

    n / offset: when known (a frame length, a hint); else found by rank (lengths up to max_len, by default what the bits
    allow). llr: soft values of the bits (positive = 0), to pick the cleanest words for the sparse checks, and for the
    checks when the bits are too noisy for the rank (`soft_dual`, about a second); soft_length: the length too
    (`soft_find_length`: seconds a length tried, so only when asked)"""
    b = np.asarray(bits, dtype=np.uint8)
    soft = False
    if n is None:
        n, offset, _ = find_length(b, max_len=max_len)
        if n is None and llr is not None and soft_length: # too noisy for the rank: the soft dual, length by length
            n, offset = soft_find_length(llr, max_len=min(max_len or 128, 128)), 0
        if n is None:
            return []
    elif offset is None:
        offset, _ = alignment(b, n)
    r = recover_dual(b, n, offset, trials=20)
    if llr is not None and r["k"] > 0: # the soft dual too: noisy words leave the hard one short
        rs = soft_dual(llr, n, offset, trials=20)
        if rs["ok"] and rs["k"] < r["k"]:
            r, soft = rs, True
    if not r["ok"]:
        return []
    H, k = r["H"], r["k"]
    if k < 1: # Every word the same: a pattern repeating every n bits (idle fill, a carrier), not a code
        return []
    W = (len(b) - offset)//n
    words = b[offset:offset + W*n].reshape(W, n)
    sat = 1.0 - ((words[:400].astype(np.int32) @ H.T.astype(np.int32)) % 2).mean()
    clean = words[((words.astype(np.int32) @ H.T.astype(np.int32)) % 2 == 0).all(axis=1)] # (passing every check found)
    base = {"n": int(n), "k": int(k), "offset": int(offset), "checks_hold": float(sat), "soft": soft}
    z = float((sat - 0.5)*2*np.sqrt(min(W, 400)*len(H)))
    if soft: # the hard bits break checks often at this SNR: the soft score says how far from chance they are
        z = float(np.min(soft_score(H, np.asarray(llr, dtype=float)[offset:offset + W*n].reshape(W, n))))
    fixed, same = trivial_checks(words, n - k)
    if fixed is None and k <= n//LOW_RATE: # A code this low a rate is rare; fill with a few bit errors is not
        fixed, same = trivial_checks(words, n - k, hold=0.9)
    if fixed is not None: # Bits that never change, or copy one another, every n bits: a frame's structure, not a code
        return [(Hypothesis("frame-blind", f"period {n} bits: {len(fixed)} bits fixed, {len(same)} pairs equal (framing or "
                            "fill, not an error-correcting code)", z, {**base, "kind": "frame", "fixed": fixed,
                                                                       "same": same}), None)]
    rec = recurrence(b, n)
    if rec is not None: # Every bit a sum of the few before it: rows of any length past that are short of rank
        L, taps, holds = rec
        return [(Hypothesis("frame-blind", f"a recurrence of degree {L} ({holds*100:.0f}% of bits): a PRBS, idle pattern or "
                            "test sequence, not an error-correcting code", z, {**base, "kind": "recurrence", "degree": L,
                                                                                 "taps": list(taps), "holds": holds}), None)]
    if k <= n//LOW_RATE:
        dist = (words != _majority(words)).mean(axis=1)
        if np.median(dist) < 0.1: # Most words the same pattern: fill, a carrier, a locked rate too high
            return [(Hypothesis("frame-blind", f"period {n} bits: most words within {np.median(dist)*100:.0f}% of one "
                                "pattern (fill, not an error-correcting code)", z, {**base, "kind": "fill"}), None)]

    prod = _product_of(b, n, k, offset)
    if prod is not None:
        return [prod]

    # (columns up to the length the bits hold enough blocks for: n2 + 24 columns, at most 4 from a block)
    m2 = max((m for m in range(3, max_n2 + 1) if n*m*(m + 24) <= 4*len(b)), default=None) # (product: 4 columns a block)
    p = product(b, n, offset, m2) if m2 else None
    if p is not None: # Rows of n are a code, and so are columns of n2 of them: a product code longer than the rank could see
        n2, ph, _ = p
        found = _product(b, n, k, H, n2, offset + ph*n)
        if found is not None:
            return [found]

    g, frac = cyclic_generator((clean if len(clean) >= 32 else words)[:200], n - k)
    if g is not None and frac > 0.5 and g & 1: # (a generator has a constant term: x divides no cyclic code's)
        N = porder(g)
        if N is not None and N < n: # g divides x^N + 1 for every multiple of its order: the smallest one that holds n bits
            N = -(-n//N)*N
        bch = bch_of(g, n)
        if bch is not None:
            return [(Hypothesis("block-blind", f"BCH({n},{k}) t={bch['t']} GF(2^{bch['m']})", z, {**base, "kind": "bch", "g": hex(g)}),
                     Guess("block", {**bch, "comment": "found by rpps.analysis.code.block.linear.solve_block"}, {**base, "words_ok": frac}))]
        hyp = Hypothesis("block-blind", f"cyclic ({n},{k}) g={g:#x}", z, {**base, "kind": "cyclic", "g": hex(g), "full_length": N})
        guess = None
        if N is not None and N <= 4096: # (the cyclic definition builds dense matrices of the full length)
            guess = Guess("block", {"base": "block", "type": "cyclic", "n": int(N), "k": int(N - (n - k)), "poly": hex(g),
                                    "shorten": int(N - n), "comment": "found by rpps.analysis.code.block.linear.solve_block"},
                          {**base, "words_ok": frac})
        return [(hyp, guess)]


    rel = None
    if llr is not None:
        rel = np.abs(np.asarray(llr, dtype=float)[offset:offset + W*n]).reshape(W, n)
    S, s_sat = sparse_checks(words, rel, k=k)
    S = lightest(S)
    if len(S) and rank(S) == n - k: # The whole dual from low-weight checks: an LDPC code (or any with a sparse dual)
        name = "LDPC" if n >= 64 else "linear, sparse checks"
        return [(Hypothesis("block-blind", f"{name} ({n},{k}) checks of weight <= {int(S.sum(axis=1).max())}", z,
                            {**base, "kind": "ldpc" if n >= 64 else "sparse", "checks": len(S)}),
                 Guess("block", {"base": "block", "type": "ldpc", "n": int(n), "k": int(k), "checks": _checks(S),
                                 "comment": "found by rpps.analysis.code.block.linear.solve_block"}, base))]
    return [(Hypothesis("block-blind", f"linear ({n},{k})", z, {**base, "kind": "linear"}),
             Guess("block", {"base": "block", "type": "ldpc", "n": int(n), "k": int(k), "checks": _checks(H),
                             "comment": "found by rpps.analysis.code.block.linear.solve_block (dense checks)"}, base))]

soft_score

soft_score(H, llr)

z of each check h (rows of H) on words of LLRs (W, n): the sum over words of prod_{j in h} tanh(llr_j/2) (each word's expected parity of h: +1 for a sure 0) over its spread. Near 0 for a vector that is no check, large for one

Source code in src/rpps/analysis/code/block/linear.py
def soft_score(H, llr):
    """z of each check h (rows of H) on words of LLRs (W, n): the sum over words of prod_{j in h} tanh(llr_j/2) (each
    word's expected parity of h: +1 for a sure 0) over its spread. Near 0 for a vector that is no check, large for one"""
    t = np.tanh(np.clip(np.asarray(llr, dtype=float), -30, 30)/2)
    H = np.asarray(H, dtype=bool)
    # product over each check's support, in logs (sign and magnitude apart), for all words at once
    la = np.log(np.maximum(np.abs(t), 1e-300))
    neg = (t < 0).astype(np.int64)
    mag = np.exp(la @ H.T.astype(float))
    sign = 1 - 2*((neg @ H.T.astype(np.int64)) % 2)
    T = sign*mag
    return T.sum(axis=0)/np.sqrt(np.sum(T**2, axis=0) + 1e-300)

soft_dual

soft_dual(llr, n, offset=0, trials=40, seed=0, z_min=8.0, size=None)

Parity checks of a linear block code of length n from soft values (LLRs, positive = 0): recover_dual for words too noisy for random subsets to be clean. Each subset of s words is drawn from the 3s likeliest to hold no error (prod 1/(1 + e^-|l|); once checks are found, words failing one go last, which cleans the next draw); null vectors are kept on their soft score (soft_score: the tanh-product syndrome over all words, above z_min). Returns dict(H, k, ok, clean) as recover_dual (clean: the words' mean chance of no error)

Source code in src/rpps/analysis/code/block/linear.py
def soft_dual(llr, n, offset=0, trials=40, seed=0, z_min=8.0, size=None):
    """Parity checks of a linear block code of length n from soft values (LLRs, positive = 0): `recover_dual` for words
    too noisy for random subsets to be clean. Each subset of s words is drawn from the 3s likeliest to hold no error
    (prod 1/(1 + e^-|l|); once checks are found, words failing one go last, which cleans the next draw); null vectors are kept on their soft score (`soft_score`: the tanh-product syndrome over all
    words, above z_min). Returns dict(H, k, ok, clean) as recover_dual (clean: the words' mean chance of no error)"""
    rng = np.random.default_rng(seed)
    l = np.asarray(llr, dtype=float).reshape(-1)[offset:]
    m = len(l)//n
    L = l[:m*n].reshape(m, n)
    words = (L < 0).astype(np.uint8)
    logc = -np.log1p(np.exp(-np.minimum(np.abs(L), 50.0))).sum(axis=1) # log P(no error in the word)
    out = {"H": np.zeros((0, n), dtype=np.uint8), "k": n, "ok": False, "clean": float(np.exp(logc).mean())}
    if m < n:
        return out
    keep = np.zeros((0, n), dtype=np.uint8)
    stale = 0
    sizes = [size] if size else [n//4, n//2, (3*n)//4, n - 1]
    for _ in range(trials):
        before = len(keep)
        ok = np.ones(m, bool) if not len(keep) else ((words.astype(np.int32) @ keep.T.astype(np.int32)) % 2 == 0).all(axis=1)
        order = np.argsort(-(logc - 1e3*~ok), kind="stable") # the likeliest clean first, those failing a check found last
        for s in sizes:
            s = min(s, m)
            pool = order[:min(m, 3*s)]
            idx = rng.choice(pool, size=s, replace=False)
            N = nullspace(words[idx])
            if len(N) == 0:
                continue
            good = N[soft_score(N, L) > z_min]
            if len(good):
                keep = nullspace(nullspace(np.concatenate((keep, good)))) # the row space of what holds
        stale = stale + 1 if len(keep) == before else 0
        if len(keep) and stale >= 3:
            break
    out["H"], out["k"], out["ok"] = keep, n - len(keep), len(keep) > 0
    return out

soft_find_length

soft_find_length(llr, min_len=4, max_len=128, offset=0, trials=3, seed=0)

Codeword length from soft values: the shortest n (rows of n from offset) whose soft dual holds a check, or None. Slower than find_length (a soft_dual a length): for words too noisy for its rank. Alignment is taken as given (a cyclic code holds at any; a frame start or a known offset for others)

Source code in src/rpps/analysis/code/block/linear.py
def soft_find_length(llr, min_len=4, max_len=128, offset=0, trials=3, seed=0):
    """Codeword length from soft values: the shortest n (rows of n from `offset`) whose soft dual holds a check, or None.
    Slower than `find_length` (a `soft_dual` a length): for words too noisy for its rank. Alignment is taken as given
    (a cyclic code holds at any; a frame start or a known offset for others)"""
    l = np.asarray(llr, dtype=float).reshape(-1)
    for n in range(min_len, max_len + 1):
        if (len(l) - offset)//n < n + EXTRA:
            break
        r = soft_dual(l, n, offset, trials=trials, seed=seed)
        if r["ok"] and 0 < r["k"] < n:
            return n
    return None

recover_dual

recover_dual(bits, n, offset=0, trials=40, seed=0, z_min=8.0)

Recover parity checks of an unknown linear block code of length n from (noisy) hard bits

Words that are codewords satisfy every parity check h. For a random set of words, the null space of their matrix contains the checks that no error among them broke, and anything that is a check satisfies the other words too: so null vectors are verified against all words, and those that stand out from 50% are kept. Needs about n words and a word error rate that leaves some subsets of words clean.

Returns dict(H, k, words, needed, ok). H is a basis of the checks (dense, not sparse).

Source code in src/rpps/analysis/code/block/linear.py
def recover_dual(bits, n, offset=0, trials=40, seed=0, z_min=8.0):
    """Recover parity checks of an unknown linear block code of length n from (noisy) hard bits

    Words that are codewords satisfy every parity check h. For a random set of words, the null space of
    their matrix contains the checks that no error among them broke, and anything that is a check satisfies
    the other words too: so null vectors are verified against all words, and those that stand out
    from 50% are kept. Needs about n words and a word error rate that leaves some subsets of words clean.

    Returns dict(H, k, words, needed, ok). H is a basis of the checks (dense, not sparse).
    """
    rng = np.random.default_rng(seed)
    bits = np.asarray(bits, dtype=np.uint8)
    m = (len(bits) - offset)//n
    words = bits[offset:offset+m*n].reshape(m, n)
    out = {"H": np.zeros((0, n), dtype=np.uint8), "k": n, "words": m, "needed": 2*n, "ok": False}
    if m < n:
        return out
    keep = np.zeros((0, n), dtype=np.uint8)
    rank, stale = 0, 0
    for _ in range(trials):
        best_rank = rank
        for s in (n//4, n//2, (3*n)//4, n-1):
            idx = rng.choice(m, size=min(s, m), replace=False)
            N = nullspace(words[idx])
            if len(N) == 0:
                continue
            sat = 1.0 - ((words.astype(np.uint8) @ N.T.astype(np.uint8)) % 2).mean(axis=0)
            z = (sat - 0.5)*2*np.sqrt(m)
            good = N[z > z_min]
            if len(good):
                cat = np.concatenate((keep, good))
                B = nullspace(nullspace(cat)) # Row space of cat: its dual's dual
                keep = B
                rank = len(keep)
            best_rank = max(best_rank, rank)
        stale = stale + 1 if rank == best_rank and best_rank == out["H"].shape[0] else 0
        out["H"] = keep
        if stale >= 3:
            break
    out["H"] = keep
    out["k"] = n - len(keep)
    out["ok"] = len(keep) > 0
    out["needed"] = max(2*n, 2*out["k"] + 64)
    return out

polar

A polar code's frozen positions, blind: which of the u bits are always 0, and which construction froze them

r = rp.analysis.code.block.polar.frozen(llr)       # frames (W, N) of LLRs, N a power of 2, aligned: the column test
r = rp.analysis.code.block.polar.recognize(llr)    # at low SNR: successive cancellation, a test per position
r = rp.analysis.code.block.polar.search(llr)       # and the construction (polarization weight, Bhattacharyya) and K it is
r.frozen, r.k

The code itself (encoding, SC and list decoding) is rpps.code.types.polar. A polar codeword is x = u G with G = F^(x n), F = [[1, 0], [1, 1]]; G is its own inverse, so u = x G and u_i is the parity of the x bits in column i of G. The frozen positions of u are 0 in every frame; the information positions are 0 half the time.

frozen (the column test): each u_i's LLR is the tanh-product of its column's x LLRs (as a parity check's); averaged over frames it is high at frozen positions and near zero at information ones (the hypothesis test of arXiv 2606.17705). A heavy column sees many x errors, and the early positions a real code freezes have the heaviest (column 0 is the parity of all N bits): a (64, 32) frozen set is found at Es/N0 6 dB from 400 frames, but a rate-1/2 code built by polarization weight is not found at +2 dB.

recognize (blind successive cancellation): the SC decoder runs over every frame at once, and at each position, in decoding order, every frame's SC LLR of u_i given the u before it (frozen ones 0, information ones as decided) is a much stronger statistic than the bare column, because the positions before it are taken out. Per position the generalised likelihood ratio of "u_i = 0 always" against "u_i uniform", sum over frames of log2(2 / (1 + e^-L)), is W times the synthetic channel's capacity when frozen and at most 0 when not; a position is information only when it is significantly negative (a channel too poor to tell is frozen, as every construction does), and the partial order every construction keeps (i at least as reliable as each j whose bits are a subset of its own) carries an information verdict upward. (In the spirit of blind SC/SCL recognition, arXiv 2605.13331, without the list.)

search names the construction: each reliability order (polarization weight, the beta-expansion 3GPP NR's sequence follows; Bhattacharyya parameters at a few design SNRs) with the K whose least reliable N - K positions are nearest the blind set; within a few positions, the construction's set is returned (which corrects the blind test's errors).

Measured, rate 1/2 built by polarization weight, 200 frames: (128, 64), (256, 128), (512, 256) found exactly down to Es/N0 -2 dB by recognize; search exact at -3 dB and within a few positions at -4 dB; frozen fails at +2 dB.

Classes:

Name Description
Frozen

Result of frozen: frozen (positions), k (information bits), score (each position's mean tanh(L/2) of u_i: 1 for

Recognition

Result of recognize: frozen (positions), k, evidence (N,): each position's summed evidence (bits; > 0 frozen),

Functions:

Name Description
frozen

Frozen positions from frames (W, N) of LLRs (log P(0)/P(1)) of aligned polar codewords (see the module).

evidence

Per frame, log2 of how much likelier an SC LLR L is with u = 0 than with u uniform: log2(2 / (1 + e^-L)). Its sum

recognize

Frozen positions of aligned polar frames (W, N) of LLRs at low SNR: blind SC (see the module). Position by

search

Which construction (and K) the frozen set of frames (W, N) of LLRs is: recognize finds the set blind, then each

Frozen

Frozen(**kw)

Result of frozen: frozen (positions), k (information bits), score (each position's mean tanh(L/2) of u_i: 1 for a frozen position on clean frames, 0 for information), threshold

Source code in src/rpps/analysis/code/block/polar.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

Recognition

Recognition(**kw)

Result of recognize: frozen (positions), k, evidence (N,): each position's summed evidence (bits; > 0 frozen), construction (the reliability order it fits, with search), score

Source code in src/rpps/analysis/code/block/polar.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

frozen

frozen(llr, threshold=None)

Frozen positions from frames (W, N) of LLRs (log P(0)/P(1)) of aligned polar codewords (see the module). threshold: the score above which a position is frozen (default halfway between the information positions' (about 0) and the frozen ones', from the scores' two clusters)

Source code in src/rpps/analysis/code/block/polar.py
def frozen(llr, threshold=None):
    """Frozen positions from frames (W, N) of LLRs (log P(0)/P(1)) of aligned polar codewords (see the module).
    threshold: the score above which a position is frozen (default halfway between the information positions' (about 0)
    and the frozen ones', from the scores' two clusters)"""
    L = np.asarray(llr, dtype=np.float64)
    W, N = L.shape
    G = transform(N)
    t = np.tanh(np.clip(L, -30, 30)/2) # (W, N): E[(-1)^x] per bit
    # u_i = parity of x over column i: tanh(L_u/2) = prod over the column of tanh(L_x/2); in logs for the sign and size
    mag = np.log(np.maximum(np.abs(t), 1e-300)) @ G.astype(np.float64) # (W, N)
    neg = ((t < 0).astype(np.int64) @ G.astype(np.int64)) % 2
    score = np.mean(np.where(neg == 1, -1.0, 1.0)*np.exp(mag), axis=0)
    if threshold is None:
        s = np.sort(score)
        gaps = np.diff(s)
        i = int(np.argmax(gaps)) # the widest gap between the two clusters
        threshold = (s[i] + s[i + 1])/2
    fz = np.flatnonzero(score > threshold)
    return Frozen(frozen=fz, k=N - len(fz), score=score, threshold=float(threshold))

evidence

evidence(L)

Per frame, log2 of how much likelier an SC LLR L is with u = 0 than with u uniform: log2(2 / (1 + e^-L)). Its sum over frames is positive (W times the synthetic channel's capacity) at a frozen position, at most 0 at an information one: the generalised likelihood ratio of the two

Source code in src/rpps/analysis/code/block/polar.py
def evidence(L):
    """Per frame, log2 of how much likelier an SC LLR L is with u = 0 than with u uniform: log2(2 / (1 + e^-L)). Its sum
    over frames is positive (W times the synthetic channel's capacity) at a frozen position, at most 0 at an information
    one: the generalised likelihood ratio of the two"""
    L = np.asarray(L, dtype=np.float64)
    return 1.0 - np.logaddexp(0.0, -L)/np.log(2)

recognize

recognize(llr, z=3.0, monotone=True)

Frozen positions of aligned polar frames (W, N) of LLRs at low SNR: blind SC (see the module). Position by position in decoding order, every frame's SC LLR of u_i (given the u before it: frozen ones 0, information ones as decided) gives its evidence; the position is information when the evidence is significantly negative (its sum under -z of its spread), else frozen: a position too poor to tell either way is a channel any construction freezes. monotone: every polar construction keeps the partial order where i is at least as reliable as each j whose set bits are a subset of its own (j & i == j): so a position over an information one is information too

Source code in src/rpps/analysis/code/block/polar.py
def recognize(llr, z=3.0, monotone=True):
    """Frozen positions of aligned polar frames (W, N) of LLRs at low SNR: blind SC (see the module). Position by
    position in decoding order, every frame's SC LLR of u_i (given the u before it: frozen ones 0, information ones as
    decided) gives its `evidence`; the position is information when the evidence is significantly negative (its sum
    under -z of its spread), else frozen: a position too poor to tell either way is a channel any construction freezes.
    monotone: every polar construction keeps the partial order where i is at least as reliable as each j whose set
    bits are a subset of its own (j & i == j): so a position over an information one is information too"""
    L = np.asarray(llr, dtype=np.float64)
    W, N = L.shape
    ev = np.zeros(N)
    info = np.zeros(N, bool)

    def decide(i, Li):
        e = evidence(Li)
        ev[i] = float(e.sum())
        is_info = ev[i] < -z*np.sqrt(float(np.sum(e**2)) + 1e-12)
        if monotone and not is_info:
            js = np.flatnonzero(info[:i])
            if np.any((js & i) == js):
                is_info = True
        info[i] = is_info
        return (Li < 0).astype(np.uint8) if is_info else np.zeros(W, np.uint8)

    sc(L, decide)
    fz = np.flatnonzero(~info)
    return Recognition(frozen=fz, k=N - len(fz), evidence=ev, construction=None, score=float(ev[fz].sum()))

search

search(llr, orders=None, tolerance=0.04, **kw)

Which construction (and K) the frozen set of frames (W, N) of LLRs is: recognize finds the set blind, then each reliability order (default polarization weight, and Bhattacharyya at -2 / 0 / 2 / 4 dB) is matched by its K whose N - K least reliable positions differ from it in the fewest places. Within tolerance x N places, the construction's set is returned (the few positions a noisy blind test got wrong come right), named; else the blind set, unnamed. kw: recognize's. Returns Recognition (score: the places the construction differs from the blind set)

Source code in src/rpps/analysis/code/block/polar.py
def search(llr, orders=None, tolerance=0.04, **kw):
    """Which construction (and K) the frozen set of frames (W, N) of LLRs is: `recognize` finds the set blind, then each
    reliability order (default polarization weight, and Bhattacharyya at -2 / 0 / 2 / 4 dB) is matched by its K whose
    N - K least reliable positions differ from it in the fewest places. Within tolerance x N places, the construction's
    set is returned (the few positions a noisy blind test got wrong come right), named; else the blind set, unnamed.
    kw: recognize's. Returns Recognition (score: the places the construction differs from the blind set)"""
    L = np.asarray(llr, dtype=np.float64)
    W, N = L.shape
    blind = recognize(L, **kw)
    if orders is None:
        orders = {"polarization weight": pw_order(N)}
        for d in (-2, 0, 2, 4):
            orders[f"Bhattacharyya {d:+d} dB"] = bhattacharyya_order(N, d)
    fz = np.zeros(N, bool)
    fz[blind.frozen] = True
    best = None
    for name, order in orders.items():
        order = np.asarray(order)
        # freezing the first m of the order: differences = blind-frozen positions left out + others put in
        inc = np.where(fz[order], -1, 1) # each position added changes the count by this
        diff = int(fz.sum()) + np.concatenate(([0], np.cumsum(inc)))
        m = int(np.argmin(diff[1:N])) + 1
        if best is None or diff[m] < best[0]:
            best = (int(diff[m]), name, np.sort(order[:m]))
    d, name, frozen = best
    if d > tolerance*N:
        blind.score = float(d)
        return blind
    return Recognition(frozen=frozen, k=N - len(frozen), evidence=blind.evidence, construction=name, score=float(d))

rs

Blind Reed-Solomon identification: length, field, generator and alignment of an unknown RS code over GF(256)

An RS codeword c(x) = sum c_i x^(n-1-i) (first byte the highest power) is a multiple of its generator g(x) = prod (x - alpha^(prim*(fcr+i))), i < n-k, so c(beta) = 0 at those roots, whatever the shortening (a shortened word is a full one with leading zeros). The Galois-field Fourier transform of an aligned word, its values at all 255 nonzero beta = alpha^j, is zero at the roots in every word; elsewhere, and for any word that is not aligned, a value is zero 1/256 of the time. So the roots show up as the j where nearly every word is zero, and they give n-k, fcr and prim.

Every byte phase is evaluated at once, with a sliding window: E_(s+1)(beta) = betaE_s(beta) + b[s+n] + b[s]beta^n. This is done for all 16 primitive field polynomials, 8 bit offsets, both bit orders within a byte (MSB or LSB first) and both polarities (inverted bits add the constant 0xFF*sum beta^i to every value) together.

What is needed: the length n, from lengths (hints, the frame period of the bits, common lengths) or tried exhaustively; at least words + 2 codewords of bits with few errors. Symbol interleaving (depth I: codeword bytes every I-th byte) is undone by depths.

Functions:

Name Description
fit_generator

(fcr, prim) with roots = {prim*(fcr+i) mod 255, i < len(roots)}, prim 1 if it can be, or None

lengths_of

Lengths to try: the hints, then the byte frame periods of the bits, then COMMON

search

Find an RS code over GF(256) in hard bits. Returns (hypotheses best first, trials, Guess or None)

fit_generator

fit_generator(roots)

(fcr, prim) with roots = {prim*(fcr+i) mod 255, i < len(roots)}, prim 1 if it can be, or None

Source code in src/rpps/analysis/code/block/rs.py
def fit_generator(roots):
    """(fcr, prim) with roots = {prim*(fcr+i) mod 255, i < len(roots)}, prim 1 if it can be, or None"""
    r = len(roots)
    R = set(int(x) for x in roots)
    for prim in _units():
        inv = pow(prim, -1, 255)
        idx = sorted((e*inv) % 255 for e in R)
        for start in idx:
            if {(start + i) % 255 for i in range(r)} == set(idx):
                return start, prim
    return None

lengths_of

lengths_of(bits, hints=())

Lengths to try: the hints, then the byte frame periods of the bits, then COMMON

Source code in src/rpps/analysis/code/block/rs.py
def lengths_of(bits, hints=()):
    """Lengths to try: the hints, then the byte frame periods of the bits, then COMMON"""
    out = list(hints)
    for nb, _ in frame_length(np.asarray(bits)[:2**17]):
        if nb % 8 == 0:
            out.append(nb//8)
    return list(dict.fromkeys(n for n in out + list(COMMON) if 8 <= n <= 255))

search

search(bits, lengths=None, hints=(), words=8, depths=(1,), polys=PRIMITIVE, exhaustive=False)

Find an RS code over GF(256) in hard bits. Returns (hypotheses best first, trials, Guess or None)

lengths: codeword lengths in bytes to try (default: lengths_of); exhaustive: every length 16..255 (minutes) words: codewords per phase the roots are counted on (a root is zero in at least 3/4 of them) Each hypothesis: params n, k, poly, fcr, prim, roots, phase (byte where a codeword starts), bit_offset, lsb_first, depth, branch, polarity, words_ok (fraction of further words whose syndromes are all zero).

Source code in src/rpps/analysis/code/block/rs.py
def search(bits, lengths=None, hints=(), words=8, depths=(1,), polys=PRIMITIVE, exhaustive=False):
    """Find an RS code over GF(256) in hard bits. Returns (hypotheses best first, trials, Guess or None)

    lengths: codeword lengths in bytes to try (default: `lengths_of`); exhaustive: every length 16..255 (minutes)
    words: codewords per phase the roots are counted on (a root is zero in at least 3/4 of them)
    Each hypothesis: params n, k, poly, fcr, prim, roots, phase (byte where a codeword starts), bit_offset, lsb_first,
    depth, branch, polarity, words_ok (fraction of further words whose syndromes are all zero)."""
    lens = list(range(16, 256)) if exhaustive else (list(lengths) if lengths else lengths_of(bits, hints))
    labels, V = _variants(bits, depths)
    EXP, LOG = _tables(polys)
    hyps, trials, seen = [], 0, set()
    for n in lens:
        if V.shape[1] < n*(words + 2):
            continue
        z0, z1 = _count_zeros(V, n, EXP, LOG, words)
        need = max(3, math.ceil(0.75*words))
        trials += n*V.shape[0]*len(polys)*2
        for invert, z in ((False, z0), (True, z1)):
            hit = z >= need
            r = hit.sum(axis=3)
            cand = (r >= 2) & (r <= n//2)
            # A code fits at one codeword phase. One that fits at several is not one: words of one repeated value (idle,
            # a dead carrier) are zero at the n-th roots of unity wherever the window is
            cand &= cand.sum(axis=0, keepdims=True) <= 1
            for phase, v, p in zip(*np.nonzero(cand)):
                roots = np.nonzero(hit[phase, v, p])[0]
                gen = fit_generator(roots)
                if gen is None:
                    continue
                fcr, prim = gen
                k = n - len(roots)
                lab = labels[v]
                key = (n, k, polys[p], fcr, prim, lab["depth"], invert)
                if key in seen: # The same code at another bit offset / branch of the same bits
                    continue
                ok, W = _verify(V[v], n, k, polys[p], fcr, prim, int(phase), invert)
                if W == 0 or ok < 2:
                    continue
                seen.add(key)
                zz = float(deviance_z(ok, W, 256.0**-len(roots)))
                hyps.append(Hypothesis("rs-blind", f"RS({n},{k})", zz,
                    {"n": n, "k": k, "poly": polys[p], "fcr": int(fcr), "prim": int(prim), "roots": roots.tolist(),
                     "phase": int(phase), "polarity": int(invert), "words_ok": ok/W, **lab}))
    hyps.sort(key=lambda h: (-h.params["words_ok"], -h.z))
    guess = None
    if hyps:
        p = hyps[0].params
        guess = Guess("rs", {"base": "block", "type": "rs", "comment": f"found by rpps.analysis.code.block.rs.search: {hyps[0].name}",
                             "n": p["n"], "k": p["k"], "m": 8, "poly": p["poly"], "fcr": p["fcr"], "prim": p["prim"]},
                      {k: p[k] for k in ("phase", "bit_offset", "lsb_first", "depth", "polarity", "words_ok")})
    return hyps, trials, guess

rpps.analysis.code.conv

Convolutional family: the mother code (generators), puncture patterns on it, turbo constituents, TCM

Modules:

Name Description
mother

Mother codes of convolutional codes, blind: the constraint length and generators of a rate 1/n feed-forward code

puncture

Blind puncture patterns: a known rate 1/2 convolutional code (a "mother code") sent through a puncture pattern that no

rsc

Recursive systematic convolutional codes (turbo constituents) and a turbo code's interleaver, found blind

tcm

Trellis-coded modulation found blind: the parity check a trellis code puts on the constellation's labels

mother

Mother codes of convolutional codes, blind: the constraint length and generators of a rate 1/n feed-forward code (for generators g_a, g_b, (c_a * g_b) xor (c_b * g_a) = 0 on codewords), a configured code's fit, and the definition a found one is saved as (a child of the configured mother code with these generators, else the generators). Its punctured rates: rpps.analysis.code.conv.puncture

Functions:

Name Description
scan_conv

Rate 1/n convolutional code scan on one bit stream. Returns (hypotheses, number of trials)

soft_mismatch_batch

The soft re-encoding mismatch of each row of LLRs (W, L): decoded from the LLRs, re-encoded, the share of |LLR| on

scan_defined_conv

Try every convolutional definition in config/fec/conv on every bit mapping and puncture alignment

decode_conv

Run the config definition behind a conv-config hypothesis on a whole bit stream

guess_conv

Definition from a conv hypothesis (generators found by the parity relation, plain or with a scrambler)

scan_conv

scan_conv(bits, ks=range(3, 8), rates=(2, 3), periods=(), tag=None, llr=None)

Rate 1/n convolutional code scan on one bit stream. Returns (hypotheses, number of trials)

Every generator pair's parity relation (c_a * g_b) ^ (c_b * g_a) against chance. llr: the bits' LLRs (log P0/P1, as long as bits): each relation bit weighted by the product of tanh(|L|/2) over the bits it combines (_soft_z), so noisy bits count for less (the hard count weighs them all alike: soft reaches lower SNR)

Source code in src/rpps/analysis/code/conv/mother.py
def scan_conv(bits, ks=range(3, 8), rates=(2, 3), periods=(), tag=None, llr=None):
    """Rate 1/n convolutional code scan on one bit stream. Returns (hypotheses, number of trials)

    Every generator pair's parity relation (c_a * g_b) ^ (c_b * g_a) against chance. llr: the bits' LLRs (log P0/P1,
    as long as bits): each relation bit weighted by the product of tanh(|L|/2) over the bits it combines (`_soft_z`),
    so noisy bits count for less (the hard count weighs them all alike: soft reaches lower SNR)"""
    hyps, trials = [], 0
    bits = np.asarray(bits, dtype=np.uint8)
    rel = None
    if llr is not None:
        rel = np.log(np.clip(np.tanh(np.abs(np.asarray(llr, dtype=np.float64)[:len(bits)])/2), 1e-12, 1.0))
    for n in rates:
        offsets = range(n) if n == 2 else (0,)
        for off in offsets:
            b = bits[off:]
            m = len(b)//n
            streams = [b[i:m*n:n] for i in range(n)]
            rs = [rel[off:][i:m*n:n] for i in range(n)] if rel is not None else None
            for K in ks:
                polys = _polys(K)
                shared = _shared(polys)
                conv = [_convolve_all(c, polys, K) for c in streams]
                sums = [_sum_all(r, polys, K) for r in rs] if rs is not None else None
                Z = _pair_z(conv, sums)
                for a, bb in itertools.combinations(range(n), 2):
                    for ia, ga in enumerate(polys):
                        # relation (c_a * g_b) ^ (c_b * g_a) for every g_b at once (polys[ib] is g_b): conv[a][ib],
                        # conv[bb][ia]; its z for every pair from matrix products (`_pair_z`), the relation itself
                        # made only where it is looked at
                        z = np.where(shared[ia], 0.0, Z[(a, bb)][:, ia])
                        trials += len(polys)
                        j = int(np.argmax(np.abs(z)))
                        if abs(z[j]) > 3.0 or periods:
                            s = conv[a] ^ conv[bb][ia] if periods else None
                        if abs(z[j]) > 3.0:
                            params = {"n": n, "K": K, "offset": off, "streams": (a, bb),
                                      "g": {a: tuple(int(x) for x in ga), bb: tuple(int(x) for x in polys[j])},
                                      "stream": tag}
                            per = _period(conv[a][j] ^ conv[bb][ia]) if abs(z[j]) > 6 else None
                            if per is None:
                                hyps.append(Hypothesis("conv", f"rate 1/{n} K={K}", float(abs(z[j])), params))
                            else: # Holds only in places: some other linear code (block, LDPC) with short checks
                                params["period_pairs"] = per[0]
                                hyps.append(Hypothesis("linear-block", f"short checks, period {per[0]:.1f} pairs", float(abs(z[j])), params))
                        for T in periods:
                            zf = np.where(shared[ia], 0.0, _fold_z(s, T))
                            trials += len(polys)
                            j = int(np.argmax(zf))
                            if zf[j] > 3.0:
                                hyps.append(Hypothesis("conv+scrambler", f"rate 1/{n} K={K} T={T}", float(zf[j]),
                                    {"n": n, "K": K, "offset": off, "T": T, "streams": (a, bb),
                                     "g": {a: tuple(int(x) for x in ga), bb: tuple(int(x) for x in polys[j])},
                                     "stream": tag}))
    return hyps, trials

soft_mismatch_batch

soft_mismatch_batch(code, llr)

The soft re-encoding mismatch of each row of LLRs (W, L): decoded from the LLRs, re-encoded, the share of |LLR| on the bits the code disagrees with (a right code's disagreements fall on unreliable bits, a wrong one's anywhere), and the effective number of bits ((sum |L|)^2 / sum L^2) that share is over. Returns (shares (W,), n_eff (W,), bits)

Source code in src/rpps/analysis/code/conv/mother.py
def soft_mismatch_batch(code, llr):
    """The soft re-encoding mismatch of each row of LLRs (W, L): decoded from the LLRs, re-encoded, the share of |LLR| on
    the bits the code disagrees with (a right code's disagreements fall on unreliable bits, a wrong one's anywhere), and
    the effective number of bits ((sum |L|)^2 / sum L^2) that share is over. Returns (shares (W,), n_eff (W,), bits)"""
    llr = np.asarray(llr, dtype=np.float64)
    dec, enc = code.decoder, code.encoder
    u = dec.decode_batch(llr, soft=True) if hasattr(dec, "decode_batch") else np.array([dec.decode(r, True) for r in llr])
    e = enc.encode_batch(u) if hasattr(enc, "encode_batch") else np.array([enc.encode(np.asarray(x).astype(bool)) for x in u])
    n = min(e.shape[1], llr.shape[1])
    w = np.abs(llr[:, :n])
    off = e[:, :n].astype(bool) != (llr[:, :n] < 0)
    tot = np.maximum(w.sum(axis=1), 1e-300)
    return (w*off).sum(axis=1)/tot, tot**2/np.maximum((w*w).sum(axis=1), 1e-300), n

scan_defined_conv

scan_defined_conv(streams, names=None, steps=2500, skip=0.1, segments=(0.1, 0.45, 0.8), decisive=20.0, llrs=None, screen=5, cut=0.85)

Try every convolutional definition in config/fec/conv on every bit mapping and puncture alignment

A correct hypothesis lets the decoder reproduce the received bits (the channel error rate, well below what a wrong one gets). Each of segments (fractions into the stream) is tried on its own: a symbol the timing slipped moves the puncture phase, so a segment across it fits two phases half well, and the others still fit one. A hypothesis says which segment (its offset holds there). Once one fits overwhelmingly (z > decisive, a tenth of a wrong code's mismatch), only definitions of the same rate are tried further (an equivalent code, the generators in the other order, also fits and the pick needs to see it; a code of another rate cannot). llrs: {tag: LLRs} of the streams that have them: a hypothesis the hard re-encoding leaves short is also scored softly (soft_mismatch_batch, against what random signs on the same reliabilities give), which holds a few dB further down. Every hypothesis is screened on a screen-th of its bits first; one not under cut x its baseline there (hard or soft) is not decoded in full. Returns (hypotheses, trials).

Source code in src/rpps/analysis/code/conv/mother.py
def scan_defined_conv(streams, names=None, steps=2500, skip=0.1, segments=(0.1, 0.45, 0.8), decisive=20.0, llrs=None,
                      screen=5, cut=0.85):
    """Try every convolutional definition in config/fec/conv on every bit mapping and puncture alignment

    A correct hypothesis lets the decoder reproduce the received bits (the channel error rate, well below
    what a wrong one gets). Each of `segments` (fractions into the stream) is tried on its own: a symbol the timing slipped
    moves the puncture phase, so a segment across it fits two phases half well, and the others still fit one. A
    hypothesis says which segment (its offset holds there). Once one fits overwhelmingly (z > `decisive`, a tenth of a
    wrong code's mismatch), only definitions of the same rate are tried further (an equivalent code, the generators in
    the other order, also fits and the pick needs to see it; a code of another rate cannot). llrs: {tag: LLRs} of the
    streams that have them: a hypothesis the hard re-encoding leaves short is also scored softly (soft_mismatch_batch,
    against what random signs on the same reliabilities give), which holds a few dB further down. Every hypothesis is
    screened on a `screen`-th of its bits first; one not under `cut` x its baseline there (hard or soft) is not decoded
    in full. Returns (hypotheses, trials).
    """
    from .... import code as coding
    names = names or coding.names("conv")
    hyps, trials = [], 0
    decided, baselines = None, {} # The rate (bits in, bits out a puncture period) of an overwhelming fit
    for name in names:
        code = cached(f"conv/{name}")
        enc = code.encoder
        pat = enc.puncture if enc.puncture is not None else np.ones((enc.den, 1), dtype=bool)
        rate = (pat.shape[1], int(pat.sum()))
        if decided is not None and rate != decided:
            continue
        L = pat.shape[1]
        nb = int(pat.sum())
        per = max(steps//L, 1)
        # What a wrong hypothesis gets: measured once per code shape (puncture period, bits a period) and
        # shared, so equivalent codes (the generators the other way round, an output inverted) tie exactly and the pick
        # is the same whichever codes were tried before (a draw per code made the winner of a tie a matter of chance)
        shape = (L, nb)
        if shape not in baselines:
            rand = np.random.default_rng(L*1000 + nb).integers(0, 2, per*nb).astype(np.uint8)
            k0, n0 = mismatch(code, rand)
            baselines[shape] = max(k0/n0, 1e-4)
        base = baselines[shape]
        for tag, bits in streams.items():
            starts = sorted({int(len(bits)*f) for f in segments if int(len(bits)*f) + nb + per*nb <= len(bits)})
            if not starts and len(bits) >= int(len(bits)*skip) + nb + per*nb:
                starts = [int(len(bits)*skip)]
            jobs = [(si, start, off) for si, start in enumerate(starts) for off in range(nb)
                    if len(bits[start+off:start+off+per*nb]) == per*nb] # Every segment and alignment, decoded together
            if not jobs:
                continue
            trials += len(jobs)
            L_ = (llrs or {}).get(tag)
            if L_ is not None and len(L_) < len(bits):
                L_ = None
            bs = None
            if L_ is not None:
                key = (shape, "soft", tag)
                if key not in baselines: # Random signs on these reliabilities: what a wrong code's soft share is
                    _, st0, of0 = jobs[0]
                    r = np.abs(np.asarray(L_[st0+of0:st0+of0+per*nb], dtype=np.float64))[None]
                    r = r*np.where(np.random.default_rng(L*1000 + nb + 1).random(r.shape) < 0.5, -1.0, 1.0)
                    baselines[key] = max(float(soft_mismatch_batch(code, r)[0][0]), 1e-4)
                bs = baselines[key]
            # Screen every job on a fifth of its bits: a wrong one comes in near its baseline, a right one well under it
            # (hard, or soft when the hard decisions are too noisy); only those decoded in full
            ps = max(per//screen, 40)
            if ps < per:
                hs, n_s = mismatch_batch(code, np.array([np.asarray(bits[st+of:st+of+ps*nb], dtype=np.uint8) for _, st, of in jobs]))
                keep = hs/n_s < cut*base
                if L_ is not None:
                    ss, _, _ = soft_mismatch_batch(code, np.array([np.asarray(L_[st+of:st+of+ps*nb], dtype=np.float64)
                                                                   for _, st, of in jobs]))
                    keep |= ss < cut*bs
                jobs = [j for j, k in zip(jobs, keep) if k]
                if not jobs:
                    continue
            ks, n = mismatch_batch(code, np.array([np.asarray(bits[start+off:start+off+per*nb], dtype=np.uint8) for _, start, off in jobs]))
            soft = None
            if L_ is not None:
                rows = np.array([np.asarray(L_[start+off:start+off+per*nb], dtype=np.float64) for _, start, off in jobs])
                sh, ne, _ = soft_mismatch_batch(code, rows)
                soft = (sh, ne, bs)
            for j, ((si, start, off), k) in enumerate(zip(jobs, ks)):
                k = int(k)
                z = float(-deviance_z(k, n, base)) # Fewer mismatches than a wrong code gives
                ok = z > 3.0 and k/n < 0.5*base # And clearly fewer, not a marginal difference on a short code
                params = {"offset": (start + off) % nb, "mismatch": k/n, "baseline": base, "stream": tag, "segment": si}
                if not ok and soft is not None: # Soft: the share of |LLR| it disagrees on, against random signs'
                    sh, ne, bs = soft
                    zs = float(-deviance_z(sh[j]*ne[j], ne[j], bs))
                    if zs > 3.0 and sh[j] < 0.5*bs:
                        ok, z = True, zs
                        params.update({"soft_mismatch": float(sh[j]), "soft_baseline": bs})
                if ok:
                    hyps.append(Hypothesis("conv-config", name, z, params, ("conv", name))) # offset: from the stream's start
                    if z > decisive and k/n < 0.1*base:
                        decided = rate
    return hyps, trials

decode_conv

decode_conv(bits, hyp)

Run the config definition behind a conv-config hypothesis on a whole bit stream

Source code in src/rpps/analysis/code/conv/mother.py
def decode_conv(bits, hyp):
    """Run the config definition behind a conv-config hypothesis on a whole bit stream"""
    from .... import code as coding
    code = coding.load("/".join(hyp.coding))
    seg = np.asarray(bits[hyp.params["offset"]:], dtype=np.uint8)
    nb = puncture_period(code)
    seg = seg[:len(seg)//nb*nb]
    return code.decoder.decode(seg)

guess_conv

guess_conv(hyp)

Definition from a conv hypothesis (generators found by the parity relation, plain or with a scrambler)

Source code in src/rpps/analysis/code/conv/mother.py
def guess_conv(hyp):
    """Definition from a conv hypothesis (generators found by the parity relation, plain or with a scrambler)"""
    p = hyp.params
    gens = [list(p["g"][i]) for i in sorted(p["g"])]
    n = p["n"]
    if len(gens) < n: # Pair relations only name two of the generators
        return None
    from ....code.serial import mother
    m = mother(gens, p["K"])
    obj = {"base": "conv", "extends": m, "comment": f"found by rpps.analysis.identify: the mother code {m}"} if m else \
          {"base": "conv", "constraint": p["K"], "generator": gens}
    return Guess("conv", obj, {"z": hyp.z, "offset": p["offset"]})

puncture

Blind puncture patterns: a known rate 1/2 convolutional code (a "mother code") sent through a puncture pattern that no definition has

A pattern of period P keeps some of the 2P coded bits of P input bits. Rate P/(P+1) (2/3, 3/4, ... 7/8) keeps P+1: one input bit's two outputs and one output of each of the others, so there are P * 2^(P-1) patterns, and a pattern turned by a column is the same one started a column later, which the bit offset covers: 2^(P-1) to try per period, each at every offset. The right one lets the Viterbi decoder reproduce what was received (only channel errors differ); others don't.

Mother codes are those in config/fec/conv (both generator orders: which of the two outputs goes first is not known).

Functions:

Name Description
patterns

Rate P/(P+1) puncture patterns (2, P), one per turn (built once per P; read only)

mothers

Rate 1/2 mother codes in config: {(K, generators): name}, both output orders

mismatches

mismatch() of each (pattern, hard bits) in rows under the mother code (K, gen) with that pattern, decoded together:

search

Find a rate 1/2 mother code with a puncture pattern in hard bit streams ({tag: bits}). Returns (hypotheses, trials)

best

The hypothesis that stands out and fits at one offset only, with its Guess (a conv definition), or (None, None)

patterns cached

patterns(P)

Rate P/(P+1) puncture patterns (2, P), one per turn (built once per P; read only)

Source code in src/rpps/analysis/code/conv/puncture.py
@functools.lru_cache(maxsize=None)
def patterns(P):
    """Rate P/(P+1) puncture patterns (2, P), one per turn (built once per P; read only)"""
    seen, out = set(), []
    for both in range(P):
        for choice in itertools.product((0, 1), repeat=P - 1):
            pat = np.zeros((2, P), dtype=bool)
            pat[:, both] = True
            for col, which in zip([c for c in range(P) if c != both], choice):
                pat[which, col] = True
            key = min(tuple(map(tuple, np.roll(pat, s, axis=1))) for s in range(P))
            if key not in seen:
                seen.add(key)
                out.append(np.array(key, dtype=bool))
    return out

mothers

mothers()

Rate 1/2 mother codes in config: {(K, generators): name}, both output orders

Source code in src/rpps/analysis/code/conv/puncture.py
def mothers():
    """Rate 1/2 mother codes in config: {(K, generators): name}, both output orders"""
    from .... import code
    out = {}
    for name in code.names("conv", blind=True):
        e = code.load(f"conv/{name}").encoder
        if e.den != 2 or e.num != 1:
            continue
        g = np.asarray(e.generator, dtype=np.uint8)
        for gg in (g, g[::-1]):
            out.setdefault((int(e.con), tuple(map(tuple, gg))), name.split("/")[0] + ("" if gg is g else " (outputs swapped)"))
    return out

mismatches

mismatches(K, gen, rows)

mismatch() of each (pattern, hard bits) in rows under the mother code (K, gen) with that pattern, decoded together: every pattern of a mother decodes on the mother's trellis with erasures where it punctures (what a punctured decoder does), so the rows go through in one batch per length. Returns (differing bits, bits compared) per row

Source code in src/rpps/analysis/code/conv/puncture.py
def mismatches(K, gen, rows):
    """mismatch() of each (pattern, hard bits) in rows under the mother code (K, gen) with that pattern, decoded together:
    every pattern of a mother decodes on the mother's trellis with erasures where it punctures (what a punctured decoder
    does), so the rows go through in one batch per length. Returns (differing bits, bits compared) per row"""
    mother = _code(K, gen, None)
    k, n = np.zeros(len(rows), dtype=np.int64), np.zeros(len(rows), dtype=np.int64)
    groups = {} # {(length, period, bits a period): {pattern: [row]}}
    for i, (pat, h) in enumerate(rows):
        groups.setdefault((len(h), pat.shape[1], int(pat.sum())), {}).setdefault(pat.tobytes(), []).append(i)
    for (L, P, m), by_pat in groups.items():
        T = L//m*P # (input bits the whole periods carry)
        if T == 0:
            continue
        order = [i for idx in by_pat.values() for i in idx] # (the batch: each pattern's rows together)
        llr = np.zeros((len(order), T, 2))
        parts, a0 = [], 0
        for idx in by_pat.values():
            pat = rows[idx[0]][0]
            h = np.array([np.asarray(rows[i][1][:T//P*m], dtype=np.uint8) for i in idx])
            llr[a0:a0 + len(idx), _mask(pat, T)] = 1.0 - 2.0*h # (punctured bits stay erasures)
            parts.append((idx, pat, h, a0))
            a0 += len(idx)
        u = mother.decoder.decode_batch(llr.reshape(len(order), -1), soft=True)
        e = mother.encoder.encode_batch(u)
        e = e[:, :e.shape[1]//2*2].reshape(len(order), -1, 2)
        Te = e.shape[1]//P*P
        for idx, pat, h, a0 in parts: # Re-encoded, punctured as sent, compared
            sent = e[a0:a0 + len(idx), :Te][:, _mask(pat, Te)]
            nn = min(sent.shape[1], h.shape[1])
            k[idx] = np.count_nonzero(sent[:, :nn] != h[:, :nn].astype(bool), axis=1)
            n[idx] = nn
    return k, n

search

search(streams, periods=range(2, 8), steps=400, confirm=4, codes=None)

Find a rate 1/2 mother code with a puncture pattern in hard bit streams ({tag: bits}). Returns (hypotheses, trials)

Each (mother, pattern) is screened at every offset on steps input bits of each stream; what gets clearly fewer mismatches than on random bits is tried again on confirm times as many (at high rates a wrong pattern reproduces random bits fairly well too, so the short screen alone says little), and is a hypothesis if it still stands out. A mother's patterns, streams and offsets decode together (mismatches: a batch per length, not a call each), first the screens, then the confirmations of what passed.

Source code in src/rpps/analysis/code/conv/puncture.py
def search(streams, periods=range(2, 8), steps=400, confirm=4, codes=None):
    """Find a rate 1/2 mother code with a puncture pattern in hard bit streams ({tag: bits}). Returns (hypotheses, trials)

    Each (mother, pattern) is screened at every offset on `steps` input bits of each stream; what gets clearly fewer
    mismatches than on random bits is tried again on `confirm` times as many (at high rates a wrong pattern reproduces
    random bits fairly well too, so the short screen alone says little), and is a hypothesis if it still stands out.
    A mother's patterns, streams and offsets decode together (`mismatches`: a batch per length, not a call each), first
    the screens, then the confirmations of what passed."""
    codes = codes or mothers()
    hyps, trials = [], 0
    # Streams that are another's bits inverted (a half turn of QPSK): for a mother whose all-ones input encodes to all
    # ones (generators of odd weight) the inverse of a codeword is a codeword, so the twin repeats its partner's result
    twin, seen = {}, {}
    for tag, bits in streams.items():
        b = np.asarray(bits[:4096], dtype=np.uint8)
        inv = (b ^ 1).tobytes()
        if inv in seen:
            twin[tag] = seen[inv]
        seen.setdefault(b.tobytes(), tag)
    key = lambda pat, L: (pat.tobytes(), pat.shape, L)
    for (K, gen), mname in codes.items():
        gen_list = [[int(x) for x in r] for r in gen]
        odd = all(int(np.sum(g)) % 2 == 1 for g in gen) # All-ones in, all-ones out: an inverted codeword is one
        jobs = [] # (P, pattern, tag, start, offset), in the order the hypotheses come
        for P in periods:
            per = steps//P
            for pat in patterns(P):
                m = int(pat.sum())
                for tag, bits in streams.items():
                    if odd and tag in twin:
                        continue
                    start = len(bits)//10
                    offs = [off for off in range(m) if len(bits[start + off:start + off + per*m]) == per*m]
                    trials += len(offs)
                    jobs += [(P, pat, tag, start, off) for off in offs]
        if not jobs:
            continue
        seg = lambda j, n: np.asarray(streams[j[2]][j[3] + j[4]:j[3] + j[4] + n*int(j[1].sum())], dtype=np.uint8)
        ks, ns = mismatches(K, gen, [(j[1], seg(j, steps//j[0])) for j in jobs])
        base = _baselines(K, gen, list({key(j[1], (steps//j[0])*int(j[1].sum())): (j[1], (steps//j[0])*int(j[1].sum()))
                                        for j in jobs}.values()))
        passed = [j for j, k, n in zip(jobs, ks, ns) if k/n < 0.5*base[key(j[1], (steps//j[0])*int(j[1].sum()))]]
        # Confirmed on a longer stretch
        long = [(j, seg(j, confirm*steps//j[0])) for j in passed]
        long = [(j, s_) for j, s_ in long if len(s_) == (confirm*steps//j[0])*int(j[1].sum())]
        if not long:
            continue
        kc, nc = mismatches(K, gen, [(j[1], s_) for j, s_ in long])
        bc = _baselines(K, gen, list({key(j[1], len(s_)): (j[1], len(s_)) for j, s_ in long}.values()))
        for (j, s_), k, n in zip(long, kc, nc):
            P, pat, tag, start, off = j
            m = int(pat.sum())
            b = bc[key(pat, len(s_))]
            z = float(-deviance_z(int(k), int(n), b))
            if z > 3.0 and k/n < 0.3*b:
                hyps.append(Hypothesis("conv-punctured", f"K={K} {mname} rate {P}/{m} {pat.astype(int).tolist()}", z,
                    {"K": K, "generator": gen_list, "puncture": pat.astype(int).tolist(),
                     "offset": (start + off) % m, "mismatch": k/n, "baseline": b, "stream": tag},
                    ("conv-punctured", f"{mname}|{pat.astype(int).tolist()}")))
    return hyps, trials

best

best(hyps, trials)

The hypothesis that stands out and fits at one offset only, with its Guess (a conv definition), or (None, None)

Source code in src/rpps/analysis/code/conv/puncture.py
def best(hyps, trials):
    """The hypothesis that stands out and fits at one offset only, with its Guess (a conv definition), or (None, None)"""
    rep = Report(hyps, trials, None)
    v = pick(rep.hyps, rep.z_crit, lambda h: h.params["mismatch"]/h.params["baseline"],
              lambda b, h: h.params["mismatch"] < 0.5*(b.params["mismatch"] + b.params["baseline"]))
    if v is None:
        return None, None
    p = v.params
    from ....code.serial import mother
    m = mother(p["generator"], p["K"])
    head = {"base": "conv", "extends": m} if m else {"base": "conv"}
    body = {"puncture": p["puncture"]} if m else {"constraint": p["K"], "generator": p["generator"], "puncture": p["puncture"]}
    return v, Guess("conv", {**head, "comment": f"found by rpps.analysis.code.conv.puncture: {v.name}", **body},
                    {"z": v.z, "offset": p["offset"], "mismatch": p["mismatch"]})

rsc

Recursive systematic convolutional codes (turbo constituents) and a turbo code's interleaver, found blind

c = rp.analysis.code.conv.rsc.constituent(s, p)            # systematic and parity streams: (g_f, g_b), e.g. 3GPP 15 / 13 octal
perm = rp.analysis.code.conv.rsc.turbo_interleaver(S, P2, c.g_f, c.g_b)   # frames: the second encoder's input order

An RSC encoder makes its parity p from the information u = s as p(D) = u(D) g_f(D) / g_b(D): so p g_b + s g_f = 0, a parity check over the two streams, one label of 2 bits a step. The same Walsh-Hadamard count as rpps.analysis.code.conv.tcm scores every pair of polynomials up to the memory at once; the strongest is (g_f, g_b) (a feedforward code: g_b = 1).

A turbo code's second encoder takes the information in another order: its parity p2 has no check with s, which says that much. With the constituent known, u' = p2 g_b / g_f (an IIR division from the all-zero start of each frame) is the interleaved information, and over many frames every position of u' matches one position of s bit for bit: the permutation, one column search per position (Burel). An error in p2 spreads through the division, so that needs clean frames.

From noisy frames (soft values), turbo_interleaver_soft uses the constituent's check instead of its inverse: p2 g_b + u' g_f = 0 holds at every step t over p2[t - d] and u'[t - d] = s[perm[t - d]], d up to the memory, so with perm[t - 1] ... perm[t - m] found, each candidate j for perm[t] is scored over all frames at once by the check's soft value: sum over frames of tanh(L_s[j]/2) times the product of tanh(L/2) of the check's other bits (one matrix- vector product a position; positions taken are excluded). A wrong pick spoils the next m checks, so a repair pass then scores every position by all m + 1 checks it is in, with every other position as found, and reassigns them greedily from the most confident (a sequential search with error correction in the spirit of Tixier & Sendrier, without BCJR). The forward search keeps a small beam, so one wrong pick doesn't take every later one with it. The check's weight w = |g_f| + |g_b| bits sets the noise it takes: its soft value falls as (1 - 2 BER)^w, so the frames needed grow as (1 - 2 BER)^(-2w) log K (3GPP's w = 6: about 100 frames of 1000 bits at 4% bit errors).

Classes:

Name Description
Constituent

g_f (feedforward), g_b (feedback): ints, bit d the coefficient of D^d; memory; holds; z

Functions:

Name Description
octal

The octal a standard writes (D^0 the most significant bit, 3GPP's 13 = 1 + D^2 + D^3)

constituent

(g_f, g_b) of the code making parity p from s (aligned streams of equal length), or None

encode

Parity of an RSC encoder from the all-zero state: p = u g_f / g_b (g_b needs a D^0 term)

invert

The information an RSC encoder (from the all-zero state) made p from: u = p g_b / g_f (g_f needs a D^0 term)

turbo_interleaver

The permutation of a turbo code's second encoder: frames S (F, K) of systematic bits and P2 (F, K) of the second

turbo_interleaver_soft

The second encoder's permutation from noisy frames: Ls (F, K) LLRs (log P(0)/P(1)) of the systematic bits, Lp2

Constituent

Constituent(**kw)

g_f (feedforward), g_b (feedback): ints, bit d the coefficient of D^d; memory; holds; z

Source code in src/rpps/analysis/code/conv/rsc.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

octal

octal(p)

The octal a standard writes (D^0 the most significant bit, 3GPP's 13 = 1 + D^2 + D^3)

Source code in src/rpps/analysis/code/conv/rsc.py
def octal(p):
    """The octal a standard writes (D^0 the most significant bit, 3GPP's 13 = 1 + D^2 + D^3)"""
    n = p.bit_length()
    return format(int(format(p, f"0{n}b")[::-1], 2), "o")

constituent

constituent(s, p, max_memory=6, pfa=1e-06)

(g_f, g_b) of the code making parity p from s (aligned streams of equal length), or None

Source code in src/rpps/analysis/code/conv/rsc.py
def constituent(s, p, max_memory=6, pfa=1e-6):
    """(g_f, g_b) of the code making parity p from s (aligned streams of equal length), or None"""
    s = np.asarray(s, dtype=np.int64) & 1
    p = np.asarray(p, dtype=np.int64) & 1
    z = s | (p << 1)
    W = max_memory + 1
    counts, N = label_windows(z, 2, W)
    bias = fwht(counts)
    bias[0] = 0
    zs = np.abs(bias)/np.sqrt(N)
    if zs.max() < np.sqrt(2*np.log((1 << (2*W))/pfa)):
        return None
    # The smallest-memory check among the strongest (a multiple of the code's check holds as well)
    top = np.flatnonzero(zs >= 0.95*zs.max())
    best = None
    for v in top:
        v = int(v)
        g = [0, 0]
        for j in range(W):
            d = W - 1 - j # window_counts: bit (W-1-d) m + i is label bit i at delay d
            for i in range(2):
                if v >> (j*2 + i) & 1:
                    g[i] |= 1 << d
        low = min(((q & -q).bit_length() - 1 for q in g if q), default=0)
        g = [q >> low for q in g]
        mem = max(q.bit_length() for q in g) - 1
        if g[1] == 0 or not g[1] & 1:
            continue
        if best is None or mem < best[0]:
            best = (mem, g, float(zs[v]), float((N + bias[v])/(2*N)))
    if best is None:
        return None
    mem, (gf, gb), zv, holds = best
    return Constituent(g_f=gf, g_b=gb, memory=mem, holds=max(holds, 1 - holds), z=zv)

encode

encode(u, g_f, g_b)

Parity of an RSC encoder from the all-zero state: p = u g_f / g_b (g_b needs a D^0 term)

Source code in src/rpps/analysis/code/conv/rsc.py
def encode(u, g_f, g_b):
    """Parity of an RSC encoder from the all-zero state: p = u g_f / g_b (g_b needs a D^0 term)"""
    if not g_b & 1:
        raise ValueError("g_b has no D^0 term: not a recursive encoder")
    return _encoder(int(g_f), int(g_b)).encode(np.asarray(u, dtype=np.int64) & 1, terminate=False)[0]

invert

invert(p, g_f, g_b)

The information an RSC encoder (from the all-zero state) made p from: u = p g_b / g_f (g_f needs a D^0 term)

Source code in src/rpps/analysis/code/conv/rsc.py
def invert(p, g_f, g_b):
    """The information an RSC encoder (from the all-zero state) made p from: u = p g_b / g_f (g_f needs a D^0 term)"""
    if not g_f & 1:
        raise ValueError("g_f has no D^0 term: not invertible")
    return encode(p, g_b, g_f) # the same recursion, the roles of the polynomials swapped

turbo_interleaver

turbo_interleaver(S, P2, g_f, g_b, min_frames=None)

The permutation of a turbo code's second encoder: frames S (F, K) of systematic bits and P2 (F, K) of the second parity (each frame from the all-zero state). Returns perm (K,): the second encoder's input i is s[perm[i]], and the agreement of each match (1: every frame)

Source code in src/rpps/analysis/code/conv/rsc.py
def turbo_interleaver(S, P2, g_f, g_b, min_frames=None):
    """The permutation of a turbo code's second encoder: frames S (F, K) of systematic bits and P2 (F, K) of the second
    parity (each frame from the all-zero state). Returns perm (K,): the second encoder's input i is s[perm[i]], and the
    agreement of each match (1: every frame)"""
    S = np.asarray(S, dtype=np.int64) & 1
    P2 = np.asarray(P2, dtype=np.int64) & 1
    F, K = S.shape
    if F < (min_frames or int(np.ceil(np.log2(K))) + 8):
        raise ValueError(f"{F} frames cannot tell {K} positions apart: need about log2(K) + 8")
    U = np.array([invert(p, g_f, g_b) for p in P2]).astype(np.int64)
    # agreement of every (u' position, s position) pair over the frames, as +-1 correlations
    A = (1 - 2*U).T @ (1 - 2*S) # (K, K)
    perm = np.argmax(A, axis=1)
    agree = (A[np.arange(K), perm] + F)/(2*F)
    return perm, agree

turbo_interleaver_soft

turbo_interleaver_soft(Ls, Lp2, g_f, g_b, beam=4, expand=3, repair=2)

The second encoder's permutation from noisy frames: Ls (F, K) LLRs (log P(0)/P(1)) of the systematic bits, Lp2 (F, K) of the second parity (hard bits work as +-large values). g_f needs a D^0 term. beam: partial permutations kept, each extended by its expand best candidates a step; repair: passes of the repair. Returns (perm (K,): input i of the second encoder is s[perm[i]], confidence (K,): each position's best check sum over its second best's; near 1 is a guess)

Source code in src/rpps/analysis/code/conv/rsc.py
def turbo_interleaver_soft(Ls, Lp2, g_f, g_b, beam=4, expand=3, repair=2):
    """The second encoder's permutation from noisy frames: Ls (F, K) LLRs (log P(0)/P(1)) of the systematic bits, Lp2
    (F, K) of the second parity (hard bits work as +-large values). g_f needs a D^0 term. beam: partial permutations
    kept, each extended by its `expand` best candidates a step; repair: passes of the repair. Returns (perm (K,): input i
    of the second encoder is s[perm[i]], confidence (K,): each position's best check sum over its second best's;
    near 1 is a guess)"""
    Ts = np.tanh(np.clip(np.asarray(Ls, dtype=np.float64), -30, 30)/2)
    Tp = np.tanh(np.clip(np.asarray(Lp2, dtype=np.float64), -30, 30)/2)
    F, K = Ts.shape
    if not g_f & 1:
        raise ValueError("g_f has no D^0 term")
    fd, bd = _taps(g_f), _taps(g_b)

    def known(t, perm, skip=None):
        """(F,): the soft value of the check at step t without s[perm[skip]] (skip: the delay left out; None: all in)"""
        v = np.ones(F)
        for d in bd:
            if t - d >= 0:
                v *= Tp[:, t - d]
        for d in fd:
            if d == skip or t - d < 0:
                continue
            if perm[t - d] < 0:
                return None
            v *= Ts[:, perm[t - d]]
        return v

    # forward: a beam of partial permutations, each extended by its best candidates, ranked by their summed check
    # values over the spread a check has on random candidates (so a wrong pick that spoils later checks falls back)
    beams = [(0.0, np.full(K, -1, np.int64), np.zeros(K, bool))]
    for t in range(K):
        ext = []
        for total, pm, used in beams:
            v = known(t, pm, skip=0)
            sc = v @ Ts
            spread = np.sqrt(np.sum(v**2)) + 1e-12
            sc[used] = -np.inf
            for j in np.argpartition(-sc, min(expand, K - 1))[:expand]:
                if np.isfinite(sc[j]):
                    ext.append((total + sc[j]/spread, pm, used, int(j)))
        ext.sort(key=lambda e: -e[0])
        beams = []
        for total, pm, used, j in ext[:beam]:
            pm, used = pm.copy(), used.copy()
            pm[t], used[j] = j, True
            beams.append((total, pm, used))
    perm = beams[0][1]

    def scores(perm):
        """(K, K): position t, candidate j: the sum over the checks t + d (d in g_f) of the check without s[perm[t]]"""
        S = np.zeros((K, K))
        for t in range(K):
            for d in fd:
                if t + d < K:
                    v = known(t + d, perm, skip=d)
                    S[t] += v @ Ts
        return S

    for _ in range(repair):
        S = scores(perm)
        top2 = np.sort(S, axis=1)[:, -2:]
        conf = top2[:, 1] - top2[:, 0]
        new = np.full(K, -1, np.int64)
        taken = np.zeros(K, bool)
        for t in np.argsort(-conf):
            row = np.where(taken, -np.inf, S[t])
            j = int(np.argmax(row))
            new[t], taken[j] = j, True
        if np.array_equal(new, perm):
            break
        perm = new
    S = scores(perm)
    best = S[np.arange(K), perm]
    S2 = S.copy()
    S2[np.arange(K), perm] = -np.inf
    second = S2.max(axis=1)
    conf = best/np.maximum(np.abs(second), 1e-12)
    return perm, conf

tcm

Trellis-coded modulation found blind: the parity check a trellis code puts on the constellation's labels

found = rp.analysis.code.conv.tcm.search(symbols, 8)            # locked symbols (any phase), an 8-point PSK
print(found[0])                                       # e.g. "h = (11, 02, 04) octal, natural labels, rotation 3:
                                                      #  Ungerboeck 8 states, z 41.0"

A trellis code over an M-point constellation with m = log2 M label bits (z^0 the least significant) satisfies a parity check (Ungerboeck 1982): sum_i h^i(D) z^i(D) = 0 over GF(2), every symbol. Ungerboeck's systematic feedback codes are written by those h^i (octal); a pragmatic code (a rate-1/2 convolutional code on the low bits, the rest uncoded) has one too (its two generators, crossed); so has any other linear trellis code. Over a window of W = nu + 1 symbols a check is a W m-bit vector, and with hard decisions it holds more often than not: (1 - 2p)^weight of the time, p the label bit error rate. Counting the windows of the stream by value and taking the Walsh-Hadamard transform of the counts gives, for every one of the 2^(W m) vectors at once, how many windows it holds on minus how many it fails (the WHT-BM method of rate k/n convolutional code recovery). A check stands out against the sqrt(N) of chance.

The labels depend on what is not known: the carrier phase (M rotations, and conjugation for an inverted spectrum) and the labelling (natural, i.e. set partitioning, for Ungerboeck codes; Gray for pragmatic ones; or the constellation's own). Every combination is tried; the label permutation does the rotation, so decisions are made once.

Classes:

Name Description
Check

A parity check found, and how well it holds

Functions:

Name Description
decisions

Nearest of M PSK points at angles 2 pi k / M + offset (the offset taken from the M-th power): k, 0..M-1

labellings

{name: label of the point at angle index k}

label_windows

Counts of every W-symbol window of m-bit labels z, as an index whose bit (W-1-d) m + i is z^i at delay d

label_errors

Per label bit, the probability a hard decision gets it wrong at the noise of these symbols: {labelling: array(m)}

search

Parity checks of a trellis code on M-PSK symbols y (locked to within a rotation). max_nu: largest memory tried

definition

The trellis code of check h as an fsm definition (rpps.code.types.fsm): the systematic feedback encoder whose

encode

Labels of a systematic feedback trellis encoder for the check h (see definition): the upper m-1 label bits are

Check

Check(**kw)

A parity check found, and how well it holds

h (one polynomial per label bit, z^0 first, as ints whose bit d is the delay-d tap), nu (memory), labels ('natural', 'gray' or 'own'), rotation (points the decisions were turned by), conj, z (its bias over chance), holds (fraction of windows it holds on), match (the known code it is, or None), expected (how often a code's check of these taps would hold, given the label bit errors the symbols' noise makes), code (holds at least CODE of the way from chance to expected: a code; else the labels are only correlated, by ISI, oversampling or the wrong modulation)

Source code in src/rpps/analysis/code/conv/tcm.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

decisions

decisions(y, M)

Nearest of M PSK points at angles 2 pi k / M + offset (the offset taken from the M-th power): k, 0..M-1

Source code in src/rpps/analysis/code/conv/tcm.py
def decisions(y, M):
    """Nearest of M PSK points at angles 2 pi k / M + offset (the offset taken from the M-th power): k, 0..M-1"""
    y = np.asarray(y, dtype=np.complex128)
    off = np.angle(np.sum(y**M))/M if M > 1 else 0.0
    # Points at off + 2 pi k/M; for the usual offsets (0 or pi/M) this is the nearest point
    return np.round((np.angle(y) - off)/(2*np.pi/M)).astype(np.int64) % M

labellings

labellings(M, own=None)

{name: label of the point at angle index k}

Source code in src/rpps/analysis/code/conv/tcm.py
def labellings(M, own=None):
    """{name: label of the point at angle index k}"""
    k = np.arange(M)
    out = {"natural": k, "gray": k ^ (k >> 1)}
    if own is not None:
        out["own"] = np.asarray(own, dtype=np.int64)
    return out

label_windows

label_windows(z, m, W)

Counts of every W-symbol window of m-bit labels z, as an index whose bit (W-1-d) m + i is z^i at delay d

Source code in src/rpps/analysis/code/conv/tcm.py
def label_windows(z, m, W):
    """Counts of every W-symbol window of m-bit labels z, as an index whose bit (W-1-d) m + i is z^i at delay d"""
    z = np.asarray(z, dtype=np.int64)
    idx = np.zeros(len(z) - W + 1, dtype=np.int64)
    for j in range(W): # j = W-1-d: oldest symbol of the window at j = 0
        idx |= z[j:len(z) - W + 1 + j] << (j*m)
    return np.bincount(idx, minlength=1 << (W*m)), len(idx)

label_errors

label_errors(y, M, labs, k, seed=0)

Per label bit, the probability a hard decision gets it wrong at the noise of these symbols: {labelling: array(m)}

Source code in src/rpps/analysis/code/conv/tcm.py
def label_errors(y, M, labs, k, seed=0):
    """Per label bit, the probability a hard decision gets it wrong at the noise of these symbols: {labelling: array(m)}"""
    from ....sync import quality
    m = int(round(np.log2(M)))
    off = np.angle(np.sum(np.asarray(y, dtype=np.complex128)**M))/M if M > 1 else 0.0
    pts = np.exp(1j*(2*np.pi*np.arange(M)/M + off))
    sigma = quality.measure(y, pts).sigma
    rng = np.random.default_rng(seed)
    n = 20000
    t = rng.integers(0, M, n)
    z = pts[t] + sigma*(rng.standard_normal(n) + 1j*rng.standard_normal(n))
    d = np.round((np.angle(z) - off)/(2*np.pi/M)).astype(np.int64) % M
    out = {}
    for name, lab in labs.items():
        diff = lab[t] ^ lab[d]
        out[name] = np.array([np.mean(diff >> i & 1) for i in range(m)])
    return out

search

search(y, M, max_nu=5, own=None, conj=True, labelling=None, pfa=1e-06, top=4, correlations=False, soft=False, shortlist=32)

Parity checks of a trellis code on M-PSK symbols y (locked to within a rotation). max_nu: largest memory tried (windows of max_nu + 1 symbols: (max_nu + 1) log2 M bits, 2^that candidates). own: the constellation's labels by angle index, tried as well. Returns Checks, most significant first (empty: no code of that memory on these labels). A check that holds well short of what a code's would at this noise is a correlation of the labels (ISI, a wrong rate or modulation), not a code: left out unless correlations, and marked (Check.code False). soft: each variant's shortlist strongest hard candidates, significant or not, are scored by the product of their taps' label-bit tanh(LLR/2) (max-log at the measured noise): a few dB more than hard decisions

Source code in src/rpps/analysis/code/conv/tcm.py
def search(y, M, max_nu=5, own=None, conj=True, labelling=None, pfa=1e-6, top=4, correlations=False, soft=False,
           shortlist=32):
    """Parity checks of a trellis code on M-PSK symbols y (locked to within a rotation). max_nu: largest memory tried
    (windows of max_nu + 1 symbols: (max_nu + 1) log2 M bits, 2^that candidates). own: the constellation's labels by
    angle index, tried as well. Returns Checks, most significant first (empty: no code of that memory on these labels).
    A check that holds well short of what a code's would at this noise is a correlation of the labels (ISI, a wrong rate or
    modulation), not a code: left out unless `correlations`, and marked (Check.code False).
    soft: each variant's `shortlist` strongest hard candidates, significant or not, are scored by the product of their
    taps' label-bit tanh(LLR/2) (max-log at the measured noise): a few dB more than hard decisions"""
    m = int(round(np.log2(M)))
    W = max_nu + 1
    if W*m > 24:
        raise ValueError(f"{W*m}-bit windows: keep (max_nu + 1) log2 M within 24")
    k = decisions(y, M)
    labs = labellings(M, own)
    if labelling is not None:
        labs = {labelling: labs[labelling]}
    perr = label_errors(y, M, labs, k)
    variants = [(name, lab, r, c) for name, lab in labs.items() for r in range(M) for c in ((False, True) if conj else (False,))]
    tests = len(variants)*(1 << (W*m))
    zmin = np.sqrt(2*np.log(tests/pfa))
    found = []
    for name, lab, r, c in variants:
        kk = (-k if c else k) + r
        z = lab[kk % M]
        counts, N = label_windows(z, m, W)
        bias = fwht(counts)
        bias[0] = 0
        zs = bias/np.sqrt(N)
        if soft:
            T = _label_tanh(y, M, lab, r, c)
            for v in np.argsort(-np.abs(zs))[:shortlist]:
                zv = _soft_z(T, int(v), m, W)
                if zv >= zmin:
                    found.append((zv, int(v), name, r, c, float((N + bias[v])/(2*N)), N))
            continue
        best = np.argsort(-np.abs(zs))[:64]
        for v in best:
            if abs(zs[v]) < zmin:
                break
            found.append((abs(float(zs[v])), int(v), name, r, c, float((N + bias[v])/(2*N)), N))
    found.sort(key=lambda t: -t[0])
    out = []
    span = {} # per variant: vectors of the checks taken and their shifts
    for zv, v, name, r, c, holds, N in found:
        key = (name, r, c)
        have = span.setdefault(key, [])
        if have and rank_ints(have + [v]) == rank_ints(have):
            continue # A shift or sum of checks already taken
        h = _polys(v, m, W)
        nu = max(p.bit_length() for p in h) - 1
        hv = holds if holds >= 0.5 else 1 - holds
        exp = _expected(h, perr[name])
        out.append(Check(h=h, nu=nu, labels=name, rotation=r, conj=c, z=zv, holds=hv, match=_match(h, m), expected=exp,
                         code=(hv - 0.5) >= CODE*(exp - 0.5)))
        for s in range(W):
            u = _vector(h, m, W, s)
            if u is not None:
                have.append(u)
        if len(out) >= 4*top:
            break
    # Equivalent forms of one code turn up under several rotations / labellings with about the same z: put the one a
    # table names first, then the unconjugated, then the smallest rotation
    # (soft: a labelling's own LLRs score its equivalent forms a little differently: wider buckets)
    zb = lambda c: round(np.log(c.z)/(0.15 if soft else 0.05)) # 5% buckets
    out.sort(key=lambda c: (not c.code, -zb(c), c.match is None, c.conj, c.rotation))
    if not correlations:
        out = [c for c in out if c.code]
    return out[:top]

definition

definition(h, m, points=None)

The trellis code of check h as an fsm definition (rpps.code.types.fsm): the systematic feedback encoder whose upper m-1 label bits are the input (z^1 the first input bit) and z^0 is solved from sum_i h^i z^i = 0 (h[0] with taps at delay 0 and nu). The state is the delays the check reaches (z^0's last nu, each z^i's as far as its h^i does); the output word is the label (z^0 its last bit). points: the constellation in label order, to decode symbols

Source code in src/rpps/analysis/code/conv/tcm.py
def definition(h, m, points=None):
    """The trellis code of check h as an `fsm` definition (rpps.code.types.fsm): the systematic feedback encoder whose
    upper m-1 label bits are the input (z^1 the first input bit) and z^0 is solved from sum_i h^i z^i = 0 (h[0] with taps
    at delay 0 and nu). The state is the delays the check reaches (z^0's last nu, each z^i's as far as its h^i does);
    the output word is the label (z^0 its last bit). points: the constellation in label order, to decode symbols"""
    h = [int(p) for p in h]
    h0 = h[0]
    nu = max(p.bit_length() for p in h) - 1
    if nu < 1 or not (h0 & 1 and h0 >> nu & 1):
        raise ValueError("h0 needs taps at delay 0 and nu")
    k = m - 1
    depth = [nu] + [max(h[i].bit_length() - 1, 0) for i in range(1, m)] # delays kept of each label bit
    shift = np.concatenate(([0], np.cumsum(depth)[:-1]))
    def step(state, u):
        hist = [[(state >> (shift[i] + d)) & 1 for d in range(depth[i])] for i in range(m)] # hist[i][d-1]: z^i at t-d
        z = [0] + [(u >> (k - i)) & 1 for i in range(1, m)]
        acc = 0
        for d in range(1, nu + 1):
            if h0 >> d & 1:
                acc ^= hist[0][d - 1]
        for i in range(1, m):
            for d in range(0, depth[i] + 1):
                if h[i] >> d & 1:
                    acc ^= z[i] if d == 0 else hist[i][d - 1]
        z[0] = acc
        new = 0
        for i in range(m):
            for d in range(depth[i]):
                b = z[i] if d == 0 else hist[i][d - 1]
                new |= b << (shift[i] + d)
        return new, sum(z[i] << i for i in range(m))
    # The states reachable from 0, numbered as found
    index, order, nxt, out = {0: 0}, [0], [], []
    while len(nxt) < len(order):
        s = order[len(nxt)]
        row_n, row_o = [], []
        for u in range(1 << k):
            n2, w = step(s, u)
            if n2 not in index:
                index[n2] = len(order)
                order.append(n2)
            row_n.append(index[n2])
            row_o.append(w)
        nxt.append(row_n)
        out.append(row_o)
    obj = {"base": "block", "type": "fsm", "comment": f"trellis code of the check h = {[oct(p) for p in h]}, {m}-bit labels",
           "k": k, "n": m, "next": nxt, "output": out, "start": 0, "end": None}
    if points is not None:
        pts = np.asarray(points, dtype=np.complex128)
        obj["symbols"] = {"bits": m, "points": [[float(p.real), float(p.imag)] for p in pts]}
    return obj

encode

encode(bits, h, m)

Labels of a systematic feedback trellis encoder for the check h (see definition): the upper m-1 label bits are bits (rows of m-1, z^1 first), z^0 is solved from sum_i h^i z^i = 0

Source code in src/rpps/analysis/code/conv/tcm.py
def encode(bits, h, m):
    """Labels of a systematic feedback trellis encoder for the check h (see `definition`): the upper m-1 label bits are
    bits (rows of m-1, z^1 first), z^0 is solved from sum_i h^i z^i = 0"""
    from ....code import init
    code = init("tcm", definition(h, m)).encoder
    sent = np.asarray(code.encode(np.asarray(bits, dtype=np.uint8).reshape(-1)), dtype=np.int64).reshape(-1, m)
    return (sent * (1 << np.arange(m - 1, -1, -1))).sum(axis=1)

rpps.analysis.framing

How the stream is cut: frames, payloads, telemetry, the CRC frames carry, what each bit of a header is, frames behind a sync marker and the scrambled block code inside them (marked); and whether decoded bits are as random as a cipher's output

Modules:

Name Description
bits

Frame structure on bits, blind: sync markers, frame length by autocorrelation, HDLC flags and the markers of a

crc

Which CRC checks a set of frames, and where it sits: the generator, init and xorout, the bits it covers

fields

What each bit of a set of frames (or bursts) is: constant, a counter, an id, a length, a few values, or random

frames

Blind symbol framing: the period a symbol stream repeats with, the unique word that marks it, and the frames cut on it

marked

Frames behind a sync marker, the scrambler restarted at each, the block code inside (rpps.analysis.framing.marked)

payload

What decoded bits carry: known framings found at any bit offset, and a verdict on what is left

randomness

Is a bit stream as random as a cipher's output? NIST SP 800-22 tests, and byte-level entropy

telemetry

Residual-carrier PM telemetry (PCM/PSK/PM): the carrier, each subcarrier's data, its line code and its frames

bits

Frame structure on bits, blind: sync markers, frame length by autocorrelation, HDLC flags and the markers of a framed code

Functions:

Name Description
find_sync

Bit offset and byte phase at which markers repeat every period bytes. Returns (fraction, bit offset, phase)

frame_length

Candidate frame/block lengths from autocorrelation peaks (sync markers, repeated headers)

scan_hdlc

HDLC framing (config/frame): many flags, and frames whose FCS checks out

frame_markers

The values that start every period units at column (units after bit offset): a pattern for sync.Align

find_sync

find_sync(bits, markers=(71, 184), period=204)

Bit offset and byte phase at which markers repeat every period bytes. Returns (fraction, bit offset, phase)

Source code in src/rpps/analysis/framing/bits.py
def find_sync(bits, markers=(0x47, 0xB8), period=204):
    """Bit offset and byte phase at which `markers` repeat every `period` bytes. Returns (fraction, bit offset, phase)"""
    bits = np.asarray(bits, dtype=np.uint8)
    best = (0.0, 0, 0)
    for off in range(8):
        b = bits[off:]
        B = np.packbits(b[:len(b)//8*8])
        n = len(B)//period*period
        if n < 4*period:
            continue
        hit = np.isin(B[:n], markers).reshape(-1, period).mean(axis=0)
        p = int(np.argmax(hit))
        if hit[p] > best[0]:
            best = (float(hit[p]), off, p)
    return best

frame_length

frame_length(bits, min_n=16, top=5)

Candidate frame/block lengths from autocorrelation peaks (sync markers, repeated headers)

Only sees fixed patterns that repeat every n bits; a code with no marker has none. Needs >= ~8 frames. Returns [(n, z)] strongest first, after removing multiples of a stronger shorter peak.

Source code in src/rpps/analysis/framing/bits.py
def frame_length(bits, min_n=16, top=5):
    """Candidate frame/block lengths from autocorrelation peaks (sync markers, repeated headers)

    Only sees fixed patterns that repeat every n bits; a code with no marker has none. Needs >= ~8 frames.
    Returns [(n, z)] strongest first, after removing multiples of a stronger shorter peak.
    """
    x = 1.0 - 2.0*np.asarray(bits, dtype=np.float64)
    N = len(x)
    x -= x.mean()
    F = np.fft.rfft(x, 2*N)
    ac = np.fft.irfft(np.abs(F)**2)[:N//4]/N/x.var()
    lags = np.arange(len(ac))
    z = np.abs(ac)*np.sqrt(N - lags)
    z[:min_n] = 0
    crit = z_critical(len(z))
    cand = []
    for i in np.argsort(-z)[:200]:
        if z[i] < crit:
            break
        cand.append((int(i), float(z[i])))
    cand.sort(key=lambda c: c[0])
    out = []
    for n, zz in cand:
        if not any(n % m == 0 for m, _ in out):
            out.append((n, zz))
    out.sort(key=lambda c: -c[1])
    return out[:top]

scan_hdlc

scan_hdlc(streams, names=None, min_frames=3)

HDLC framing (config/frame): many flags, and frames whose FCS checks out

Looks at flag counts first (a 0x7E pattern shows up at random once per 256 bits), then deframes the streams that have far more than that. Returns (hypotheses, trials).

Source code in src/rpps/analysis/framing/bits.py
def scan_hdlc(streams, names=None, min_frames=3):
    """HDLC framing (config/frame): many flags, and frames whose FCS checks out

    Looks at flag counts first (a 0x7E pattern shows up at random once per 256 bits), then deframes the
    streams that have far more than that. Returns (hypotheses, trials).
    """
    from ... import link as encap
    names = names or encap.ls().get("frame", [])
    hyps, trials = [], 0
    for name in names:
        h = encap.load(f"frame/{name}").encoder
        if not isinstance(h, encap.hdlc): # (byte-stuffed framing: no bit flags to count)
            continue
        f = h.flag_bits
        for tag, bits in streams.items():
            for pol in (0, 1):
                b = np.asarray(bits, dtype=np.uint8) ^ pol
                work = b
                if h.nrzi:
                    work = np.concatenate(([0], (b[1:] == b[:-1]).astype(np.uint8)))
                nflag = len(bitops.find(work, f))
                trials += 1
                if nflag < 6:
                    continue
                frames, aborts = h.deframe(b[:200000])
                good = [p for p, ok in frames if ok]
                if len(good) >= min_frames:
                    z = float(deviance_z(len(good), max(len(frames), 1), 2.0**-(8*h.fcs.width//8)))
                    hyps.append(Hypothesis("hdlc", name, z, {"frames": len(good), "bad": len(frames)-len(good), "polarity": pol,
                        "stream": tag}, ("frame", name)))
    return hyps, trials

frame_markers

frame_markers(bits, period, offset, column, unit=8, threshold=0.9, lengths=(1, 2, 4, 8, 16))

The values that start every period units at column (units after bit offset): a pattern for sync.Align

The shortest repeating pattern each of whose positions holds one value at least threshold of the time (DVB-S: 0xB8 then 0x47 seven times), over the later half of the periods. Returns (pattern, worst fraction), or (None, 0.0).

Source code in src/rpps/analysis/framing/bits.py
def frame_markers(bits, period, offset, column, unit=8, threshold=0.9, lengths=(1, 2, 4, 8, 16)):
    """The values that start every `period` units at `column` (units after bit `offset`): a pattern for `sync.Align`

    The shortest repeating pattern each of whose positions holds one value at least `threshold` of the time (DVB-S:
    0xB8 then 0x47 seven times), over the later half of the periods. Returns (pattern, worst fraction), or (None, 0.0)."""
    b = np.asarray(bits, dtype=np.uint8)[offset:]
    span = period*unit
    P = len(b)//span
    if P < 8:
        return None, 0.0
    vals = b[:P*span].reshape(P, period, unit)[:, column].astype(np.int64) @ (1 << np.arange(unit-1, -1, -1))
    if P >= 32: # The later half (the start of a window is where the sync before it was settling), but enough periods
        vals = vals[max(0, min(P//2, P - 3*max(lengths))):] # left for the longest pattern (a low code rate brings fewer)
    P = len(vals)
    for L in lengths:
        if P < 3*L: # At least three periods at every position of the pattern
            break
        pat, frac = [], 1.0
        for r in range(L):
            cnt = np.bincount(vals[r::L], minlength=1 << unit)
            pat.append(int(np.argmax(cnt)))
            frac = min(frac, cnt.max()/len(vals[r::L]))
        if frac >= threshold:
            return pat, float(frac)
    return None, 0.0

crc

Which CRC checks a set of frames, and where it sits: the generator, init and xorout, the bits it covers

fit = rp.analysis.framing.crc.search(frames)     # frames: bit arrays as sent (bool), any lengths
print(fit)        # "CRC-16 poly 0x1021 init 0xffff xorout 0x0 (crc16_ccitt_false) over bits 0..95, field at 96..111, ..."
fit.check(frame)  # True when a frame passes
fit.guess.save("mine")   # config/crc/guess/mine.json when no shipped definition matched

The method (RevEng's, on bit streams). On bits fed in the order sent, a CRC's register is linear in the message: r(m) = I x^n + m(x) x^w mod P, and the field sent is r XOR a constant, most significant bit first (a reflected CRC sent least significant bit first reads the same way, with xorout reflected; refin only says how bytes become that stream). So for two frames of one length, the XOR of their bits up to the field's end is a polynomial P divides, whatever init and xorout are:

  1. Generator and field end: the GCD of a few such differences, the frame cut at each candidate end from the last bit back (powers of x stripped). A degree in widths is a candidate; the end moves back over constant columns (fill after the field). When bits before the coverage differ between frames (an uncovered header: an address, a counter), the differences are first combined to cancel them (row reduction on the leading columns), which needs more frames than that header has varying bits.
  2. Coverage start: K = field XOR r0 (r0 the register from zero over the covered bits) is the same for every frame of a length (K = I x^n mod P XOR xorout) at the right start only. Every start is scored at once (suffix XORs of x^j mod P); the start passing the most frames wins, a start where init and xorout come out plain (0 or all ones, or a shipped definition) breaking ties across constant leading bits, which any init absorbs.
  3. Init and xorout: two message lengths separate them (K_n1 XOR K_n2 = I (x^n1 + x^n2) mod P), all but the inits P's common factors with x^n1 + x^n2 hide (any generator with x + 1); with one length only their combination is known. Then (ambiguous) a shipped definition (config/crc) or plain values (0, all ones) pick one.
  4. Evidence: frames not used to find the generator that pass, against 2^-w each by chance.

Limits: frames must be error free (decoded, or a CRC would not be there to find); several frames are tried in turn (trials), so some bad frames are tolerated. A per-frame value XORed onto the field (LTE's RNTI mask) looks like a varying xorout and is not found. Needs four frames of one length and a few more to confirm.

Classes:

Name Description
CRCFit

What search found: a CRC's parameters and where it sits

Functions:

Name Description
search

The CRC the frames (bit arrays as sent; bytes are unpacked MSB first) carry, as a CRCFit, or None. Frames of the

CRCFit

CRCFit(**kw)

What search found: a CRC's parameters and where it sits

width, poly (without the x^w term), init, xorout (in the definition's convention: reflected when refout), refin, refout, start (first covered bit), end (bit after the field, frame length minus tail), tail, names (the config/crc definitions that match: bit streams cannot tell those differing in refin / refout only apart), name (the first of them, else None), ambiguous (init and xorout not separated: one frame length, or a generator sharing a factor with x^n1 + x^n2, as any with x + 1 does), hits / frames (frames that pass), used (frames that found the generator), log10_chance, guess

Methods:

Name Description
end

The bit after the CRC field in a frame of length bits

check

True when the frame (bits as sent) carries this CRC at this place

Attributes:

Name Type Description
guess

A Guess to save as config/crc/guess/.json

Source code in src/rpps/analysis/framing/crc.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))
guess property
guess

A Guess to save as config/crc/guess/.json

end
end(length)

The bit after the CRC field in a frame of length bits

Source code in src/rpps/analysis/framing/crc.py
def end(self, length):
    """The bit after the CRC field in a frame of `length` bits"""
    return length - self.tail
check
check(frame)

True when the frame (bits as sent) carries this CRC at this place

Source code in src/rpps/analysis/framing/crc.py
def check(self, frame):
    """True when the frame (bits as sent) carries this CRC at this place"""
    b = np.asarray(frame).astype(bool).reshape(-1)
    E = len(b) - self.tail
    if E - self.width < self.start:
        return False
    P = (1 << self.width) | self.poly
    xp = _xpow(P, self.width, E)
    r0 = int(np.bitwise_xor.reduce(np.where(b[self.start:E - self.width], xp[E - 1 - np.arange(self.start, E - self.width)], 0)))
    n = E - self.width - self.start
    return _value(b[E - self.width:E]) == r0 ^ gf2.pmod(self.init << n, P) ^ self._xstar()

search

search(frames, widths=range(3, 65), trials=8, false_alarm=0.001, seed=0)

The CRC the frames (bit arrays as sent; bytes are unpacked MSB first) carry, as a CRCFit, or None. Frames of the most common length find the generator; every frame is checked against it. widths: CRC sizes to accept

Source code in src/rpps/analysis/framing/crc.py
def search(frames, widths=range(3, 65), trials=8, false_alarm=1e-3, seed=0):
    """The CRC the frames (bit arrays as sent; bytes are unpacked MSB first) carry, as a CRCFit, or None. Frames of the
    most common length find the generator; every frame is checked against it. widths: CRC sizes to accept"""
    F = _frames(frames)
    widths = set(int(w) for w in widths if 1 <= int(w) <= 64)
    lengths, counts = np.unique([len(f) for f in F], return_counts=True)
    rng = np.random.default_rng(seed)
    best, tried = None, set()

    def consider(g, e, B, L, used):
        nonlocal best
        for P in _reductions(g, widths):
            if (P, e) in tried:
                continue
            tried.add((P, e))
            f = _verify(F, B, P, L, e, used)
            if f is not None and (best is None or (f.hits, f.width) > (best.hits, best.width)): # a divisor of P passes wherever P does
                best = f
        return best is not None and best.hits == best.frames

    for L in lengths[np.argsort(-counts)]:
        L = int(L)
        B = np.array([f for f in F if len(f) == L])
        B = B[np.sort(np.unique(B, axis=0, return_index=True)[1])] # repeated frames say nothing new
        if len(B) < 3:
            continue
        done = False
        for t in range(trials):
            pick = rng.choice(len(B), size=min(6, len(B)), replace=False) if t else np.arange(min(6, len(B)))
            for g, e in _gcd_ends(B[pick[1:]] ^ B[pick[0]], widths, min(widths) + 1):
                if consider(g, e, B, L, len(pick)):
                    done = True
                    break
            if done or (best is not None and t >= 2):
                break
        if (best is None or best.hits < best.frames) and len(B) >= 8: # an uncovered header that varies: cancel it first
            for e in range(L, min(widths), -1):
                D = _cancel_leading(B[1:] ^ B[0], e)
                if D is not None and consider(_strip_x(gf2.pgcd(*[_poly(r) for r in D])), e, B, L, len(D) + 1):
                    break
        if best is not None:
            break
    if best is None or best.log10_chance > np.log10(false_alarm) - np.log10(max(len(tried), 1)):
        return None
    return best

fields

What each bit of a set of frames (or bursts) is: constant, a counter, an id, a length, a few values, or random

m = rp.analysis.framing.fields.map(frames, groups=terminal)   # frames: bit rows as sent, aligned at their start
print(m)          # one line a field: "bits 0..15 constant 0x1acf", "bits 32..43 counter +1 a frame (msb)", ...
m.guess.save("mine")   # config/header/link/guess/mine.json: the fields, named by kind and place

Frames are read up to the shortest (or length). Each field is a run of columns, found in this order, each test against what chance gives over that many frames:

  • constant: a column one value in hold of the frames (a bit error or two allowed); runs of them, with their value
  • id: with groups, a run constant within every group and differing between groups (columns constant everywhere inside it included; found before counters: within a group an id and the counter after it step together). A counter's top bits that never change within a group over the record read as id too: only a carry through them tells them apart
  • counter: a value stepping by the same amount (mod 2^width) from frame to frame, in either bit order. Its lowest bit that changes flips every frame (step odd times 2^k); the field is grown from it both ways while the step holds in hold of the frames and each new bit changes at all (the counter's top bits never reached in the record read as constant). With groups (a terminal per frame, e.g. from rpps.analysis.burst), steps within each group: frames in record order, each group its own count
  • length: with lengths (each frame's own, in bits or symbols), a run whose value is a*length + b for one a, b
  • enum: a run taking at most max_values values over the frames (a type, a flag set), grown while it stays few: at most half the values its width holds, and well under the distinct values random bits show over as many frames
  • random: the rest, each run's bias (mean of its bits) given; "varying" for a lone column between fields

Classes:

Name Description
Field

start (bit), width, kind (constant, counter, id, length, enum, random, varying), detail (dict: value, step,

FieldMap

map: fields (covering bits 0 .. length - 1 in order), length, frames

Functions:

Name Description
map

FieldMap of the frames (bit rows, aligned at their first bit). groups: a label a frame (a terminal), for counters

Field

Field(start, width, kind, **detail)

start (bit), width, kind (constant, counter, id, length, enum, random, varying), detail (dict: value, step, order, values {value: count}, scale, offset, bias)

Source code in src/rpps/analysis/framing/fields.py
def __init__(self, start, width, kind, **detail):
    self.start, self.width, self.kind, self.detail = int(start), int(width), kind, detail

FieldMap

FieldMap(fields, length, frames)

map: fields (covering bits 0 .. length - 1 in order), length, frames

Attributes:

Name Type Description
guess

The fields as a link header definition (config/header/link/guess/.json when saved): each named by its

Source code in src/rpps/analysis/framing/fields.py
def __init__(self, fields, length, frames):
    self.fields, self.length, self.frames = fields, length, frames
guess property
guess

The fields as a link header definition (config/header/link/guess/.json when saved): each named by its kind and first bit, an enum's values listed, the rest of the frame after them

map

map(frames, groups=None, lengths=None, length=None, hold=0.95, max_width=32, max_values=8)

FieldMap of the frames (bit rows, aligned at their first bit). groups: a label a frame (a terminal), for counters within each and ids; lengths: each frame's length, for length fields; length: bits to map (default: the shortest frame's)

Source code in src/rpps/analysis/framing/fields.py
def map(frames, groups=None, lengths=None, length=None, hold=0.95, max_width=32, max_values=8):
    """FieldMap of the frames (bit rows, aligned at their first bit). groups: a label a frame (a terminal), for counters
    within each and ids; lengths: each frame's length, for length fields; length: bits to map (default: the shortest
    frame's)"""
    rows = [np.asarray(f).astype(bool).reshape(-1) for f in frames]
    L = min(len(r) for r in rows) if length is None else int(length)
    rows = [r for r in rows if len(r) >= L]
    F = np.array([r[:L] for r in rows], dtype=np.uint8)
    N = len(F)
    if N < 4:
        raise ValueError(f"{N} frames: need 4 at least to tell fields from chance")
    groups = None if groups is None else np.asarray(groups)
    p1 = F.mean(axis=0)
    const = (p1 >= hold) | (p1 <= 1 - hold)
    fields, taken = [], const.copy()
    # ids: constant within every group of 2 frames or more, not across them
    if groups is not None:
        within = np.ones(L, bool)
        G = [F[groups == g] for g in np.unique(groups)]
        many = [g for g in G if len(g) >= 2]
        for g in many:
            q = g.mean(axis=0)
            within &= (q >= hold) | (q <= 1 - hold)
        if len(many) >= 2: # runs constant within the groups, through columns constant everywhere, ends that vary
            for a, b in zip(*runs(within)):
                vary = np.flatnonzero(~const[a:b])
                if len(vary) == 0:
                    continue
                a, b = a + int(vary[0]), a + int(vary[-1]) + 1
                vals = {int(v) for v in _value(F[:, a:b])}
                fields.append(Field(a, b - a, "id", ids=len(vals), groups=len(G)))
                taken[a:b] = True
    counters, used = _counters(F, taken, groups, hold, max_width)
    fields += counters
    taken |= used
    # length fields
    if lengths is not None:
        ln = np.asarray([l for l, r in zip(lengths, frames) if len(np.asarray(r).reshape(-1)) >= L], dtype=np.float64)
        if len(np.unique(ln)) >= 3:
            for a, b in zip(*runs(~taken)):
                best = None
                for w in range(2, min(16, b - a) + 1):
                    for o in range(a, b - w + 1):
                        v = _value(F[:, o:o + w]).astype(np.float64)
                        if len(np.unique(v)) < 3:
                            continue
                        A = np.vstack((ln, np.ones_like(ln))).T
                        (k, c), *_ = np.linalg.lstsq(A, v, rcond=None)
                        if k != 0 and np.mean(np.abs(A @ (k, c) - v) < 0.5) >= hold and (best is None or w > best[1]):
                            best = (o, w, k, c)
                if best is not None:
                    o, w, k, c = best
                    fields.append(Field(o, w, "length", scale=float(np.round(k, 6)), offset=float(np.round(c, 3))))
                    taken[o:o + w] = True
    # enums: runs of few values, grown while they stay few
    for a, b in zip(*runs(~taken)):
        o = a
        while o < b:
            e = o + 1
            while e < b and len(np.unique(_value(F[:, o:e + 1]))) <= max_values and e + 1 - o <= 16:
                e += 1
            vals, cnt = np.unique(_value(F[:, o:e]), return_counts=True)
            M = 2**(e - o)
            chance = M*(1 - (1 - 1/M)**N) # distinct values random bits show over N frames
            if e - o >= 2 and len(vals) <= min(max_values, M//2) and chance >= 1.5*len(vals) + 2:
                fields.append(Field(o, e - o, "enum", values={int(v): int(c) for v, c in zip(vals, cnt)}))
                taken[o:e] = True
            o = e
    # constants, random and what is left
    for a, b in zip(*runs(const & ~used & ~_inside(fields, L))):
        fields.append(Field(a, b - a, "constant", value=int(_value((p1[None, a:b] > 0.5).astype(np.uint8))[0])))
    for a, b in zip(*runs(~taken)):
        if b - a == 1:
            fields.append(Field(a, 1, "varying"))
        else:
            fields.append(Field(a, b - a, "random", bias=float(F[:, a:b].mean())))
    return FieldMap(sorted(fields, key=lambda f: f.start), L, N)

frames

Blind symbol framing: the period a symbol stream repeats with, the unique word that marks it, and the frames cut on it

fr = rp.analysis.framing.frames.find(symbols, "qpsk")    # Frame(period, uw_start, uw_length, coherence, ...) or None
frames = rp.analysis.framing.frames.cut(symbols, fr)     # frames x period, each turned so its unique word matches the first
bits = rp.analysis.framing.frames.payload_bits(frames, fr, "qpsk")   # frames x payload bits, for rpps.analysis.code.block.linear / fec.solve

A modem that frames its symbols (a unique word ahead of each block of coded data: TPC and LDPC SCPC modems, TDM framing, a TDMA burst's preamble) sends the same few symbols every P symbols. The product y[n] conj(y[n+P]) is then coherent at those positions and random elsewhere: averaged over many frames, it stands out where the unique word is, and P is the lag whose average stands out most (find). The carrier phase may differ frame to frame by a multiple of 360/M degrees (the M-fold ambiguity of a feed-forward carrier, or a slip), which the unique word itself resolves (cut).

Coded data under the unique word is random-looking; data that repeats (idle frames, fill) makes whole frames equal, and repeats finds the period of that (a superframe, or how often a frame is sent again).

Classes:

Name Description
Frame

find: period (symbols), uw_start (position in the period), uw_length (symbols), coherence (of the unique word,

Hit

find_word: at (sample of the word's first symbol), score (0..1, 1 = the word alone, noiseless), baud, sps

Burst

bursts: start, stop (samples), det (rpps.sync.Detection of this burst alone, None if too short), symbols

Functions:

Name Description
comb_lags

[(lag, z)] the lags in [min_lag, max_lag] a frame structure may repeat at, most significant first

periods

[(lag, z)] the lags locked symbols may repeat at with a frame, most significant first (comb_lags over their

coherence

Per position in the period: |mean over frames of y[n] conj(y[n+period])| over their rms, 1 where every frame has the

find

The frame structure of locked symbols y: a Frame, or None (no lag with a unique word standing out)

grid_of

The turns a constellation is symmetric under. The largest M of 2, 4, 8, 16 that turns its points onto

cut

Frames x period symbols starting at the unique word, each turned onto the others by its unique word

payload_bits

Frames x bits of the symbols after each unique word, hard-decided on constellation (a name or a Constellation)

repeats

(period, fraction of frames equal to the one period before): the smallest such period, or (None, 0.0). Frames

word_waveform

The symbols word shaped by an RRC pulse at a fractional sps samples per symbol

find_word

Where a known symbol word (a preamble, a burst's unique word) is in baseband samples x at Fs: [Hit] best first

split

Where touching bursts meet in x[a:b]: [(start, stop)]

occupied

The bandwidth holding share of the power above the noise floor (Hz): about the symbol rate of a shaped signal

gate

[(start, stop)] where the power is on: above the geometric mean of its low and high levels (contrast apart at

centroid

The power-weighted mean frequency (Hz) of the spectrum's bins above twice its 10th-percentile floor: a coarse

tone_pair

The middle (Hz) of the strongest pair of spectral lines sep apart (to tol of it) in the samples x, or None:

bursts

The bursts of x (gate), each acquired on its own: rate (or baud for all), modulation, offset, timing (as a

preamble

What the bursts' first symbols share: (length, differential symbols d[n] = s[n] conj(s[n-1]) of it, where it starts

coarse_cfo

Carrier offset [Hz] from the line of x^M (the modulation's M-fold symmetry taken off)

pilot_frames

Frames of symbols synchronized on their unique word as pilots: (frames x period symbols from each word on, the words'

Frame

Frame(**kw)

find: period (symbols), uw_start (position in the period), uw_length (symbols), coherence (of the unique word, 1 = the same symbols every frame), floor (of the other positions), uw (the unique word's symbols, from the first frame), frames (how many the estimate is over)

Source code in src/rpps/analysis/framing/frames.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

Hit

Hit(at, score, baud, sps)

find_word: at (sample of the word's first symbol), score (0..1, 1 = the word alone, noiseless), baud, sps

Source code in src/rpps/analysis/framing/frames.py
def __init__(self, at, score, baud, sps):
    self.at, self.score, self.baud, self.sps = at, score, baud, sps

Burst

Burst(start, stop, det=None, symbols=None)

bursts: start, stop (samples), det (rpps.sync.Detection of this burst alone, None if too short), symbols (matched-filtered at det's rate and timing, carrier offset and phase taken off)

Source code in src/rpps/analysis/framing/frames.py
def __init__(self, start, stop, det=None, symbols=None):
    self.start, self.stop, self.det, self.symbols = start, stop, det, symbols

comb_lags

comb_lags(za, min_lag, max_lag, top=32, mean=RAYLEIGH_MEAN, var=RAYLEIGH_VAR)

[(lag, z)] the lags in [min_lag, max_lag] a frame structure may repeat at, most significant first

za: |autocorrelation| at every lag 0..n-1 in noise units (|sum of products| / its standard deviation under noise), whose |.| has mean and var there (Rayleigh for complex, half-normal for real). A word of U symbols every P adds only U/P to the correlation at lag P, against noise of 1/sqrt(n): alone that takes hundreds of frames to show. But it adds the same at every multiple kP, where the noise is new: z sums za less its mean over the multiples of a lag up to half the stream, each weighted by the signal it can hold (sqrt(n - kL)). That is what a fold of the stream at that lag measures, so a short word is a candidate about sqrt(frames) times sooner; magnitudes are summed, so a carrier left turning slowly (a residual offset, phase noise) or a polarity that changes costs only the coherence across the multiples. The top lags by that sum, and the PLAIN_TOP lags by their own correlation alone (a structure seen once a frame at one lag only, which the sum spreads out).

Source code in src/rpps/analysis/framing/frames.py
def comb_lags(za, min_lag, max_lag, top=32, mean=RAYLEIGH_MEAN, var=RAYLEIGH_VAR):
    """[(lag, z)] the lags in [min_lag, max_lag] a frame structure may repeat at, most significant first

    za: |autocorrelation| at every lag 0..n-1 in noise units (|sum of products| / its standard deviation under noise),
    whose |.| has `mean` and `var` there (Rayleigh for complex, half-normal for real). A word of U symbols every P adds
    only U/P to the correlation at lag P, against noise of 1/sqrt(n): alone that takes hundreds of frames to show. But
    it adds the same at every multiple kP, where the noise is new: z sums za less its mean over the multiples of a lag up
    to half the stream, each weighted by the signal it can hold (sqrt(n - kL)). That is what a fold of the stream at
    that lag measures, so a short word is a candidate about sqrt(frames) times sooner; magnitudes are summed, so a
    carrier left turning slowly (a residual offset, phase noise) or a polarity that changes costs only the coherence
    across the multiples. The `top` lags by that sum, and the PLAIN_TOP lags by their own correlation alone (a
    structure seen once a frame at one lag only, which the sum spreads out)."""
    n = len(za)
    max_lag = min(max_lag, n//4)
    if max_lag <= min_lag:
        return []
    zl = za - mean
    w = np.sqrt((n - np.arange(n))/n)
    L = np.arange(min_lag, max_lag + 1)
    num, den = np.zeros(len(L)), np.zeros(len(L))
    # Short lags have many multiples, so they go one lag at a time over all of them; the rest one multiple at a time
    # over all those lags
    split = max(min_lag, int(np.sqrt(n/2)))
    for i, lag in enumerate(L[L < split]):
        idx = lag*np.arange(1, n//2//lag + 1)
        num[i], den[i] = np.sum(w[idx]*zl[idx]), np.sum(w[idx]**2)
    long = L >= split
    for k in range(1, n//2//split + 1):
        m = long & (k*L <= n//2)
        if not m.any():
            break
        idx = k*L[m]
        num[m] += w[idx]*zl[idx]
        den[m] += w[idx]**2
    z = num/np.sqrt(var*np.maximum(den, 1e-30))
    out = []
    for score, n_top in ((z, top), (zl[L], PLAIN_TOP)):
        got = 0
        for i in np.argsort(-score)[:8*n_top]: # One per peak: a lag next to a stronger one is its shoulder
            lag = int(L[i])
            if all(abs(lag - k) > 2 for k, _ in out):
                out.append((lag, float(z[i])))
                got += 1
            if got == n_top:
                break
    out.sort(key=lambda t: -t[1])
    return out

periods

periods(y, max_lag=20000, min_lag=16, top=32)

[(lag, z)] the lags locked symbols may repeat at with a frame, most significant first (comb_lags over their autocorrelation, one FFT)

Source code in src/rpps/analysis/framing/frames.py
def periods(y, max_lag=20000, min_lag=16, top=32):
    """[(lag, z)] the lags locked symbols may repeat at with a frame, most significant first (`comb_lags` over their
    autocorrelation, one FFT)"""
    y = _normalized(y)
    n = len(y)
    if min(max_lag, n//4) <= min_lag:
        return []
    Y = np.fft.fft(y, 1 << int(np.ceil(np.log2(2*n))))
    za = np.abs(np.fft.ifft(np.abs(Y)**2)[:n])/np.sqrt(n - np.arange(n)) # (unit-power symbols: noise sd sqrt(n - lag))
    return comb_lags(za, min_lag, max_lag, top)

coherence

coherence(y, period)

Per position in the period: |mean over frames of y[n] conj(y[n+period])| over their rms, 1 where every frame has the same symbol. A product over 3 times the rms is clipped there, so one loud sample can't stand for a word; by chance (m frames) a position reaches c with probability about exp(-m c^2)

Source code in src/rpps/analysis/framing/frames.py
def coherence(y, period):
    """Per position in the period: |mean over frames of y[n] conj(y[n+period])| over their rms, 1 where every frame has the
    same symbol. A product over 3 times the rms is clipped there, so one loud sample can't stand for a word; by chance (m
    frames) a position reaches c with probability about exp(-m c^2)"""
    y = _normalized(y)
    c = y[:-period]*np.conj(y[period:])
    m = len(c)//period
    c = c[:m*period]
    mag = np.abs(c)
    lim = 3*np.sqrt(np.mean(mag**2))
    c = c*np.minimum(1.0, lim/np.maximum(mag, 1e-30))
    return np.abs(c.reshape(m, period).mean(axis=0))/np.sqrt(np.mean(np.abs(c)**2))

find

find(y, mod=None, max_lag=20000, min_frames=8, threshold=0.5, false_alarm=0.001, min_coherence=0.2)

The frame structure of locked symbols y: a Frame, or None (no lag with a unique word standing out)

The candidate periods are the lags whose multiples the symbols correlate at (periods), with their divisors (a multiple of the frame is a superframe, kept for repeats); at a period, the unique word is the longest run of positions whose coherence passes threshold (with many frames less: sqrt(4/m), but at least min_coherence: a unique word is in every frame, which a weak signal's 0.2 or more still shows), taken only when chance could not have made it (_chance, times every position and candidate period looked at, under false_alarm): one coherent symbol is not a word. Data that itself repeats every few frames doesn't average out, which hides the unique word (most positions coherent): then frame by hand and use repeats.

Source code in src/rpps/analysis/framing/frames.py
def find(y, mod=None, max_lag=20000, min_frames=8, threshold=0.5, false_alarm=1e-3, min_coherence=0.2):
    """The frame structure of locked symbols y: a Frame, or None (no lag with a unique word standing out)

    The candidate periods are the lags whose multiples the symbols correlate at (`periods`), with their divisors (a
    multiple of the frame is a superframe, kept for `repeats`); at a period, the unique word is the longest
    run of positions whose coherence passes `threshold` (with many frames less: sqrt(4/m), but at least `min_coherence`:
    a unique word is in every frame, which a weak signal's 0.2 or more still shows), taken only when chance could
    not have made it (`_chance`, times every position and candidate period looked at, under `false_alarm`): one
    coherent symbol is not a word. Data that itself repeats every few frames doesn't average
    out, which hides the unique word (most positions coherent): then frame by hand and use `repeats`."""
    y = _normalized(y)
    cands = {L for L, _ in periods(y, max_lag)}
    # Frames that repeat (fill, a superframe) correlate most at the repeat: the frame is a divisor of it
    cands |= {L//k for L in list(cands) for k in range(2, 17) if L % k == 0 and L//k >= 16}
    best = None
    for L in sorted(cands):
        m = len(y)//L - 1 # (frame pairs the coherence averages)
        if m + 1 < min_frames:
            continue
        prof = coherence(y, L)
        floor = float(np.median(prof))
        if floor > threshold: # Most positions coherent: data repeating, no word to single out
            continue
        hot = prof > max(min_coherence, min(threshold, np.sqrt(4/m))) # (with many frames, lower: a weak signal's word is
        # lower too, and the run's own test below keeps chance out; never under min_coherence: a word is in every frame,
        # not a structure a few percent of them share, which many frames make significant)
        if not hot.any():
            continue
        # The longest run of coherent positions (circular: the word may straddle the fold)
        h = np.concatenate((hot, hot))
        runs, start = [], None
        for i, v in enumerate(h):
            if v and start is None:
                start = i
            elif not v and start is not None:
                runs.append((start, i - start))
                start = None
        if start is not None:
            runs.append((start, len(h) - start))
        s0, ln = max(runs, key=lambda t: t[1])
        ln = min(ln, L)
        s0 %= L
        word = prof[(s0 + np.arange(ln)) % L]
        if L*len(cands)*_chance(m, word) > false_alarm: # Chance could have made it
            continue
        coh = float(np.mean(word))
        f = Frame(period=L, uw_start=int(s0), uw_length=int(ln), coherence=coh, floor=floor,
                  uw=y[s0:s0 + ln].copy(), frames=len(y)//L)
        # A shorter period wins unless much weaker; a multiple of it by far more (over fewer frames its word's coherence,
        # and the noise positions joining the run, are biased up: it is the superframe, for `repeats`)
        multiple = best is not None and abs(L - best.period*round(L/best.period)) <= 2
        if best is None or ln*coh > best.uw_length*best.coherence*(4.0 if multiple else 1.5):
            best = f
    return best

grid_of

grid_of(constellation)

The turns a constellation is symmetric under. The largest M of 2, 4, 8, 16 that turns its points onto themselves by 360/M degrees (BPSK 2, QPSK and square QAM 4, 8PSK 8), 1 for none. cut's grid

Source code in src/rpps/analysis/framing/frames.py
def grid_of(constellation):
    """The turns a constellation is symmetric under. The largest M of 2, 4, 8, 16 that turns its points onto
    themselves by 360/M degrees (BPSK 2, QPSK and square QAM 4, 8PSK 8), 1 for none. `cut`'s grid"""
    from ... import symbol
    c = symbol.load_or_generate(constellation) if isinstance(constellation, str) else constellation
    pts = np.asarray(c.points, dtype=np.complex128)
    best = 1
    for M in (2, 4, 8, 16):
        turned = pts*np.exp(2j*np.pi/M)
        if np.all(np.min(np.abs(turned[:, None] - pts[None, :]), axis=1) < 1e-6*np.max(np.abs(pts))):
            best = M
    return best

cut

cut(y, fr, M=None, grid=4)

Frames x period symbols starting at the unique word, each turned onto the others by its unique word

The reference is the word averaged over all frames (one frame's own word is as noisy as any symbol), found in two passes: frames turned onto the first frame's word by multiples of 90 degrees, averaged, then every frame onto that average. M=None: by the angle measured (also takes off a carrier phase drifting frame to frame); M: by the nearest multiple of 360/M degrees only (the ambiguity alone). Then the whole set is turned so the payload sits on a grid-fold symmetric constellation (QPSK points at 45 + 90k degrees, as rpps.symbol's), by its grid-th power: the constellation's own symmetry (grid_of; 4 on BPSK turns it 45 degrees off its points).

Source code in src/rpps/analysis/framing/frames.py
def cut(y, fr, M=None, grid=4):
    """Frames x period symbols starting at the unique word, each turned onto the others by its unique word

    The reference is the word averaged over all frames (one frame's own word is as noisy as any symbol), found in two
    passes: frames turned onto the first frame's word by multiples of 90 degrees, averaged, then every frame onto that
    average. M=None: by the angle measured (also takes off a carrier phase drifting frame to frame); M: by the nearest
    multiple of 360/M degrees only (the ambiguity alone). Then the whole set is turned so the payload sits on a
    `grid`-fold symmetric constellation (QPSK points at 45 + 90k degrees, as rpps.symbol's), by its grid-th power: the
    constellation's own symmetry (`grid_of`; 4 on BPSK turns it 45 degrees off its points)."""
    y = _normalized(y)
    F = (len(y) - fr.uw_start)//fr.period
    f = y[fr.uw_start:fr.uw_start + F*fr.period].reshape(F, fr.period)
    U = fr.uw_length
    first = f[0, :U]
    a0 = np.angle(np.sum(f[:, :U]*np.conj(first), axis=1))
    ref = np.mean(f[:, :U]*np.exp(-1j*(np.pi/2)*np.round(a0/(np.pi/2)))[:, None], axis=0)
    a = np.angle(np.sum(f[:, :U]*np.conj(ref), axis=1))
    if M:
        a = 2*np.pi/M*np.round(a/(2*np.pi/M))
    f = f*np.exp(-1j*a)[:, None]
    if grid:
        pay = f[:, U:].ravel()
        g = (np.angle(-np.mean(pay**grid)) if grid == 4 else np.angle(np.mean(pay**grid)))/grid # QPSK: (e^{j pi/4})^4 = -1
        f = f*np.exp(-1j*g)
    return f

payload_bits

payload_bits(frames, fr, constellation)

Frames x bits of the symbols after each unique word, hard-decided on constellation (a name or a Constellation)

Source code in src/rpps/analysis/framing/frames.py
def payload_bits(frames, fr, constellation):
    """Frames x bits of the symbols after each unique word, hard-decided on `constellation` (a name or a Constellation)"""
    from ... import symbol
    c = symbol.load_or_generate(constellation) if isinstance(constellation, str) else constellation
    pay = frames[:, fr.uw_length:]
    pts = np.asarray(c.points)/np.sqrt(np.mean(np.abs(c.points)**2))
    labels = np.asarray(c.mapping.arr if hasattr(c, "mapping") else np.arange(len(pts)))
    idx = np.argmin(np.abs(pay[..., None] - pts[None, None, :]), axis=-1)
    lab = labels[idx]
    k = c.bits_per_symbol
    bits = (lab[..., None] >> np.arange(k - 1, -1, -1)) & 1
    return bits.reshape(len(frames), -1).astype(np.uint8)

repeats

repeats(frame_bits, max_period=64, agree=0.99)

(period, fraction of frames equal to the one period before): the smallest such period, or (None, 0.0). Frames that come again (idle, fill, a fixed superframe) are content, not code

Source code in src/rpps/analysis/framing/frames.py
def repeats(frame_bits, max_period=64, agree=0.99):
    """(period, fraction of frames equal to the one `period` before): the smallest such period, or (None, 0.0). Frames
    that come again (idle, fill, a fixed superframe) are content, not code"""
    b = np.asarray(frame_bits, dtype=np.uint8)
    for p in range(1, min(max_period, len(b)//2) + 1):
        same = np.mean(np.mean(b[p:] == b[:-p], axis=1) >= agree)
        if same >= 0.5:
            return p, float(same)
    return None, 0.0

word_waveform

word_waveform(word, sps, beta=0.35, span=8)

The symbols word shaped by an RRC pulse at a fractional sps samples per symbol

Source code in src/rpps/analysis/framing/frames.py
def word_waveform(word, sps, beta=0.35, span=8):
    """The symbols `word` shaped by an RRC pulse at a fractional `sps` samples per symbol"""
    from ...signal.filters import rrc_pulse
    word = np.asarray(word, dtype=np.complex128)
    n = int(np.ceil((len(word) + 2*span)*sps))
    t = np.arange(n)/sps - span
    out = np.zeros(n, dtype=np.complex128)
    for k, s in enumerate(word):
        d = t - k
        m = np.abs(d) <= span
        out[m] += s*rrc_pulse(d[m], beta)
    return out

find_word

find_word(x, Fs, word, bauds, beta=0.35, segments=8, threshold=0.5, top=16)

Where a known symbol word (a preamble, a burst's unique word) is in baseband samples x at Fs: [Hit] best first

bauds: the symbol rates to try. The word's shaped waveform is cut into segments pieces, each correlated on its own and their magnitudes added, so a carrier offset that turns the phase across the word (up to about baud/len(word)* segments/4) and an unknown phase cost nothing. score: that sum over what the samples' energy allows (Cauchy-Schwarz), near 1 where the word is, about 1/sqrt(samples per segment) elsewhere.

Source code in src/rpps/analysis/framing/frames.py
def find_word(x, Fs, word, bauds, beta=0.35, segments=8, threshold=0.5, top=16):
    """Where a known symbol word (a preamble, a burst's unique word) is in baseband samples x at Fs: [Hit] best first

    bauds: the symbol rates to try. The word's shaped waveform is cut into `segments` pieces, each correlated on its own
    and their magnitudes added, so a carrier offset that turns the phase across the word (up to about baud/len(word)*
    segments/4) and an unknown phase cost nothing. score: that sum over what the samples' energy allows (Cauchy-Schwarz),
    near 1 where the word is, about 1/sqrt(samples per segment) elsewhere."""
    x = np.asarray(x, dtype=np.complex128)
    n = len(x)
    hits = []
    e = np.concatenate(([0.0], np.cumsum(np.abs(x)**2)))
    for baud in np.atleast_1d(bauds):
        sps = Fs/baud
        w = word_waveform(word, sps, beta)
        L = len(w)
        if L >= n:
            continue
        edges = np.linspace(0, L, segments + 1).astype(int)
        acc = np.zeros(n - L + 1)
        X = np.fft.fft(x, n + L)
        for a, b in zip(edges[:-1], edges[1:]):
            seg = np.zeros(L, dtype=np.complex128)
            seg[a:b] = w[a:b]
            c = np.fft.ifft(X*np.conj(np.fft.fft(seg, n + L)))[:n - L + 1] # sum x[t+i] conj(seg[i])
            win = e[np.arange(n - L + 1) + b] - e[np.arange(n - L + 1) + a]
            acc += np.abs(c)/np.sqrt(np.maximum(win, 1e-30)*np.sum(np.abs(w[a:b])**2))
        acc /= segments
        for k in np.argsort(-acc)[:top]:
            if acc[k] >= threshold:
                hits.append(Hit(int(k + round(8*sps)), float(acc[k]), float(baud), float(sps))) # (the pulse's lead)
    hits.sort(key=lambda h: -h.score)
    out = []
    for h in hits: # One per burst: a hit within the word's length of a better one is that one
        if all(abs(h.at - o.at) > len(word)*o.sps for o in out):
            out.append(h)
    return out[:top]

split

split(x, Fs, a, b, win=4e-06, min_len=6.4e-05, min_gap=2e-06, thr=None, bw=None, guards=True)

Where touching bursts meet in x[a:b]: [(start, stop)]

no gap the gate sees, or one shorter than its hang. Found by
  • guard times: dips of the power (smoothed over a quarter of a symbol) 10 dB under the span's level, min_gap long at least and much longer than the bursts' own envelope dips (_guards)
  • power steps between transmitters' levels: binary segmentation of the power (dB) in windows of win (32 samples at least), the gain over its noise above thr (default 30 + 6 ln(windows): above chance over every position)

bw: the occupied bandwidth (Hz), when known: windows of 8 symbols and guards of a symbol at least (a slow signal's envelope dips within a symbol). guards: look for guard times (not when the bursts stand under 10 dB over the floor, where noise dips as deep). Parts min_len long at least. Not cut: bursts at one level with no guard between them, told apart only by their carriers (the line of x^M in a few symbols is mostly the data's own noise; tried and dropped)

Source code in src/rpps/analysis/framing/frames.py
def split(x, Fs, a, b, win=4e-6, min_len=64e-6, min_gap=2e-6, thr=None, bw=None, guards=True):
    """Where touching bursts meet in x[a:b]: [(start, stop)]

    Touching: no gap the gate sees, or one shorter than its `hang`. Found by
      - guard times: dips of the power (smoothed over a quarter of a symbol) 10 dB under the span's level, `min_gap`
        long at least and much longer than the bursts' own envelope dips (`_guards`)
      - power steps between transmitters' levels: binary segmentation of the power (dB) in windows of `win` (32 samples
        at least), the gain over its noise above `thr` (default 30 + 6 ln(windows): above chance over every position)
    bw: the occupied bandwidth (Hz), when known: windows of 8 symbols and guards of a symbol at least (a slow
    signal's envelope dips within a symbol). guards: look for guard times (not when the bursts stand under 10 dB over
    the floor, where noise dips as deep). Parts `min_len` long at least. Not cut: bursts at one level with no guard between them, told apart only by their
    carriers (the line of x^M in a few symbols is mostly the data's own noise; tried and dropped)"""
    x = np.asarray(x[a:b], dtype=np.complex128)
    if bw:
        win, min_gap = max(win, 8/bw), max(min_gap, 1/bw)
    w = max(32, int(Fs*win))
    n = len(x)//w
    min_seg = max(2, int(np.ceil(min_len*Fs/w)))
    if n < 2*min_seg:
        return [(a, b)]
    pw = np.abs(x)**2
    P = 10*np.log10(np.mean(pw[:n*w].reshape(n, w), axis=1) + 1e-30)
    top = np.percentile(P, 90)
    f = max(2, int(Fs/bw/4) if bw else w//16) # a quarter of a symbol
    fine = np.convolve(pw, np.ones(f)/f, mode="same")
    # The level around each sample (the louder of the windows within min_len either side: a quiet burst beside a loud
    # one is judged against its own level), 10 dB under it a guard time
    from numpy.lib.stride_tricks import sliding_window_view
    Pm = np.median(sliding_window_view(np.pad(P, min_seg//2, mode="edge"), 2*(min_seg//2) + 1), axis=1)[:n]
    Pl = np.max(sliding_window_view(np.pad(Pm, 1, mode="edge"), 3), axis=1)
    local = np.repeat(Pl, w)
    local = np.concatenate((local, np.full(len(x) - len(local), local[-1])))
    gaps = _guards(fine, 10**((local - 10)/10), int(min_gap*Fs)) if guards else []
    cuts = []
    lp = 10*np.log10(fine + 1e-30)
    for k in _segments((P/_noise(P))[:, None], min_seg, 30 + 6*np.log(n) if thr is None else thr):
        c = w*k
        if any(g0 - 2*w <= c <= g1 + 2*w for g0, g1 in gaps): # a guard time there already parts them, exactly
            continue
        lo, hi = max(0, c - 3*w), min(len(x), c + 3*w) # to the sample: the best single split of the fine power near it
        seg = lp[lo:hi]
        cs = np.cumsum(seg)
        j = np.arange(1, len(seg))
        gain = j*(len(seg) - j)*((cs[j - 1]/j - (cs[-1] - cs[j - 1])/(len(seg) - j))**2)
        cuts.append(lo + int(j[np.argmax(gain)]))
    cuts = sorted(cuts)
    out, last = [], 0
    for c in cuts + [len(x)]:
        segs = [[last, c]]
        last = c
        for g0, g1 in gaps: # the guard times taken out
            segs = [r for s0, s1 in segs for r in (([[s0, s1]]) if g1 <= s0 or g0 >= s1 else [[s0, g0], [g1, s1]])
                    if r[1] > r[0]]
        out += [(a + s0, a + s1) for s0, s1 in segs
                if s1 - s0 >= min_len*Fs and np.median(fine[s0:s1]) > 10**((top - 10)/10)]
    return out or [(a, b)]

occupied

occupied(x, Fs, nfft=1024, share=0.9)

The bandwidth holding share of the power above the noise floor (Hz): about the symbol rate of a shaped signal

Source code in src/rpps/analysis/framing/frames.py
def occupied(x, Fs, nfft=1024, share=0.9):
    """The bandwidth holding `share` of the power above the noise floor (Hz): about the symbol rate of a shaped signal"""
    x = np.asarray(x, dtype=np.complex128)
    n = min(nfft, 1 << int(np.floor(np.log2(max(len(x), 16)))))
    k = len(x)//n
    if k == 0:
        return Fs
    S = np.fft.fftshift(np.mean(np.abs(np.fft.fft(x[:k*n].reshape(k, n)*np.hanning(n), axis=1))**2, axis=0))
    floor = np.percentile(S, 10)
    e = np.maximum(S - 2*floor, 0)
    if e.sum() <= 0:
        return Fs
    c = np.cumsum(e)/e.sum()
    lo, hi = np.searchsorted(c, (1 - share)/2), np.searchsorted(c, (1 + share)/2)
    return max(hi - lo + 1, 1)*Fs/n

gate

gate(x, Fs, smooth=4e-06, contrast=2.5, min_len=6.4e-05, hang=8e-06, touching=True)

[(start, stop)] where the power is on: above the geometric mean of its low and high levels (contrast apart at least), bursts closer than hang merged, those shorter than min_len dropped; each span then cut where bursts touch (split: a power step or a guard time), unless touching is False. Times scale with a symbol, 1/bw (the occupied bandwidth, occupied): - the levels from the power averaged over 64 symbols (noise alone then spans under 2 between its 5th and 99th percentiles, so contrast tells bursts from noise; averaged over a sample or two, noise alone would pass it) - on and off from the power averaged over enough symbols that noise stays 4 standard deviations from the threshold ((4/(sqrt(hi/lo) - 1))^2 symbols, 2 to 64, and smooth at least: a weak signal is averaged longer) - hang at least 6 symbols and twice that average (a slow or weak signal's own dips do not open the gate)

Source code in src/rpps/analysis/framing/frames.py
def gate(x, Fs, smooth=4e-6, contrast=2.5, min_len=64e-6, hang=8e-6, touching=True):
    """[(start, stop)] where the power is on: above the geometric mean of its low and high levels (`contrast` apart at
    least), bursts closer than `hang` merged, those shorter than `min_len` dropped; each span then cut where bursts
    touch (`split`: a power step or a guard time), unless `touching` is False. Times scale with a symbol, 1/bw (the
    occupied bandwidth, `occupied`):
      - the levels from the power averaged over 64 symbols (noise alone then spans under 2 between its 5th and 99th
        percentiles, so `contrast` tells bursts from noise; averaged over a sample or two, noise alone would pass it)
      - on and off from the power averaged over enough symbols that noise stays 4 standard deviations from the threshold
        ((4/(sqrt(hi/lo) - 1))^2 symbols, 2 to 64, and `smooth` at least: a weak signal is averaged longer)
      - `hang` at least 6 symbols and twice that average (a slow or weak signal's own dips do not open the gate)"""
    p = np.abs(np.asarray(x))**2
    bw = occupied(x, Fs)
    sym = Fs/bw # samples a symbol, about
    def avg(w):
        w = max(2, int(w))
        return np.convolve(p, np.ones(w)/w, mode="same")
    e = avg(max(Fs*smooth, 64*sym))
    lo, hi = np.percentile(e, 5), np.percentile(e, 99)
    if hi < contrast*lo:
        return []
    n_sym = float(np.clip((4/(np.sqrt(hi/lo) - 1))**2, 2, 64))
    w = max(Fs*smooth, n_sym*sym)
    on = avg(w) > np.sqrt(lo*hi)
    hang = max(hang, 6/bw, 2*w/Fs)
    spans = list(zip(*runs(on)))
    merged = []
    for a, b in spans:
        if merged and a - merged[-1][1] < hang*Fs:
            merged[-1][1] = b
        else:
            merged.append([a, b])
    spans = [(int(a), int(b)) for a, b in merged if b - a >= min_len*Fs]
    if touching:
        spans = [p for a, b in spans for p in (split(x, Fs, a, b, min_len=min_len, bw=bw, guards=hi/lo > 10)
                                               if b - a >= 2*min_len*Fs else [(a, b)])]
    return spans

centroid

centroid(x, Fs, nfft=1024)

The power-weighted mean frequency (Hz) of the spectrum's bins above twice its 10th-percentile floor: a coarse carrier for a signal cut off-centre

Source code in src/rpps/analysis/framing/frames.py
def centroid(x, Fs, nfft=1024):
    """The power-weighted mean frequency (Hz) of the spectrum's bins above twice its 10th-percentile floor: a coarse
    carrier for a signal cut off-centre"""
    x = np.asarray(x, dtype=np.complex128)
    n = min(nfft, 1 << int(np.floor(np.log2(max(len(x), 16)))))
    k = len(x)//n
    if k == 0:
        return 0.0
    S = np.fft.fftshift(np.mean(np.abs(np.fft.fft(x[:k*n].reshape(k, n)*np.hanning(n), axis=1))**2, axis=0))
    f = np.fft.fftshift(np.fft.fftfreq(n, 1/Fs))
    e = np.maximum(S - 2*np.percentile(S, 10), 0)
    return float(np.sum(f*e)/np.sum(e)) if e.sum() > 0 else 0.0

tone_pair

tone_pair(x, Fs, sep, tol=0.02, min_snr=20.0)

The middle (Hz) of the strongest pair of spectral lines sep apart (to tol of it) in the samples x, or None: a periodic preamble (1100...: tones at the carrier +-baud/4) puts its carrier between two lines, which squaring cannot tell from the lines themselves. Lines are taken over the floor (median of the spectrum), both min_snr over it

Source code in src/rpps/analysis/framing/frames.py
def tone_pair(x, Fs, sep, tol=0.02, min_snr=20.0):
    """The middle (Hz) of the strongest pair of spectral lines `sep` apart (to `tol` of it) in the samples x, or None:
    a periodic preamble (1100...: tones at the carrier +-baud/4) puts its carrier between two lines, which squaring
    cannot tell from the lines themselves. Lines are taken over the floor (median of the spectrum), both `min_snr` over it"""
    x = np.asarray(x, dtype=np.complex128)
    n = 1 << int(np.ceil(np.log2(max(len(x), 64))))
    X = np.abs(np.fft.fftshift(np.fft.fft(x*np.hanning(len(x)), 2*n)))**2
    f = np.fft.fftshift(np.fft.fftfreq(2*n, 1/Fs))
    floor = np.median(X) + 1e-30
    df = f[1] - f[0]
    k = int(round(sep/df))
    w = max(1, int(round(tol*sep/df)))
    if k <= w or k >= len(X):
        return None
    from numpy.lib.stride_tricks import sliding_window_view
    pad = np.concatenate((X, np.zeros(k + w)))
    partner = sliding_window_view(pad[k - w:], 2*w + 1).max(axis=1)[:len(X)] # the strongest line near sep above each
    score = np.minimum(X, partner)/floor
    i = int(np.argmax(score))
    if score[i] < min_snr:
        return None
    j = i + k - w + int(np.argmax(pad[i + k - w:i + k + w + 1]))
    return float((f[i] + f[min(j, len(f) - 1)])/2)

bursts

bursts(x, Fs, names=None, baud=None, min_symbols=128, betas=(0.2, 0.25, 0.35), **kw)

The bursts of x (gate), each acquired on its own: rate (or baud for all), modulation, offset, timing (as a TDMA receiver must: every burst comes from another transmitter, with its own clock and carrier). The rate is the |x|^2 line within 0.7 to 1.4 times the burst's occupied bandwidth (occupied). What is known narrows each burst's search: baud (no rate search), names (the modulations to try), betas (the roll-offs). [Burst]

Source code in src/rpps/analysis/framing/frames.py
def bursts(x, Fs, names=None, baud=None, min_symbols=128, betas=(0.2, 0.25, 0.35), **kw):
    """The bursts of x (`gate`), each acquired on its own: rate (or `baud` for all), modulation, offset, timing (as a
    TDMA receiver must: every burst comes from another transmitter, with its own clock and carrier). The rate is the
    |x|^2 line within 0.7 to 1.4 times the burst's occupied bandwidth (`occupied`). What is known
    narrows each burst's search: `baud` (no rate search), `names` (the modulations to try), `betas` (the roll-offs).
    [Burst]"""
    from ...sync.acquire import detect, candidates, symmetry
    from ...sync.rate import find_baud
    x = np.asarray(x, dtype=np.complex128)
    out = []
    for a, b in gate(x, Fs, **kw):
        seg = x[a:b]
        bu = Burst(a, b)
        try:
            b0 = baud
            if b0 is None: # the rate's line near the burst's occupied bandwidth only (a preamble's own lines lie
                bwb = occupied(seg, Fs) #  at fractions and multiples of it; the default search starts at Fs/16)
                b0, _ = find_baud(seg, Fs, lo=0.7*bwb, hi=min(1.4*bwb, Fs/2.5))
                b0 = b0 or None
            det = detect(seg, Fs, names, betas=betas, baud=b0)
            sps = Fs/baud if baud is not None else det.sps
            if len(seg)/sps >= min_symbols:
                # The matched filter needs the pulse's span either side: widen the segment by it, so the burst's first
                # symbols (the preamble) are taken too; the timing found on the gated part carries over
                pad = int(np.ceil(10*sps))
                a2, b2 = max(0, a - pad), min(len(x), b + pad)
                seg = x[a2:b2]
                t0 = det.tau + (a - a2)
                t0 -= np.floor((t0 - 8*sps - 5)/sps)*sps
                pts = candidates([det.mod])[det.mod]
                M = symmetry(pts)
                rate = Fs/sps
                # Carriers to try, the samples shifted by each before the matched filter: none (the blind estimate is
                # taken from the symbols); a quarter of the rate either side, where that is not a turn of the
                # constellation's symmetry (BPSK: a long 1100... preamble is a pair of tones at +-baud/4 a blind carrier
                # can lock onto; for QPSK the turn is invisible to the decisions); and the middle of such a tone pair
                # in the spectrum of the samples themselves (`tone_pair`: unambiguous, and strong where the preamble is)
                shifts = [0.0]
                if M % 4: # (a quarter of the rate turns each symbol 90 degrees: a symmetry of QPSK, 8PSK...)
                    shifts += [rate/4, -rate/4]
                tp = tone_pair(seg, Fs, rate/2)
                if tp is not None:
                    shifts.append(tp)
                # and the blind estimate and the burst's spectral centroid, taken off before the matched filter (a burst
                # cut far off-centre loses its edge to the filter otherwise, or lies past the blind search)
                shifts += [float(det.cfo), centroid(seg, Fs)]
                n_ = np.arange(len(seg))
                best = _take(seg, t0, sps, det.beta, shifts, pts, M, Fs)
                if best[2]: # a shifted carrier: detected again there (modulation, Es/N0, and the timing and roll-off the
                    try:    #   first, aliased, detection had wrong), and the symbols taken again with them
                        sh = seg*np.exp(-2j*np.pi*best[2]/Fs*n_)
                        d2 = detect(sh, Fs, names, betas=betas, baud=det.baud)
                        t2 = d2.tau - np.floor((d2.tau - 8*d2.sps - 5)/d2.sps)*d2.sps
                        again = _take(seg, t2, d2.sps, d2.beta, [best[2]], pts, M, Fs)
                        if again[0] <= best[0]:
                            best = again
                        d2.cfo = float(d2.cfo + best[2])
                        det = d2
                    except Exception: # (keep the first detection, with the carrier corrected)
                        pass
                bu.symbols = best[1]
                det.cfo = float(best[3]) # the carrier these symbols were taken at (the shift tried, and what was left)
                bu.det = det
        except Exception: # A burst too short or too weak to acquire is kept, without symbols
            pass
        out.append(bu)
    return out

preamble

preamble(burst_list, max_len=512, agree=0.8, search=8)

What the bursts' first symbols share: (length, differential symbols d[n] = s[n] conj(s[n-1]) of it, where it starts in each burst's symbols) or (0, None, None). Differential, so each burst's own carrier phase drops out; each burst is slid by up to search symbols onto the first (the gate finds a start to within a few symbols), and the preamble is the leading run where the bursts' d[n] agree (|mean| over bursts above agree)

Source code in src/rpps/analysis/framing/frames.py
def preamble(burst_list, max_len=512, agree=0.8, search=8):
    """What the bursts' first symbols share: (length, differential symbols d[n] = s[n] conj(s[n-1]) of it, where it starts
    in each burst's symbols) or (0, None, None). Differential, so each burst's own carrier phase drops out; each burst is slid by up to `search`
    symbols onto the first (the gate finds a start to within a few symbols), and the preamble is the leading run where
    the bursts' d[n] agree (|mean| over bursts above `agree`)"""
    S = [b.symbols for b in burst_list if b.symbols is not None and len(b.symbols) > 2*search + 32]
    if len(S) < 3:
        return 0, None, None
    D = [s[1:]*np.conj(s[:-1])/(np.abs(s[1:]*s[:-1]) + 1e-12) for s in S]
    ref = D[0][search:search + 64]
    offs = []
    for d in D: # Burst i's symbol k + offs[i] is the first burst's symbol k
        sc = [np.abs(np.vdot(ref, d[k:k + 64])) for k in range(2*search + 1)]
        offs.append(int(np.argmax(sc)) - search)
    c = max(0, -min(offs)) # From the first symbol every burst has
    L = min(max_len, min(len(d) - o - c for d, o in zip(D, offs)))
    rows = [d[o + c:o + c + L] for d, o in zip(D, offs)]
    m = np.abs(np.mean(np.array(rows), axis=0))
    s0 = next((i for i in range(min(len(m), 2*search + 2)) if m[i] > agree), None) # (the gate may open a little early)
    if s0 is None:
        return 0, None, None
    n = 0
    while s0 + n < len(m) and m[s0 + n] > agree:
        n += 1
    return n, np.mean(np.array(rows), axis=0)[s0:s0 + n], [o + c + s0 for o in offs]

coarse_cfo

coarse_cfo(x, Fs, M=4, pad=4)

Carrier offset [Hz] from the line of x^M (the modulation's M-fold symmetry taken off)

Source code in src/rpps/analysis/framing/frames.py
def coarse_cfo(x, Fs, M=4, pad=4):
    """Carrier offset [Hz] from the line of x^M (the modulation's M-fold symmetry taken off)"""
    from ...math.interp import peak
    n = 1 << int(np.ceil(np.log2(min(len(x), 2**21))))
    z = np.asarray(x[:n], dtype=np.complex128)**M
    S = np.abs(np.fft.fft(z*np.hanning(len(z)), pad*n))
    k, d = peak(S, circular=True)
    f = (k + d)/(pad*n)
    return (f - (1 if f > 0.5 else 0))*Fs/M

pilot_frames

pilot_frames(x, Fs, uw, baud, period, beta=0.35, span=8, threshold=0.45, M=4, dropout=0.6, track=64, smooth=8)

Frames of symbols synchronized on their unique word as pilots: (frames x period symbols from each word on, the words' sample times)

Each word is found in the samples (find_word) and timed to a fraction of a sample; the symbols of a frame lie evenly between its word and the next one, which follows the transmitter's clock frame by frame. The carrier phase is measured on each word and taken linearly across the frame to the next (a frequency per frame), so no loop has to settle and a slip can't carry over. uw: the word's symbols (from cut: the first frame's, or their mean). The coarse carrier offset comes off first, from the M-th power (coarse_cfo). threshold: the first word's match (find_word; a short word's pulse tails overlap random neighbours, which caps it near 0.6); dropout: a word under this times the running level is taken as missing, and the clock carried over it. track: symbols over which the phase left between the words (LNB phase noise) is taken off by the M-th power (0: none). smooth: the words' times are fitted with a line over this many frames either side (a short word times one frame noisily; 0: as measured).

Source code in src/rpps/analysis/framing/frames.py
def pilot_frames(x, Fs, uw, baud, period, beta=0.35, span=8, threshold=0.45, M=4, dropout=0.6, track=64, smooth=8):
    """Frames of symbols synchronized on their unique word as pilots: (frames x period symbols from each word on, the words'
    sample times)

    Each word is found in the samples (`find_word`) and timed to a fraction of a sample; the symbols of a frame lie evenly
    between its word and the next one, which follows the transmitter's clock frame by frame. The carrier phase is measured
    on each word and taken linearly across the frame to the next (a frequency per frame), so no loop has to settle and a
    slip can't carry over. uw: the word's symbols (from `cut`: the first frame's, or their mean). The coarse carrier offset
    comes off first, from the M-th power (`coarse_cfo`). threshold: the first word's match (`find_word`; a short word's
    pulse tails overlap random neighbours, which caps it near 0.6); dropout: a word under this times the running level is
    taken as missing, and the clock carried over it. track: symbols over which the phase left between the words (LNB
    phase noise) is taken off by the M-th power (0: none). smooth: the words' times are fitted with a line over this many
    frames either side (a short word times one frame noisily; 0: as measured)."""
    from ...sync.time.mat import matrix_mf
    x = np.asarray(x, dtype=np.complex128)
    # The coarse carrier offset off first: across a frame the words' phases may only turn by less than half a turn
    cfo = coarse_cfo(x, Fs, M)
    x = x*np.exp(-2j*np.pi*cfo/Fs*np.arange(len(x)))
    uw = np.asarray(uw, dtype=np.complex128)
    uw = uw/np.sqrt(np.mean(np.abs(uw)**2))
    sps = Fs/baud
    # A short word matches random data now and then: anchor on the strongest match, then walk frame by frame, each word
    # looked for only near where the last one and the clock put it (the clock taken from the words found so far)
    first = find_word(x[:int(min(len(x), 4*period*sps))], Fs, uw, [baud], beta, threshold=threshold, top=4,
                      segments=1 if len(uw) < 32 else 8)
    if not first:
        return np.zeros((0, period), complex), np.zeros(0)
    t0, r0 = _refine(x, first[0].at, uw, sps, beta, span)
    while t0 is not None and t0 - period*sps > span*sps + 2: # Back to the first word in x
        t0 -= period*sps
    t0, r0 = _refine(x, t0, uw, sps, beta, span) if t0 is not None else (None, 0)
    times, phases = [], []
    T, t = period*sps, t0
    floor = None
    while t is not None and t + T + (span + 2)*sps < len(x):
        best = (None, 0.0)
        for d in range(-2, 3): # Within two symbols of where the word should be
            tt, r = _refine(x, t + d*sps, uw, sps, beta, span)
            if tt is not None and abs(r) > abs(best[1]):
                best = (tt, r)
        tt, r = best
        q = abs(r)/len(uw)
        if floor is None:
            floor = q
        if tt is None or q < dropout*floor: # Not there (a dropout): carry the clock over it
            times.append(None)
            phases.append(None)
        else:
            times.append(tt)
            phases.append(np.angle(r))
            known = [(i, v) for i, v in enumerate(times) if v is not None][-16:]
            if len(known) >= 2:
                T = (known[-1][1] - known[0][1])/(known[-1][0] - known[0][0])
            floor = 0.9*floor + 0.1*q
        t = (tt if tt is not None else t) + T
    # A short word times each frame noisily, the transmitter's clock is steady: each word's time from a straight line
    # through the words within `smooth` frames of it
    if smooth:
        idx = np.array([i for i, t in enumerate(times) if t is not None])
        tv = np.array([times[i] for i in idx])
        fitted = list(times)
        for j, i in enumerate(idx):
            m = np.abs(idx - i) <= smooth
            if m.sum() >= 3:
                a, b = np.polyfit(idx[m] - i, tv[m], 1)
                fitted[i] = b
        times = fitted
    frames, starts = [], []
    for i in range(len(times) - 1):
        if times[i] is None or times[i + 1] is None:
            continue
        T = times[i + 1] - times[i]
        if abs(T/period - sps) > 0.01*sps: # Not the next frame's word (one missed between): no clock to take from it
            continue
        c = times[i] + np.arange(period)*T/period
        if c[0] - span*sps - 2 < 0 or c[-1] + span*sps + 2 >= len(x):
            continue
        y = matrix_mf(x, c, T/period, beta, span)
        dphi = np.angle(np.exp(1j*(phases[i + 1] - phases[i]))) # The turn over one frame (a carrier offset under half a turn a frame)
        y = y*np.exp(-1j*(phases[i] + dphi*np.arange(period)/period))
        if track and M:
            # Phase noise between the words: what is left, a small turn, by the M-th power over `track` symbols (on the
            # words' reference already, so no ambiguity: only the part under 180/M degrees is taken)
            ref = np.mean(uw**M)
            for a in range(0, period, track):
                seg = y[a:a + track]
                y[a:a + track] = seg*np.exp(-1j*np.angle(np.mean(seg**M)*np.conj(ref))/M)
        frames.append(y)
        starts.append(times[i])
    f = np.array(frames)
    return (f/np.sqrt(np.mean(np.abs(f)**2)) if len(f) else f), np.array(starts)

marked

Frames behind a sync marker, the scrambler restarted at each, the block code inside (rpps.analysis.framing.marked)

layer(bits) on any bit stream: a shipped profile's marker (markers) repeating at one period, within MAX_ERRORS bits, either polarity; then none or each additive scrambler restarted per frame; then each byte RS code dividing the frame, behind each block interleaver with a depth, scored by the words that decode within t against a random word's chance (chance). Returns Frames, whose steps are the profile steps that read it (CCSDS TM: ASM, randomizer, RS interleaved to depth I).

Classes:

Name Description
Frames

A frame layer layer found. steps: the profile steps that read it (sync delimit, code marker, scramble,

Functions:

Name Description
markers

{name: bits} of the profiles' sync markers. MIN_MARKER bits or longer

chance

A random word's chance to decode. Within t of an RS codeword: about C(n, t) (q - 1)^t / q^(2t), q = 2^m

layer

The frame layer in bits: a Frames, or None. None when no marker repeats. Without a code that

Frames

Frames(**kw)

A frame layer layer found. steps: the profile steps that read it (sync delimit, code marker, scramble, interleave, block), as identify lays steps out

Source code in src/rpps/analysis/framing/marked.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

markers

markers()

{name: bits} of the profiles' sync markers. MIN_MARKER bits or longer

Source code in src/rpps/analysis/framing/marked.py
def markers():
    """{name: bits} of the profiles' sync markers. MIN_MARKER bits or longer"""
    from ... import _config
    return dict(_markers(_config.state()))

chance

chance(code)

A random word's chance to decode. Within t of an RS codeword: about C(n, t) (q - 1)^t / q^(2t), q = 2^m

Source code in src/rpps/analysis/framing/marked.py
def chance(code):
    """A random word's chance to decode. Within t of an RS codeword: about C(n, t) (q - 1)^t / q^(2t), q = 2^m"""
    n, k, m = code.den, code.num, getattr(code, "m", 8)
    t = (n - k)//2
    q = 2.0**m
    lg = math.lgamma(n + 1) - math.lgamma(t + 1) - math.lgamma(n - t + 1) + t*math.log(q - 1) - 2*t*math.log(q)
    return min(1.0, math.exp(lg))

layer

layer(bits, min_frames=4, z=None)

The frame layer in bits: a Frames, or None. None when no marker repeats. Without a code that decodes inside, the Frames has the marker, period and scrambler as far as they go (code None). z: the z a code hypothesis must pass (default: rpps.math.prob.z_critical over the hypotheses tried)

Source code in src/rpps/analysis/framing/marked.py
def layer(bits, min_frames=4, z=None):
    """The frame layer in `bits`: a Frames, or None. None when no marker repeats. Without a code that
    decodes inside, the Frames has the marker, period and scrambler as far as they go (code None). z: the z a code
    hypothesis must pass (default: rpps.math.prob.z_critical over the hypotheses tried)"""
    from ...math.prob import z_critical
    bits = np.asarray(bits, dtype=np.uint8).reshape(-1)
    found = []
    for ref, m in markers().items():
        f = _find(bits, m, min_frames=min_frames)
        if f is not None:
            found.append((f[2], ref, f))
    if not found:
        return None
    _, ref, (period, first, count, inverted) = max(found, key=lambda t: t[0])
    L = len(markers()[ref])
    body = _bodies(bits, period, first, L, inverted)
    out = Frames(marker=ref, inverted=inverted, period=period, first=first, frames=count, scrambler=None,
                 interleaver=None, depth=None, code=None, ok=None, words=None, z=None)
    hyps = []
    for scr in _scramblers():
        try:
            d = body ^ _keystream(scr, body.shape[1])[None, :] if scr else body
        except Exception:
            continue
        need = z if z is not None else z_critical(max(1, 4*len(_rs_codes())*(1 + len(_scramblers()))))
        best, _ = _codes_in(d, need)
        if best is not None:
            hyps.append((best, scr, _structure(d)))
    if hyps:
        # A keystream that is itself a codeword (the CCSDS randomizer's 255-bit period over one 255-byte word) decodes
        # either way: then what the frames carry tells, the bits that stay the same frame to frame (a header's)
        (code, iname, I, ok, W, zz), scr, _ = max(hyps, key=lambda h: (h[0][3]/h[0][4], h[0][5], h[2]))
        out.scrambler, out.code, out.interleaver, out.depth, out.ok, out.words, out.z = scr, code, iname, I, ok, W, zz
    return out

payload

What decoded bits carry: known framings found at any bit offset, and a verdict on what is left

found = rp.analysis.framing.payload.signatures(bits)     # [Found("E1 G.704", period 512, offset 37, ...), ...]
v = rp.analysis.framing.payload.verdict(bits)            # "structured" / "scrambled" / "random-looking", and why

Each signature is a test whose chance rate is known, run at every bit offset, so a hit is judged against how often random bits would give it: E1 (ITU G.704) the frame alignment word x0011011 in time slot 0 of every other 256-bit frame (period 512) T1 (ITU G.704) one framing bit every 193, repeating the superframe pattern (100011011100 for D4/SF, a 001011 pattern every 4th bit for ESF): a column of the 193-bit grid far from random ATM cells (I.432) 53-byte cells whose fifth byte is the CRC-8 (x^8 + x^2 + x + 1) of the first four, xor 0x55 GFP (G.7041) a core header whose 16-bit cHEC is the CRC-16 (x^16 + x^12 + x^5 + 1) of its length field, the four bytes xored with 0xB6AB31E0, and the next header that length + 4 bytes on HDLC / PPP / LAPD every run of six ones a flag 01111110 (bit stuffing), not half of them IPv4 20-byte headers starting 0x45 whose ones-complement checksum holds CCSDS the attached sync marker 0x1ACFFC1D at a period MPEG-TS 0x47 every 188 bytes (204 with Reed-Solomon parity) fixed word any bits constant at a period (frame structure in general, a unique word after demodulation, bit errors and all), the period from the autocorrelation summed over its multiples

verdict combines them with the plain statistics: bias, byte distribution, autocorrelation, linear complexity over windows (an additive LFSR scrambler shows as complexity much below half a window), and how well zlib compresses.

Classes:

Name Description
Found

A signature found: name, period (bits, or None), offset (first bit), hits, expected (by chance), z, detail; a

Verdict

Result of verdict: kind ("structured", "scrambled", "random-looking"), why, signatures, bias (|mean - 1/2|*2),

Functions:

Name Description
e1

G.704 frame alignment: x0011011 every 512 bits (the first bit, Si, is free), in most frames (a framed stream's own

t1

A column of the 193-bit grid far from random: its bits repeat with the superframe (12 for SF, 4-bit steps in ESF)

atm

53-byte cells: HEC = CRC-8(x^8+x^2+x+1) of the first four header bytes, xor 0x55 (I.432), at some bit offset

gfp

GFP core headers: PLI (16) + cHEC = CRC-16 of PLI, the four bytes xored with 0xB6AB31E0; frames chained by PLI

hdlc

HDLC / PPP / LAPD: bit stuffing leaves no run of six ones but a flag's (01111110), where in random bits half of the

ipv4

20-byte IPv4 headers: 0x45, total length >= 20, ones-complement checksum of the ten words 0xFFFF

ccsds

The attached sync marker 0x1ACFFC1D at a period (any of periods, default every multiple of 8 up to 16384 found

mpeg_ts

0x47 every 188 or 204 bytes

fixed_word

Bits constant at a period, as a unique word after demodulation: Found with the period, the word (its longest run

signatures

Every signature that holds on the bits (see the module), strongest first (on the first max_bits)

verdict

structured (a signature, bias, uneven bytes, or zlib compresses it), scrambled (an LFSR: windows' linear

Found

Found(**kw)

A signature found: name, period (bits, or None), offset (first bit), hits, expected (by chance), z, detail; a word found (fixed_word): word (hex, first bit sent most significant), bits, mismatches (median, 99%) per frame

Source code in src/rpps/analysis/framing/payload.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

Verdict

Verdict(**kw)

Result of verdict: kind ("structured", "scrambled", "random-looking"), why, signatures, bias (|mean - 1/2|*2), byte_chi (z of the byte distribution, the worst of 8 offsets), lc (linear complexity over windows / their length), compress (zlib size / size)

Source code in src/rpps/analysis/framing/payload.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

e1

e1(bits, z_min=8.0, share=0.6)

G.704 frame alignment: x0011011 every 512 bits (the first bit, Si, is free), in most frames (a framed stream's own fixed fields can hold the word at a period by chance, in some of them)

Source code in src/rpps/analysis/framing/payload.py
def e1(bits, z_min=8.0, share=0.6):
    """G.704 frame alignment: x0011011 every 512 bits (the first bit, Si, is free), in most frames (a framed stream's own
    fixed fields can hold the word at a period by chance, in some of them)"""
    f = _periodic_word(bits, 0b0011011, 7, (512,), "E1 G.704 (FAS)", z_min)
    if f is None or f.hits < share*(len(bits)//512):
        return None
    return f

t1

t1(bits, z_min=8.0)

A column of the 193-bit grid far from random: its bits repeat with the superframe (12 for SF, 4-bit steps in ESF)

Source code in src/rpps/analysis/framing/payload.py
def t1(bits, z_min=8.0):
    """A column of the 193-bit grid far from random: its bits repeat with the superframe (12 for SF, 4-bit steps in ESF)"""
    b = np.asarray(bits, dtype=np.uint8)
    P = 193
    n = len(b)//P
    if n < 48:
        return None
    G = b[:n*P].reshape(n, P).astype(np.int8)
    best = None
    for L in (12, 24):
        m = n//L*L
        pats = G[:m].reshape(-1, L, P) # (superframes, L, columns)
        agree = np.mean(pats == pats[:1], axis=(0, 1)) # per column: how often a superframe repeats the first's pattern
        # biased or framed data repeats patterns too: a column stands out against the other columns, not against 1/2
        med, mad = np.median(agree), np.median(np.abs(agree - np.median(agree))) + 1e-9
        col = int(np.argmax(agree))
        z = (agree[col] - med)/(1.4826*mad)
        if z > z_min and agree[col] > 0.9 and (best is None or z > best.z):
            best = Found(name=f"T1 G.704 ({'SF' if L == 12 else 'ESF'} framing bit)", period=P, offset=col,
                         hits=int(agree[col]*m), expected=float(med*m), z=float(z),
                         detail=f"pattern {''.join(map(str, pats[0, :, col]))}")
    return best

atm

atm(bits, z_min=8.0)

53-byte cells: HEC = CRC-8(x^8+x^2+x+1) of the first four header bytes, xor 0x55 (I.432), at some bit offset

Source code in src/rpps/analysis/framing/payload.py
def atm(bits, z_min=8.0):
    """53-byte cells: HEC = CRC-8(x^8+x^2+x+1) of the first four header bytes, xor 0x55 (I.432), at some bit offset"""
    best = None
    for off in range(8):
        B = _bytes_at(bits, off)
        if len(B) < 53*20:
            continue
        n = len(B) - 4
        hdr = np.lib.stride_tricks.sliding_window_view(B, 5)[:n]
        ok = (_crc(hdr[:, :4], 0x07, 8) ^ 0x55) == hdr[:, 4]
        m = len(ok)//53*53
        cols = ok[:m].reshape(-1, 53).sum(axis=0)
        k = int(np.argmax(cols))
        z = _z(int(cols[k]), m//53, 1/256)
        if z > z_min and (best is None or z > best.z):
            best = Found(name="ATM cells (HEC)", period=424, offset=8*k + off, hits=int(cols[k]), expected=m/53/256,
                         z=float(z), detail=f"{100*cols[k]/(m//53):.0f}% of cells")
    return best

gfp

gfp(bits, z_min=8.0)

GFP core headers: PLI (16) + cHEC = CRC-16 of PLI, the four bytes xored with 0xB6AB31E0; frames chained by PLI

Source code in src/rpps/analysis/framing/payload.py
def gfp(bits, z_min=8.0):
    """GFP core headers: PLI (16) + cHEC = CRC-16 of PLI, the four bytes xored with 0xB6AB31E0; frames chained by PLI"""
    best = None
    for off in range(8):
        B = _bytes_at(bits, off).astype(np.int64)
        if len(B) < 256:
            continue
        w = np.lib.stride_tricks.sliding_window_view(B, 4)
        hdr = w ^ np.array([0xB6, 0xAB, 0x31, 0xE0])[None, :]
        ok = _crc(hdr[:, :2], 0x1021, 16) == ((hdr[:, 2] << 8) | hdr[:, 3])
        # chained: a header PLI + 4 bytes after another
        idx = np.flatnonzero(ok)
        pli = (hdr[idx, 0] << 8) | hdr[idx, 1]
        nxt = idx + pli + 4
        chain = np.isin(nxt, idx).sum()
        z = _z(int(chain), len(idx) + 1, 2.0**-16*max(1, len(idx)))
        if chain >= 4 and (best is None or chain > best.hits):
            best = Found(name="GFP (cHEC, chained)", period=None, offset=8*int(idx[0]) + off, hits=int(chain),
                         expected=len(w)*2.0**-16*len(idx)*2.0**-16, z=float(min(z, 1e6)), detail=f"{len(idx)} headers")
    return best if best is not None and best.hits >= 4 else None

hdlc

hdlc(bits, z_min=8.0)

HDLC / PPP / LAPD: bit stuffing leaves no run of six ones but a flag's (01111110), where in random bits half of the windows 0111111 go on with a 1

Source code in src/rpps/analysis/framing/payload.py
def hdlc(bits, z_min=8.0):
    """HDLC / PPP / LAPD: bit stuffing leaves no run of six ones but a flag's (01111110), where in random bits half of the
    windows 0111111 go on with a 1"""
    v8 = _window_bits(bits, 8)
    flags = int(np.sum(v8 == 0x7E))
    six = flags + int(np.sum(v8 == 0x7F)) # 0111111 then 0 (a flag) or 1
    if flags < 8:
        return None
    z = _z(flags, six, 0.5)
    if z > z_min:
        return Found(name="HDLC flags (bit-stuffed)", period=None, offset=int(np.argmax(v8 == 0x7E)), hits=flags,
                     expected=six/2, z=float(z), detail=f"{100*flags/max(six, 1):.0f}% of 0111111 runs end in a flag")
    return None

ipv4

ipv4(bits, z_min=8.0)

20-byte IPv4 headers: 0x45, total length >= 20, ones-complement checksum of the ten words 0xFFFF

Source code in src/rpps/analysis/framing/payload.py
def ipv4(bits, z_min=8.0):
    """20-byte IPv4 headers: 0x45, total length >= 20, ones-complement checksum of the ten words 0xFFFF"""
    best = None
    for off in range(8):
        B = _bytes_at(bits, off).astype(np.int64)
        if len(B) < 40:
            continue
        cand = np.flatnonzero(B[:-20] == 0x45)
        if not len(cand):
            continue
        H = B[cand[:, None] + np.arange(20)[None, :]]
        w = (H[:, 0::2] << 8) | H[:, 1::2]
        s = w.sum(axis=1)
        while np.any(s >> 16):
            s = (s & 0xFFFF) + (s >> 16)
        tl = w[:, 1]
        ok = (s == 0xFFFF) & (tl >= 20)
        h = int(ok.sum())
        z = _z(h, len(cand), 2.0**-16)
        if h >= 3 and z > z_min and (best is None or z > best.z):
            best = Found(name="IPv4 headers", period=None, offset=8*int(cand[ok][0]) + off, hits=h,
                         expected=len(cand)*2.0**-16, z=float(z), detail=f"{h} with valid checksums")
    return best

ccsds

ccsds(bits, z_min=8.0, periods=None)

The attached sync marker 0x1ACFFC1D at a period (any of periods, default every multiple of 8 up to 16384 found from its own hits)

Source code in src/rpps/analysis/framing/payload.py
def ccsds(bits, z_min=8.0, periods=None):
    """The attached sync marker 0x1ACFFC1D at a period (any of `periods`, default every multiple of 8 up to 16384 found
    from its own hits)"""
    v = _window_bits(bits, 32)
    idx = np.flatnonzero(v == 0x1ACFFC1D)
    if len(idx) < 3:
        return None
    d = np.diff(idx)
    P = int(np.bincount(d).argmax())
    h = int(np.sum(d == P))
    return Found(name="CCSDS ASM 0x1ACFFC1D", period=P, offset=int(idx[0]), hits=len(idx), expected=len(v)*2.0**-32,
                 z=float(_z(len(idx), len(v), 2.0**-32)), detail=f"{h} gaps of {P} bits")

mpeg_ts

mpeg_ts(bits, z_min=8.0)

0x47 every 188 or 204 bytes

Source code in src/rpps/analysis/framing/payload.py
def mpeg_ts(bits, z_min=8.0):
    """0x47 every 188 or 204 bytes"""
    best = None
    for P in (188*8, 204*8):
        f = _periodic_word(bits, 0x47, 8, (P,), f"MPEG-TS ({P//8}-byte packets)", z_min)
        if f is not None and (best is None or f.z > best.z):
            best = f
    return best

fixed_word

fixed_word(bits, max_period=16384, z_min=8.0, min_bits=8, agree=0.75, alpha=0.001, false_alarm=1e-06)

Bits constant at a period, as a unique word after demodulation: Found with the period, the word (its longest run of constant positions: word, a hex string sent first bit first, bits long, at offset), hits (every constant position), and in mismatches the bits each frame's copy differs by (median, 99th percentile)

The candidate periods sum the bits' autocorrelation over the multiples of each lag (frames.comb_lags), so a short word shows within a few dozen frames. A position is constant when at least agree of the frames hold the same bit there, which channel bit errors mostly leave it (an exact agreement they would not); one such position is common by chance over few frames, a stretch of them is not. The word is the stretch where they gather most (one position bit errors left short breaks it not), taken when its chance over every position and candidate looked at is under alpha. The whole stream inverted keeps its words (the word given is as received). errors in detail is what a delimit step could allow: a margin over the 99th percentile, no more than rpps.sync.word_errors at false_alarm over a period of positions.

Source code in src/rpps/analysis/framing/payload.py
def fixed_word(bits, max_period=16384, z_min=8.0, min_bits=8, agree=0.75, alpha=1e-3, false_alarm=1e-6):
    """Bits constant at a period, as a unique word after demodulation: Found with the period, the word (its longest run
    of constant positions: `word`, a hex string sent first bit first, `bits` long, at `offset`), `hits` (every constant
    position), and in `mismatches` the bits each frame's copy differs by (median, 99th percentile)

    The candidate periods sum the bits' autocorrelation over the multiples of each lag (frames.comb_lags), so a short
    word shows within a few dozen frames. A position is constant when at least `agree` of the frames hold the same bit
    there, which channel bit errors mostly leave it (an exact agreement they would not); one such position is common by
    chance over few frames, a stretch of them is not. The word is the stretch where they gather most (one position bit
    errors left short breaks it not), taken when its chance over every position and candidate looked at is under
    `alpha`. The whole stream inverted keeps its words (the
    word given is as received). `errors` in `detail` is what a delimit step could allow: a margin over the 99th
    percentile, no more than rpps.sync.word_errors at `false_alarm` over a period of positions."""
    from math import log, lgamma
    from ...math.prob import log_binom_half_cdf
    from ...sync.frame import word_errors
    from .frames import comb_lags, HALF_NORMAL_MEAN, HALF_NORMAL_VAR
    b = np.asarray(bits, dtype=np.uint8)
    n = len(b)
    if n < 4*64:
        return None
    x = 1 - 2*b.astype(np.float64)
    x = x - x.mean()
    v = max(float(np.mean(x**2)), 1e-12)
    F = np.fft.rfft(x, 1 << int(np.ceil(np.log2(2*n))))
    za = np.abs(np.fft.irfft(np.abs(F)**2)[:n])/(v*np.sqrt(n - np.arange(n)))
    cands = [L for L, _ in comb_lags(za, 8, max_period, mean=HALF_NORMAL_MEAN, var=HALF_NORMAL_VAR)]
    cands = sorted({c//d for c in cands for d in range(1, 7) if c % d == 0 and c//d >= 8}) # their submultiples too
    best = None
    for P in cands:
        m = n//P
        if m < 8:
            continue
        G = b[:m*P].reshape(m, P)
        ones = G.sum(axis=0, dtype=np.int64)
        k = int(np.ceil(agree*m)) # (frames that must agree)
        lp = min(0.0, log(2) + log_binom_half_cdf(m, m - k)) # log chance a random position agrees so, either way
        hot = np.maximum(ones, m - ones) >= k
        if hot.sum() < min_bits or lp >= 0:
            continue
        if lp >= log(WORD_AGREE):
            continue
        # The word: the segment (circular: it may straddle the fold) scoring most when a constant position counts for
        # it and any other against, as likely in a word as WORD_AGREE (a position its bit errors leave short of `agree`
        # breaks no word); then taken only if chance could not have made it, over every position and candidate
        h2 = np.concatenate((hot, hot))
        sc = np.where(h2, log(WORD_AGREE) - lp, log(1 - WORD_AGREE) - np.log1p(-np.exp(lp)))
        S = np.concatenate(([0.0], np.cumsum(sc)))
        lo = np.minimum.accumulate(S)
        at = np.arange(len(S))
        lo_at = np.maximum.accumulate(np.where(S <= lo, at, 0)) # (where the running minimum was last reached)
        gain = S - lo
        e = int(np.argmax(gain))
        s0 = int(lo_at[e])
        ln = min(e - s0, P)
        hits = int(h2[s0:s0 + ln].sum())
        chance = lgamma(ln + 1) - lgamma(hits + 1) - lgamma(ln - hits + 1) + hits*lp # (ln positions, hits of them constant)
        if hits < min_bits or hits < WORD_DENSITY*ln or chance > log(alpha) - log(P*len(cands)):
            continue
        s0 %= P
        cols = (s0 + np.arange(ln)) % P
        colz = np.abs(2*ones - m)/np.sqrt(m)
        z = float(min(np.sum(colz[cols])/np.sqrt(ln), 1e6)) # (Stouffer, over the word's positions)
        if z < z_min:
            continue
        word = 2*ones[cols] > m
        rows = G[:, cols] if s0 + ln <= P else b[s0:s0 + (m - 1)*P].reshape(m - 1, P)[:, :ln] # (frames whose copy is whole)
        mis = np.count_nonzero(rows != word[None, :], axis=1)
        med, p99 = float(np.median(mis)), float(np.percentile(mis, 99))
        allowed = word_errors(ln, false_alarm, P)
        errors = min(max(int(np.ceil(2*p99)), int(p99) + 2), allowed) if allowed >= 0 else -1
        value = int("".join("1" if w else "0" for w in word), 2)
        f = Found(name="fixed word at a period", period=P, offset=int(s0), hits=int(hits),
                     expected=float(P*len(cands)*np.exp(chance)), z=z, word=f"{value:#0{(ln + 3)//4 + 2}x}", bits=int(ln),
                     mismatches=(med, p99),
                     detail=f"{int(hits)} constant bit positions; a {ln}-bit word at {s0}, each frame's copy off by "
                            f"{med:.0f} bits (99%: {p99:.0f}); errors {errors} for a delimit step"
                            + ("" if allowed >= 0 else f" (too short to search {P} positions at {false_alarm:g})"))
        if best is None or chance < best[0]: # The word chance is least likely to make: a multiple of the period, over
            best = (chance, f)              # fewer frames, or a divisor, where other frames' data dilutes it, makes it less
    return None if best is None else best[1]

signatures

signatures(bits, z_min=8.0, tests=TESTS, max_bits=2000000)

Every signature that holds on the bits (see the module), strongest first (on the first max_bits)

Source code in src/rpps/analysis/framing/payload.py
def signatures(bits, z_min=8.0, tests=TESTS, max_bits=2_000_000):
    """Every signature that holds on the bits (see the module), strongest first (on the first `max_bits`)"""
    bits = np.asarray(bits, dtype=np.uint8)[:max_bits]
    out = [f for t in tests if (f := t(bits, z_min=z_min)) is not None]
    return sorted(out, key=lambda f: -f.z)

verdict

verdict(bits, window=512, z_min=8.0, frame=None, max_bits=2000000)

structured (a signature, bias, uneven bytes, or zlib compresses it), scrambled (an LFSR: windows' linear complexity well under half their length), or random-looking (encrypted, compressed, or under something not linear). frame: bits a frame (or frames (F, n) given): whole frames that repeat (idle fill) are set aside first, as they would make random data compress. On the first max_bits

Source code in src/rpps/analysis/framing/payload.py
def verdict(bits, window=512, z_min=8.0, frame=None, max_bits=2_000_000):
    """structured (a signature, bias, uneven bytes, or zlib compresses it), scrambled (an LFSR: windows' linear
    complexity well under half their length), or random-looking (encrypted, compressed, or under something not linear).
    frame: bits a frame (or frames (F, n) given): whole frames that repeat (idle fill) are set aside first, as they would
    make random data compress. On the first `max_bits`"""
    b = np.asarray(bits, dtype=np.uint8)
    repeats = 0
    if b.ndim == 2 or frame:
        F = b if b.ndim == 2 else b[:len(b)//frame*frame].reshape(-1, frame)
        _, first = np.unique(np.packbits(F, axis=1), axis=0, return_index=True)
        repeats = len(F) - len(first)
        b = F[np.sort(first)].reshape(-1)
    b = b[:max_bits]
    sig = signatures(b, z_min)
    bias = float(abs(2*b.mean() - 1))
    chi = 0.0
    for off in range(8):
        B = _bytes_at(b, off)
        if len(B) < 512:
            continue
        c = np.bincount(B, minlength=256)
        e = len(B)/256
        chi = max(chi, (float(((c - e)**2).sum()/e) - 255)/np.sqrt(510))
    lcs = [berlekamp_massey(b[a:a + window])[1]/window for a in range(0, len(b) - window + 1, window)][:16]
    lc = float(np.median(lcs)) if lcs else 0.5
    raw = np.packbits(b[:len(b)//8*8]).tobytes()
    comp = len(zlib.compress(raw, 9))/max(len(raw), 1)
    if sig:
        kind, why = "structured", "; ".join(str(s) for s in sig[:3])
    elif bias*np.sqrt(len(b)) > z_min or chi > z_min or comp < 0.95:
        kind, why = "structured", "uneven bits or bytes, or it compresses"
    elif lc < 0.4:
        kind, why = "scrambled", f"an LFSR of about {int(lc*window)} stages makes {window}-bit windows of it"
    else:
        kind, why = "random-looking", "no framing, even bits and bytes, full linear complexity, incompressible: " \
                                      "encrypted, compressed, or under a layer not found"
    rnd = None
    if kind == "random-looking": # The NIST SP 800-22 tests tell a cipher's output from most compressors' (randomness)
        from .randomness import test as _randomness
        rnd = _randomness(b)
        if rnd is not None and rnd.passed:
            why = (f"no framing, full linear complexity, and it passes the NIST SP 800-22 tests ({rnd.entropy:.2f} bits a "
                   "byte): as random as a cipher's output: encrypted or keyed (or a strong compressor's output)")
        elif rnd is not None:
            why = (f"no framing, full linear complexity, {rnd.entropy:.2f} bits a byte, but it fails "
                   f"{', '.join(rnd.failed)}: compressed, or a weak cipher or scrambler")
    return Verdict(kind=kind, why=why, signatures=sig, bias=bias, byte_chi=chi, lc=lc, compress=comp, repeats=repeats,
                   randomness=rnd)

randomness

Is a bit stream as random as a cipher's output? NIST SP 800-22 tests, and byte-level entropy

r = rp.analysis.framing.randomness.test(bits)
r.p                    # {test: P-value}: frequency, block_frequency, runs, serial_1, serial_2, approximate_entropy,
                       #   cusum_forward, cusum_backward, byte_chi2
r.passed, r.failed     # each against alpha / (number of P-values): a random stream fails one test in 100 runs
r.entropy              # Shannon entropy of the bytes [bits a byte], 8 at most
r.verdict              # "random" (indistinguishable from a cipher's output), "high entropy" (fails some test,
                       #   its bytes near uniform), or "low entropy"

The tests are NIST SP 800-22 rev. 1a (section 2), as the standard defines them, each checked against its worked examples: frequency (2.1), frequency within a block (2.2), runs (2.3), serial (2.11), approximate entropy (2.12) and cumulative sums (2.13), plus a chi-square test of the 256 byte values. Entropy alone cannot tell encrypted from compressed data, both are near 8 bits a byte; the tests that work best at it are block frequency, cumulative sums, serial and approximate entropy, and the byte chi-square (De Gaspari et al., "Reliable detection of compressed and encrypted data", 2022; HEDGE, 2019; Davies et al., "Comparison of entropy calculation methods for ransomware encrypted file identification", 2022). So a stream that passes every test is called "random": encrypted, keyed (a stream cipher), or a true random source; one with high byte entropy that fails some test is "high entropy": compressed, or a weak scrambler or cipher. A short stream cannot tell either well: the tests' input-size recommendations are kept (each test needs at least 100 bits, the block, serial and entropy lengths grow with n).

Classes:

Name Description
Result

test: p {test: P-value}, alpha (per test, after the multiple-test correction), passed, failed [test names],

Functions:

Name Description
frequency

2.1: the proportion of ones

block_frequency

2.2: the proportion of ones in M-bit blocks (M >= 20, M > n/100, fewer than 100 blocks)

runs

2.3: the number of runs of identical bits (0 when the frequency prerequisite fails)

serial

2.11: every overlapping m-bit pattern equally often (m < log2 n - 2). Returns (P-value 1, P-value 2)

approximate_entropy

2.12: the frequencies of overlapping m- and (m+1)-bit patterns (m < log2 n - 5)

cusum

2.13: the largest excursion of the random walk of +-1 (mode 0 forward, mode 1 backward)

byte_chi2

Chi-square of the 256 byte values against uniform (255 degrees of freedom)

byte_entropy

Shannon entropy of the bytes [bits a byte]

test

Every test on (the first max_bits of) the bits. A test fails below alpha / (number of P-values), so a random

Result

Result(**kw)

test: p {test: P-value}, alpha (per test, after the multiple-test correction), passed, failed [test names], entropy (bits a byte), n (bits tested), verdict

Source code in src/rpps/analysis/framing/randomness.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

frequency

frequency(eps)

2.1: the proportion of ones

Source code in src/rpps/analysis/framing/randomness.py
def frequency(eps):
    """2.1: the proportion of ones"""
    n = len(eps)
    s = abs(2*int(eps.sum()) - n)/sqrt(n)
    return erfc(s/sqrt(2.0))

block_frequency

block_frequency(eps, M=None)

2.2: the proportion of ones in M-bit blocks (M >= 20, M > n/100, fewer than 100 blocks)

Source code in src/rpps/analysis/framing/randomness.py
def block_frequency(eps, M=None):
    """2.2: the proportion of ones in M-bit blocks (M >= 20, M > n/100, fewer than 100 blocks)"""
    n = len(eps)
    M = M or max(20, n//99 + 1)
    N = n//M
    pi = eps[:N*M].reshape(N, M).mean(axis=1)
    chi = 4.0*M*float(((pi - 0.5)**2).sum())
    return igamc(N/2.0, chi/2.0)

runs

runs(eps)

2.3: the number of runs of identical bits (0 when the frequency prerequisite fails)

Source code in src/rpps/analysis/framing/randomness.py
def runs(eps):
    """2.3: the number of runs of identical bits (0 when the frequency prerequisite fails)"""
    n = len(eps)
    pi = float(eps.mean())
    if abs(pi - 0.5) >= 2.0/sqrt(n):
        return 0.0
    v = 1 + int(np.count_nonzero(eps[1:] != eps[:-1]))
    return erfc(abs(v - 2*n*pi*(1 - pi))/(2*sqrt(2*n)*pi*(1 - pi)))

serial

serial(eps, m=None)

2.11: every overlapping m-bit pattern equally often (m < log2 n - 2). Returns (P-value 1, P-value 2)

Source code in src/rpps/analysis/framing/randomness.py
def serial(eps, m=None):
    """2.11: every overlapping m-bit pattern equally often (m < log2 n - 2). Returns (P-value 1, P-value 2)"""
    n = len(eps)
    m = m or max(2, min(16, int(np.log2(n)) - 3))
    p0, p1, p2 = _psi2(eps, m), _psi2(eps, m - 1), _psi2(eps, m - 2)
    return igamc(2.0**(m - 2), (p0 - p1)/2.0), igamc(2.0**(m - 3), (p0 - 2*p1 + p2)/2.0)

approximate_entropy

approximate_entropy(eps, m=None)

2.12: the frequencies of overlapping m- and (m+1)-bit patterns (m < log2 n - 5)

Source code in src/rpps/analysis/framing/randomness.py
def approximate_entropy(eps, m=None):
    """2.12: the frequencies of overlapping m- and (m+1)-bit patterns (m < log2 n - 5)"""
    n = len(eps)
    m = m or max(2, min(14, int(np.log2(n)) - 6))
    def phi(k):
        c = _pattern_counts(eps, k)/n
        c = c[c > 0]
        return float((c*np.log(c)).sum())
    apen = phi(m) - phi(m + 1)
    return igamc(2.0**(m - 1), n*(log(2.0) - apen))

cusum

cusum(eps, backward=False)

2.13: the largest excursion of the random walk of +-1 (mode 0 forward, mode 1 backward)

Source code in src/rpps/analysis/framing/randomness.py
def cusum(eps, backward=False):
    """2.13: the largest excursion of the random walk of +-1 (mode 0 forward, mode 1 backward)"""
    n = len(eps)
    x = 2*eps.astype(np.int64) - 1
    z = int(np.abs(np.cumsum(x[::-1] if backward else x)).max())
    if z == 0:
        return 1.0
    sn = sqrt(n)
    s1 = sum(_phi((4*k + 1)*z/sn) - _phi((4*k - 1)*z/sn) for k in range(int((-n/z + 1)/4), int((n/z - 1)/4) + 1))
    s2 = sum(_phi((4*k + 3)*z/sn) - _phi((4*k + 1)*z/sn) for k in range(int((-n/z - 3)/4), int((n/z - 1)/4) + 1))
    return 1.0 - s1 + s2

byte_chi2

byte_chi2(eps)

Chi-square of the 256 byte values against uniform (255 degrees of freedom)

Source code in src/rpps/analysis/framing/randomness.py
def byte_chi2(eps):
    """Chi-square of the 256 byte values against uniform (255 degrees of freedom)"""
    B = np.packbits(eps[:len(eps)//8*8])
    c = np.bincount(B, minlength=256).astype(np.float64)
    e = len(B)/256.0
    return igamc(127.5, float(((c - e)**2).sum()/e)/2.0)

byte_entropy

byte_entropy(eps)

Shannon entropy of the bytes [bits a byte]

Source code in src/rpps/analysis/framing/randomness.py
def byte_entropy(eps):
    """Shannon entropy of the bytes [bits a byte]"""
    B = np.packbits(eps[:len(eps)//8*8])
    c = np.bincount(B, minlength=256).astype(np.float64)
    q = c[c > 0]/len(B)
    return float(-(q*np.log2(q)).sum())

test

test(bits, alpha=ALPHA, max_bits=1000000)

Every test on (the first max_bits of) the bits. A test fails below alpha / (number of P-values), so a random stream fails any one in about 1 run of 1/alpha. Fewer than 1000 bits: None (too short to say)

Source code in src/rpps/analysis/framing/randomness.py
def test(bits, alpha=ALPHA, max_bits=1_000_000):
    """Every test on (the first `max_bits` of) the bits. A test fails below alpha / (number of P-values), so a random
    stream fails any one in about 1 run of 1/alpha. Fewer than 1000 bits: None (too short to say)"""
    eps = np.asarray(bits, dtype=np.uint8)[:max_bits] & 1
    n = len(eps)
    if n < 1000:
        return None
    s1, s2 = serial(eps)
    p = {"frequency": frequency(eps), "block_frequency": block_frequency(eps), "runs": runs(eps), "serial_1": s1,
         "serial_2": s2, "approximate_entropy": approximate_entropy(eps), "cusum_forward": cusum(eps),
         "cusum_backward": cusum(eps, backward=True), "byte_chi2": byte_chi2(eps)}
    a = alpha/len(p)
    failed = [k for k, v in p.items() if v < a]
    H = byte_entropy(eps)
    full = 8.0 - 255.0/(2.0*(n//8)*log(2.0)) # What uniform bytes give from this many (the plug-in estimate falls short)
    verdict = "random" if not failed else ("high entropy" if H > full - 0.1 else "low entropy")
    return Result(p=p, alpha=a, passed=not failed, failed=failed, entropy=H, n=n, verdict=verdict)

telemetry

Residual-carrier PM telemetry (PCM/PSK/PM): the carrier, each subcarrier's data, its line code and its frames

t = rp.analysis.framing.telemetry.analyze(x, Fs)      # None when x has no residual carrier
print(t)                                      # the carrier, then a line per subcarrier
t.subcarriers[0].bits                         # data bits (line code removed), t.subcarriers[0].frame

Spacecraft telemetry and command links phase-modulate a carrier by less than 90 degrees, so part of the power stays in a carrier line (rpps.analysis.modulation.pm finds it, the index, and the phase phi(t) around it). The data rides in phi, on the carrier itself or on subcarriers: a subcarrier is BPSK-modulated (a square or sine wave whose sign is the data), at a rate set apart from the others. Per subcarrier: 1. its rate: the cyclic line at baseband (rpps.analysis.spectrum.cyclic), twice the spacing of its line pair (idle 1010 shows as lines at +-rate/2), and twice those (Manchester chips): the one whose integrate-and-dump symbols split cleanest, of those whose symbols don't come in equal pairs (twice the real rate) 2. BPSK symbols: the subcarrier's phase from its square (a squared-carrier reference smoothed over 20 ms), integrated over each symbol from the boundary that splits them best 3. the line code: Manchester (biphase-L: every pair of chips opposite) halves the rate; differential (NRZ-M/S) shows as frames that only line up after XOR with the previous bit 4. idle (alternating or constant bits), else frames: the period of the bits' autocorrelation, the fixed bits within it, and counters (a field that steps by one every frame)

Classes:

Name Description
TelemetryFrame

period (bits), fixed (bits constant over the frames), frames (how many folded), counters [(bit, width, step)]

Subcarrier

One subcarrier (or the data on the carrier itself: freq 0): freq, baud (symbol rate), quality (|mean|/std of the

Telemetry

pm: the rpps.analysis.modulation.pm result; subcarriers: [Subcarrier]

Functions:

Name Description
bpsk

(soft symbols, quality, Es/N0 dB) of BPSK at complex baseband z: phase from z^2, integrate and dump at the boundary

doubled

Whether chips come in equal pairs (at one alignment): symbols at twice the real rate

manchester

(fraction of chip pairs opposite, alignment, data bits (the first chip of each pair)) at the better alignment

idle

What idle pattern bits are (alternating, constant), or None

period

(lag, |r|, fixed fraction) of the frame period: of the autocorrelation peaks past min_lag standing out of the noise

counters

[(bit, width, step)] of fields in the folded frames F that step by +-1 a frame (in hold of the frames: a bit

frame

TelemetryFrame of the bits, or None when no period shows

line_code

(manchester, differential, data bits) of hard chips: Manchester when nearly every pair is opposite; differential

subcarrier

Subcarrier at fsc (Hz) of the phase phi: its rate, symbols, line code, and frames (see the module)

symmetry

(symmetry, sidebands): how well the spectrum mirrors about the carrier, 0..1 (sum(min)/sum(max) of the power

analyze

Telemetry of x (complex baseband, Fs), or None when rpps.analysis.modulation.pm finds no residual carrier

TelemetryFrame

TelemetryFrame(**kw)

period (bits), fixed (bits constant over the frames), frames (how many folded), counters [(bit, width, step)]

Source code in src/rpps/analysis/framing/telemetry.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

Subcarrier

Subcarrier(**kw)

One subcarrier (or the data on the carrier itself: freq 0): freq, baud (symbol rate), quality (|mean|/std of the soft symbols' size), esn0 (dB), manchester, differential, rate (data bits/s), idle (None, or what pattern), bits (data), frame (TelemetryFrame or None), why (when no symbols split)

Methods:

Name Description
head

Where, the modulation and line code, without the bits' content

Source code in src/rpps/analysis/framing/telemetry.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))
head
head()

Where, the modulation and line code, without the bits' content

Source code in src/rpps/analysis/framing/telemetry.py
def head(self):
    """Where, the modulation and line code, without the bits' content"""
    where = f"subcarrier {self.freq/1e3:.3f} kHz" if self.freq else "on the carrier"
    if not self.ok:
        return where
    code = ", ".join(c for c, on in (("Manchester", self.manchester), ("differential", self.differential)) if on) or "NRZ-L"
    return f"{where}: BPSK {self.baud:.6g} Bd, Es/N0 {self.esn0:.1f} dB; {code}: {self.rate:.6g} bit/s"

Telemetry

Telemetry(pm, subcarriers)

pm: the rpps.analysis.modulation.pm result; subcarriers: [Subcarrier]

Source code in src/rpps/analysis/framing/telemetry.py
def __init__(self, pm, subcarriers):
    self.pm, self.subcarriers = pm, subcarriers

bpsk

bpsk(z, fs, baud)

(soft symbols, quality, Es/N0 dB) of BPSK at complex baseband z: phase from z^2, integrate and dump at the boundary whose symbols split cleanest

Source code in src/rpps/analysis/framing/telemetry.py
def bpsk(z, fs, baud):
    """(soft symbols, quality, Es/N0 dB) of BPSK at complex baseband z: phase from z^2, integrate and dump at the boundary
    whose symbols split cleanest"""
    L = max(3, int(SMOOTH*fs)) | 1
    ref = np.convolve(z**2, np.hanning(L), mode="same")
    y = (z*np.exp(-0.5j*np.unwrap(np.angle(ref)))).real # Unwrapped: half a wrapped angle jumps by pi
    c = np.concatenate(([0.0], np.cumsum(y)))
    sps = fs/baud
    if sps < 2 or len(y) < 16*sps:
        return None, 0.0, None
    best = (None, -1.0)
    for tau in np.arange(0, sps, sps/32):
        b = tau + sps*np.arange(int((len(y) - tau)//sps) - 1)
        v = c[np.round(b + sps).astype(np.int64)] - c[np.round(b).astype(np.int64)]
        a = np.abs(v)
        q = float(a.mean()/(a.std() + 1e-12))
        if q > best[1]:
            best = (v, q)
    v, q = best
    a = np.abs(v)
    esn0 = float(10*np.log10(a.mean()**2/(2*a.var() + 1e-30)))
    return v, q, esn0

doubled

doubled(chips, hold=0.9)

Whether chips come in equal pairs (at one alignment): symbols at twice the real rate

Source code in src/rpps/analysis/framing/telemetry.py
def doubled(chips, hold=0.9):
    """Whether chips come in equal pairs (at one alignment): symbols at twice the real rate"""
    c = np.asarray(chips)
    for off in (0, 1):
        n = (len(c) - off)//2
        if n >= 16 and np.mean(c[off:off + 2*n:2] == c[off + 1:off + 2*n:2]) >= hold:
            return True
    return False

manchester

manchester(bits)

(fraction of chip pairs opposite, alignment, data bits (the first chip of each pair)) at the better alignment

Source code in src/rpps/analysis/framing/telemetry.py
def manchester(bits):
    """(fraction of chip pairs opposite, alignment, data bits (the first chip of each pair)) at the better alignment"""
    out = []
    for off in (0, 1):
        n = (len(bits) - off)//2
        p = bits[off:off + 2*n].reshape(n, 2)
        out.append((float(np.mean(p[:, 0] != p[:, 1])), off, p[:, 0].copy()))
    return max(out, key=lambda t: t[0])

idle

idle(bits)

What idle pattern bits are (alternating, constant), or None

Source code in src/rpps/analysis/framing/telemetry.py
def idle(bits):
    """What idle pattern bits are (alternating, constant), or None"""
    if len(bits) < 32:
        return None
    t = float(np.mean(bits[1:] != bits[:-1]))
    if t > 0.95:
        return "alternating 1010"
    if t < 0.05:
        return "constant"
    return None

period

period(bits, min_lag=MIN_FRAME, top=12)

(lag, |r|, fixed fraction) of the frame period: of the autocorrelation peaks past min_lag standing out of the noise (and above FRAME_R) and their divisors, the smallest whose fold leaves nearly the most bits fixed beyond chance (byte or word structure correlates at short lags but fixes nothing; a frame's sync and header do). (None, 0, 0) when none fixes MIN_FIXED of its bits

Source code in src/rpps/analysis/framing/telemetry.py
def period(bits, min_lag=MIN_FRAME, top=12):
    """(lag, |r|, fixed fraction) of the frame period: of the autocorrelation peaks past min_lag standing out of the noise
    (and above FRAME_R) and their divisors, the smallest whose fold leaves nearly the most bits fixed beyond chance (byte
    or word structure correlates at short lags but fixes nothing; a frame's sync and header do). (None, 0, 0) when none
    fixes MIN_FIXED of its bits"""
    s = np.asarray(bits, dtype=np.float64)*2 - 1
    s = s - s.mean()
    n = len(s)
    if n < 3*min_lag:
        return None, 0.0, 0.0
    S = np.fft.fft(s, 2*n)
    r = np.fft.ifft(np.abs(S)**2).real[:n]
    r = r/(n - np.arange(n))/max(r[0]/n, 1e-12)
    lags = np.arange(min_lag, n//3 + 1)
    if not len(lags):
        return None, 0.0, 0.0
    cands = []
    for L in lags[np.argsort(np.abs(r[lags]))[::-1][:top]]:
        if abs(r[L]) < max(FRAME_R, 6/np.sqrt(n - L)):
            break
        cands.append(int(L))
    # Divisors of the peaks too: the frame itself may correlate less than its multiples
    cands = sorted({L//d for L in cands for d in range(1, L//min_lag + 1) if L % d == 0 and L//d >= min_lag})
    if not cands:
        return None, 0.0, 0.0
    # Bits fixed beyond chance: over F frames a bit with ones-density p holds one value by chance p^F + (1-p)^F of the
    # time, so fewer frames (a multiple of the frame) fix more by chance; a multiple of the frame fixes no more beyond it.
    # The smallest period fixing nearly the most beyond chance is the frame
    p1 = float(np.mean(bits))
    cands = [L for L in cands if n//L >= 3]
    ex = {}
    for L in cands:
        F = n//L
        c = p1**F + (1 - p1)**F
        ex[L] = (_fixed(bits, L) - c)/(1 - c) if c < 1 else 0.0
    top_x = max(ex.values(), default=0.0)
    if top_x < MIN_FIXED:
        return None, 0.0, 0.0
    L = min(L for L in cands if ex[L] >= 0.9*top_x)
    return L, float(abs(r[L])), _fixed(bits, L)

counters

counters(F, widths=(16, 8), hold=0.9)

[(bit, width, step)] of fields in the folded frames F that step by +-1 a frame (in hold of the frames: a bit error breaks a step or two), the widest first

Source code in src/rpps/analysis/framing/telemetry.py
def counters(F, widths=(16, 8), hold=0.9):
    """[(bit, width, step)] of fields in the folded frames F that step by +-1 a frame (in `hold` of the frames: a bit
    error breaks a step or two), the widest first"""
    found = []
    if len(F) < 4:
        return found
    P = F.shape[1]
    for W in widths:
        pw = 1 << np.arange(W - 1, -1, -1)
        for o in range(P - W + 1):
            if any(o < b + w and b < o + W for b, w, _ in found):
                continue
            v = F[:, o:o + W] @ pw
            d = np.diff(v) % (1 << W)
            if np.mean(d == 1) >= hold:
                found.append((o, W, 1))
            elif np.mean(d == (1 << W) - 1) >= hold:
                found.append((o, W, -1))
    return found

frame

frame(bits)

TelemetryFrame of the bits, or None when no period shows

Source code in src/rpps/analysis/framing/telemetry.py
def frame(bits):
    """TelemetryFrame of the bits, or None when no period shows"""
    L, r, f = period(bits)
    if L is None:
        return None
    F = np.asarray(bits[:len(bits)//L*L], dtype=np.int64).reshape(-1, L)
    return TelemetryFrame(period=L, r=r, fixed=int(round(f*L)), frames=len(F), counters=counters(F))

line_code

line_code(chips)

(manchester, differential, data bits) of hard chips: Manchester when nearly every pair is opposite; differential when the XOR of neighbours frames with more bits fixed than the bits themselves

Source code in src/rpps/analysis/framing/telemetry.py
def line_code(chips):
    """(manchester, differential, data bits) of hard chips: Manchester when nearly every pair is opposite; differential
    when the XOR of neighbours frames with more bits fixed than the bits themselves"""
    frac, _, data = manchester(chips)
    man = frac >= MANCHESTER
    bits = data if man else chips
    diff = bits[1:] ^ bits[:-1]
    _, _, f0 = period(bits)
    _, _, f1 = period(diff)
    if f1 > f0:
        return man, True, diff
    return man, False, bits

subcarrier

subcarrier(phi, Fs, fsc, half=None, rates=None)

Subcarrier at fsc (Hz) of the phase phi: its rate, symbols, line code, and frames (see the module)

Source code in src/rpps/analysis/framing/telemetry.py
def subcarrier(phi, Fs, fsc, half=None, rates=None):
    """Subcarrier at fsc (Hz) of the phase phi: its rate, symbols, line code, and frames (see the module)"""
    from ..spectrum.cyclic import features
    bw0 = max(4*half, 12e3) if half else 16e3
    z0 = _pm.subcarrier(phi, Fs, fsc, bw0)
    D = max(1, int(Fs/(4*bw0)))
    cands = set(rates or [])
    if half:
        cands.add(2*half)
    try:
        f = features(z0[::D][:2**19], Fs/D)
        if f.baud:
            cands.update((f.baud, 2*f.baud))
    except Exception:
        pass
    best = None
    for baud in sorted(c for c in cands if c and c < fsc):
        bw = 4*baud
        D = max(1, int(Fs/(4*bw)))
        z = _pm.subcarrier(phi, Fs, fsc, bw)[::D]
        v, q, esn0 = bpsk(z, Fs/D, baud)
        if v is None or doubled(v > 0):
            continue
        if best is None or q > best[1]:
            best = (baud, q, esn0, v)
    if best is None or best[1] < SPLIT:
        return Subcarrier(freq=fsc, baud=best[0] if best else None, quality=best[1] if best else 0.0,
                          why="no rate whose BPSK symbols split into two levels" +
                              (f" (best {best[0]:.6g} Bd, {best[1]:.2f})" if best else ""))
    baud, q, esn0, v = best
    chips = (v > 0).astype(np.uint8)
    idl = idle(chips)
    if idl:
        return Subcarrier(freq=fsc, baud=baud, quality=q, esn0=esn0, manchester=False, differential=False, rate=baud,
                          idle=idl, bits=chips, frame=None)
    man, diff, bits = line_code(chips)
    rate = baud/2 if man else baud
    idl = idle(bits)
    return Subcarrier(freq=fsc, baud=baud, quality=q, esn0=esn0, manchester=man, differential=diff, rate=rate, idle=idl,
                      bits=bits, frame=None if idl else frame(bits))

symmetry

symmetry(x, Fs, carrier, nfft=4096, band=None, snr_db=None)

(symmetry, sidebands): how well the spectrum mirrors about the carrier, 0..1 (sum(min)/sum(max) of the power standing clear of the noise, ABOVE times its level per bin, at carrier +-f), and that power's ratio to the carrier's. Phase modulation by a real phase whose sign flips as often as not (data) has a real autocorrelation, so a spectrum symmetric about its carrier, with sidebands that hold power; a tone beside another signal mirrors badly, a tone in noise has no sidebands. A Hann window keeps a strong carrier's own leakage out of them. band (Hz, centred) and snr_db (the signal's SNR in it): x was filtered to that band, so the noise is band-limited, not the median bin (which sits in the filter's stopband: in-band noise alone would stand clear of it, and mirror). Its level is then the band's mean over 1 + SNR

Source code in src/rpps/analysis/framing/telemetry.py
def symmetry(x, Fs, carrier, nfft=4096, band=None, snr_db=None):
    """(symmetry, sidebands): how well the spectrum mirrors about the carrier, 0..1 (sum(min)/sum(max) of the power
    standing clear of the noise, ABOVE times its level per bin, at carrier +-f), and that power's ratio to the carrier's.
    Phase modulation by a real phase whose sign flips as often as not (data) has a real autocorrelation, so a spectrum
    symmetric about its carrier, with sidebands that hold power; a tone beside another signal mirrors badly, a tone in
    noise has no sidebands. A Hann window keeps a strong carrier's own leakage out of them.
    band (Hz, centred) and snr_db (the signal's SNR in it): x was filtered to that band, so the noise is band-limited, not
    the median bin (which sits in the filter's stopband: in-band noise alone would stand clear of it, and mirror). Its
    level is then the band's mean over 1 + SNR"""
    x = np.asarray(x)
    k = len(x)//nfft
    if k < 1:
        return 0.0, 0.0
    w = np.hanning(nfft).astype(np.float32)
    P = np.fft.fftshift(np.mean(np.abs(np.fft.fft(x[:k*nfft].reshape(k, nfft)*w, axis=1))**2, axis=0))
    if band and snr_db is not None:
        f = (np.arange(nfft) - nfft//2)*Fs/nfft
        nf = float(np.mean(P[np.abs(f) < band/2]))/(1 + 10**(snr_db/10))
    else:
        nf = np.median(P)
    P = np.where(P > ABOVE*nf, P - nf, 0.0) # Only what stands clear of the noise: noise bins alone mirror at random
    c = nfft//2 + int(round(carrier*nfft/Fs))
    m = min(c, nfft - 1 - c)
    if m < 8:
        return 0.0, 0.0
    lo, hi = P[c - m:c - 3][::-1], P[c + 4:c + m + 1] # Three bins either side left out: the carrier's main lobe
    n = min(len(lo), len(hi))
    lo, hi = lo[:n], hi[:n]
    side = float(np.sum(lo) + np.sum(hi))
    sym = float(np.sum(np.minimum(lo, hi))/max(np.sum(np.maximum(lo, hi)), 1e-30))
    return sym, side/max(float(np.sum(P[c - 3:c + 4])), 1e-30)

analyze

analyze(x, Fs, **kw)

Telemetry of x (complex baseband, Fs), or None when rpps.analysis.modulation.pm finds no residual carrier

Source code in src/rpps/analysis/framing/telemetry.py
def analyze(x, Fs, **kw):
    """Telemetry of x (complex baseband, Fs), or None when rpps.analysis.modulation.pm finds no residual carrier"""
    p = _pm.analyze(x, Fs, **kw)
    if p.carrier is None:
        return None
    phi = p.phase if p.phase is not None and len(p.phase) == len(x) else _pm.carrier_phase(x, Fs, p.carrier)[0]
    subs = []
    if p.rate:
        tau = p.tau or 0.0
        v = _pm.nrz(phi, Fs, p.rate, tau)
        a = np.abs(v)
        q = float(a.mean()/(a.std() + 1e-12))
        if q >= SPLIT:
            chips = (v > 0).astype(np.uint8)
            man, diff, bits = line_code(chips)
            idl = idle(bits)
            subs.append(Subcarrier(freq=0.0, baud=p.rate, quality=q, esn0=float(10*np.log10(a.mean()**2/(2*a.var()))),
                                   manchester=man, differential=diff, rate=p.rate/2 if man else p.rate, idle=idl,
                                   bits=bits, frame=None if idl else frame(bits)))
    for fsc, half in p.subcarriers:
        if fsc < Fs/2:
            subs.append(subcarrier(phi, Fs, fsc, half))
    return Telemetry(p, subs)

rpps.analysis.identify

Blind FEC identification

Takes hard bits (what a demodulator produced, with an unknown bit mapping, rotation and alignment) and asks which code they are most likely carrying. Every test is a parity relation that holds on codewords but is a coin flip on anything else, so a hypothesis is scored by how far its relation sits from 50% (a deviance z-score), then corrected for how many hypotheses were tried.

conv: rate 1/n feed-forward convolutional codes. For generators g_a, g_b: (c_a * g_b) xor (c_b * g_a) = 0 block: any linear block code / LDPC given its parity-check matrix H, at every word alignment scramblers: an additive scrambler of period T just adds a fixed pattern to the relation, so folding the relation by T (with periods) finds it. Self-synchronising scramblers are undone with descramblers first.

The tests are about structure, not about being right: a noisy channel weakens them, and the verdict is None when nothing stands out.

rpps.analysis.modulation

What carries the symbols (see rpps.analysis)

How low an Es/N0 cumulants.classify (and rpps.sync.detect) names each constellation at: tools/modclass_bench.py, its findings in its docstring, kept by tests/unit/analysis/modulation/test_modclass_threshold.py

Modules:

Name Description
cancel

How much of a signal we are locked to: regenerate it from its symbols, subtract it, and measure what is left

cpm

GMSK and SOQPSK: binary continuous-phase modulation demodulated by a sequence detector, blind to timing and carrier

cumulants

Higher-order cumulants of symbols: which constellation, blind to Gaussian noise and to the carrier phase

fsk

Frequency-shift keying and continuous-phase modulation from the instantaneous frequency: tones, rate, index, pulse

impairments

What else than noise is in locked symbols: amplifier compression (AM/AM, AM/PM), IQ imbalance, phase noise, neighbours

pm

Phase modulation with a residual carrier (PCM/PM, telemetry and ranging): carrier, index, the data on the carrier, tones

quality

Whether hard decisions from locked symbols can be trusted for blind tests (gate); the Es/N0 it uses is

cancel

How much of a signal we are locked to: regenerate it from its symbols, subtract it, and measure what is left

c = rp.analysis.modulation.cancel.cancel(x, Fs, symbols, sps, tau)   # x: samples; symbols: decided (or re-encoded) symbols,
                                                          # symbol k at sample tau + k sps
print(c)       # e.g. "excess 0.2 dB over the floor: SNR 18.3 dB after cancelling, 18.5 dB the floor allows"
c.residual     # x without the signal: run rp.analysis.survey / cyclic.features on it for what was underneath

The paired-carrier (PCMA) receiver's step, used as a measurement. A linear modulation is x[n] = sum_k s_k h(n - tau - k sps) + noise. With the symbols known (decisions, or better the decoded bits encoded again), the pulse h, gain, phase, timing, a fractional rate and any linear distortion are one least-squares fit: h is a combination of band-limited kernels half a symbol apart (span symbols each side), fitted again every block symbols so slow phase, gain and timing drift are followed. What the fit cannot take off is noise plus whatever our model of the signal misses: phase noise faster than a block, non-linearity, symbol decisions that are wrong, interference, a slip.

The measure is the residual's density in the signal's band against the noise floor outside it (the capture must be wider than the signal): excess_db 0 means everything left is thermal noise, and the SNR after cancelling equals the SNR the floor allows; every dB of excess is signal we are not locked to. profile is the excess block by block (where lock is lost or a burst of interference arrives). The residual is also how a second, weaker signal under the first is found: the strong one taken off, survey the rest.

Classes:

Name Description
Cancelled

Result of cancel. residual: x less the regenerated signal; model: the regenerated signal; excess_db: residual

Functions:

Name Description
kernel

Band-limited kernel (|f| < 1/sps cycles a sample, the band of a pulse with roll-off up to 1) of half-symbol

regressors

The basis signals: column j (of 4 span + 1) is sum_k s_k kernel(n - tau - k sps - j' sps/2), j' = j - 2 span.

decide

Nearest constellation point of each symbol

cancel

Regenerate the signal from its symbols and take it off x (see the module). symbols: complex symbol values, symbol k

align

Where the symbols are in x: tau (samples) of symbol 0, from the cross-correlation of x with the symbols shaped by

Cancelled

Cancelled(**kw)

Result of cancel. residual: x less the regenerated signal; model: the regenerated signal; excess_db: residual density in band over the floor outside (None without an outside); snr_cancel_db: signal over residual in band; snr_floor_db: signal over the floor in band (what perfect lock leaves); profile: excess per block (dB); bandwidth: the band (Hz) measured; cfo: the frequency (Hz) taken off before fitting; explained: fraction of x's in-band power the model takes off

Attributes:

Name Type Description
loss_db

SNR lost to what we are not locked to

Source code in src/rpps/analysis/modulation/cancel.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))
loss_db property
loss_db

SNR lost to what we are not locked to

kernel

kernel(t, sps, span)

Band-limited kernel (|f| < 1/sps cycles a sample, the band of a pulse with roll-off up to 1) of half-symbol spacing, Hann-tapered to +-span symbols: t in samples

Source code in src/rpps/analysis/modulation/cancel.py
def kernel(t, sps, span):
    """Band-limited kernel (|f| < 1/sps cycles a sample, the band of a pulse with roll-off up to 1) of half-symbol
    spacing, Hann-tapered to +-span symbols: t in samples"""
    u = t/(sps/2)
    w = np.where(np.abs(t) < span*sps, 0.5 + 0.5*np.cos(np.pi*t/(span*sps)), 0.0)
    return np.sinc(u)*w

regressors

regressors(n, symbols, sps, tau, span=6)

The basis signals: column j (of 4 span + 1) is sum_k s_k kernel(n - tau - k sps - j' sps/2), j' = j - 2 span. Returns an n x (4 span + 1) complex array

Source code in src/rpps/analysis/modulation/cancel.py
def regressors(n, symbols, sps, tau, span=6):
    """The basis signals: column j (of 4 span + 1) is sum_k s_k kernel(n - tau - k sps - j' sps/2), j' = j - 2 span.
    Returns an n x (4 span + 1) complex array"""
    s = np.asarray(symbols, dtype=np.complex128)
    J = np.arange(-2*span, 2*span + 1)
    t = np.arange(n, dtype=np.float64) - tau
    k0 = np.floor(t/sps).astype(np.int64)
    u = t - k0*sps # where in its symbol each sample is
    A = np.zeros((n, len(J)), dtype=np.complex128)
    reach = int(np.ceil(1.5*span + 1)) # symbols each side a sample hears: kernel span + its offset
    off = J*sps/2
    # The kernels depend on a sample only through its place u in its symbol: tabulate over u (linear interpolation
    # between 1024 points a symbol: -80 dB) instead of evaluating them for every sample
    G = 1024
    grid = np.arange(G + 1)/G*sps
    g = u/sps*G
    i = np.minimum(g.astype(np.int64), G - 1)
    w = (g - i)[:, None]
    for d in range(-reach, reach + 1):
        k = k0 + d
        ok = (k >= 0) & (k < len(s))
        if not ok.any():
            continue
        T = kernel(grid[:, None] - d*sps - off[None, :], sps, span) # (G + 1) x columns
        io, wo = i[ok], w[ok]
        A[ok] += s[k[ok], None]*(T[io]*(1 - wo) + T[io + 1]*wo)
    return A

decide

decide(y, points)

Nearest constellation point of each symbol

Source code in src/rpps/analysis/modulation/cancel.py
def decide(y, points):
    """Nearest constellation point of each symbol"""
    pts = np.asarray(points, dtype=np.complex128)
    return pts[np.argmin(np.abs(np.asarray(y)[:, None] - pts[None, :]), axis=1)]

cancel

cancel(x, Fs, symbols, sps, tau=0.0, span=6, block=256, widely=False, cfo=None, nfft=1024)

Regenerate the signal from its symbols and take it off x (see the module). symbols: complex symbol values, symbol k at sample tau + k sps (sps may be fractional; a slow clock drift is followed by the block fits). block: symbols per fit. widely: fit the conjugate too (IQ imbalance). cfo: Hz to take off first (None: estimated from the fits)

Source code in src/rpps/analysis/modulation/cancel.py
def cancel(x, Fs, symbols, sps, tau=0.0, span=6, block=256, widely=False, cfo=None, nfft=1024):
    """Regenerate the signal from its symbols and take it off x (see the module). symbols: complex symbol values, symbol k
    at sample tau + k sps (sps may be fractional; a slow clock drift is followed by the block fits). block: symbols per
    fit. widely: fit the conjugate too (IQ imbalance). cfo: Hz to take off first (None: estimated from the fits)"""
    x = np.asarray(x, dtype=np.complex128)
    n = len(x)
    A = regressors(n, symbols, sps, tau, span)
    block_n = max(int(block*sps), 8*A.shape[1])
    t = np.arange(n)
    f0 = 0.0
    if cfo is None:
        # The fits' phase from block to block is the residual frequency: take it off and fit again
        _, coefs = _fit(x, A, block_n, widely)
        if len(coefs) > 2:
            ph = np.unwrap([np.angle(np.vdot(coefs[0], c)) for c in coefs])
            centres = (np.arange(len(coefs)) + 0.5)*block_n
            f0 = float(np.polyfit(centres, ph, 1)[0]/(2*np.pi)*Fs)
    else:
        f0 = float(cfo)
    rot = np.exp(-2j*np.pi*f0/Fs*t)
    model, coefs = _fit(x*rot, A, block_n, widely)
    model = model*np.conj(rot)
    r = x - model
    P = A.shape[1]*(2 if widely else 1)
    dof = block_n/max(block_n - P, 1) # each fit takes P of the block's noise dimensions with it
    # In-band against out-of-band densities
    nfft = int(min(nfft, 2**int(np.log2(max(n//8, 16)))))
    Px, Pr, Pm = _psd(x, nfft), _psd(r, nfft)*dof, _psd(model, nfft)
    floor = spectrum_floor(Px)
    band = Pm > 2*floor # where the signal stands over the floor
    out = ~band & (Px < 3*floor)
    bw = Fs*np.count_nonzero(band)/nfft
    sig = np.sum(Pm[band])
    res = np.sum(Pr[band])
    explained = float(1 - res/max(np.sum(Px[band]), 1e-300))
    snr_c = 10*np.log10(max(sig, 1e-300)/max(res, 1e-300))
    if np.count_nonzero(out) >= nfft//16:
        N0 = float(np.median(Px[out])) # the median: skirts of the signal or another one nearby stay out of it
        excess = 10*np.log10(max(np.mean(Pr[band]), 1e-300)/N0)
        snr_f = 10*np.log10(max(sig, 1e-300)/(N0*np.count_nonzero(band)))
        # Block by block: the residual's power over what the floor gives that band, every `block` symbols
        frac = np.count_nonzero(band)/nfft
        prof = []
        for a in range(0, n - block_n + 1, block_n):
            seg = r[a:a + block_n]
            # The residual is not only in band; filter it to the band through the PSD bins
            S = np.fft.fftshift(np.fft.fft(seg*np.hanning(len(seg))))
            k = np.linspace(0, nfft, len(S), endpoint=False).astype(int)
            pin = np.sum(np.abs(S[band[k]])**2)/np.sum(np.hanning(len(seg))**2)
            prof.append(10*np.log10(max(pin*dof, 1e-300)/(N0*frac*len(seg))))
    else:
        excess, snr_f, prof = None, None, []
    return Cancelled(residual=r.astype(np.complex64), model=model.astype(np.complex64), excess_db=excess,
                     snr_cancel_db=float(snr_c), snr_floor_db=snr_f, profile=np.asarray(prof), bandwidth=bw, cfo=f0,
                     explained=explained, taps=A.shape[1])

align

align(x, symbols, sps, search=None, span=6)

Where the symbols are in x: tau (samples) of symbol 0, from the cross-correlation of x with the symbols shaped by the basis's centre kernel. Only the symbol offset needs to be right: the fitted pulse takes up any timing error within a few symbols. search: the samples tau may be in (default the first quarter of x)

Source code in src/rpps/analysis/modulation/cancel.py
def align(x, symbols, sps, search=None, span=6):
    """Where the symbols are in x: tau (samples) of symbol 0, from the cross-correlation of x with the symbols shaped by
    the basis's centre kernel. Only the symbol offset needs to be right: the fitted pulse takes up any timing error
    within a few symbols. search: the samples tau may be in (default the first quarter of x)"""
    x = np.asarray(x, dtype=np.complex128)
    n = len(x)
    s = np.asarray(symbols, dtype=np.complex128)
    m = min(len(s), 2000)
    probe = regressors(int(m*sps) + int(2*span*sps), s[:m], sps, 0.0, span)[:, 2*span]
    N = 1 << int(np.ceil(np.log2(n + len(probe))))
    c = np.fft.ifft(np.fft.fft(x, N)*np.conj(np.fft.fft(probe, N)))
    hi = n//4 if search is None else search
    cand = np.concatenate((c[:hi], c[N - int(2*sps):])) # tau a little negative too (symbol 0 before x starts)
    lags = np.concatenate((np.arange(hi), np.arange(-int(2*sps), 0)))
    return float(lags[int(np.argmax(np.abs(cand)))])

cpm

GMSK and SOQPSK: binary continuous-phase modulation demodulated by a sequence detector, blind to timing and carrier

r = rp.analysis.modulation.cpm.demodulate(x, Fs, "gmsk_0.3")          # or "soqpsk_tg", "soqpsk_mil", "msk", "gmsk_0.5" ...
r.bits, r.baud, r.cfo, r.match                              # bits, symbol rate, carrier offset (Hz), fit 0..1
best = rp.analysis.modulation.cpm.identify(x, Fs)                      # [(match, scheme)], best first: which pulse it is
y = rp.analysis.modulation.cpm.modulate(bits, "soqpsk_tg", sps=8)     # the reference transmitter (tests, regeneration)

A CPM signal is exp(j theta(t)), theta(t) = 2 pi h sum_k alpha_k q(t - kT), with q the integral of the frequency pulse g (q(LT) = 1/2). Here h = 1/2 throughout (MSK, GMSK, SOQPSK), and the symbols alpha_k come from the bits: msk / gmsk alpha_k = 2 b_k - 1; g rectangular over 1 symbol (MSK) or Gaussian (BT 0.25 / 0.3 / 0.5, L 4 / 4 / 3) gmsk_diff GSM's differential precoding first: alpha_k = 1 - 2 (b_k xor b_{k-1}) (3GPP TS 45.004) soqpsk_mil ternary alpha_k = (-1)^(k+1) a_{k-1} (a_k - a_{k-2}) / 2, a = 2b - 1 (MIL-STD-188-181), g rectangular soqpsk_tg the same precoder; g the windowed spectral raised cosine of IRIG 106 (rho 0.7, B 1.25, T1 1.5, T2 0.5: 8 symbols long) SOQPSK's precoder gives the same symbols for the bits, their complement, and (with the other parity) the bits with every other one inverted: the signal can't tell these four apart, so SOQPSK bits come out up to that (a frame word settles it).

The detector is a Viterbi search with per-survivor processing (Raheli, Polydoros & Tzou 1995): a trellis state is the last S bits; each survivor carries the older symbols of the pulse's tail, its settled phase, and its own second-order carrier loop (the error is the angle of its branch correlation), so a carrier offset left by the coarse estimate, a pulse longer than S symbols (SOQPSK-TG's 8) and the phase all need no states of their own. Branch metric: Re sum r(t) conj(s(t)) over the symbol at ns samples a symbol. match is the best path's metric over sqrt(energy of r x energy of s): 1 for a clean signal of exactly this scheme; a wrong pulse, rate or timing scores lower, which is how identify tells the schemes apart.

Front end (what demodulate does before the detector): lines for h = 1/2, x^2 has lines at 2 fc +- baud/2 (MSK's two tones squared; weaker under a Gaussian or TG pulse): the strongest pair gives the symbol rate (their spacing) and the carrier (their middle, halved) rate without the lines, rpps.analysis.modulation.fsk.analyze's (or baud given: then the pair is looked for baud apart) carrier without the lines, the median instantaneous frequency timing the detector run at every 1/ns of a symbol on a stretch; the best metric wins. On a long record, stretches across it are timed too and a line through them corrects the symbol clock (ppm) Limits: h = 1/2 binary CPM only; the coarse carrier must leave under about baud/50 for the loop (loop) to pull in; the bits of a spectrally inverted signal come out inverted.

Classes:

Name Description
CPM

Result of demodulate: bits, scheme, baud (Hz, clock-corrected), cfo (Hz), tau (s: the first symbol's start),

Functions:

Name Description
frequency_pulse

The frequency pulse g of a scheme at sps samples a symbol, L*sps samples, sum(g)/sps = 1/2 (q(LT) = 1/2)

phase_table

Q (L, ns): 2 pi h q((j + n/ns) T) at sample n of a symbol for the symbol j symbols back (q from g at ns samples:

alpha_table

atab (2, 8) int8: alpha_k for (k's parity, b_k + 2 b_{k-1} + 4 b_{k-2})

alphas

The CPM symbols of bits (the bits before the first are 0)

modulate

Complex baseband of bits at sps samples a symbol (unit amplitude, phase 0 at the start)

mlse

Bits of r: samples at ns a symbol, sample 0 at a symbol's start, carrier near 0. S: trellis state bits (default

square_lines

The x^2 line pair of an h = 1/2 CPM signal (see the module): (baud, cfo, ratio), ratio the weaker line over the

front

(baud, cfo, lines) of an h = 1/2 CPM signal: the x^2 pair, else fsk.analyze's rate and the median frequency

demodulate

Bits of a GMSK / SOQPSK signal x (complex baseband at Fs, a channel around it; see the module). baud: the symbol

identify

Which scheme fits x best: [(match, scheme)] best first, each timed on its own over n symbols

CPM

CPM(**kw)

Result of demodulate: bits, scheme, baud (Hz, clock-corrected), cfo (Hz), tau (s: the first symbol's start), match (0..1), lines (the weaker x^2 line over the spectrum's median; 0 when rate and carrier came from the instantaneous frequency instead)

Source code in src/rpps/analysis/modulation/cpm.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

frequency_pulse

frequency_pulse(name, sps)

The frequency pulse g of a scheme at sps samples a symbol, L*sps samples, sum(g)/sps = 1/2 (q(LT) = 1/2)

Source code in src/rpps/analysis/modulation/cpm.py
def frequency_pulse(name, sps):
    """The frequency pulse g of a scheme at sps samples a symbol, L*sps samples, sum(g)/sps = 1/2 (q(LT) = 1/2)"""
    kind, p, L, _ = SCHEMES[name]
    n = L*sps
    t = (np.arange(n) + 0.5)/sps - L/2 # symbol times, centred on the pulse
    if kind == "rect":
        g = np.ones(n)
    elif kind == "gaussian":
        # A rectangle of one symbol through a Gaussian filter of bandwidth-time BT
        s = np.sqrt(np.log(2))/(2*np.pi*p)
        from math import erf
        e = np.vectorize(erf)
        g = 0.5*(e((t + 0.5)/(np.sqrt(2)*s)) - e((t - 0.5)/(np.sqrt(2)*s)))
    elif kind == "tg":
        rho, B, T1, T2 = 0.7, 1.25, 1.5, 0.5
        u = t/2 # t / 2Ts
        x = rho*B*u
        den = 1 - 4*x**2
        with np.errstate(divide="ignore", invalid="ignore"):
            a = np.where(np.abs(den) < 1e-9, np.pi/4, np.cos(np.pi*x)/np.where(den == 0, 1, den))
            b = np.where(u == 0, 1.0, np.sin(np.pi*B*u)/(np.pi*B*np.where(u == 0, 1, u)))
        au = np.abs(u)
        w = np.where(au < T1, 1.0, np.where(au <= T1 + T2, 0.5 + 0.5*np.cos(np.pi/T2*(au - T1)), 0.0))
        g = a*b*w
    else:
        raise ValueError(kind)
    return g/g.sum()*sps/2

phase_table

phase_table(name, ns)

Q (L, ns): 2 pi h q((j + n/ns) T) at sample n of a symbol for the symbol j symbols back (q from g at ns samples: q at the sample's end)

Source code in src/rpps/analysis/modulation/cpm.py
def phase_table(name, ns):
    """Q (L, ns): 2 pi h q((j + n/ns) T) at sample n of a symbol for the symbol j symbols back (q from g at ns samples:
    q at the sample's end)"""
    g = frequency_pulse(name, ns)
    q = np.cumsum(g)/ns # q at the end of each sample, q[-1] = 1/2
    L = SCHEMES[name][2]
    return (2*np.pi*H*q).reshape(L, ns)

alpha_table

alpha_table(name)

atab (2, 8) int8: alpha_k for (k's parity, b_k + 2 b_{k-1} + 4 b_{k-2})

Source code in src/rpps/analysis/modulation/cpm.py
def alpha_table(name):
    """atab (2, 8) int8: alpha_k for (k's parity, b_k + 2 b_{k-1} + 4 b_{k-2})"""
    pre = SCHEMES[name][3]
    t = np.zeros((2, 8), np.int8)
    for par in range(2):
        for i in range(8):
            b0, b1, b2 = i & 1, i >> 1 & 1, i >> 2 & 1
            if pre == "none":
                a = 2*b0 - 1
            elif pre == "diff":
                a = 1 - 2*(b0 ^ b1)
            else: # soqpsk: (-1)^(k+1) a_{k-1} (a_k - a_{k-2}) / 2
                a0, a1, a2 = 2*b0 - 1, 2*b1 - 1, 2*b2 - 1
                a = (-1)**(par + 1)*a1*(a0 - a2)//2
            t[par, i] = a
    return t

alphas

alphas(bits, name, parity=0)

The CPM symbols of bits (the bits before the first are 0)

Source code in src/rpps/analysis/modulation/cpm.py
def alphas(bits, name, parity=0):
    """The CPM symbols of bits (the bits before the first are 0)"""
    b = np.concatenate(([0, 0], np.asarray(bits, dtype=np.int64) & 1))
    idx = b[2:] + 2*b[1:-1] + 4*b[:-2]
    par = (np.arange(len(idx)) + parity) & 1
    return alpha_table(name)[par, idx].astype(np.float64)

modulate

modulate(bits, name, sps=8, parity=0)

Complex baseband of bits at sps samples a symbol (unit amplitude, phase 0 at the start)

Source code in src/rpps/analysis/modulation/cpm.py
def modulate(bits, name, sps=8, parity=0):
    """Complex baseband of bits at sps samples a symbol (unit amplitude, phase 0 at the start)"""
    a = alphas(bits, name, parity)
    g = frequency_pulse(name, sps)
    f = np.zeros(len(a)*sps + len(g))
    f[:len(a)*sps:sps] = a
    f = np.convolve(f, g)[:len(a)*sps] # frequency, in symbols' units (each symbol integrates to alpha/2)
    theta = 2*np.pi*H*np.cumsum(f)/sps
    return np.exp(1j*theta)

mlse

mlse(r, name, ns, parity=0, S=None, loop=(0.08, 0.002))

Bits of r: samples at ns a symbol, sample 0 at a symbol's start, carrier near 0. S: trellis state bits (default 3; at least 2, the SOQPSK precoder's memory). loop: (k1, k2) of each survivor's carrier loop, per symbol. Returns (bits, match)

Source code in src/rpps/analysis/modulation/cpm.py
def mlse(r, name, ns, parity=0, S=None, loop=(0.08, 0.002)):
    """Bits of r: samples at ns a symbol, sample 0 at a symbol's start, carrier near 0. S: trellis state bits (default
    3; at least 2, the SOQPSK precoder's memory). loop: (k1, k2) of each survivor's carrier loop, per symbol.
    Returns (bits, match)"""
    r = np.ascontiguousarray(r, dtype=np.complex128)
    Q = np.ascontiguousarray(phase_table(name, ns))
    atab = np.ascontiguousarray(alpha_table(name))
    S = (3 if SCHEMES[name][2] <= 4 else 5) if S is None else max(2, int(S))
    n = len(r)//ns
    if n < 1:
        raise ValueError("fewer samples than a symbol")
    r = r[:n*ns]
    nat = _accel.native
    if nat is not None:
        bits, best = nat.cpm_psp(r, Q, atab, S, int(parity), float(loop[0]), float(loop[1]))
        bits = np.asarray(bits)
    else:
        bits, best = _mlse_python(r, Q, atab, S, int(parity), loop)
    match = best/np.sqrt(np.sum(np.abs(r)**2)*n*ns)
    return bits, float(match)

square_lines

square_lines(x, Fs, baud=None, min_ratio=10.0, top=12)

The x^2 line pair of an h = 1/2 CPM signal (see the module): (baud, cfo, ratio), ratio the weaker line over the spectrum's median (power); None when there is no pair over min_ratio. baud given: the pair is looked for that far apart

Source code in src/rpps/analysis/modulation/cpm.py
def square_lines(x, Fs, baud=None, min_ratio=10.0, top=12):
    """The x^2 line pair of an h = 1/2 CPM signal (see the module): (baud, cfo, ratio), ratio the weaker line over the
    spectrum's median (power); None when there is no pair over min_ratio. baud given: the pair is looked for that far
    apart"""
    x = np.asarray(x, dtype=np.complex128)
    nfft = min(1 << int(np.ceil(np.log2(max(len(x), 1024)))), 1 << 22)
    y = x[:nfft]**2
    P = np.abs(np.fft.fft(y*np.hanning(len(y)), nfft))**2
    f = np.fft.fftfreq(nfft, 1/Fs)
    med = float(np.median(P))
    if baud is not None:
        d = int(round(baud/(Fs/nfft)))
        Pm = np.minimum(P, np.roll(P, -d)) # the weaker of the lines at f and f + baud
        k = int(np.argmax(Pm))
        if Pm[k] < min_ratio*med:
            return None
        f1, f2 = _peak(P, f, k), _peak(P, f, (k + d) % nfft)
        return float(baud), float((f1 + f2)/4), float(Pm[k]/med)
    # every local maximum over min_ratio, strongest first; the pair whose weaker line is strongest
    loc = np.flatnonzero((P > np.roll(P, 1)) & (P >= np.roll(P, -1)) & (P > min_ratio*med))
    loc = loc[np.argsort(-P[loc])][:top]
    best = None
    for i in range(len(loc)):
        for j in range(i + 1, len(loc)):
            a, b = loc[i], loc[j]
            w = min(P[a], P[b])
            if abs(f[a] - f[b]) > 8*Fs/nfft and (best is None or w > best[0]):
                best = (w, a, b)
    if best is None:
        return None
    w, a, b = best
    f1, f2 = _peak(P, f, a), _peak(P, f, b)
    return float(abs(f1 - f2)), float((f1 + f2)/4), float(w/med)

front

front(x, Fs, baud=None)

(baud, cfo, lines) of an h = 1/2 CPM signal: the x^2 pair, else fsk.analyze's rate and the median frequency

Source code in src/rpps/analysis/modulation/cpm.py
def front(x, Fs, baud=None):
    """(baud, cfo, lines) of an h = 1/2 CPM signal: the x^2 pair, else fsk.analyze's rate and the median frequency"""
    sq = square_lines(x, Fs, baud)
    if sq is not None:
        return sq
    if baud is None:
        from . import fsk
        r = fsk.analyze(x, Fs, force=True)
        if r.baud is None:
            raise ValueError(f"no symbol rate: no x^2 lines, and {r.why}")
        baud = r.baud
    ph = np.angle(x[1:]*np.conj(x[:-1]))
    return float(baud), float(np.median(ph)*Fs/(2*np.pi)), 0.0

demodulate

demodulate(x, Fs, scheme='gmsk_0.3', baud=None, ns=8, S=None, loop=(0.08, 0.002), train=1500, clock=True)

Bits of a GMSK / SOQPSK signal x (complex baseband at Fs, a channel around it; see the module). baud: the symbol rate when known. train: symbols the timing search runs on. clock: correct the symbol clock from stretches across a long record. Returns CPM

Source code in src/rpps/analysis/modulation/cpm.py
def demodulate(x, Fs, scheme="gmsk_0.3", baud=None, ns=8, S=None, loop=(0.08, 0.002), train=1500, clock=True):
    """Bits of a GMSK / SOQPSK signal x (complex baseband at Fs, a channel around it; see the module). baud: the symbol
    rate when known. train: symbols the timing search runs on. clock: correct the symbol clock from stretches across a
    long record. Returns CPM"""
    if scheme not in SCHEMES:
        raise ValueError(f"scheme: one of {list(SCHEMES)}")
    x = np.asarray(x, dtype=np.complex128)
    baud, cfo, lines = front(x, Fs, baud)
    x = x*np.exp(-2j*np.pi*cfo*np.arange(len(x))/Fs)
    sps = Fs/baud
    nsym = int((len(x) - 16)/sps) - 2
    if nsym < 8:
        raise ValueError("fewer than 8 symbols")
    T = 1/baud
    m, tau = _time(x, Fs, baud, scheme, ns, 8/Fs, min(train, nsym), S, loop)
    rate = 1.0
    if clock and nsym > 4*train:
        # time stretches across the record; a line through their starts (in symbols) is the clock error
        starts = np.linspace(0, nsym - train - 2, 5).astype(int)
        taus = []
        for s0 in starts:
            _, tt = _time(x, Fs, baud, scheme, ns, tau + s0*T - T/2, train, S, loop)
            taus.append(tt - tau - s0*T)
        taus = np.unwrap(np.array(taus)*2*np.pi/T)*T/(2*np.pi)
        slope = np.polyfit(starts*T, taus, 1)[0] # seconds of drift a second
        rate = 1/(1 + slope)
    n = int((len(x)/Fs - tau - 16/Fs)*baud*rate) - 1
    bits, match = mlse(_symbols(x, Fs, baud, ns, tau, n, rate), scheme, ns, 0, S, loop)
    return CPM(bits=bits, scheme=scheme, baud=baud*rate, cfo=cfo, tau=tau, match=match, lines=lines)

identify

identify(x, Fs, baud=None, schemes=None, n=1500, ns=8)

Which scheme fits x best: [(match, scheme)] best first, each timed on its own over n symbols

Source code in src/rpps/analysis/modulation/cpm.py
def identify(x, Fs, baud=None, schemes=None, n=1500, ns=8):
    """Which scheme fits x best: [(match, scheme)] best first, each timed on its own over n symbols"""
    x = np.asarray(x, dtype=np.complex128)
    baud, _, _ = front(x, Fs, baud)
    x = x[:int((n + 40)*Fs/baud)]
    out = []
    for name in schemes or SCHEMES:
        r = demodulate(x, Fs, name, baud, ns=ns, train=n, clock=False)
        out.append((r.match, name))
    return sorted(out, key=lambda t: -t[0])

cumulants

Higher-order cumulants of symbols: which constellation, blind to Gaussian noise and to the carrier phase

r = rp.analysis.modulation.cumulants.classify(symbols)      # symbol-spaced samples (timing recovered; carrier need not be)
print(r[0])        # e.g. "16QAM: distance 0.02, Es/N0 14.8 dB"   (best first)
rp.analysis.modulation.cumulants.measure(symbols)           # {"C40": .., "C42": .., "C63": .., "C80": ..} normalized

C_pq is the cumulant of order p with q of its factors conjugated: the moment M_pq = E[x^(p-q) conj(x)^q] less what the lower orders explain (the moment-cumulant formula over the set partitions of the p factors). Gaussian noise has none above order 2, so C40, C42, C63, C80 of signal plus noise are the signal's; only C21 (the power) has the noise in it. A carrier phase turns C_pq by (p - 2q) times it: C42 and C63 (as many conjugated as not) do not turn, the others are compared by magnitude. Normalized by the signal power to the p/2, each constellation has its own values (Swami & Sadler 2000): BPSK C42 -2, QPSK -1, 8PSK -1 with C40 0, 16QAM -0.68, 64QAM -0.62, OFDM and noise 0.

theory computes them for any point set, so every constellation rpps knows is a candidate. classify fits, for each, the signal's share of the measured power (what the noise does not have) and compares; the share is an Es/N0.

Classes:

Name Description
Match

One candidate: name, distance (weighted, of the phase-free cumulants), share (the signal's part of the power that

Functions:

Name Description
cumulant

C_pq from a moment table: sum over partitions of (-1)^(k-1) (k-1)! prod of the blocks' moments

measure

{name: C_pq / power^(p/2)}: power the signal's (default C21, which counts the noise too)

theory

The normalized cumulants of equiprobable points (unit power)

candidates

{name: points} of the constellations to compare with

classify

Candidates by how well the symbols' cumulants match theirs, best first. points: {name: points} (default

Match

Match(**kw)

One candidate: name, distance (weighted, of the phase-free cumulants), share (the signal's part of the power that fits best), esn0_db (from the share), values (measured, normalized by the signal power), expected (theory)

Source code in src/rpps/analysis/modulation/cumulants.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

cumulant

cumulant(M, p, q)

C_pq from a moment table: sum over partitions of (-1)^(k-1) (k-1)! prod of the blocks' moments

Source code in src/rpps/analysis/modulation/cumulants.py
def cumulant(M, p, q):
    """C_pq from a moment table: sum over partitions of (-1)^(k-1) (k-1)! prod of the blocks' moments"""
    total = 0j
    for c, keys in _terms(p, q):
        term = complex(c)
        for key in keys:
            term *= M[key]
        total += term
    return total

measure

measure(x, features=FEATURES, power=None)

{name: C_pq / power^(p/2)}: power the signal's (default C21, which counts the noise too)

Source code in src/rpps/analysis/modulation/cumulants.py
def measure(x, features=FEATURES, power=None):
    """{name: C_pq / power^(p/2)}: power the signal's (default C21, which counts the noise too)"""
    M = _moment_table(x, max(p for _, p, _ in features))
    c21 = float(np.real(M[1, 1] - abs(M[1, 0])**2))
    P = c21 if power is None else power
    return {name: cumulant(M, p, q)/P**(p/2) for name, p, q in features}

theory

theory(points, features=FEATURES)

The normalized cumulants of equiprobable points (unit power)

Source code in src/rpps/analysis/modulation/cumulants.py
def theory(points, features=FEATURES):
    """The normalized cumulants of equiprobable points (unit power)"""
    pts = np.asarray(points, dtype=np.complex128)
    pts = pts/np.sqrt(np.mean(np.abs(pts)**2))
    return measure(pts, features)

candidates

candidates()

{name: points} of the constellations to compare with

Source code in src/rpps/analysis/modulation/cumulants.py
def candidates():
    """{name: points} of the constellations to compare with"""
    return {name: pts.copy() for name, pts in _candidates().items()}

classify

classify(x, points=None, esn0_db=None, shares=np.linspace(0.05, 1.0, 96))

Candidates by how well the symbols' cumulants match theirs, best first. points: {name: points} (default candidates()). For each, the signal's share of the power is fitted (noise adds only to C21) unless esn0_db fixes it.

Families separate on their own (PSK orders, QAM, APSK, ASK, BPSK); orders within QAM or ASK do not without the SNR: a larger QAM at a higher SNR has the cumulants of a smaller one with more noise. Give esn0_db (rpps.sync.quality, or the residual of rpps.analysis.modulation.cancel) to tell them apart, or fit the constellation (rpps.sync.detect)

Source code in src/rpps/analysis/modulation/cumulants.py
def classify(x, points=None, esn0_db=None, shares=np.linspace(0.05, 1.0, 96)):
    """Candidates by how well the symbols' cumulants match theirs, best first. points: {name: points} (default
    `candidates()`). For each, the signal's share of the power is fitted (noise adds only to C21) unless esn0_db fixes it.

    Families separate on their own (PSK orders, QAM, APSK, ASK, BPSK); orders within QAM or ASK do not without the SNR:
    a larger QAM at a higher SNR has the cumulants of a smaller one with more noise. Give esn0_db (rpps.sync.quality,
    or the residual of rpps.analysis.modulation.cancel) to tell them apart, or fit the constellation (rpps.sync.detect)"""
    if esn0_db is not None:
        shares = [1/(1 + 10**(-esn0_db/10))]
    x = np.asarray(x, dtype=np.complex128)
    x = x - np.mean(x)
    M = _moment_table(x, 8)
    c21 = float(np.real(M[1, 1]))
    raw = {name: cumulant(M, p, q) for name, p, q in FEATURES}
    shares = np.asarray(shares, dtype=float)
    # The measured values at every share at once (one row each): raw C_pq / (share C21)^(p/2)
    V = np.stack([_vector({k: raw[k]/(s*c21)**(p/2) for k, p, _ in FEATURES}) for s in shares])
    pts = _candidates() if points is None else points
    out = []
    for name, P in pts.items():
        t = _expected(np.asarray(P, dtype=np.complex128).tobytes())
        i = int(np.argmin(np.sum(_W*(V - t)**2, axis=1))) # the first best share, as a loop over them would pick
        d, s, v = float(np.sqrt(np.sum(_W*(V[i] - t)**2))), float(shares[i]), V[i]
        es = 10*np.log10(s/(1 - s)) if s < 1 else None
        out.append(Match(name=name, distance=d, share=float(s), esn0_db=es, values=v, expected=t))
    out.sort(key=lambda m: m.distance)
    return out

fsk

Frequency-shift keying and continuous-phase modulation from the instantaneous frequency: tones, rate, index, pulse

r = rp.analysis.modulation.fsk.analyze(x, Fs)     # x at baseband (a channel), constant envelope
print(r)                               # e.g. "2-FSK: 9600.0 Bd, tones 4800.0 Hz apart (h 0.50: MSK), deviation
                                       #  +-2400.0 Hz, centre +312.0 Hz, Gaussian-like transitions (0.6 symbols)"
sym = rp.analysis.modulation.fsk.demodulate(x, Fs, r)   # tone index per symbol, 0 = lowest

A constant-envelope signal carries its data in its frequency: the discriminator output f(t) = d/dt arg x / (2 pi) is a pulse-amplitude signal whose levels are the tones. So: rate the symbol rate is a line of f^2 / (df)^2 (rpps.analysis.spectrum.cyclic.lines: significant or not, with a P_fa) timing transitions (df)^2 pulse once a symbol at the symbol boundaries; the centres are half a symbol later tones f at the centres clusters at M equally spaced levels: M (2, 4, 8) is the largest whose clusters are well apart (spacing over 4 rms widths); spacing / rate is the modulation index h (0.5 MSK, 1 Sunde's FSK) pulse a frequency pulse longer than a symbol (Gaussian: GMSK, GFSK; raised cosine: partial-response CPM) pulls a symbol's frequency toward its neighbours'; rectangular pulses (CPFSK, MSK) do not

Classes:

Name Description
FSK

Result of analyze. M: tones (None: not FSK). baud (Hz), baud_line (cyclic.Line), spacing (Hz between adjacent

Functions:

Name Description
analyze

FSK / CPM parameters of baseband samples x (see the module); lo/hi: symbol rates searched (Hz). A signal whose

demodulate

Tone index (0 = lowest) of every symbol, at the centres analyze found (r: its result; the same x, filtered the

cpm_index

The modulation index h of a full-response CPM (CPFSK, MSK, M-ary), from the phase lattice: between symbol

FSK

FSK(**kw)

Result of analyze. M: tones (None: not FSK). baud (Hz), baud_line (cyclic.Line), spacing (Hz between adjacent tones), h (spacing / baud), deviation (Hz, of the outer tones from the centre), centre (Hz: the carrier offset), levels (Hz, the tones), separation (spacing over the clusters' rms width), isi (how far neighbours pull a symbol off its tone, in spacings: ~0 rectangular, 0.1 and more Gaussian / partial response), tau (first symbol centre, samples), envelope (E|x|^4 / (E|x|^2)^2), why (when M is None)

Attributes:

Name Type Description
gaussian

The frequency pulse is longer than a symbol (Gaussian, raised cosine): neighbours pull a symbol off its tone

Source code in src/rpps/analysis/modulation/fsk.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))
gaussian property
gaussian

The frequency pulse is longer than a symbol (Gaussian, raised cosine): neighbours pull a symbol off its tone

analyze

analyze(x, Fs, lo=None, hi=None, pfa=0.001, mask=True, force=False, max_samples=2 ** 21)

FSK / CPM parameters of baseband samples x (see the module); lo/hi: symbol rates searched (Hz). A signal whose envelope (in its band) is not nearly constant is not analysed unless force

Source code in src/rpps/analysis/modulation/fsk.py
def analyze(x, Fs, lo=None, hi=None, pfa=1e-3, mask=True, force=False, max_samples=2**21):
    """FSK / CPM parameters of baseband samples x (see the module); lo/hi: symbol rates searched (Hz). A signal whose
    envelope (in its band) is not nearly constant is not analysed unless `force`"""
    x = np.asarray(x, dtype=np.complex128)[:max_samples]
    p2 = np.mean(np.abs(x)**2) if len(x) else 0.0
    env = float(np.mean(np.abs(x)**4)/max(p2**2, 1e-300)) if len(x) else 0.0
    out = dict(envelope=env)
    if len(x) < 512:
        return FSK(why="too few samples", **out)
    if len(x) >= 1024 and mask:
        # Out-of-band noise only, with a wide margin: an FSK spectrum's skirts carry its transitions and its deviation
        x = _band(x, Fs)
    p2b = np.mean(np.abs(x)**2)
    out["envelope"] = float(np.mean(np.abs(x)**4)/max(p2b**2, 1e-300)) # in band: less of the noise
    if out["envelope"] > ENVELOPE and not force:
        return FSK(why=f"the envelope is not constant ({out['envelope']:.2f}): a linear modulation, OFDM or noise", **out)
    lo = Fs/256 if lo is None else lo
    hi = Fs/2 if hi is None else hi
    f = discriminate(np.asarray(x, dtype=np.complex128), Fs)
    f = f - np.median(f)
    lines = []
    # f is white noise plus a symbol-rate signal: smoothing it (over 1, 4, 16 samples) before squaring keeps the line of
    # a slow or Gaussian-filtered signal (GMSK's f^2 is nearly flat) out of the noise
    for k in (1, 4, 16):
        if hi*k > 2*Fs and k > 1:
            hi_k = min(hi, Fs/k)
        else:
            hi_k = hi
        fk = _smooth(f, k)
        for z, kind in ((fk**2, f"f^2/{k}"), (np.diff(fk)**2, f"(df)^2/{k}")):
            for l in cyclic.lines(z, Fs, lo, hi_k, pfa, top=4):
                if l.significant:
                    l.kind = kind
                    lines.append(l)
    if not lines:
        return FSK(why="no symbol-rate line in the instantaneous frequency", **out)
    baud, line = comb_rate(lines, Fs, lo)
    tau = _timing(f, Fs/baud)
    centres, v = _centre_freqs(x, Fs, Fs/baud, tau)
    M, lev, sep = _levels(v)
    if M is not None and _repeats(v, lev) > 1/M + REPEAT and baud/2 >= lo:
        # Every tone comes twice: a Gaussian pulse can leave the rate's own line weaker than its second harmonic's
        t2 = _timing(f, 2*Fs/baud)
        c2, v2 = _centre_freqs(x, Fs, 2*Fs/baud, t2)
        M2, lev2, sep2 = _levels(v2)
        if M2 is not None and _repeats(v2, lev2) <= 1/M2 + REPEAT:
            baud, tau, centres, v, M, lev, sep = baud/2, t2, c2, v2, M2, lev2, sep2
    best = (None, baud, line, tau, centres, v, M, lev, sep)
    _, baud, line, tau, centres, v, M, lev, sep = best
    off = float(np.median(discriminate(np.asarray(x, dtype=np.complex128), Fs)))
    out.update(baud=baud, baud_line=line, tau=tau, separation=sep)
    if M is None:
        return FSK(why=f"the frequency at the symbol centres does not fall in equally spaced clusters (best {sep:.1f} widths)",
                   **out)
    spacing = float(np.median(np.diff(lev)))
    centre = float(np.mean(lev)) + off
    # ISI: how far a symbol's frequency is pulled off its tone (in tone spacings) when both neighbours are other tones,
    # less the same when both are its own (noise alone): about 0 for rectangular pulses (CPFSK, MSK), 0.1-0.3 for a
    # Gaussian pulse (GMSK BT 0.3-0.5) or a raised-cosine one (partial-response CPM)
    lab = np.argmin(np.abs(v[:, None] - lev[None, :]), axis=1)
    dev = np.abs(v - lev[lab])/spacing
    other = np.zeros(len(v), bool)
    own = np.zeros(len(v), bool)
    other[1:-1] = (lab[:-2] != lab[1:-1]) & (lab[2:] != lab[1:-1])
    own[1:-1] = (lab[:-2] == lab[1:-1]) & (lab[2:] == lab[1:-1])
    isi = float(np.mean(dev[other]) - np.mean(dev[own])) if other.any() and own.any() else 0.0
    out.update(M=M, spacing=spacing, h=spacing/baud, deviation=spacing*(M - 1)/2, centre=centre,
               levels=lev + off, isi=max(isi, 0.0))
    return FSK(**out)

demodulate

demodulate(x, Fs, r, mask=True)

Tone index (0 = lowest) of every symbol, at the centres analyze found (r: its result; the same x, filtered the same way: mask)

Source code in src/rpps/analysis/modulation/fsk.py
def demodulate(x, Fs, r, mask=True):
    """Tone index (0 = lowest) of every symbol, at the centres `analyze` found (r: its result; the same x, filtered the
    same way: mask)"""
    if r.M is None:
        raise ValueError(f"Not FSK: {r.why}")
    x = np.asarray(x, dtype=np.complex128)
    if len(x) >= 1024 and mask:
        x = _band(x, Fs)
    _, v = _centre_freqs(x, Fs, Fs/r.baud, r.tau)
    v = v + np.median(discriminate(np.asarray(x, dtype=np.complex128), Fs)) # _centre_freqs is relative to the median
    return np.argmin(np.abs(v[:, None] - np.asarray(r.levels)[None, :]), axis=1)

cpm_index

cpm_index(x, Fs, baud, tau=None, h_range=(0.05, 2.0), steps=1951, lags=(1, 2, 3, 4))

The modulation index h of a full-response CPM (CPFSK, MSK, M-ary), from the phase lattice: between symbol boundaries N apart the phase moves pi h (a sum of N odd levels), whose parity is N's, so exp(j dphi / h) is (-1)^N for every pair at the right h, and averages away at a wrong one. A submultiple of h fits too: the largest h scoring near the best is taken. tau: a symbol centre (samples, as analyze gives; default from the discriminator). Returns (h, score 0..1). Partial-response CPM (L > 1, GMSK) leaves pulses straddling the boundaries: lower scores

Source code in src/rpps/analysis/modulation/fsk.py
def cpm_index(x, Fs, baud, tau=None, h_range=(0.05, 2.0), steps=1951, lags=(1, 2, 3, 4)):
    """The modulation index h of a full-response CPM (CPFSK, MSK, M-ary), from the phase lattice: between symbol
    boundaries N apart the phase moves pi h (a sum of N odd levels), whose parity is N's, so exp(j dphi / h) is (-1)^N for
    every pair at the right h, and averages away at a wrong one. A submultiple of h fits too: the largest h scoring near
    the best is taken. tau: a symbol centre (samples, as `analyze` gives; default from the discriminator).
    Returns (h, score 0..1). Partial-response CPM (L > 1, GMSK) leaves pulses straddling the boundaries: lower scores"""
    x = np.asarray(x, dtype=np.complex128)
    sps = Fs/baud
    f = discriminate(np.asarray(x, dtype=np.complex128), Fs)
    if tau is None:
        tau = _timing(f - np.median(f), sps)
    ph = np.concatenate(([0.0], np.cumsum(np.angle(x[1:]*np.conj(x[:-1]))))) # unwrapped phase, rad
    b = (tau - sps/2) % sps + sps*np.arange(int((len(x) - 1 - (tau - sps/2) % sps)//sps))
    pb = np.interp(b, np.arange(len(ph)), ph)
    # The carrier offset adds 2 pi f N sps/Fs to every N-symbol step: take it off (the steps' mean, lattice symmetric)
    hs = np.linspace(h_range[0], h_range[1], steps)
    score = np.zeros(steps)
    for N in lags:
        d = pb[N:] - pb[:-N]
        d = d - np.mean(d)
        score += np.abs(np.mean(np.exp(1j*d[None, :]/hs[:, None]), axis=1))
    score /= len(lags)
    best = score.max()
    peaks = np.flatnonzero((score[1:-1] >= score[:-2]) & (score[1:-1] >= score[2:]) & (score[1:-1] >= 0.9*best)) + 1
    k = peaks[-1] if len(peaks) else int(np.argmax(score)) # the largest h whose peak is about the best
    return float(hs[k]), float(score[k])

impairments

What else than noise is in locked symbols: amplifier compression (AM/AM, AM/PM), IQ imbalance, phase noise, neighbours

a = rp.analysis.modulation.impairments.amplifier(y, points)   # per ring: gain (dB) and phase (deg) against the inner ring
q = rp.analysis.modulation.impairments.iq(y)                  # image rejection (dB), the imbalance, and y corrected
p = rp.analysis.modulation.impairments.phase_noise(y, points) # rms phase error against what the noise explains, and how slow
n = rp.analysis.modulation.impairments.neighbours(x, Fs)      # other bands over the floor, and whether they touch this one

When Es/N0 and the SNR the floor allows disagree (rpps.analysis.modulation.cancel's excess, or a gap between SNR and Es/N0 over 1 dB) these say why: amplifier a saturating amplifier gives outer points less gain (AM/AM) and turns them (AM/PM): each ring's mean symbol against its point, relative to the innermost ring iq a receiver whose I and Q arms differ in gain or phase adds a little of the conjugate: y = mu s + nu s*. For a constellation symmetric under 90 degree turns (QPSK, QAM, APSK, 8PSK) E[s^2] = 0, so E[y^2] / E[|y|^2] = 2 mu nu / (|mu|^2 + |nu|^2): blind, no decisions needed; the image rejection is |mu/nu|^2 phase noise the phase of each symbol against its decision: white noise turns each symbol on its own (its part is half the variance of neighbours' differences), slow phase noise turns neighbours alike; the excess and its spectrum say whether it is slow (a loop too narrow, an oscillator's close-in noise) or fast neighbours every band over the floor (rpps.analysis.spectrum.cyclic.occupied's runs) besides the strongest, and whether the spectrum drops to the floor between them: one that does not overlaps the signal

Classes:

Name Description
Amplifier

Result of amplifier: rings (radius of each ring's points), gain_db and phase_deg (each ring's mean symbol against

IQ

Result of iq: ratio (nu/mu: the conjugate's part), irr_db (image rejection, |mu/nu|^2 in dB), gain_db (I arm over Q),

PhaseNoise

Result of phase_noise: rms_deg (of the phase error), white_deg (what the measured Es/N0 explains), excess_deg

Neighbour

A band over the floor besides the signal's: lo, hi (Hz), power (relative to the signal's), touching (the spectrum

Functions:

Name Description
amplifier

AM/AM and AM/PM from locked symbols y and the constellation's points (rings: points within tol of a radius)

iq

IQ imbalance of symbols (or samples) of a constellation with E[s^2] = 0, blind (see the module)

phase_noise

The phase of each symbol against its decision, against what white noise at the measured Es/N0 gives

neighbours

Bands over the floor besides the strongest (the signal), from a Welch PSD: whether each reaches the floor between

Amplifier

Amplifier(**kw)

Result of amplifier: rings (radius of each ring's points), gain_db and phase_deg (each ring's mean symbol against its points, relative to the innermost ring), compression_db (the outermost ring's gain), am_pm (the outermost ring's turn, degrees)

Source code in src/rpps/analysis/modulation/impairments.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

IQ

IQ(**kw)

Result of iq: ratio (nu/mu: the conjugate's part), irr_db (image rejection, |mu/nu|^2 in dB), gain_db (I arm over Q), phase_deg (their angle off 90 degrees), dc (mean / rms), corrected (y with nu s* taken off and the DC)

Source code in src/rpps/analysis/modulation/impairments.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

PhaseNoise

PhaseNoise(**kw)

Result of phase_noise: rms_deg (of the phase error), white_deg (what the measured Es/N0 explains), excess_deg (the rest, rms), slow (the share of the phase error's power below a tenth of the symbol rate: much over 0.1 is phase noise slower than the symbols), spectrum (the phase error's, against frequency in symbol rates)

Source code in src/rpps/analysis/modulation/impairments.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

Neighbour

Neighbour(**kw)

A band over the floor besides the signal's: lo, hi (Hz), power (relative to the signal's), touching (the spectrum does not reach the floor between it and the signal)

Source code in src/rpps/analysis/modulation/impairments.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

amplifier

amplifier(y, points, tol=0.05)

AM/AM and AM/PM from locked symbols y and the constellation's points (rings: points within tol of a radius)

Source code in src/rpps/analysis/modulation/impairments.py
def amplifier(y, points, tol=0.05):
    """AM/AM and AM/PM from locked symbols y and the constellation's points (rings: points within tol of a radius)"""
    y, pts = _normalize(y, points)
    r = np.abs(pts)
    rings = []
    for v in np.sort(r):
        if not rings or v - rings[-1] > tol:
            rings.append(v)
    d = _decide(y, pts)
    g, ph = [], []
    for R in rings:
        sel = np.abs(np.abs(d) - R) <= tol
        c = np.mean(y[sel]*np.conj(d[sel]))/np.mean(np.abs(d[sel])**2) # the ring's complex gain
        g.append(20*np.log10(abs(c)))
        ph.append(np.degrees(np.angle(c)))
    g = np.array(g) - g[0]
    ph = np.array(ph) - ph[0]
    return Amplifier(rings=np.array(rings), gain_db=g, phase_deg=ph, compression_db=float(g[-1]), am_pm=float(ph[-1]))

iq

iq(y)

IQ imbalance of symbols (or samples) of a constellation with E[s^2] = 0, blind (see the module)

Source code in src/rpps/analysis/modulation/impairments.py
def iq(y):
    """IQ imbalance of symbols (or samples) of a constellation with E[s^2] = 0, blind (see the module)"""
    y = np.asarray(y, dtype=np.complex128)
    dc = np.mean(y)
    z = y - dc
    rho = np.mean(z**2)/np.mean(np.abs(z)**2) # 2 mu nu / (|mu|^2 + |nu|^2) = 2 k / (1 + |k|^2), k = nu/mu*
    # solve 2k/(1 + |k|^2) = rho for the root with |k| < 1
    a = abs(rho)
    m = (1 - np.sqrt(max(1 - a**2, 0.0)))/a if a > 1e-12 else 0.0
    k = m*np.exp(1j*np.angle(rho)) if a > 1e-12 else 0j
    corrected = (z - k*np.conj(z))/(1 - abs(k)**2)
    # y = s + k s* is I scaled by (1 + Re k) - ..., Q by (1 - Re k), and Q turned by -Im k: small-imbalance reading
    gain = 20*np.log10((1 + k.real)/(1 - k.real)) if abs(k.real) < 1 else np.inf
    phase = np.degrees(2*k.imag)
    irr = -20*np.log10(abs(k)) if abs(k) > 0 else np.inf
    return IQ(ratio=complex(k), irr_db=float(irr), gain_db=float(gain), phase_deg=float(phase),
              dc=complex(dc/np.sqrt(np.mean(np.abs(y)**2))), corrected=corrected)

phase_noise

phase_noise(y, points, nfft=1024)

The phase of each symbol against its decision, against what white noise at the measured Es/N0 gives

Source code in src/rpps/analysis/modulation/impairments.py
def phase_noise(y, points, nfft=1024):
    """The phase of each symbol against its decision, against what white noise at the measured Es/N0 gives"""
    y, pts = _normalize(y, points)
    d = _decide(y, pts)
    th = np.angle(y*np.conj(d))
    # White noise turns each symbol independently; slow phase noise turns neighbours alike, so a difference of
    # neighbours has twice the white variance and little of the rest
    white = np.sqrt(np.var(np.diff(th))/2)
    rms = float(np.sqrt(np.mean(th**2)))
    nfft = int(min(nfft, 2**int(np.log2(max(len(th)//8, 16)))))
    seg = len(th)//nfft
    S = np.mean(np.abs(np.fft.rfft(th[:seg*nfft].reshape(seg, nfft)*np.hanning(nfft), axis=1))**2, axis=0)
    f = np.fft.rfftfreq(nfft)
    flat = np.median(S[f > 0.25]) # white part's level, from the fast half
    excess = np.maximum(S - flat, 0)
    slow = float(excess[f < 0.1].sum()/max(S.sum(), 1e-300))
    return PhaseNoise(rms_deg=float(np.degrees(rms)), white_deg=float(np.degrees(white)),
                      excess_deg=float(np.degrees(np.sqrt(max(rms**2 - white**2, 0.0)))), slow=slow, spectrum=S, freq=f)

neighbours

neighbours(x, Fs, nfft=1024, margin_db=3.0)

Bands over the floor besides the strongest (the signal), from a Welch PSD: whether each reaches the floor between it and the signal (touching: a gap less than margin_db over the floor never opens)

Source code in src/rpps/analysis/modulation/impairments.py
def neighbours(x, Fs, nfft=1024, margin_db=3.0):
    """Bands over the floor besides the strongest (the signal), from a Welch PSD: whether each reaches the floor between
    it and the signal (touching: a gap less than `margin_db` over the floor never opens)"""
    x = np.asarray(x, dtype=np.complex128)
    nfft = int(min(nfft, 2**int(np.log2(max(len(x)//8, 16)))))
    seg = len(x)//nfft
    S = np.fft.fftshift(np.mean(np.abs(np.fft.fft(x[:seg*nfft].reshape(seg, nfft)*np.hanning(nfft), axis=1))**2, axis=0))
    S = np.convolve(S, np.ones(5)/5, mode="same")
    f = (np.arange(nfft) - nfft//2)*Fs/nfft
    N0 = spectrum_floor(S)
    on = S > 4*N0 # bands: 6 dB over the floor (a valley between two that touch stays over the floor)
    runs = []
    i = 0
    while i < nfft:
        if on[i]:
            j = i
            while j + 1 < nfft and on[j + 1]:
                j += 1
            if j - i + 1 >= 3:
                runs.append((i, j, float(np.sum(S[i:j + 1] - N0))))
            i = j + 1
        else:
            i += 1
    # Two bands that overlap make one run: split a run where it dips 6 dB under the peaks on both sides
    split = []
    for a, b, p in runs:
        while True:
            seg = S[a:b + 1]
            best = None
            for v in range(1, len(seg) - 1):
                left, right = seg[:v].max(), seg[v + 1:].max()
                if seg[v] < 0.25*min(left, right) and (best is None or seg[v]/min(left, right) < best[1]):
                    best = (v, seg[v]/min(left, right))
            if best is None:
                split.append((a, b, float(np.sum(S[a:b + 1] - N0))))
                break
            v = a + best[0]
            split.append((a, v, float(np.sum(S[a:v + 1] - N0))))
            a = v + 1
    # ... or where its level steps by 6 dB between two plateaus (overlapping bands of different power: no valley). Bands
    # of the same power overlapping cannot be told apart here (rpps.analysis.spectrum.cyclic separates them by rate and carrier)
    runs = []
    wide = max(16, nfft//32) # a band is wider than this; so is each side of a split
    L = 10*np.log10(np.maximum(S, 1e-300))
    for a, b, p in split:
        pieces = [(a, b)]
        flat = lambda seg: np.percentile(seg, 75) - np.percentile(seg, 25) < 4.0 # a plateau, not a skirt
        while pieces:
            a_, b_ = pieces.pop()
            best = None
            for v in range(a_ + wide, b_ - wide + 1):
                lft, rgt = L[a_:v], L[v:b_ + 1]
                step = abs(np.median(lft) - np.median(rgt))
                if step >= 6 and (best is None or step > best[1]) and flat(lft[len(lft)//4:]) and flat(rgt[:3*len(rgt)//4]):
                    best = (v, step)
            if best is None:
                mid = L[a_ + (b_ - a_)//4:b_ - (b_ - a_)//4 + 1]
                if (a_, b_) == (a, b) or flat(mid): # a piece split off that is no plateau is a skirt between two
                    runs.append((a_, b_, float(np.sum(S[a_:b_ + 1] - N0))))
            else:
                pieces += [(a_, best[0] - 1), (best[0], b_)]
    # ... and a narrower carrier on top of a wider one: a stretch 6 dB over the run's own plateau (its median)
    tops = []
    for a, b, p in runs:
        plateau = np.median(L[a:b + 1])
        up = L[a:b + 1] > plateau + 6
        i = 0
        while i < len(up):
            if up[i]:
                j = i
                while j + 1 < len(up) and up[j + 1]:
                    j += 1
                if j - i + 1 >= wide//2 and (j - i + 1) < 0.8*(b - a + 1):
                    tops.append((a + i, a + j, float(np.sum(S[a + i:a + j + 1] - N0))))
                i = j + 1
            else:
                i += 1
    runs = runs + tops
    runs = [r for r in runs if r[1] - r[0] + 1 >= wide//2] # pieces of a skirt the splits leave are no band
    if not runs:
        return []
    main = max(runs, key=lambda r: r[2])
    out = []
    for a, b, p in runs:
        if (a, b) == main[:2]:
            continue
        lo, hi = (b, main[0]) if b < main[0] else (main[1], a)
        gap = S[lo:hi + 1].min() if hi >= lo else S[min(a, main[0])]
        out.append(Neighbour(lo=float(f[a]), hi=float(f[b]), power=p/main[2],
                             touching=bool(gap > N0*10**(margin_db/10))))
    return out

pm

Phase modulation with a residual carrier (PCM/PM, telemetry and ranging): carrier, index, the data on the carrier, tones and subcarriers

p = rp.analysis.modulation.pm.analyze(x, Fs)        # x at baseband (a channel)
print(p)          # e.g. "PM, residual carrier at -1206.8 Hz with 45% of the power (index 0.84 rad); data on the
                  #  carrier at 131072.0 Bd; subcarrier 72000.0 Hz (lines +-4800.0 Hz); tones 19000.0 Hz"
s = rp.analysis.modulation.pm.subcarrier(p.phase, Fs, 72000.0, 20e3)   # the subcarrier at complex baseband: cyclic / detect it
y = rp.analysis.modulation.pm.nrz(p.phase, Fs, p.rate, p.tau)          # soft symbols of the data on the carrier

A transmitter that phase modulates its carrier by less than 90 degrees leaves part of the power in the carrier (cos^2 of the index, for data of +-index), so the receiver can lock to it with a narrow loop (CCSDS 401: PCM/PM/NRZ, PCM/PM/biphase, PCM/PSK/PM on a subcarrier, ranging tones). Looking for a PSK it seems an unbalanced constellation with a spectral line in x itself, near-constant envelope, rates no PSK fits. The phase around the carrier, phi(t), is a real baseband signal holding everything else: data on the carrier NRZ: phi^2 has a line at the rate (phi itself, none). biphase (Manchester): a line in phi at the rate a subcarrier a band around f_sc in phi, and (BPSK on it, squared) a line of phi^2 at 2 f_sc: a rate search on phi^2 or |x|^2 finds 2 f_sc and calls it the symbol rate. Sending idle (alternating) bits it is two lines of phi at f_sc +- rate/2. subcarrier takes it to complex baseband for its own rate tones single lines in phi (ranging, a subcarrier with nothing on it)

Classes:

Name Description
PM

Result of analyze. carrier: offset (Hz) of the residual carrier, None if there is none; share: the carrier's part

Functions:

Name Description
carrier_phase

(phi, z, ref): phi(t) the phase of x around a carrier at fc (Hz); z, x with fc taken off; ref, the carrier as the

share_of

The carrier's part of the power: the tracked carrier's power over all of it (a carrier that drifts or wanders over

analyze

Residual carrier, index, data rate on the carrier, tones and subcarriers of baseband samples x (see the module)

subcarrier

A subcarrier at fsc (Hz) of the phase phi at complex baseband, bw (Hz) wide: rpps.analysis.spectrum.cyclic / detect it

nrz

Soft symbols of NRZ data on the carrier: phi integrated over each bit (the matched filter of a rectangular pulse),

biphase_symbols

Soft symbols of biphase (Manchester) data on the carrier: the first half-bit's integral less the second's

PM

PM(**kw)

Result of analyze. carrier: offset (Hz) of the residual carrier, None if there is none; share: the carrier's part of the power; index: the modulation index (rad) that leaves that share for +-index data, arccos(sqrt(share)); phase_rms (rad); rate: of the data on the carrier (Hz), None without a line; biphase: the rate's line is in phi itself; tau: the first symbol boundary (samples) of the data on the carrier; tones: lines of phi that are no pair (Hz); subcarriers: [(f_sc, half spacing of its line pair)]; phase: phi(t) (rad, a sample each input sample); lines: phi's

Source code in src/rpps/analysis/modulation/pm.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

carrier_phase

carrier_phase(x, Fs, fc, loop=200.0)

(phi, z, ref): phi(t) the phase of x around a carrier at fc (Hz); z, x with fc taken off; ref, the carrier as the loop sees it, z smoothed over about 1/loop seconds (a narrow loop: it follows drift and phase noise slower than that, never the data)

Source code in src/rpps/analysis/modulation/pm.py
def carrier_phase(x, Fs, fc, loop=200.0):
    """(phi, z, ref): phi(t) the phase of x around a carrier at fc (Hz); z, x with fc taken off; ref, the carrier as the
    loop sees it, z smoothed over about 1/loop seconds (a narrow loop: it follows drift and phase noise slower than that,
    never the data)"""
    x = np.asarray(x, dtype=np.complex128)
    n = np.arange(len(x))
    z = x*np.exp(-2j*np.pi*fc/Fs*n)
    ref = _smooth(z, max(3, int(Fs/loop)))
    return np.angle(z*np.conj(ref)), z, ref

share_of

share_of(z, ref)

The carrier's part of the power: the tracked carrier's power over all of it (a carrier that drifts or wanders over the capture keeps its share; |mean z|^2 would average it away)

Source code in src/rpps/analysis/modulation/pm.py
def share_of(z, ref):
    """The carrier's part of the power: the tracked carrier's power over all of it (a carrier that drifts or wanders over
    the capture keeps its share; |mean z|^2 would average it away)"""
    return float(np.mean(np.abs(ref)**2)/max(np.mean(np.abs(z)**2), 1e-300))

analyze

analyze(x, Fs, pfa=1e-06, loop=200.0, lo=None, candidates=4, max_samples=2 ** 22)

Residual carrier, index, data rate on the carrier, tones and subcarriers of baseband samples x (see the module)

Source code in src/rpps/analysis/modulation/pm.py
def analyze(x, Fs, pfa=1e-6, loop=200.0, lo=None, candidates=4, max_samples=2**22):
    """Residual carrier, index, data rate on the carrier, tones and subcarriers of baseband samples x (see the module)"""
    x = np.asarray(x, dtype=np.complex128)[:max_samples]
    if len(x) < 4096:
        return PM(why="too few samples")
    G, _, _ = cyclic.occupied(x, Fs)
    x = np.fft.ifft(np.fft.fft(x)*G)
    # Carrier candidates from a short span (a carrier drifting some Hz over the capture stays in a bin of it; over all of
    # it, it would spread over many fine bins under a steady spur), each judged by the share it holds when tracked
    span = int(min(len(x), max(4096, 2**int(np.log2(4*Fs/loop)))))
    xs = x[:span]
    ls = [l for l in cyclic.lines(xs/np.sqrt(np.mean(np.abs(xs)**2)), Fs, -Fs/2, Fs/2, pfa, top=candidates) if l.significant]
    if not ls:
        return PM(why="no carrier line")
    best = None
    for l in ls:
        phi_, z_, ref_ = carrier_phase(x, Fs, l.freq, loop)
        sh = share_of(z_, ref_)
        if best is None or sh > best[0]:
            best = (sh, l.freq, phi_, z_)
    share, fc, phi, z = best
    if share < MIN_SHARE:
        return PM(why=f"the line at {fc:.1f} Hz holds {100*share:.1f}% of the power: a pilot or a leak")
    lo = 2*loop if lo is None else lo
    lp = [l for l in cyclic.lines(phi, Fs, lo, Fs/2, pfa, top=12) if l.significant]
    l2 = [l for l in cyclic.lines(phi**2, Fs, lo, Fs/2, pfa, top=12) if l.significant]
    tol = lambda f: 2e-3*f + 2*Fs/len(phi)
    # phi's spectrum in coarse bins, against its floor: where a band (a subcarrier with data on it) is
    nb = 256
    seg = len(phi)//nb
    S = np.mean(np.abs(np.fft.rfft(phi[:seg*nb].reshape(seg, nb)*np.hanning(nb), axis=1))**2, axis=0)
    fS = np.fft.rfftfreq(nb, 1/Fs)
    floor = np.median(S) # phi's own floor: most of its bins are noise (below it the band mask's -20 dB, no floor at all)
    S = np.convolve(S, np.ones(3)/3, mode="same")
    # NRZ data on the carrier puts phi's power at DC (a sinc^2), and its rate's harmonics in phi^2 (and, the band edges
    # ringing alike at every transition, in phi): first, so they are not taken for subcarriers or tones
    rate, biphase, tau = None, False, None
    if l2 and S[1] > 0.1*S[1:].max(): # DC within 10 dB of phi's strongest part (a subcarrier's band is far over it)
        rate, _ = comb_rate(l2, Fs, lo)
        biphase = S[1] < S[int(np.argmin(np.abs(fS - rate)))] # biphase moves the power from DC to the rate
        n = np.arange(len(phi))
        g = np.diff(phi)**2 # transitions pulse at the boundaries
        c = np.sum(g*np.exp(-2j*np.pi*rate/Fs*n[1:]))
        tau = float((-np.angle(c)/(2*np.pi)*Fs/rate) % (Fs/rate) + 1.0)
        # Data really on the carrier demodulates to two clusters (a mean |y| several times its scatter); lines of a rate
        # alone (tones, products of subcarriers near DC) do not
        y = biphase_symbols(phi, Fs, rate, tau) if biphase else nrz(phi, Fs, rate, tau)
        a = np.abs(y)
        sg = np.sign(y)
        # ... and data (scrambled or not) changes from symbol to symbol unpredictably, where tones repeat a pattern
        periodic = len(sg) >= 256 and max(abs(np.mean(sg[k:]*sg[:-k])) for k in range(1, 65)) > PATTERN
        if len(a) < 16 or np.mean(a) < BIMODAL*np.std(a) or periodic:
            rate, biphase, tau = None, False, None
    harmonic = lambda f: rate is not None and abs(f/rate - round(f/rate)) < tol(f)/rate and round(f/rate) >= 1
    l2 = [l for l in l2 if not harmonic(l.freq)]
    lp = [l for l in lp if not harmonic(l.freq)]
    def peak(f):
        """The coarse bin of the band f is in, if f is at a peak of phi's spectrum well over its floor (else None)"""
        k = int(np.argmin(np.abs(fS - f)))
        if k < 1 or k >= len(S) - 1 or S[k] < 8*floor:
            return None
        return k if S[k] >= S[k - 1] and S[k] >= S[k + 1] else None
    # Subcarriers: a BPSK subcarrier at f squared is a line at 2 f, at the peak of a band of phi at f; a band, one
    subs, bands = [], set()
    for l in sorted(l2, key=lambda l: -l.strength):
        f = l.freq/2
        k = peak(f) if f > lo else None
        if k is not None and not ({k - 1, k, k + 1} & bands):
            subs.append((f, 0.0))
            bands.add(k)
    # ... or, sending idle (alternating) bits, two lines of phi at f +- rate/2
    pool = sorted(lp, key=lambda l: -l.strength)
    used = set()
    for i, a_ in enumerate(pool):
        for j, b_ in enumerate(pool):
            if j <= i or i in used or j in used or abs(a_.db - b_.db) > 6:
                continue
            fsc, half = (a_.freq + b_.freq)/2, abs(a_.freq - b_.freq)/2
            if half < lo or half > fsc/2 or (peak(fsc) is None and not any(abs(fsc - x) < tol(fsc) for x, _ in subs)):
                continue
            k = next((m for m, (x, _) in enumerate(subs) if abs(fsc - x) < tol(fsc)), None)
            if k is None:
                subs.append((fsc, half))
            elif subs[k][1] == 0.0:
                subs[k] = (subs[k][0], half)
            used.update((i, j))
    # Tones: phi's other lines (not a subcarrier's sideband or centre)
    tones = []
    for i, l in enumerate(pool):
        if i in used or any(abs(l.freq - fsc) < max(half, 0.0) + tol(fsc) for fsc, half in subs):
            continue
        tones.append(l.freq)
    subs = sorted(subs)
    return PM(carrier=fc, share=share, index=float(np.arccos(np.sqrt(min(share, 1.0)))), phase_rms=float(np.std(phi)),
              rate=rate, biphase=biphase, tau=tau, tones=sorted(tones), subcarriers=sorted(subs), phase=phi, lines=lp)

subcarrier

subcarrier(phi, Fs, fsc, bw)

A subcarrier at fsc (Hz) of the phase phi at complex baseband, bw (Hz) wide: rpps.analysis.spectrum.cyclic / detect it

Source code in src/rpps/analysis/modulation/pm.py
def subcarrier(phi, Fs, fsc, bw):
    """A subcarrier at fsc (Hz) of the phase phi at complex baseband, bw (Hz) wide: rpps.analysis.spectrum.cyclic / detect it"""
    n = np.arange(len(phi))
    z = 2*np.asarray(phi, dtype=np.float64)*np.exp(-2j*np.pi*fsc/Fs*n)
    Z = np.fft.fft(z)
    f = np.abs(np.fft.fftfreq(len(z), 1/Fs))
    # A raised-cosine edge over a fifth of the band: a brick wall would ring, and its edges make lines of their own
    edge = np.clip((f - 0.4*bw)/(0.2*bw), 0, 1)
    return np.fft.ifft(Z*0.5*(1 + np.cos(np.pi*edge)))

nrz

nrz(phi, Fs, rate, tau)

Soft symbols of NRZ data on the carrier: phi integrated over each bit (the matched filter of a rectangular pulse), from the boundary tau (samples)

Source code in src/rpps/analysis/modulation/pm.py
def nrz(phi, Fs, rate, tau):
    """Soft symbols of NRZ data on the carrier: phi integrated over each bit (the matched filter of a rectangular pulse),
    from the boundary tau (samples)"""
    sps = Fs/rate
    c = np.concatenate(([0.0], np.cumsum(phi)))
    b = tau + sps*np.arange(int((len(phi) - tau)//sps))
    i = np.round(b).astype(np.int64)
    j = np.round(b + sps).astype(np.int64)
    ok = j <= len(phi)
    return (c[j[ok]] - c[i[ok]])/sps

biphase_symbols

biphase_symbols(phi, Fs, rate, tau)

Soft symbols of biphase (Manchester) data on the carrier: the first half-bit's integral less the second's

Source code in src/rpps/analysis/modulation/pm.py
def biphase_symbols(phi, Fs, rate, tau):
    """Soft symbols of biphase (Manchester) data on the carrier: the first half-bit's integral less the second's"""
    sps = Fs/rate
    c = np.concatenate(([0.0], np.cumsum(phi)))
    b = tau + sps*np.arange(int((len(phi) - tau)//sps))
    i, m, j = (np.round(b + f*sps).astype(np.int64) for f in (0.0, 0.5, 1.0))
    ok = j <= len(phi)
    return ((c[m[ok]] - c[i[ok]]) - (c[j[ok]] - c[m[ok]]))/sps

quality

Whether hard decisions from locked symbols can be trusted for blind tests (gate); the Es/N0 it uses is rpps.sync.quality.measure

Classes:

Name Description
Gate

Result of gate: whether hard decisions from these symbols can be trusted for blind tests (rank, LFSR, code

Functions:

Name Description
gate

Check locked symbols before their hard decisions go into a blind test (see Gate). A frame turned by a phase

Gate

Gate(**kw)

Result of gate: whether hard decisions from these symbols can be trusted for blind tests (rank, LFSR, code search), and why not. rotation: the symbols' mean angle off their decisions (degrees); drift: the largest change of that over the blocks (degrees); near: fraction of decisions within margin minimum distances of a boundary, and near_expected: the same for Gaussian noise at the measured Es/N0 (more than twice that: something other than noise moves the symbols toward the boundaries); ser: expected symbol error rate at the measured Es/N0; quality: measure's; displaced: the largest distance of a cluster's mean from its point, in minimum distances (compression, AM/PM, IQ imbalance or the wrong constellation: a few hundredths is noise). ok: rotation and drift under max_turn of the half-angle between points, near under twice expected, displaced under a quarter

Source code in src/rpps/analysis/modulation/quality.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

gate

gate(y, points, blocks=16, margin=0.1, max_turn=0.15, seed=0)

Check locked symbols before their hard decisions go into a blind test (see Gate). A frame turned by a phase reference error, a carrier that slips through a block, a gain or constellation mismatch: each shows as a rotation, a drift, or decisions crowding the boundaries, which noise at the measured Es/N0 does not explain

Source code in src/rpps/analysis/modulation/quality.py
def gate(y, points, blocks=16, margin=0.1, max_turn=0.15, seed=0):
    """Check locked symbols before their hard decisions go into a blind test (see Gate). A frame turned by a phase
    reference error, a carrier that slips through a block, a gain or constellation mismatch: each shows as a rotation,
    a drift, or decisions crowding the boundaries, which noise at the measured Es/N0 does not explain"""
    y = np.asarray(y, dtype=np.complex128)
    pts = np.asarray(points, dtype=np.complex128)
    pts = pts/np.sqrt(np.mean(np.abs(pts)**2))
    q = measure(y, pts)
    y = y/np.sqrt(np.mean(np.abs(y)**2))
    for _ in range(3): # The same amplitude fit as measure
        dec = pts[np.argmin(np.abs(y[:, None] - pts[None, :]), axis=1)]
        y = y/(np.sum((y*np.conj(dec)).real)/np.sum(np.abs(dec)**2))
    d2 = np.abs(y[:, None] - pts[None, :])**2
    dec = pts[np.argmin(d2, axis=1)]
    rot = float(np.degrees(np.angle(np.sum(y*np.conj(dec)))))
    n = len(y)
    B = max(1, min(blocks, n//64))
    turns = [np.degrees(np.angle(np.sum(b*np.conj(c)))) for b, c in zip(np.array_split(y, B), np.array_split(dec, B))]
    drift = float(np.max(turns) - np.min(turns)) if B > 1 else 0.0
    dmin = np.min(np.abs(pts[:, None] - pts[None, :]) + np.eye(len(pts))*1e9)
    a, b = _second(d2)
    m = (np.sqrt(b) - np.sqrt(a))/dmin
    near = float(np.mean(m < margin))
    # The same statistics for these points under Gaussian noise at the measured sigma
    rng = np.random.default_rng(seed)
    k = 20000
    s = pts[rng.integers(0, len(pts), k)]
    z = s + q.sigma*(rng.standard_normal(k) + 1j*rng.standard_normal(k))
    dz = np.abs(z[:, None] - pts[None, :])**2
    za, zb = _second(dz)
    near_exp = float(np.mean((np.sqrt(zb) - np.sqrt(za))/dmin < margin))
    ser = float(np.mean(pts[np.argmin(dz, axis=1)] != s))
    # The angle between neighbouring points seen from the origin, for the outermost ring: what a turn may not approach
    r = np.abs(pts)
    outer = pts[r > 0.999*r.max()]
    half = 180.0/len(outer) if len(outer) > 1 else 90.0
    limit = max_turn*half
    why = []
    if abs(rot) > limit:
        why.append(f"turned {rot:+.1f} deg off the points")
    if drift > limit:
        why.append(f"the turn changes by {drift:.1f} deg across the blocks (a slipping or drifting carrier)")
    idx = np.argmin(d2, axis=1)
    off = [abs(np.mean(y[idx == j] - pts[j])) for j in range(len(pts)) if np.count_nonzero(idx == j) >= 8]
    displaced = float(max(off)/dmin) if off else 0.0
    if displaced > 0.25:
        why.append(f"clusters sit up to {displaced:.2f} minimum distances off their points (compression, IQ imbalance, or "
                   "not this constellation)")
    if near > 2*near_exp + 3/np.sqrt(n):
        why.append(f"{100*near:.1f}% of decisions near a boundary, noise explains {100*near_exp:.1f}%")
    return Gate(ok=not why, why="; ".join(why), rotation=rot, drift=drift, near=near, near_expected=near_exp, ser=ser,
                quality=q, limit=limit, displaced=displaced)

rpps.analysis.sequence

What was XOR'd in or spread with (see rpps.analysis)

Modules:

Name Description
recurrence

Every linear recurrence up to a degree, scored at once: the taps of a scrambler (feedthrough or additive), a

scrambler

Blind scrambler search: self-synchronising (feedthrough) scramblers, and additive ones (and bare LFSR sequences: PRBS)

spread

Direct-sequence spread spectrum below the noise: the code period, the chip rate, the code, and the data under it

recurrence

Every linear recurrence up to a degree, scored at once: the taps of a scrambler (feedthrough or additive), a differential code, or a short code's checks, from hard bits

found = rp.analysis.sequence.recurrence.search(bits, max_degree=20)
print(found[0])     # e.g. "1 + x^3 + x^20 (taps 20, 3): holds 87.5% (z 412.0), weight 3: data bias 0.75 per bit if
                    #  additive, 0.75 if feedthrough"

A polynomial f(D) = 1 + f_1 D + ... + f_L D^L is a check on bits s when f(D) s = 0 holds more often than chance. Both scramblers make one: feedthrough (self-synchronising, multiplicative): s = d / f(D), so f(D) s = d: the check holds as often as a data bit is its common value (idle fill, flags, headers: data bias b, the same for every multiple of f) additive (synchronous, an LFSR with f its feedback polynomial): s = d + k with f(D) k = 0, so f(D) s = f(D) d: the data bits at the taps, holding with bias b^w (w the taps, weight of f), weaker the more taps A differential code (1 + D) or a short code's parity check is one too. Counting the stream's (L+1)-bit windows by value and taking the Walsh-Hadamard transform of the counts gives every polynomial of degree up to L at once: how many windows it holds on less how many it fails (the same transform as rpps.analysis.code.conv.tcm; Ding et al. 2022/2023 test the primitive polynomials one by one with the same statistic). Checks that are multiples of a smaller one found are dropped, as are those without a constant term (shifts).

Below the stream's own structure (no bias in the data: compressed, encrypted, or coded) nothing holds: then the checks of a code under a feedthrough scrambler are f(D) h(D), and gcd of several gives f (Han, Zhang et al., IEEE 2018).

Classes:

Name Description
Recurrence

A check found: taps (delays, descending, without 0), poly (int: bit j = the coefficient of D^j), degree, weight

Keystream

Result of keystream: bits (the LFSR sequence, regenerated over the whole stream), agree (the share of the

Functions:

Name Description
bit_windows

Counts of the (L+1)-bit windows of bits, as an index whose bit j is the bit at delay j (bit 0 the newest)

soft_z

The soft statistic of a check over signed reliabilities t = tanh(LLR/2) (s's +-1 expected values): sum over

search

Checks f(D) s = 0 with a constant term, of degree up to max_degree (memory: 2^(max_degree+1) counts), significant at

keystream

An additive scrambler's keystream from the scrambled stream, its polynomial known (search finds it) and the data

lfsr

A linear recurrence of any degree up to window/2 that the bits keep (an LFSR scrambler over constant or periodic

Recurrence

Recurrence(**kw)

A check found: taps (delays, descending, without 0), poly (int: bit j = the coefficient of D^j), degree, weight (taps + 1), holds (fraction of windows it holds on), z (its bias over chance), bias (2 holds - 1, signed)

Methods:

Name Description
data_bias

The data's bias per bit this check implies: |bias| for a feedthrough scrambler, |bias|^(1/weight) additive

Source code in src/rpps/analysis/sequence/recurrence.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))
data_bias
data_bias(additive)

The data's bias per bit this check implies: |bias| for a feedthrough scrambler, |bias|^(1/weight) additive

Source code in src/rpps/analysis/sequence/recurrence.py
def data_bias(self, additive):
    """The data's bias per bit this check implies: |bias| for a feedthrough scrambler, |bias|^(1/weight) additive"""
    b = abs(self.bias)
    return b**(1/self.weight) if additive else b

Keystream

Keystream(**kw)

Result of keystream: bits (the LFSR sequence, regenerated over the whole stream), agree (the share of the decoded bits it matches), data (the stream with it taken off), checks (share of the checks holding after decoding)

Source code in src/rpps/analysis/sequence/recurrence.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

bit_windows

bit_windows(bits, L)

Counts of the (L+1)-bit windows of bits, as an index whose bit j is the bit at delay j (bit 0 the newest)

Source code in src/rpps/analysis/sequence/recurrence.py
def bit_windows(bits, L):
    """Counts of the (L+1)-bit windows of bits, as an index whose bit j is the bit at delay j (bit 0 the newest)"""
    b = np.asarray(bits, dtype=np.int64) & 1
    n = len(b) - L
    idx = np.zeros(n, dtype=np.int64)
    for j in range(L + 1):
        idx |= b[L - j:L - j + n] << j
    return np.bincount(idx, minlength=1 << (L + 1)), n

soft_z

soft_z(t, taps)

The soft statistic of a check over signed reliabilities t = tanh(LLR/2) (s's +-1 expected values): sum over positions of the product over its taps, over its own standard deviation (a check that holds makes it large)

Source code in src/rpps/analysis/sequence/recurrence.py
def soft_z(t, taps):
    """The soft statistic of a check over signed reliabilities t = tanh(LLR/2) (s's +-1 expected values): sum over
    positions of the product over its taps, over its own standard deviation (a check that holds makes it large)"""
    t = np.asarray(t, dtype=np.float64)
    L = max(taps)
    N = len(t)
    p = np.ones(N - L)
    for j in taps:
        p = p*t[L - j:N - j]
    return float(abs(p.sum())/np.sqrt(max(np.sum(p**2), 1e-300))), float(np.sign(p.sum()))

search

search(bits, max_degree=20, pfa=1e-06, top=8, llr=None, shortlist=256)

Checks f(D) s = 0 with a constant term, of degree up to max_degree (memory: 2^(max_degree+1) counts), significant at pfa over all of them, multiples of a stronger smaller one dropped: Recurrences, smallest degree first among the strongest.

llr: soft values of the bits (log P(0)/P(1); bits may then be None): the hard transform shortlists the shortlist strongest candidates, significant or not, and each is scored by the product of its own taps' tanh(LLR/2) (2-4 dB more than hard decisions: a check over 3 taps no longer pays for errors in the 18 other bits of a window)

Source code in src/rpps/analysis/sequence/recurrence.py
def search(bits, max_degree=20, pfa=1e-6, top=8, llr=None, shortlist=256):
    """Checks f(D) s = 0 with a constant term, of degree up to max_degree (memory: 2^(max_degree+1) counts), significant at
    pfa over all of them, multiples of a stronger smaller one dropped: Recurrences, smallest degree first among the
    strongest.

    llr: soft values of the bits (log P(0)/P(1); bits may then be None): the hard transform shortlists the `shortlist`
    strongest candidates, significant or not, and each is scored by the product of its own taps' tanh(LLR/2) (2-4 dB more
    than hard decisions: a check over 3 taps no longer pays for errors in the 18 other bits of a window)"""
    if llr is not None:
        llr = np.asarray(llr, dtype=np.float64)
        bits = (llr < 0).astype(np.uint8)
    if max_degree > 24:
        raise ValueError("max_degree up to 24 (2^25 counts); a sparse search (rpps.analysis.sequence.scrambler) goes further")
    L = int(max_degree)
    counts, n = bit_windows(bits, L)
    w = fwht(counts)
    w[0] = 0
    w[::2] = 0 # No constant term: a shift of a smaller check (or nothing)
    z = np.abs(w)/np.sqrt(n)
    zmin = np.sqrt(2*np.log((1 << L)/pfa))
    if llr is not None:
        t = np.tanh(np.clip(llr, -30, 30)/2)
        cand = np.argsort(-z)[:shortlist]
        z = np.zeros_like(z)
        for v in cand:
            v = int(v)
            taps = [j for j in range(L + 1) if v >> j & 1]
            zz, sg = soft_z(t, taps)
            z[v] = zz
            w[v] = sg*abs(w[v]) # the sign (holds or fails) from the soft sum; the size for `bias` stays the hard one's
    idx = np.flatnonzero(z >= zmin)
    idx = idx[np.argsort(-z[idx])][:512]
    out = []
    # Smallest degree first among checks of about the strength of the best: then a multiple is never taken first
    for v in sorted(idx, key=lambda v: (-round(np.log(z[v])/0.1), int(v).bit_length())):
        v = int(v)
        if any(pmod(v, r.poly) == 0 for r in out):
            continue
        taps = tuple(j for j in range(L, 0, -1) if v >> j & 1)
        b = float(w[v]/n)
        out.append(Recurrence(poly=v, taps=taps, degree=v.bit_length() - 1, weight=len(taps) + 1, holds=(1 + b)/2,
                              z=float(z[v]), bias=b))
        if len(out) >= top:
            break
    out.sort(key=lambda r: (-round(np.log(r.z)/0.1), r.degree))
    return out

keystream

keystream(bits, poly, data_bias=None, squarings=4, iters=30, alpha=0.8)

An additive scrambler's keystream from the scrambled stream, its polynomial known (search finds it) and the data under it biased (idle fill, mostly-constant fields): the fast correlation attack (Meier & Staffelbach 1989). Every bit is the keystream seen through a binary channel whose crossover is the data's minority share; the keystream obeys f(D) and its squares f(D^2^i), sparse checks at every position; min-sum over them decodes it, and the whole sequence is regenerated from the most reliable window of degree decoded bits. data_bias: 2 P(data = common value) - 1 (default from how often f holds: (2 holds - 1)^(1 / weight)). The data's common value is taken as 0 (flip the result if not). On 20000 bits it is exact down to data 60/40 for DVB's 1 + x^14 + x^15 and 70/30 for a five-term polynomial (more taps, weaker checks)

Source code in src/rpps/analysis/sequence/recurrence.py
def keystream(bits, poly, data_bias=None, squarings=4, iters=30, alpha=0.8):
    """An additive scrambler's keystream from the scrambled stream, its polynomial known (`search` finds it) and the data
    under it biased (idle fill, mostly-constant fields): the fast correlation attack (Meier & Staffelbach 1989). Every bit
    is the keystream seen through a binary channel whose crossover is the data's minority share; the keystream obeys
    f(D) and its squares f(D^2^i), sparse checks at every position; min-sum over them decodes it, and the whole sequence is
    regenerated from the most reliable window of `degree` decoded bits. data_bias: 2 P(data = common value) - 1 (default
    from how often f holds: (2 holds - 1)^(1 / weight)). The data's common value is taken as 0 (flip the result if not).
    On 20000 bits it is exact down to data 60/40 for DVB's 1 + x^14 + x^15 and 70/30 for a five-term polynomial (more
    taps, weaker checks)"""
    s = np.asarray(bits, dtype=np.uint8)
    n = len(s)
    L = int(poly).bit_length() - 1
    w = bin(int(poly)).count("1")
    if data_bias is None:
        d = Feedthrough.descramble(s, _taps(poly))[L:] # f(D) s = f(D) data for an additive scrambler
        b_w = abs(2*np.mean(d == 0) - 1)
        data_bias = max(min(b_w**(1/w), 0.999), 1e-3)
    prior = np.log((1 + data_bias)/(1 - data_bias))*(1 - 2.0*s) # LLR of k = s (data 0 most likely)
    polys = [int(poly)]
    for _ in range(squarings):
        if polys[-1].bit_length() - 1 > n//4:
            break
        polys.append(_square(polys[-1]))
    checks = []
    for p in polys:
        taps = np.array([j for j in range(p.bit_length()) if p >> j & 1])
        t = np.arange(taps.max(), n)
        checks.append(t[:, None] - taps[None, :]) # (instances, w): positions of each check instance
    msgs = [np.zeros(c.shape) for c in checks]
    total = prior.copy()
    for _ in range(iters):
        new = prior.copy()
        for i, idx in enumerate(checks):
            q = total[idx] - msgs[i]
            a = np.abs(q)
            sgn = np.where(q < 0, -1.0, 1.0)
            prod = np.prod(sgn, axis=1, keepdims=True)
            o = np.argsort(a, axis=1)
            m1 = np.take_along_axis(a, o[:, :1], axis=1)
            m2 = np.take_along_axis(a, o[:, 1:2], axis=1)
            mag = np.where(np.arange(idx.shape[1])[None, :] == o[:, :1], m2, m1)
            msgs[i] = alpha*prod*sgn*mag
            np.add.at(new, idx.ravel(), msgs[i].ravel())
        total = new
    k = (total < 0).astype(np.uint8)
    held = float(np.mean([np.mean(np.bitwise_xor.reduce(k[c], axis=1) == 0) for c in checks]))
    # Regenerate from the most reliable L consecutive decoded bits, forward and back through the recurrence
    rel = np.convolve(np.abs(total), np.ones(L), mode="valid")
    a0 = int(np.argmax(rel))
    taps = [j for j in range(1, L + 1) if poly >> j & 1]
    out = np.zeros(n, np.uint8)
    out[a0:a0 + L] = k[a0:a0 + L]
    for t in range(a0 + L, n): # k[t] = sum over taps k[t - j]
        v = 0
        for j in taps:
            v ^= out[t - j]
        out[t] = v
    for t in range(a0 - 1, -1, -1): # k[t + L] = k[t] + sum over other taps: k[t] = k[t + L] + sum_{j<L} k[t + L - j]
        v = out[t + L]
        for j in taps:
            if j != L:
                v ^= out[t + L - j]
        out[t] = v
    return Keystream(bits=out, agree=float(np.mean(out == k)), data=s ^ out, checks=held)

lfsr

lfsr(bits, window=1024, windows=16, seed=0)

A linear recurrence of any degree up to window/2 that the bits keep (an LFSR scrambler over constant or periodic data: a scrambler of degree d applied twice over an idle word is degree 2d + the word's period, beyond search's transform): Berlekamp-Massey on windows windows, the connection polynomial most of them agree on, and how often it holds over the whole stream. Returns (poly int, degree, holds) or None when no polynomial shorter than window/2 repeats

Source code in src/rpps/analysis/sequence/recurrence.py
def lfsr(bits, window=1024, windows=16, seed=0):
    """A linear recurrence of any degree up to window/2 that the bits keep (an LFSR scrambler over constant or periodic
    data: a scrambler of degree d applied twice over an idle word is degree 2d + the word's period, beyond `search`'s transform): Berlekamp-Massey
    on `windows` windows, the connection polynomial most of them agree on, and how often it holds over the whole stream.
    Returns (poly int, degree, holds) or None when no polynomial shorter than window/2 repeats"""
    b = np.asarray(bits, dtype=np.uint8)
    rng = np.random.default_rng(seed)
    starts = rng.choice(max(1, len(b) - window), min(windows, max(1, len(b) - window)), replace=False)
    seen = {}
    for a in starts:
        C, L = berlekamp_massey(b[a:a + window])
        if L < window//2 - 8: # windows a clean recurrence made
            seen[C] = seen.get(C, 0) + 1
    if not seen:
        return None
    C = max(seen, key=seen.get)
    if seen[C] < 2:
        return None
    holds = float(np.mean(Feedthrough.descramble(b, _taps(C))[C.bit_length():] == 0))
    return C, C.bit_length() - 1, holds

scrambler

Blind scrambler search: self-synchronising (feedthrough) scramblers, and additive ones (and bare LFSR sequences: PRBS)

A feedthrough scrambler sends y[n] = d[n] ^ y[n-a] ^ y[n-b] ^ ...: descrambling is d[n] = y[n] ^ y[n-a] ^ y[n-b] ^ ..., with no seed to find (the register fills from the received bits). Descrambling white bits with a wrong polynomial gives white bits; the right one gives the data back, which almost always has structure: idle ones or zeros, HDLC flags, fixed headers, frames. So every polynomial up to a degree is tried and the one whose output is furthest from white wins.

"White" here means looking random: about half ones, no byte pattern more common than another, no autocorrelation. Bits that come out all ones (an idle line) or full of one pattern are the opposite, and the strongest evidence there is.

A multiple of the right polynomial also leaves structure (it is the right one followed by another descrambler, which keeps a constant constant), so among the polynomials that stand out the one of lowest degree, then fewest taps, is taken. Output that stays white under every polynomial was not scrambled this way, or what is under it is itself random (compressed or encrypted data, or another layer such as an additive scrambler or a code).

An additive (synchronous) scrambler sends y[n] = d[n] ^ s[n], s an LFSR sequence. Wherever the data is constant for a while (idle fill, padding, a fixed header) y is the LFSR sequence itself, or its complement, and a stretch of it has linear complexity L (its register length) where random bits have half their length (additive_search, by Berlekamp-Massey over sliding windows). A bare PRBS (a test pattern: ITU-T O.150/O.151) is the same everywhere.

Functions:

Name Description
structure

How far bits are from white, as z-scores: {"bias", "bytes", "autocorr", "score" (the largest)}

polynomials

Tap sets to try: every 1..max_taps taps up to max_degree (1 + x^a is differential decoding / NRZI at a=1)

search

Find the feedthrough scrambler on hard bits. Returns (hypotheses best first, trials, Guess or None)

explain

Factor an LFSR recurrence into known scramblers and what is left: (scramblers [(taps, name, times)], the period

lfsr_name

A known name for these taps (or their reciprocal), else the polynomial written out

recurrence_holds

Per bit n >= max(taps): whether s[n] = XOR s[n-t] holds (1) there

additive_search

Find an LFSR sequence in hard bits: a bare PRBS, or an additive scrambler showing through constant data. Returns

descramblers

Self-synchronising descramblers {name: taps}: out[t] = in[t] ^ in[t-k] for each tap

cached_scrambler

A scrambler definition's JSON (its "poly": the taps), read once

structure

structure(bits, lags=4096)

How far bits are from white, as z-scores: {"bias", "bytes", "autocorr", "score" (the largest)}

bias: ones vs zeros. bytes: chi-square of the byte values (the most uneven of the 8 bit alignments). autocorr: the strongest autocorrelation up to lags (frames, repeated headers; 0 when lags is 0)

Source code in src/rpps/analysis/sequence/scrambler.py
def structure(bits, lags=4096):
    """How far bits are from white, as z-scores: {"bias", "bytes", "autocorr", "score" (the largest)}

    bias: ones vs zeros. bytes: chi-square of the byte values (the most uneven of the 8 bit alignments). autocorr: the
    strongest autocorrelation up to `lags` (frames, repeated headers; 0 when lags is 0)"""
    b = np.asarray(bits, dtype=np.uint8)
    N = len(b)
    out = {"bias": float(abs(2*b.mean() - 1)*np.sqrt(N)) if N else 0.0}
    chi = 0.0
    for off in range(8):
        B = np.packbits(b[off:][:(N - off)//8*8])
        if len(B) < 512:
            continue
        c = np.bincount(B, minlength=256)
        e = len(B)/256
        chi = max(chi, (float(((c - e)**2).sum()/e) - 255)/np.sqrt(510))
    out["bytes"] = chi
    out["autocorr"] = 0.0
    if lags and N > 4*lags:
        x = 1.0 - 2.0*b
        x = x - x.mean()
        v = x.var()
        if v > 0:
            F = np.fft.rfft(x, 2*N)
            ac = np.fft.irfft(np.abs(F)**2)[1:lags + 1]/N/v
            out["autocorr"] = float(np.abs(ac).max()*np.sqrt(N))
    out["score"] = max(out.values())
    return out

polynomials

polynomials(max_degree=31, max_taps=2)

Tap sets to try: every 1..max_taps taps up to max_degree (1 + x^a is differential decoding / NRZI at a=1)

Source code in src/rpps/analysis/sequence/scrambler.py
def polynomials(max_degree=31, max_taps=2):
    """Tap sets to try: every 1..max_taps taps up to max_degree (1 + x^a is differential decoding / NRZI at a=1)"""
    out = []
    for k in range(1, max_taps + 1):
        out += [tuple(sorted(c, reverse=True)) for c in itertools.combinations(range(1, max_degree + 1), k)]
    return out

search

search(bits, max_degree=31, max_taps=2, top=20)

Find the feedthrough scrambler on hard bits. Returns (hypotheses best first, trials, Guess or None)

Every polynomial (and none) is scored on bias and byte statistics; the top best get the autocorrelation too. A polynomial stands out when its score is far above what the others typically get (robust z over all of them) and the structure is itself significant, both against the threshold for that many trials times the lags each score is the largest of. The Guess is the feedthrough definition of the lowest-degree one that stands out (see the module docstring), never decoded unless saved and loaded.

Source code in src/rpps/analysis/sequence/scrambler.py
def search(bits, max_degree=31, max_taps=2, top=20):
    """Find the feedthrough scrambler on hard bits. Returns (hypotheses best first, trials, Guess or None)

    Every polynomial (and none) is scored on bias and byte statistics; the `top` best get the autocorrelation too. A
    polynomial stands out when its score is far above what the others typically get (robust z over all of them) and the
    structure is itself significant, both against the threshold for that many trials times the lags each score is the
    largest of. The Guess is the feedthrough definition of the
    lowest-degree one that stands out (see the module docstring), never decoded unless saved and loaded."""
    y = np.asarray(bits, dtype=np.uint8)
    cands = [()] + polynomials(max_degree, max_taps)
    quick = np.array([structure(Feedthrough.descramble(y, t), lags=0)["score"] for t in cands])
    order = np.argsort(-quick)[:top]
    full = quick.copy()
    for i in order:
        full[i] = structure(Feedthrough.descramble(y, cands[i]))["score"]
    med = float(np.median(quick))
    mad = float(np.median(np.abs(quick - med)))*1.4826 or 1.0
    crit = z_critical(len(cands)*4096) # Each score is itself the largest of many (byte alignments, autocorrelation lags)
    hyps = []
    for i in np.argsort(-full)[:top]:
        rz = (full[i] - med)/mad
        if rz > crit and full[i] > crit:
            t = cands[i]
            hyps.append(Hypothesis("scrambler", "none" if not t else "1 + " + " + ".join(f"x^{a}" for a in t), float(rz),
                                   {"taps": list(t), "score": float(full[i]), "median": med}))
    guess = None
    if hyps:
        best = hyps[0].z
        near = [h for h in hyps if h.z >= 0.5*best]
        pick = min(near, key=lambda h: (max(h.params["taps"], default=0), len(h.params["taps"]), -h.z))
        hyps.remove(pick)
        hyps.insert(0, pick)
        if pick.params["taps"]:
            taps = pick.params["taps"]
            guess = Guess("scramble", {"base": "scramble", "type": "feedthrough", "register": "fibonacci",
                                       "comment": f"found by rpps.analysis.sequence.scrambler.search: {pick.name}",
                                       "poly": taps, "seed": [1]*max(taps)},
                          {"z": pick.z, "score": pick.params["score"], "median": med})
    return hyps, len(cands), guess

explain

explain(taps, max_period=4096)

Factor an LFSR recurrence into known scramblers and what is left: (scramblers [(taps, name, times)], the period the data under them repeats with (the least P whose x^P + 1 the rest divides; None if none up to max_period), rest)

A feedthrough scrambler over data that repeats every P bits gives a sequence whose minimal polynomial is the scrambler's times a divisor of x^P + 1 (the data's own recurrence); two scramblers in cascade multiply.

Source code in src/rpps/analysis/sequence/scrambler.py
def explain(taps, max_period=4096):
    """Factor an LFSR recurrence into known scramblers and what is left: (scramblers [(taps, name, times)], the period
    the data under them repeats with (the least P whose x^P + 1 the rest divides; None if none up to max_period), rest)

    A feedthrough scrambler over data that repeats every P bits gives a sequence whose minimal polynomial is the
    scrambler's times a divisor of x^P + 1 (the data's own recurrence); two scramblers in cascade multiply."""
    rest = _poly(taps)
    found = []
    for t, name in sorted(_scrambler_polys().items(), key=lambda kv: -max(kv[0])):
        g, k = _poly(t), 0
        while rest.bit_length() > g.bit_length() - 1 and rest != 1:
            q, r = pdivmod(rest, g)
            if r:
                break
            rest, k = q, k + 1
        if k:
            found.append((list(t), name, k))
    period = None
    if rest == 1:
        period = 1
    else:
        x_p = 1 # x^P mod rest, P counting up: rest divides x^P + 1 where that is 1
        for P in range(1, max_period + 1):
            x_p = pdivmod(x_p << 1, rest)[1]
            if x_p == 1:
                period = P
                break
    return found, period, rest

lfsr_name

lfsr_name(taps)

A known name for these taps (or their reciprocal), else the polynomial written out

Source code in src/rpps/analysis/sequence/scrambler.py
def lfsr_name(taps):
    """A known name for these taps (or their reciprocal), else the polynomial written out"""
    t = tuple(sorted(taps, reverse=True))
    if not t:
        return "constant"
    L = t[0]
    rec = tuple(sorted([L - a for a in t[1:]] + [L], reverse=True))
    name = KNOWN_LFSR.get(t) or KNOWN_LFSR.get(rec)
    return name or "1 + " + " + ".join(f"x^{a}" for a in sorted(t))

recurrence_holds

recurrence_holds(bits, taps)

Per bit n >= max(taps): whether s[n] = XOR s[n-t] holds (1) there

Source code in src/rpps/analysis/sequence/scrambler.py
def recurrence_holds(bits, taps):
    """Per bit n >= max(taps): whether s[n] = XOR s[n-t] holds (1) there"""
    s = np.asarray(bits, dtype=np.uint8)
    L = max(taps)
    acc = s[L:].copy()
    for t in taps:
        acc ^= s[L - t:len(s) - t]
    return (acc == 0).astype(np.uint8)
additive_search(bits, window=512, max_len=None, step=None)

Find an LFSR sequence in hard bits: a bare PRBS, or an additive scrambler showing through constant data. Returns (hypotheses best first, windows tried, Guess or None)

Every step bits a window of window bits is put through Berlekamp-Massey; one whose linear complexity is at most max_len (random bits: window/2, within a few) is a stretch of some LFSR's output. The polynomial most windows agree on is the scrambler's; how much of the stream its recurrence predicts tells a PRBS (all of it) from a scrambler over data (the constant stretches) and gives where those stretches are (a frame period, when they repeat).

Source code in src/rpps/analysis/sequence/scrambler.py
def additive_search(bits, window=512, max_len=None, step=None):
    """Find an LFSR sequence in hard bits: a bare PRBS, or an additive scrambler showing through constant data. Returns
    (hypotheses best first, windows tried, Guess or None)

    Every `step` bits a window of `window` bits is put through Berlekamp-Massey; one whose linear complexity is at most
    `max_len` (random bits: window/2, within a few) is a stretch of some LFSR's output. The polynomial most windows agree
    on is the scrambler's; how much of the stream its recurrence predicts tells a PRBS (all of it) from a scrambler over
    data (the constant stretches) and gives where those stretches are (a frame period, when they repeat)."""
    b = np.asarray(bits, dtype=np.uint8)
    step = step or window//2
    max_len = window//2 - 32 if max_len is None else max_len # Random windows come in within a few bits of window/2
    hits, tried = {}, 0
    for start in range(0, len(b) - window + 1, step):
        tried += 1
        C, L = berlekamp_massey(b[start:start + window])
        taps = lfsr_taps(C, L)
        if 0 < L <= max_len and 2*L + 64 <= window and taps:
            hits.setdefault(taps, []).append(start)
    if not hits:
        return [], tried, None
    hyps = []
    for taps, starts in hits.items():
        holds = recurrence_holds(b, taps)
        frac = float(holds.mean())
        # Each window is overwhelming evidence alone (random bits fall that short of window/2 about 2^-(window - 2L) of
        # the time), so the score is how many windows agree
        hyps.append(Hypothesis("scrambler-additive", lfsr_name(taps), float(len(starts)),
                               {"taps": list(taps), "length": max(taps), "windows": len(starts), "of": tried,
                                "holds": frac, "first": starts[0], "prbs": frac > 0.95}))
    hyps.sort(key=lambda h: (-h.params["windows"], h.params["length"]))
    best = hyps[0]
    kind = "a bare PRBS (test pattern)" if best.params["prbs"] else "an additive scrambler showing through constant data"
    scr, period, _ = explain(best.params["taps"])
    if scr and best.name not in KNOWN_LFSR.values():
        # Not a PRBS of its own: known feedthrough scramblers over data that repeats
        names = " then ".join(f"{name} x{k}" if k > 1 else name for _, name, k in scr)
        kind = (f"{names} over data repeating every {period} bits" if period and period > 1 else
                f"{names} over constant data" if period == 1 else f"{names} over data with recurrence of its own")
        best.params["scramblers"] = [{"taps": t, "name": n, "times": k} for t, n, k in scr]
        best.params["data_period"] = period
        if period and period <= 4096: # The data itself: descrambled, the commonest word of `period` bits
            d = b
            for t, _, k in scr:
                for _ in range(k):
                    d = Feedthrough.descramble(d, t)
            d = d[64*max(max(t) for t, _, _ in scr):]
            words = d[:len(d)//period*period].reshape(-1, period)
            vals, counts = np.unique(words, axis=0, return_counts=True)
            w = vals[np.argmax(counts)]
            best.params["pattern"] = "".join(map(str, w))
            best.params["pattern_holds"] = float(counts.max()/len(words))
            kind += f": {best.params['pattern']} ({best.params['pattern_holds']*100:.1f}% of words)"
    best.params["what"] = kind
    best.name = f"{best.name}: {kind}"
    guess = Guess("scramble", {"base": "scramble", "type": "additive", "comment": f"found by rpps.analysis.sequence.scrambler.additive_search: "
                               f"{best.name}, {kind}; the seed and where it restarts are not known yet",
                               "poly": best.params["taps"]}, {"windows": best.params["windows"], "holds": best.params["holds"]})
    return hyps, tried, guess

descramblers

descramblers()

Self-synchronising descramblers {name: taps}: out[t] = in[t] ^ in[t-k] for each tap

Source code in src/rpps/analysis/sequence/scrambler.py
def descramblers():
    """Self-synchronising descramblers {name: taps}: out[t] = in[t] ^ in[t-k] for each tap"""
    return {"g3ruh": (12, 17), "v34": (18, 23), "none": ()}

cached_scrambler cached

cached_scrambler(ref)

A scrambler definition's JSON (its "poly": the taps), read once

Source code in src/rpps/analysis/sequence/scrambler.py
@functools.lru_cache(maxsize=None)
def cached_scrambler(ref):
    """A scrambler definition's JSON (its "poly": the taps), read once"""
    from ... import _config
    return _config.read(_config.find("scramble", ref))

spread

Direct-sequence spread spectrum below the noise: the code period, the chip rate, the code, and the data under it

p = rp.analysis.sequence.spread.period(x, Fs)                      # code period (s), from autocorrelation fluctuations
f = rp.analysis.spectrum.cyclic.features(x, Fs)                    # the chip rate is the |x|^2 line (f.baud)
c = rp.analysis.sequence.spread.code(x, Fs, chip_rate, p.chips)    # the code's chips (up to sign and a cyclic shift)
y = rp.analysis.sequence.spread.despread(c.chips_rx, c.code)       # the data symbols, the code's gain back

A DSSS signal spreads each data symbol over a code of N chips: under the noise, its spectrum shows nothing. Its autocorrelation over a window R(tau) = sum x(t) x*(t + tau) has, at lags of a whole code period, a part from the code repeating, signed by the data: averaged it cancels, but its square does not. So the variance of R_w(tau) over many short windows w (Burel's fluctuation method, the deterministic part taken off: a pulse's own correlation and its ringing are the same in every window) peaks at multiples of the period, while noise alone gives it flat.

With the chip rate (rpps.analysis.spectrum.cyclic: chips are symbols to it) the signal is taken at one sample a chip; cut into windows of the period, the windows are +-code (a symbol each) plus noise when they start at a symbol boundary: their covariance's leading eigenvector is the code (Bouder & Burel). Detection goes further under the noise than recovery: the period's fluctuation peak gains with the record, the chip rate needs the |x|^2 line (searched for in a narrow window once the period is known, still a few dB short: a 127-chip code over 600k samples is detected at -13 dB, recovered at -11). Not aligned, it splits into two eigenvectors, each the code over part of the window and zero elsewhere: the leading one's support gives the misalignment, and windows from there give the code.

Classes:

Name Description
Period

Result of period: lag (samples), fine (the lag between samples, from the peak's shape), seconds, chips (when

Code

Result of code: code (+-1 chips, one period), offset (chips: where a symbol starts in the chip stream),

Functions:

Name Description
fluctuations

Variance over windows of R_w(tau), tau = 0 .. max_lag (R_w the autocorrelation of window w): E|R_w|^2 - |E R_w|^2.

period

The code period of a DSSS signal from autocorrelation fluctuations (see the module). max_period: longest tried

code

The spreading code (chips long) of a DSSS signal at chip_rate (see the module). The carrier must be off to

despread

Symbols: each period of chip samples correlated with the code (the processing gain back; rpps.symbol.despread.correlate)

chip_rate

The chip rate given the code period (lag, samples, maybe a sample off): |x|^2 of a code repeating every period has

Period

Period(**kw)

Result of period: lag (samples), fine (the lag between samples, from the peak's shape), seconds, chips (when chip_rate is given), contrast (the peak over the fluctuations' median at other lags: noise alone stays near 1 + a few sigma), significant

Source code in src/rpps/analysis/sequence/spread.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

Code

Code(**kw)

Result of code: code (+-1 chips, one period), offset (chips: where a symbol starts in the chip stream), chips_rx (the chip-rate samples, from offset), gain (leading eigenvalue over the next: how clear)

Source code in src/rpps/analysis/sequence/spread.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

fluctuations

fluctuations(x, max_lag, window)

Variance over windows of R_w(tau), tau = 0 .. max_lag (R_w the autocorrelation of window w): E|R_w|^2 - |E R_w|^2. A spread code's part is signed by the data, so its mean is 0 and it is all variance; a signal's own correlation (the pulse, its ringing) is the same in every window: all mean, taken off

Source code in src/rpps/analysis/sequence/spread.py
def fluctuations(x, max_lag, window):
    """Variance over windows of R_w(tau), tau = 0 .. max_lag (R_w the autocorrelation of window w): E|R_w|^2 - |E R_w|^2.
    A spread code's part is signed by the data, so its mean is 0 and it is all variance; a signal's own correlation (the
    pulse, its ringing) is the same in every window: all mean, taken off"""
    x = np.asarray(x, dtype=np.complex128)
    nw = (len(x) - max_lag)//window
    p2 = np.zeros(max_lag + 1)
    m = np.zeros(max_lag + 1, dtype=np.complex128)
    N = 1 << int(np.ceil(np.log2(window + max_lag)))
    for i in range(nw):
        seg = x[i*window:i*window + window + max_lag]
        a = np.fft.fft(seg[:window], N)
        b = np.fft.fft(seg, N)
        r = np.fft.ifft(np.conj(a)*b)[:max_lag + 1] # sum_t x*(t) x(t + tau) over the window
        p2 += np.abs(r)**2
        m += r
    nw = max(nw, 1)
    return p2/nw - np.abs(m/nw)**2

period

period(x, Fs, max_period=None, window=None, chip_rate=None, min_lag=None, z_min=6.0)

The code period of a DSSS signal from autocorrelation fluctuations (see the module). max_period: longest tried (samples, default len/64). window: samples a window (default 2 max_period: the code's part adds a symbol at a time, so short windows, more of them, are what helps). min_lag: shortest (default 4 Fs / the occupied bandwidth: the pulse's own correlation). The peak's contrast over the other lags is about 1 + T SNR^2 (T the period in samples, SNR per sample): a long code is found further under the noise. Significance: (contrast - 1) sqrt(windows) over z_min

Source code in src/rpps/analysis/sequence/spread.py
def period(x, Fs, max_period=None, window=None, chip_rate=None, min_lag=None, z_min=6.0):
    """The code period of a DSSS signal from autocorrelation fluctuations (see the module). max_period: longest tried
    (samples, default len/64). window: samples a window (default 2 max_period: the code's part adds a symbol at a time,
    so short windows, more of them, are what helps). min_lag: shortest (default 4 Fs / the occupied bandwidth: the
    pulse's own correlation).
    The peak's contrast over the other lags is about 1 + T SNR^2 (T the period in samples, SNR per sample): a long code
    is found further under the noise. Significance: (contrast - 1) sqrt(windows) over z_min"""
    x = np.asarray(x, dtype=np.complex128)
    max_period = int(max_period or len(x)//64)
    window = int(window or 2*max_period)
    if min_lag is None: # the pulse's own correlation lasts a few times Fs / bandwidth (under the noise: unknown, 8)
        _, bw, _ = cyclic.occupied(x, Fs)
        min_lag = int(max(8, 4*Fs/bw)) if bw > Fs/64 else 8
        min_lag = min(min_lag, max_period//4)
    F = fluctuations(x, max_period, window)
    nw = (len(x) - max_period)//window
    base = np.median(F[min_lag:])
    G = F/base
    G[:min_lag] = 0
    z = (G - 1)*np.sqrt(max(nw, 1))
    # A code period is a peak standing clear of the lags around it; a signal's own correlation decays from lag 0
    _, bw_, _ = cyclic.occupied(x, Fs)
    d = int(max(2, 2*np.ceil(Fs/max(bw_, Fs/8))))
    left = np.concatenate((np.full(d, np.inf), F[:-d]))
    right = np.concatenate((F[d:], np.full(d, np.inf)))
    peak = F > 1.5*np.minimum(left, right) # above at least one side by half again: not on a slope from lag 0
    peak &= F >= np.maximum(np.concatenate(([0], F[:-1])), np.concatenate((F[1:], [0])))
    z = np.where(peak, z, 0.0)
    top = z.max()
    lag = int(np.flatnonzero(z >= 0.7*top)[0]) if top > 0 else 0 # the first lag standing out: its multiples do too
    chips = int(round(lag/Fs*chip_rate)) if chip_rate else None
    if 0 < lag < len(F) - 1: # the peak between samples: a parabola through it and its neighbours
        a, b, c = F[lag - 1], F[lag], F[lag + 1]
        den = a - 2*b + c
        frac = float(lag + 0.5*(a - c)/den) if abs(den) > 1e-300 else float(lag)
    else:
        frac = float(lag)
    return Period(lag=lag, fine=frac, seconds=lag/Fs, chips=chips, contrast=float(G[lag]), significant=bool(z[lag] > z_min), z=float(z[lag]),
                  fluct=F)

code

code(x, Fs, chip_rate, chips, beta=0.35)

The spreading code (chips long) of a DSSS signal at chip_rate (see the module). The carrier must be off to well under the symbol rate (chip_rate / chips) or the windows turn: take cyclic.features' cfo off first

Source code in src/rpps/analysis/sequence/spread.py
def code(x, Fs, chip_rate, chips, beta=0.35):
    """The spreading code (`chips` long) of a DSSS signal at `chip_rate` (see the module). The carrier must be off to
    well under the symbol rate (chip_rate / chips) or the windows turn: take cyclic.features' cfo off first"""
    s, _ = cyclic.symbol_instants(x, Fs, chip_rate, beta)
    P = int(chips)
    n = len(s)//P
    if n < 32:
        raise ValueError(f"{n} periods: need 32 or more")
    V = s[:n*P].reshape(n, P)
    w, U = _eig(V)
    e = np.abs(U[:, 0])
    # The leading eigenvector is the code over one run of the window (cyclically) and ~0 elsewhere: where it starts
    big = e > 0.5*e.max()
    starts = np.flatnonzero(big & ~np.roll(big, 1))
    if len(starts) and not big.all():
        # the run's start is where symbols start, unless the run is the shorter part: then the other eigenvector's
        lengths = [(np.flatnonzero(~np.roll(big, -st)[1:])[0] + 1 if (~np.roll(big, -st)).any() else P) for st in starts]
        st = int(starts[int(np.argmax(lengths))])
        offset = st if max(lengths) >= P/2 else (st + max(lengths)) % P
    else:
        offset = 0
    s2 = s[offset:]
    n2 = len(s2)//P
    V2 = s2[:n2*P].reshape(n2, P)
    w2, U2 = _eig(V2)
    c = U2[:, 0]
    c = c*np.exp(-1j*np.angle(np.sum(c))) # one phase for all: real chips +-1
    code_ = np.where(c.real >= 0, 1, -1)
    return Code(code=code_, offset=int(offset), chips_rx=s2, gain=float(w2[0]/max(w2[1], 1e-30)))

despread

despread(chips_rx, code_)

Symbols: each period of chip samples correlated with the code (the processing gain back; rpps.symbol.despread.correlate)

Source code in src/rpps/analysis/sequence/spread.py
def despread(chips_rx, code_):
    """Symbols: each period of chip samples correlated with the code (the processing gain back; rpps.symbol.despread.correlate)"""
    from ...sequence.code import Code as Chips
    from ...symbol.despread import correlate
    P = len(code_)
    n = len(chips_rx)//P
    return correlate(np.asarray(chips_rx)[:n*P], Chips("blind", code_), 1)[:, 0]

chip_rate

chip_rate(x, Fs, lag, min_sps=2.0, pfa=0.001, fluct=None, fine=None)

The chip rate given the code period (lag, samples, maybe a sample off): |x|^2 of a code repeating every period has lines at multiples of 1/period; the chip rate is the strongest significant one (the pulse's line) near such a multiple, at most Fs / min_sps; without one (far under the noise), from the width of the fluctuation peak (fluct, Period.fluct, and fine, Period.fine, for the narrow search): a chip. Returns (chip rate Hz, chips a period, the period refined: chips / chip rate, s)

Source code in src/rpps/analysis/sequence/spread.py
def chip_rate(x, Fs, lag, min_sps=2.0, pfa=1e-3, fluct=None, fine=None):
    """The chip rate given the code period (lag, samples, maybe a sample off): |x|^2 of a code repeating every period has
    lines at multiples of 1/period; the chip rate is the strongest significant one (the pulse's line) near such a
    multiple, at most Fs / min_sps; without one (far under the noise), from the width of the fluctuation peak (`fluct`,
    Period.fluct, and `fine`, Period.fine, for the narrow search): a chip. Returns (chip rate Hz, chips a period, the period refined: chips / chip rate, s)"""
    x = np.asarray(x, dtype=np.complex128)
    ls = [l for l in cyclic.lines(np.abs(x)**2, Fs, 2*Fs/lag, Fs/min_sps, pfa, top=16) if l.significant]
    best = None
    for l in sorted(ls, key=lambda l: -l.strength):
        k = round(l.freq*lag/Fs)
        if k >= 2 and abs(l.freq - k*Fs/lag) < 1.2*k*Fs/lag**2 + 0.05*Fs/lag: # a sample of lag error moves it k Fs/lag^2
            best = (l.freq, k)
            break
    if best is None:
        if fluct is None:
            raise ValueError("no |x|^2 line at a multiple of the code rate (pass the fluctuations for the peak's width)")
        # Under the noise the line goes first: the fluctuation peak at the period is a chip wide (the code's
        # correlation moved by a chip is gone), so its half-height width is a chip
        F = np.asarray(fluct, dtype=float)
        lo = max(lag - lag//4, 1)
        seg = F[lo:lag + lag//4]
        base = np.median(F[8:])
        h = seg - base
        top = h.max()
        above = np.flatnonzero(h >= top/2)
        width = float(above[-1] - above[0] + 1) if len(above) else 1.0
        k0 = lag/max(width, 1.0)
        # the width is the pulse's (about 0.75 of a chip for root-raised cosine chips): among the harmonics of the
        # period near it, the chip rate is the one |x|^2 has the most power at, line or not
        z = np.abs(x)**2
        z = (z - z.mean())*np.hanning(len(z))
        N = 1 << int(np.ceil(np.log2(4*len(z))))
        S = np.abs(np.fft.rfft(z, N))**2
        ks = np.arange(max(2, int(0.5*k0)), int(2.0*k0) + 2)
        bins = np.round(ks*Fs/lag/(Fs/N)).astype(int)
        ok = bins < len(S) - 3
        ks, bins = ks[ok], bins[ok]
        # a lag error e moves harmonic k by k Fs e / lag^2: e a sample for an integer lag, a quarter for a fine one
        err = 0.25 if fine else 1.2
        lag = fine or lag
        bins = np.round(ks*Fs/lag/(Fs/N)).astype(int)
        win = int(np.ceil(err*ks.max()*Fs/lag**2/(Fs/N))) + 1
        pw = np.array([S[max(b_ - win, 0):b_ + win + 1].max() for b_ in bins])
        # ... and of the strongest few, the one whose code comes out clearest (the leading eigenvalue's lead): at the
        # wrong chip rate the windows hold no fixed code
        # The period is known to a sample, so harmonic k only to k Fs/lag^2: a rate that far off slips the chips by
        # hundreds over the record and no window holds the code. Its line, searched for in that small window only, is
        # found far under the threshold a whole-band search needs: the rate to a fraction of a bin
        best = None
        for k in ks[np.argsort(-pw)[:5]]:
            b0 = int(round(k*Fs/lag/(Fs/N)))
            lo_, hi_ = max(b0 - win, 1), min(b0 + win + 1, len(S) - 1)
            j = lo_ + int(np.argmax(S[lo_:hi_]))
            a, b, c = np.log(S[j - 1:j + 2] + 1e-300)
            d = 0.5*(a - c)/(a - 2*b + c) if abs(a - 2*b + c) > 1e-12 else 0.0
            R = (j + d)*Fs/N
            try:
                g = code(x, Fs, R, int(k)).gain
            except ValueError:
                continue
            if best is None or g > best[0]:
                best = (g, R, int(k))
        if best is None:
            k = int(ks[int(np.argmax(pw))])
            return k*Fs/lag, k, lag/Fs
        _, R, k = best
        return float(R), k, k/R
    R, k = best
    return float(R), int(k), k/R

rpps.analysis.signal_profile

A signal's profile: every step it takes to process it, as far as analysis can tell, and what it might be where it can't

profiles = rp.analysis.profile(rp.source.File("ci16t", "capture.cs16", Fs=100e6))   # every signal the survey finds
profiles = rp.analysis.profile(src, signals=[0, 3])                                   # or some of them
for p in profiles:
    print(p)                       # numbered steps; an unsolved one ends the list with its top candidates
p.solved, p.to_dict(), p.rx()      # whether every step is known, a JSON-able form, the receiver (when solved)

Each signal goes through the chain once: its channel (every signal's from one rp.signal.FFTBank: one FFT of the capture a hop for all of them), Acquire (rate, modulation, offset), the matrix matched filter and feed-forward carrier, then AcquireFEC (the code, its bit map and alignment, with the blind tools when blind). When no code is found, shipped profiles that find their own frames (a preamble and a header: DVB-S2) are run on the timed symbols, and named by what their own checks verify (rank: a step whose CRC or header code passes; the most general profile when nothing past a shared header tells them apart). A step is "found" (a definition covers it), "guess" (a blind find: a definition once saved, see rpps.analysis.result.Guess) or "unsolved", which ends the profile with what it might be: hypotheses and their weight, a softmax over their z-scores (a clear leader near 100%, close calls shared).

rpps.analysis.spectrum

What is in a capture and at what rate (see rpps.analysis)

Modules:

Name Description
burst

Moved to rpps.analysis.burst. demodulate (stable API) stays here for one release with a DeprecationWarning

cyclic

Cyclostationary features: the symbol rate and carrier lines a signal has, and how sure each one is

find

Signals in a capture: centre, width, SNR and when they are on, with a false-alarm rate you set

hopping

Frequency hopping: the hops, their dwell, the hop set and its spacing, and the signal de-hopped

levels

The finder's steps 4-6 (rpps.analysis.spectrum.find): a line raised from the floor; a signal comes up and holds

ofdm_pilots

OFDM pilot patterns, blind: which cells of the time-frequency grid carry known values, and the lattice they form

pencil

Spectral lines from short records: the matrix pencil (Hua & Sarkar 1990)

psd
scf

Spectral coherence over all cycle frequencies (FFT accumulation), the significant ones, and blind FRESH filtering

separate

Two signals of equal power on one channel, separated: each one's carrier and timing, then both symbol streams

signal
waveform

What kind of waveform a signal is, when it isn't a single linearly modulated carrier: tones, OFDM, bursts

burst

Moved to rpps.analysis.burst. demodulate (stable API) stays here for one release with a DeprecationWarning

Functions:

Name Description
demodulate

rpps.analysis.burst.demodulate, under its old name: it goes in the next release

demodulate

demodulate(*args, **kwargs)

rpps.analysis.burst.demodulate, under its old name: it goes in the next release

Source code in src/rpps/analysis/spectrum/burst.py
3
4
5
6
7
8
9
def demodulate(*args, **kwargs):
    """rpps.analysis.burst.demodulate, under its old name: it goes in the next release"""
    import warnings
    from ..burst import demodulate as _demodulate
    warnings.warn("rp.analysis.spectrum.burst.demodulate moved to rp.analysis.burst.demodulate; the old name goes in "
                  "the next release", DeprecationWarning, stacklevel=2)
    return _demodulate(*args, **kwargs)

cyclic

Cyclostationary features: the symbol rate and carrier lines a signal has, and how sure each one is

f = rp.analysis.spectrum.cyclic.features(x, Fs)    # x at baseband, a few times wider than the signal
print(f)                                  # e.g. "baud 1.000 MHz (line 31 dB over the floor, P_fa 1e-12); carrier
                                          #  lines x^4 at +12.3 kHz: QPSK / QAM / APSK"
f.baud, f.order, f.cfo                    # None where no line is significant: "no rate" is an answer

A linearly modulated signal is cyclostationary: its statistics repeat every symbol. Put through a nonlinearity, it gives spectral lines a stationary signal (noise, OFDM without its prefix, a carrier with a continuous phase) does not: |x|^2 a line at the symbol rate (stronger the larger the roll-off: the line lives in the band edges) x^M a line at M times the carrier offset when the constellation repeats every 360/M degrees (x^2 for BPSK / ASK, x^4 for QPSK and QAM, x^8 for 8PSK, x^12 for 4+12 / 4+12+16 APSK), with side lines at that +- the symbol rate. Between symbols the pulses overlap and spoil high powers, so once the rate is known the powers are also taken of matched-filtered samples at the symbol instants (symbol_instants), far more sensitive at small roll-off and for x^8 / x^12; noise raised to the 12th power needs Es/N0 near 15 dB or more x a line at the carrier itself if any of it is left (a pilot tone, AM, an unbalanced constellation) |d|^2 d = the instantaneous frequency (x[n] conj(x[n-1])): a line at the symbol rate for a constant-envelope signal (FSK, MSK, CPM) whose |x|^2 is flat

Each line is tested against the spectrum around it. Without a line, the power of a periodogram bin is exponential about its local mean, so a bin r times over the floor happens with probability exp(-r); over K bins searched, the chance noise alone gives one that high is P_fa = 1 - (1 - exp(-r))^K; the floor is itself estimated from about m bins, which makes the tail (1 + r/m)^-m instead. A line is significant when P_fa is under pfa. The floor is the local median over ln 2 (robust to the lines themselves).

The band the signal occupies is estimated first (Welch PSD over its floor) and everything else is filtered off (a Wiener mask), so the noise outside the signal does not dilute the lines.

scf is the spectral correlation function (FFT accumulation method) for a picture of all cyclic frequencies at once.

Classes:

Name Description
Line

A spectral line of a nonlinearity of the signal. kind: one of KINDS. freq: where it is (Hz; for x^M, M times the

Features

Result of features.

Functions:

Name Description
lines

Significant spectral lines of the sequence z (sampled at Fs) between lo and hi Hz (negative frequencies allowed for

spectrum_floor

The noise floor of a power spectrum: its q-th percentile, the bins more than stop_db under the median left out

occupied

(Wiener mask over FFT bins of x's length, occupied bandwidth Hz, (lowest, highest) frequency over the floor Hz): the

comb_rate

The symbol rate behind a set of significant lines (cyclic.Line) of a nonlinearity of the signal: every line is a

symbol_instants

Matched-filtered samples at the symbol instants: an RRC at the baud (roll-off beta, a guess: a mismatch only

features

Symbol rate and carrier lines of baseband samples x (see the module). lo/hi: the symbol rates searched, Hz

scf

Spectral correlation function by the FFT accumulation method (Roberts, Brown & Loomis 1991).

alpha_profile

Max over frequency of |SCF| against cyclic frequency alpha (alpha = 0 removed): (alpha Hz, profile). The symbol rate

Line

Line(kind, freq, strength, pfa, significant)

A spectral line of a nonlinearity of the signal. kind: one of KINDS. freq: where it is (Hz; for x^M, M times the carrier offset). strength: its power over the local floor (linear). pfa: chance noise gives one that strong in the band searched. significant: pfa under the threshold asked for

Source code in src/rpps/analysis/spectrum/cyclic.py
def __init__(self, kind, freq, strength, pfa, significant):
    self.kind, self.freq, self.strength, self.pfa, self.significant = kind, freq, strength, pfa, significant

Features

Features(**kw)

Result of features.

baud: the symbol rate (Hz) from the strongest significant |x|^2 line, else from |d|^2 (constant envelope), else None. baud_line: that Line. baud_from: "|x|^2" or "|d|^2". order: the smallest M whose x^M spectrum has a significant line (1, 2, 4, 8), None without one. cfo: carrier offset (Hz) from that line (ambiguous by Fs/M). carrier: {M: Line} of every significant x^M line. confirmed: the x^M line has side lines at +- baud (the rate and carrier belong to one signal). envelope: E|x|^4 / (E|x|^2)^2 (1 constant envelope, 1.3-1.8 filtered PSK/QAM, 2 Gaussian). bandwidth: of the occupied band (Hz). lines: every line tested.

Attributes:

Name Type Description
linear

A symbol rate seen in |x|^2: a linearly modulated carrier (PSK, QAM, APSK, ASK)

Source code in src/rpps/analysis/spectrum/cyclic.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))
linear property
linear

A symbol rate seen in |x|^2: a linearly modulated carrier (PSK, QAM, APSK, ASK)

lines

lines(z, Fs, lo, hi, pfa=0.001, top=4, pad=2, width=None, exclude=None)

Significant spectral lines of the sequence z (sampled at Fs) between lo and hi Hz (negative frequencies allowed for a complex z): up to top Lines, strongest first, each at least exclude Hz from a stronger one (default 4 bins)

Source code in src/rpps/analysis/spectrum/cyclic.py
def lines(z, Fs, lo, hi, pfa=1e-3, top=4, pad=2, width=None, exclude=None):
    """Significant spectral lines of the sequence `z` (sampled at Fs) between lo and hi Hz (negative frequencies allowed for
    a complex z): up to `top` Lines, strongest first, each at least `exclude` Hz from a stronger one (default 4 bins)"""
    z = np.asarray(z)
    n = len(z)
    if n < 64:
        return []
    w = np.hanning(n)
    z = (z - np.mean(z))*w if np.isrealobj(z) else z*w
    N = pad*n
    P = np.abs(np.fft.fft(z, N))**2/np.sum(w**2)
    f = np.fft.fftfreq(N, 1/Fs)
    order = np.argsort(f)
    P, f = P[order], f[order]
    width = width or 128*pad + 1
    fl = _floor(P, width)
    m = max(4.0, 0.43*width/pad) # Effective exponential samples behind a median floor (Hann: ~1.5 bins each)
    r = P/np.maximum(fl, 1e-300)
    band = (f >= lo) & (f <= hi)
    if not band.any():
        return []
    K = max(1, int(band.sum()//pad)) # independent bins searched
    idx = np.flatnonzero(band)
    exclude = 4*Fs/n if exclude is None else exclude
    out = []
    rb = r[idx].copy()
    for _ in range(top):
        j = int(np.argmax(rb))
        if rb[j] <= 0:
            break
        k = idx[j]
        d = parabolic_offset(*np.log(P[k-1:k+2] + 1e-300)) if 0 < k < N - 1 else 0.0
        fk = f[k] + d*Fs/N
        s = float(r[k])
        q = np.exp(-m*np.log1p(s/m)) # One bin over s: (1 + s/m)^-m, the floor itself being an estimate
        p = float(-np.expm1(K*np.log1p(-min(q, 1 - 1e-16)))) # Any of K bins: 1 - (1 - q)^K
        out.append(Line(None, float(fk), s, p, p < pfa))
        rb[np.abs(f[idx] - f[k]) < exclude] = 0
    return out

spectrum_floor

spectrum_floor(S, q=10, stop_db=50.0)

The noise floor of a power spectrum: its q-th percentile, the bins more than stop_db under the median left out (a channelizer's stopband, zeros: not noise, and far under it)

Source code in src/rpps/analysis/spectrum/cyclic.py
def spectrum_floor(S, q=10, stop_db=50.0):
    """The noise floor of a power spectrum: its q-th percentile, the bins more than `stop_db` under the median left out
    (a channelizer's stopband, zeros: not noise, and far under it)"""
    S = np.asarray(S, dtype=float)
    keep = S > np.median(S)*10**(-stop_db/10)
    return float(np.percentile(S[keep], q)) if keep.any() else float(np.percentile(S, q))

occupied

occupied(x, Fs, nfft=1024)

(Wiener mask over FFT bins of x's length, occupied bandwidth Hz, (lowest, highest) frequency over the floor Hz): the signal's band estimated from a Welch PSD over its floor (the quietest tenth of the spectrum)

Source code in src/rpps/analysis/spectrum/cyclic.py
def occupied(x, Fs, nfft=1024):
    """(Wiener mask over FFT bins of x's length, occupied bandwidth Hz, (lowest, highest) frequency over the floor Hz): the
    signal's band estimated from a Welch PSD over its floor (the quietest tenth of the spectrum)"""
    n = len(x)
    nfft = int(min(nfft, 2**int(np.log2(max(n//8, 16)))))
    seg = n//nfft
    S = np.mean(np.abs(np.fft.fft(x[:seg*nfft].reshape(seg, nfft)*np.hanning(nfft), axis=1))**2, axis=0)
    S = np.convolve(np.concatenate((S[-2:], S, S[:2])), np.ones(5)/5, mode="valid") # a little smoothing, circular
    N0 = spectrum_floor(S)
    sig = np.maximum(S - N0, 0)
    bw = Fs*np.count_nonzero(sig >= N0)/nfft # Bins over 0 dB SNR
    # Wiener gain, never under -20 dB and smoothed over a few bins: a mask with hard zeros or steps makes edges a running
    # floor cannot follow (false lines there)
    band, edges = _edges(sig >= N0, sig, Fs)
    G = np.maximum(sig/np.maximum(S, 1e-300)*band, 0.01) # only the signal's own band: a spur elsewhere would make lines
    G = np.convolve(np.concatenate((G[-5:], G, G[:5])), np.hanning(11)/np.sum(np.hanning(11)), mode="valid")
    G = np.sqrt(G) # Amplitude gain
    fb = np.fft.fftfreq(nfft)
    fx = np.fft.fftfreq(n)
    o = np.argsort(fb)
    mask = np.interp(fx, fb[o], G[o], period=1.0)
    return mask, bw, edges

comb_rate

comb_rate(lines, Fs, lo=0.0, explain=0.85)

The symbol rate behind a set of significant lines (cyclic.Line) of a nonlinearity of the signal: every line is a harmonic k R, or one folded about the sample rate, Fs - k R. The rate is the largest R whose harmonics explain explaining the most of the lines' strength (dB over the floor, summed), within (1 - explain)/3 of the best: a submultiple of R explains them as well but is smaller, a multiple leaves R's own line unexplained. Returns (R, the strongest line on R's comb)

Source code in src/rpps/analysis/spectrum/cyclic.py
def comb_rate(lines, Fs, lo=0.0, explain=0.85):
    """The symbol rate behind a set of significant lines (cyclic.Line) of a nonlinearity of the signal: every line is a
    harmonic k R, or one folded about the sample rate, Fs - k R. The rate is the largest R whose harmonics explain
    explaining the most of the lines' strength (dB over the floor, summed), within (1 - `explain`)/3 of the best: a
    submultiple of R explains them as well but is smaller, a multiple leaves R's own line unexplained. Returns (R, the strongest line on R's comb)"""
    pool = []
    for l in sorted(lines, key=lambda l: -l.strength): # one per frequency
        if all(abs(l.freq - m.freq) > 1e-3*l.freq for m in pool):
            pool.append(l)
    total = sum(l.db for l in pool)
    def on(f, R):
        tol = 2e-3*f + 1e-6*Fs
        for g in (f, Fs - f):
            k = round(g/R)
            if 1 <= k <= HARMONICS and abs(g - k*R) < tol: # the 61st harmonic of some R lands near anything
                return True
        return False
    cands = []
    for l in pool:
        for d in range(1, 7):
            R = l.freq/d
            if R < lo:
                break
            cands.append((sum(m.db for m in pool if on(m.freq, R))/total, R))
    top = max(c[0] for c in cands)
    # The most explained; of those about as good (a submultiple explains as much), the largest
    R = max(R for share, R in cands if share >= top - (1 - explain)/3)
    near = [l for l in pool if abs(l.freq - R) < 2e-3*R + 1e-6*Fs]
    if near: # The rate from its own line where there is one (a better estimate than a harmonic's divided)
        R = near[0].freq
    line = max((l for l in pool if on(l.freq, R)), key=lambda l: l.strength)
    return R, line

symbol_instants

symbol_instants(x, Fs, baud, beta=0.35, taps=8)

Matched-filtered samples at the symbol instants: an RRC at the baud (roll-off beta, a guess: a mismatch only leaves a little ISI), timing from the phase of the |y|^2 line (its cyclic component peaks at the instants). Returns (symbols, first instant in samples)

Source code in src/rpps/analysis/spectrum/cyclic.py
def symbol_instants(x, Fs, baud, beta=0.35, taps=8):
    """Matched-filtered samples at the symbol instants: an RRC at the baud (roll-off `beta`, a guess: a mismatch only
    leaves a little ISI), timing from the phase of the |y|^2 line (its cyclic component peaks at the instants).
    Returns (symbols, first instant in samples)"""
    from ...signal.filters.shaping import rrc_pulse
    sps = Fs/baud
    span = 8
    t = np.arange(-int(np.ceil(span*sps)), int(np.ceil(span*sps)) + 1)/sps
    h = rrc_pulse(t, beta)
    h = h/np.sqrt(np.sum(h**2))
    nfft = 1 << int(np.ceil(np.log2(len(x) + len(h))))
    y = np.fft.ifft(np.fft.fft(x, nfft)*np.fft.fft(h, nfft))[len(h)//2:len(h)//2 + len(x)]
    n = np.arange(len(y))
    c = np.sum(np.abs(y)**2*np.exp(-2j*np.pi*baud*n/Fs))
    tau = (-np.angle(c)/(2*np.pi)*sps) % sps # c ~ exp(-j 2 pi tau/sps): the line peaks at tau
    k = np.arange(int(np.ceil((REACH - tau)/sps)), int((len(y) - REACH - 1 - tau)//sps))
    from ...math import interp
    return interp.fractional(y, tau + k*sps, taps), tau

features

features(x, Fs, lo=None, hi=None, pfa=0.001, orders=(1, 2, 4, 8, 12), mask=True, max_samples=2 ** 22)

Symbol rate and carrier lines of baseband samples x (see the module). lo/hi: the symbol rates searched, Hz (default Fs/64 .. Fs/1.5). pfa: false-alarm probability of a line. mask: filter to the occupied band first

Silence (zeros, too few samples) has no lines, whatever np.seterr the caller set; samples that are not finite (NaN, inf) are a ValueError that says so

Source code in src/rpps/analysis/spectrum/cyclic.py
def features(x, Fs, lo=None, hi=None, pfa=1e-3, orders=(1, 2, 4, 8, 12), mask=True, max_samples=2**22):
    """Symbol rate and carrier lines of baseband samples x (see the module). lo/hi: the symbol rates searched, Hz
    (default Fs/64 .. Fs/1.5). pfa: false-alarm probability of a line. mask: filter to the occupied band first

    Silence (zeros, too few samples) has no lines, whatever np.seterr the caller set; samples that are not finite (NaN,
    inf) are a ValueError that says so"""
    x = np.asarray(x, dtype=np.complex128)[:max_samples]
    if not np.all(np.isfinite(x)):
        raise ValueError("features: the samples are not all finite (NaN or inf)")
    with np.errstate(divide="ignore", invalid="ignore", over="ignore", under="ignore"):
        return _features(x, Fs, lo, hi, pfa, orders, mask)

scf

scf(x, Fs, nfft=64, frames=None, hop=None)

Spectral correlation function by the FFT accumulation method (Roberts, Brown & Loomis 1991).

Returns (f, alpha, S): S[i, j] = |S_x^alpha(f)| at f[i], alpha[j] (Hz), on the grid of channel pairs. nfft: channels (frequency resolution Fs/nfft). frames: how many windows of hop samples are used (alpha resolution Fs/(frames hop))

Source code in src/rpps/analysis/spectrum/cyclic.py
def scf(x, Fs, nfft=64, frames=None, hop=None):
    """Spectral correlation function by the FFT accumulation method (Roberts, Brown & Loomis 1991).

    Returns (f, alpha, S): S[i, j] = |S_x^alpha(f)| at f[i], alpha[j] (Hz), on the grid of channel pairs. nfft: channels
    (frequency resolution Fs/nfft). frames: how many windows of hop samples are used (alpha resolution Fs/(frames hop))"""
    x = np.asarray(x, dtype=np.complex128)
    hop = nfft//4 if hop is None else hop
    P = (len(x) - nfft)//hop + 1 if frames is None else frames
    P = int(2**int(np.log2(max(P, 2))))
    if (P - 1)*hop + nfft > len(x):
        raise ValueError("Too few samples for the frames asked")
    idx = np.arange(nfft)[None, :] + hop*np.arange(P)[:, None]
    X = np.fft.fftshift(np.fft.fft(x[idx]*np.hamming(nfft), axis=1), axes=1) # P x nfft channels
    k = np.arange(-nfft//2, nfft//2)
    X = X*np.exp(-2j*np.pi*k[None, :]*hop*np.arange(P)[:, None]/nfft) # Each channel to baseband (its time reference)
    w = np.hamming(P)[:, None]
    fk = k*Fs/nfft
    Q = P # Output bins per channel pair
    ff, aa, ss = [], [], []
    for a in range(nfft):
        prod = X[:, a:a + 1]*np.conj(X)*w # pairs (a, b) for every b
        Z = np.fft.fftshift(np.fft.fft(prod, axis=0), axes=0)/P # Q x nfft
        q = np.arange(-Q//2, Q//2)*Fs/(hop*P)
        alpha = fk[a] - fk[None, :] + q[:, None]
        f = (fk[a] + fk[None, :])/2 + 0*q[:, None]
        keep = np.abs(q[:, None]) <= Fs/(2*nfft) # The part of each pair's output the pair is responsible for
        keep = np.broadcast_to(keep, Z.shape)
        ff.append(f[keep]); aa.append(alpha[keep]); ss.append(np.abs(Z[keep]))
    return np.concatenate(ff), np.concatenate(aa), np.concatenate(ss)

alpha_profile

alpha_profile(x, Fs, nfft=64, frames=None, bins=None)

Max over frequency of |SCF| against cyclic frequency alpha (alpha = 0 removed): (alpha Hz, profile). The symbol rate and its multiples stand out for a linear modulation

Source code in src/rpps/analysis/spectrum/cyclic.py
def alpha_profile(x, Fs, nfft=64, frames=None, bins=None):
    """Max over frequency of |SCF| against cyclic frequency alpha (alpha = 0 removed): (alpha Hz, profile). The symbol rate
    and its multiples stand out for a linear modulation"""
    f, a, s = scf(x, Fs, nfft, frames)
    bins = bins or 4*nfft*4
    edges = np.linspace(-Fs, Fs, bins + 1)
    j = np.clip(np.digitize(a, edges) - 1, 0, bins - 1)
    prof = np.zeros(bins)
    np.maximum.at(prof, j, s)
    c = (edges[:-1] + edges[1:])/2
    zero = np.abs(c) <= Fs/(nfft)
    prof[zero] = 0
    return c, prof

find

Signals in a capture: centre, width, SNR and when they are on, with a false-alarm rate you set

sv = rp.analysis.spectrum.find.find(x, Fs, cf=cf)       # a Survey of Signal (the same types as find_signals)
for s in sv: s.lo, s.hi, s.snr, s.t0, s.t1, s.bursts

How it works, each step a known detector:

  1. One spectrogram: Hann frames, |FFT|^2 (P[t, f]; every later step reads only this).
  2. The noise floor as a function of frequency (the receiver's passband: tilt, ripple, roll-off), so the spectrum can be whitened: Z = P / floor. The band is cut into blocks, each the mean of its noise bins (FCME: bins clearly in signals are cut out and the floor fitted again), a block with too little noise left interpolated from its neighbours. The floor shows between carriers side by side in their notches: a block whose notches (its least 4-bin means) sit well under its fit is held to them. The first guess is a line through the blocks' low percentiles, fitted again without the blocks over it (a plateau even half the band wide stays out); the receiver's roll-off at the edges is left out.
  3. Detection at a false-alarm rate: under noise the mean of k bins over m frames of Z is Gamma distributed with known degrees of freedom (the window's correlation between bins and between overlapping frames counted), so a threshold for pfa comes from its quantile (Wilson-Hilferty). Widths k = 1, 2, 4... bins are each tested, on means over k bins at a stride of k/2 (a GLRT over an unknown width: a weak wide signal is found at a coarse scale, a narrow one at a fine one), on the mean over all frames and on the most of each group of frames (bursts, which the average dilutes; a max-hold of single frames loses weak steady signals). The test count is split over scales and groups (Bonferroni) and the floor's own error, measured on the noise bins, widens each threshold. A high threshold seeds a detection and a low one grows it (hysteresis, LAD's double threshold); what a width finds is excised before the next (CLEAN).
  4. When it is on: each span's band power frame by frame, gated by the same two thresholds (bursts timed on frames 32 bins of the span wide); a bursty span is measured on the frames it is on.
  5. The signals, read by level (rpps.analysis.spectrum.levels): in each region the detector marked, a line is raised from the floor a step of a few noise deviations at a time. What comes up and holds its sides from one step to the next is a signal; one that comes up out of a wider one stands on it (over; the wider holds it: a pedestal, or a carrier under a narrower signal); a hump's sides never hold. Two carriers side by side come up as one run and part at the notch: the run is only them. Lines (a few bins wide: tones, spurs) are taken out first: no signal.
  6. Each signal's edges: where it falls drop_db under its top, or halfway to where it came up (the floor, a notch, a pedestal) when that is less; it passes the detector at its own width and has an SNR of 3 dB or more (what can't be processed is no signal). A Finder keeps each region's reading while it holds (measured again each step).

Effort (rp.set_effort): fast skips frame overlap and tests bursts only in groups of 8 frames; balanced and max overlap frames by half and test groups of 2 and 8. Every level tests widths up to a quarter of the band: capped lower, a wide weak signal or a hump is found as fragments, each passing on its own.

Classes:

Name Description
FloorFit

The noise floor fitted to a spectrogram (find's step 2): floor per bin (power per Hz), the usable bins a..b (past

Finder

Signals in a stream, block by block (a live display): find over the last frames frames, the floor refitted every

Functions:

Name Description
spectrogram

P[t, f] (fftshifted, power per Hz) and the hop

find

Signals in a capture (see the module): a Survey of Signal sorted by frequency, each with t0/t1 (when it is on,

fit_floor

find's step 2 on a spectrogram P[t, f]: the FloorFit

FloorFit

FloorFit(floor, a, b, sys, busy)

The noise floor fitted to a spectrogram (find's step 2): floor per bin (power per Hz), the usable bins a..b (past the receiver's roll-off), the floor's own error sys (natural log) and busy: the bins clearly signal (left out of the fit, before it was widened)

Source code in src/rpps/analysis/spectrum/find.py
def __init__(self, floor, a, b, sys, busy):
    self.floor, self.a, self.b, self.sys, self.busy = floor, a, b, sys, busy

Finder

Finder(Fs, nfft=4096, cf=0.0, frames=32, refit=None, overlap=None, track=True, hold=-1.0, **kw)

Signals in a stream, block by block (a live display): find over the last frames frames, the floor refitted every refit frames [4 x frames: the receiver's passband changes slowly], ids kept from block to block (Survey.match)

f = Finder(Fs, nfft=4096, cf=cf, frames=frames_in_a_second)
for blk in source(65536):
    sv = f.step(blk.data)       # a Survey (None before a first frame); times [s] from the stream's start

For a display, hold about a second of frames: what is shown then changes little from step to step, and a box follows a change within about that. A step costs the FFTs of its new frames, a detection on the mean (a running sum) and on each new group of frames (one complete is detected once), and the boxes: each region keeps its reading while its span and level hold, its boxes measured again, and is read again when they move or once a window (rpps.analysis.spectrum.levels.boxes; track=False: every step). Bursts are timed by the frames (find times them finer). Frames are cut at fixed places in the stream and the floor refitted at fixed frame counts, so without tracking what it holds after a stretch of samples doesn't depend on how the stretch came in blocks. overlap: of the frames [the effort level's when made]; the rest (pfa, edge, drop_db, ...) as find's.

hold [s]: how long a signal not found again stays in the Survey, marked stale (Signal.stale, as last seen; Signal.seen when it was last found): -1 for good [the default: a display keeps what it has seen], 0 not at all. A stale signal found again has its id back (Survey.match)

Methods:

Name Description
reset

Forget the stream: the next step starts a new one

step

Take a block of samples; the Survey of the frames now held (None while there are fewer than 2)

Source code in src/rpps/analysis/spectrum/find.py
def __init__(self, Fs, nfft=4096, cf=0.0, frames=32, refit=None, overlap=None, track=True, hold=-1.0, **kw):
    self.Fs, self.nfft, self.cf = float(Fs), int(nfft), cf
    self.frames = int(frames)
    self.refit = max(1, int(4*self.frames if refit is None else refit))
    self.track = track
    ov = _SETTINGS[_effort.level()]["overlap"] if overlap is None else overlap
    self.hop = max(1, int(self.nfft*(1 - ov)))
    self.kw = dict(pfa=1e-3, edge=0.005, drop_db=10.0, min_bins=1, min_across=8)
    self.kw.update({k: v for k, v in kw.items() if k in self.kw})
    self.blocks, self.sys_db = kw.get("blocks", 64), kw.get("sys_db")
    self.hold = float(hold)
    self.reset()
reset
reset()

Forget the stream: the next step starts a new one

Source code in src/rpps/analysis/spectrum/find.py
def reset(self):
    """Forget the stream: the next step starts a new one"""
    self._raw = np.zeros(0, np.complex64) # samples from the next frame's start on
    self._P = _Tail(self.frames, (self.nfft,))
    self._Pw = _Tail(self.frames, (self.nfft,)) # the held frames over the floor
    self._Cw = _Tail(self.frames, (self.nfft + 1,), np.float64) # their running sums over bins (_Ctx.band)
    self._sum = np.zeros(self.nfft)       # their sum (the mean spectrum, running)
    self._n = 0                           # frames made so far
    self._fit = None
    self._fit_held = 0                    # frames held at the floor's last fit
    self._state = {}
    self.survey = None
step
step(block)

Take a block of samples; the Survey of the frames now held (None while there are fewer than 2)

Source code in src/rpps/analysis/spectrum/find.py
def step(self, block):
    """Take a block of samples; the Survey of the frames now held (None while there are fewer than 2)"""
    x = np.asarray(block, np.complex64)
    raw = np.concatenate((self._raw, x))
    if len(raw) >= self.nfft:
        P, _ = spectrogram(raw, self.Fs, self.nfft, 1 - self.hop/self.nfft)
        self._add(P)
        raw = raw[len(P)*self.hop:]
    self._raw = raw
    if len(self._P) < 2 or self._fit is None:
        return None
    M = len(self._P)
    st = self._state
    st["A"], st["Pw"], st["Cw"], st["frame0"] = self._sum/M, self._Pw.view, self._Cw.view, self._n - M
    st["frame"], st["refresh"] = self._n, (self.frames if self.track else None)
    t_start = (self._n - M)*self.hop/self.Fs # (the oldest held frame's start)
    sv = _find_frames(self._P.view, self.hop, None, self.Fs, self.cf, self._fit, t_start=t_start, state=st,
                      **self.kw)
    now = self._n*self.hop/self.Fs # (the end of the newest frame [s from the stream's start])
    for g in sv:
        g.stale, g.seen = False, now
    if self.survey is not None:
        sv.match(self.survey)
        if self.hold != 0: # (what was not found again: kept, stale, for its hold)
            found = {g.id for g in sv}
            kept = [g for g in self.survey if g.id not in found and (self.hold < 0 or now - g.seen <= self.hold)]
            for g in kept:
                g.stale = True
            sv.extend(kept)
            sv.sort(key=lambda g: g.mid)
    self.survey = sv
    return sv

spectrogram

spectrogram(x, Fs, nfft, overlap=0.5)

P[t, f] (fftshifted, power per Hz) and the hop

Source code in src/rpps/analysis/spectrum/find.py
def spectrogram(x, Fs, nfft, overlap=0.5):
    """P[t, f] (fftshifted, power per Hz) and the hop"""
    x = np.ascontiguousarray(x, dtype=np.complex64)
    hop = max(1, int(nfft*(1 - overlap)))
    M = (len(x) - nfft)//hop + 1
    if M < 1:
        raise ValueError(f"Need at least {nfft} samples")
    win = _hann_win(nfft)
    frames = np.lib.stride_tricks.as_strided(x, (M, nfft), (x.strides[0]*hop, x.strides[0]))
    X = np.fft.fft(frames*win, axis=1) # (in double: numpy's complex64 FFT is the slower)
    P = X.real**2
    P += X.imag**2
    P = np.fft.fftshift(P, axes=1).astype(np.float32)
    P *= np.float32(1/(np.sum(win**2)*Fs))
    return P, hop

find

find(x, Fs: float = 1.0, cf=0.0, nfft=None, pfa=0.001, edge=0.005, drop_db=10.0, min_bins=1, min_across=8, blocks=64, sys_db=None)

Signals in a capture (see the module): a Survey of Signal sorted by frequency, each with t0/t1 (when it is on, [s from the start]), bursts ([(t0, t1)], None when continuous or too weak a frame to tell; one with bursts is a Burst), score (dB over the threshold that found it) and over (the box it stands on, or None)

pfa: expected false boxes in a capture of pure noise (spread over every width and group tested) nfft: FFT size [N/16, 64 to 65536] edge: fraction of the band at each end not looked at [0.5%: the receiver's roll-off is found from the spectrum, and carriers can run to within 1% of the band's edge] drop_db: a carrier's edges are this far under its top [dB] (or halfway to the floor or valley beside it) min_bins: narrowest signal; min_across: bins across under which its edges aren't trusted (Signal.resolved False) blocks: blocks the floor is fitted in (at least 8 bins each); sys_db: the floor's own error [measured] For a stream (a display), Finder: the same, block by block.

Source code in src/rpps/analysis/spectrum/find.py
def find(x, Fs: float = 1.0, cf=0.0, nfft=None, pfa=1e-3, edge=0.005, drop_db=10.0, min_bins=1, min_across=8,
         blocks=64, sys_db=None):
    """Signals in a capture (see the module): a Survey of Signal sorted by frequency, each with t0/t1 (when it is on,
    [s from the start]), bursts ([(t0, t1)], None when continuous or too weak a frame to tell; one with bursts is a
    Burst), score (dB over the threshold that found it) and over (the box it stands on, or None)

    pfa: expected false boxes in a capture of pure noise (spread over every width and group tested)
    nfft: FFT size [N/16, 64 to 65536]
    edge: fraction of the band at each end not looked at [0.5%: the receiver's roll-off is found from the spectrum, and
        carriers can run to within 1% of the band's edge]
    drop_db: a carrier's edges are this far under its top [dB] (or halfway to the floor or valley beside it)
    min_bins: narrowest signal; min_across: bins across under which its edges aren't trusted (Signal.resolved False)
    blocks: blocks the floor is fitted in (at least 8 bins each); sys_db: the floor's own error [measured]
    For a stream (a display), Finder: the same, block by block.
    """
    st = _SETTINGS[_effort.level()]
    x = np.asarray(x)
    nfft = _nfft_for(len(x)) if nfft is None else int(nfft)
    P, hop = spectrogram(x, Fs, nfft, st["overlap"])
    fit = fit_floor(P, hop, edge, blocks, sys_db)
    return _find_frames(P, hop, x, Fs, cf, fit, pfa, edge, drop_db, min_bins, min_across)

fit_floor

fit_floor(P, hop, edge=0.005, blocks=64, sys_db=None)

find's step 2 on a spectrogram P[t, f]: the FloorFit

Source code in src/rpps/analysis/spectrum/find.py
def fit_floor(P, hop, edge=0.005, blocks=64, sys_db=None):
    """find's step 2 on a spectrogram P[t, f]: the FloorFit"""
    M, nfft = P.shape
    A = P.mean(axis=0, dtype=np.float64)
    cut = int(np.ceil(max(edge, 0.0)*nfft))
    fl = _Floor(A, cut, nfft - cut, blocks)
    a_use, b_use = _rolloff(A, cut, fl.bs)
    fl = _Floor(A, a_use, b_use, blocks)
    floor = fl.first()
    # Only what is clearly signal is cut out of the fit: narrow lines and carriers (the finest widths), and levels
    # 1.5 dB over the floor over an eighth of a block (0.1 dB of scatter). What the coarse widths find at a fraction of
    # a dB is as likely the floor's own misfit, which cutting out would freeze (the fit can't correct what it can't see)
    fine = _Detector(nfft, hop, M, 1e-2, 16)
    for _ in range(3):
        Z = A/floor
        occ, _s, _k = fine.detect(Z, M)
        occ |= 10*np.log10(_box(Z, max(1, fl.bs//8)) + 1e-30) > 1.5
        busy = occ
        # Widen each cut with its signal: the floor beside a wide hump is fitted past its flanks, not up them
        s0, s1 = runs(occ)
        grow = np.clip((s1 - s0)//2, fl.bs//8, 2*fl.bs) # (at most two blocks: past that the passband's ripple misleads)
        occ = _paint(nfft, s0 - grow, s1 + grow)[0]
        lone = Z > _gamma_isf(1e-3, _dof(nfft, hop, M, 1)) # lines a box mean leaves
        floor = fl.fit(~occ & ~lone)
    sys = (sys_db or 0.0)/4.343
    if sys_db is None: # what the noise bins scatter beyond chance, over a quarter block
        Z = A/floor
        noise = ~occ & ~lone
        noise[:a_use] = noise[b_use:] = False
        kr = max(1, fl.bs//4)
        r = 10*np.log10(_box(Z, kr) + 1e-30)[noise]
        if len(r) > 8*kr:
            emp = 1.4826*np.median(np.abs(r - np.median(r)))
            sys = np.sqrt(max(0.0, emp**2 - (4.343/np.sqrt(_dof(nfft, hop, M, kr)))**2))/4.343
    return FloorFit(floor, a_use, b_use, float(sys), busy)

hopping

Frequency hopping: the hops, their dwell, the hop set and its spacing, and the signal de-hopped

h = rp.analysis.spectrum.hopping.track(x, Fs)        # Hops: dwells (start, end, frequency), dwell time, channels, spacing
y = rp.analysis.spectrum.hopping.dehop(x, Fs, h)     # every dwell mixed to 0 Hz and joined: one channel's signal to analyse

A hopper is a narrow signal that jumps: over the capture the spectrum looks wide and flat, at any instant it is one narrow peak. A short-time spectrum (frames much shorter than a dwell, bins much narrower than the hop set) has, frame by frame, its strongest bin over the frame's floor where the signal is; a run of frames at one frequency (within a channel spacing) is a dwell. The dwell time is the median of whole dwells (the first and last are cut by the capture); the hop set is the frequencies the dwells visit, clustered; the spacing is the greatest common step between them (the median of the smallest differences, then refined over all of them).

Classes:

Name Description
Hops

Result of track: dwells (Dwell: start, end s, freq Hz), dwell (s, median of whole dwells), rate (hops/s),

Functions:

Name Description
track

Dwells of a frequency-hopping signal (see the module). nfft: frame length (shorter than a dwell, bins narrower than

dehop

The signal with every dwell mixed to 0 Hz, the dwells joined in order (a guard share of each dwell's ends

Hops

Hops(**kw)

Result of track: dwells (Dwell: start, end s, freq Hz), dwell (s, median of whole dwells), rate (hops/s), channels (Hz, the hop set's frequencies), spacing (Hz), active (share of frames with a signal), hopping (more than one channel visited, dwells shorter than a quarter of the capture, the signal at an instant under half as wide as over the capture)

Source code in src/rpps/analysis/spectrum/hopping.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

track

track(x, Fs, nfft=256, hop=None, snr_db=6.0, merge=None, width=None)

Dwells of a frequency-hopping signal (see the module). nfft: frame length (shorter than a dwell, bins narrower than the channel spacing), hop: frame step (default nfft/2). snr_db: a frame's peak over its median bin to count. merge: frequency (Hz) within which consecutive frames are one dwell (default 2 bins). width: bins each side of a frame's peak its frequency is the power centroid of (default nfft/32)

Source code in src/rpps/analysis/spectrum/hopping.py
def track(x, Fs, nfft=256, hop=None, snr_db=6.0, merge=None, width=None):
    """Dwells of a frequency-hopping signal (see the module). nfft: frame length (shorter than a dwell, bins narrower than
    the channel spacing), hop: frame step (default nfft/2). snr_db: a frame's peak over its median bin to count.
    merge: frequency (Hz) within which consecutive frames are one dwell (default 2 bins). width: bins each side of a
    frame's peak its frequency is the power centroid of (default nfft/32)"""
    x = np.asarray(x, dtype=np.complex128)
    hop = hop or nfft//2
    S = _spectrogram(x, nfft, hop)
    k = np.argmax(S, axis=1)
    peak = S[np.arange(len(S)), k]
    floor = np.median(S, axis=1)
    on = peak > floor*10**(snr_db/10)
    # each frame's frequency: the power centroid within `width` bins of its peak (an FSK's tones, a PSK's spectrum,
    # sit around the dwell's frequency: the peak bin alone jumps between them)
    width = width or max(2, nfft//32)
    b = np.arange(-width, width + 1)
    idx = np.clip(k[:, None] + b[None, :], 0, nfft - 1)
    P = S[np.arange(len(S))[:, None], idx] - floor[:, None]
    P = np.maximum(P, 0)
    fr = (np.sum(P*idx, axis=1)/np.maximum(P.sum(axis=1), 1e-300) - nfft//2)*Fs/nfft
    t = (np.arange(len(S))*hop + nfft/2)/Fs
    T = len(x)/Fs
    # 1: the channels: active frames' frequencies clustered (a histogram's peaks, a bin apart at least)
    merge = merge or 2*Fs/nfft
    fa = np.sort(fr[on])
    chans = []
    for fq in fa:
        if chans and fq - chans[-1][-1] < merge:
            chans[-1].append(fq)
        else:
            chans.append([fq])
    chans = [c for c in chans if len(c) >= 2] # a frame alone is noise or a transition
    channels = [float(np.median(c)) for c in chans]
    spacing = 0.0
    if len(channels) > 1:
        diffs = np.diff(channels)
        s0 = float(np.median(diffs[diffs < 1.5*np.min(diffs)])) # the smallest step, as a start
        steps = np.round((np.array(channels) - channels[0])/s0) # every channel a whole number of steps from the first
        ok = steps > 0
        spacing = float(np.sum((np.array(channels)[ok] - channels[0])*steps[ok])/np.sum(steps[ok]**2)) if ok.any() else s0
    # 2: every active frame to its nearest channel; a dwell is a run of frames on one channel
    ch = np.full(len(S), -1)
    if channels:
        cf = np.array(channels)
        near = np.argmin(np.abs(fr[:, None] - cf[None, :]), axis=1)
        close = np.abs(fr - cf[near]) < max(merge, 0.4*spacing if spacing else merge)
        ch = np.where(on & close, near, -1)
    dwells = []
    i = 0
    while i < len(S):
        if ch[i] < 0:
            i += 1
            continue
        j = i
        while j + 1 < len(S) and ch[j + 1] == ch[i]:
            j += 1
        if j > i: # a dwell is two frames or more
            dwells.append(Dwell(float(t[i] - hop/(2*Fs)), float(t[j] + hop/(2*Fs)), float(channels[ch[i]]),
                                float(np.median(peak[i:j + 1]))))
        i = j + 1
    whole = [d.end - d.start for d in dwells[1:-1]] or [d.end - d.start for d in dwells]
    dwell = float(np.median(whole)) if whole else 0.0
    # a hopper is narrow at any instant and wide over time: a wide signal's peak bin wanders too, without hopping
    long = S.mean(axis=0)
    wide_bins = np.count_nonzero(long > spectrum_floor(long)*10**(snr_db/10))
    frame_bins = np.median([np.count_nonzero(S[i] > floor[i]*10**(snr_db/10)) for i in np.flatnonzero(on)[:400]]) \
        if on.any() else wide_bins
    narrow = frame_bins < 0.5*wide_bins
    hopping = len(channels) > 1 and len(dwells) >= 4 and dwell < T/4 and narrow
    return Hops(dwells=dwells, dwell=dwell, rate=1/dwell if dwell else 0.0, channels=channels, spacing=spacing,
                active=float(np.mean(on)), hopping=hopping)

dehop

dehop(x, Fs, hops, guard=0.0)

The signal with every dwell mixed to 0 Hz, the dwells joined in order (a guard share of each dwell's ends dropped: the synthesizer settling); between dwells nothing. Returns complex samples at Fs

Source code in src/rpps/analysis/spectrum/hopping.py
def dehop(x, Fs, hops, guard=0.0):
    """The signal with every dwell mixed to 0 Hz, the dwells joined in order (a `guard` share of each dwell's ends
    dropped: the synthesizer settling); between dwells nothing. Returns complex samples at Fs"""
    x = np.asarray(x, dtype=np.complex128)
    out = []
    for d in hops.dwells:
        a = int(round(d.start*Fs))
        b = int(round(d.end*Fs))
        g = int(guard*(b - a))
        a, b = max(a + g, 0), min(b - g, len(x))
        if b <= a:
            continue
        n = np.arange(a, b)
        out.append(x[a:b]*np.exp(-2j*np.pi*d.freq/Fs*n))
    return np.concatenate(out) if out else np.zeros(0, complex)

levels

The finder's steps 4-6 (rpps.analysis.spectrum.find): a line raised from the floor; a signal comes up and holds its sides

In a region the detector marked, a line is raised from the floor a step at a time (STEP_K noise deviations, at least STEP_DB), and at each the runs over it are found. A run whose sides hold from one step to the next (to HOLD of its width) is one thing going on up; a run that comes up out of a wider one, or out of the floor, is a new thing standing on it. A thing is what held its sides for a step or more (a hump's move in at every step: it is none) and is not only what comes up out of it (FILL of it or more: two carriers side by side come up as one run and part at the notch; a carrier's top comes up out of it); what stands on a pedestal leaves most of it. Its top is the middle of its own points over where its sides last held (not those of what stands on it), its sides where it stands halfway up from where it came up (or drop_db under its top). Lines (LINE_BINS wide or less) are taken out first (a median over twice that): no signal. A box passes the detector at its width and has an SNR of MIN_SNR or more.

In a Finder each region's reading is kept from step to step: one whose span and level hold keeps its things, measured again, and is read again when they move or once a window (see boxes).

Functions:

Name Description
boxes

find's steps 4-6 by levels: the Signals of context c (see find._find_frames), the detector's marks occ.

boxes

boxes(c, occ, groups, min_snr=None, state=None)

find's steps 4-6 by levels: the Signals of context c (see find._find_frames), the detector's marks occ. state: a Finder's: each region's reading kept from step to step; one whose span and level hold (find._same) keeps its things, measured again (find._remeasure), and is read again when they move or a window (state["refresh"] frames) on, the regions' turns spread over it

Source code in src/rpps/analysis/spectrum/levels.py
def boxes(c, occ, groups, min_snr=None, state=None):
    """find's steps 4-6 by levels: the Signals of context c (see find._find_frames), the detector's marks occ.
    state: a Finder's: each region's reading kept from step to step; one whose span and level hold (find._same) keeps
    its things, measured again (find._remeasure), and is read again when they move or a window (state["refresh"]
    frames) on, the regions' turns spread over it"""
    from .find import _copies, _dof, _on, _remeasure, _same
    from .signal import Signal
    if min_snr is None:
        min_snr = MIN_SNR
    s0, s1 = runs(occ)
    keep = (s1 - s0) >= max(c.min_bins, LINE_BINS)
    s0, s1 = s0[keep], s1[keep]
    if len(s0) > 1: # (spans a gap of under a quarter of the narrower apart: one region)
        gap = s0[1:] - s1[:-1]
        narrow = np.minimum(s1[:-1] - s0[:-1], s1[1:] - s0[1:])
        new = np.concatenate(([True], gap > np.maximum(4, narrow//4)))
        s0, s1 = s0[new], s1[np.concatenate((new[1:], [True]))]
    recs = state.get("levels", []) if state is not None else []
    now, refresh = (state.get("frame", 0), state.get("refresh")) if state is not None else (0, None)
    out, kept = [], []
    for j, (a, b) in enumerate(zip(s0, s1)):
        a, b = int(a), int(b)
        lvl = 10*np.log10(max(float(c.Z[a:b].mean()), 1e-30))
        rec = _same(recs, a, b, lvl)
        if rec is not None and refresh is not None and now < rec["due"]: # (as it was: its things measured again)
            sigs = _remeasure(c, rec["sig"])
            wait = rec["due"] - now
        else:
            mg = int(np.clip((b - a)//4, 4, 2048))
            r0 = max(c.cut[0], a - mg, (int(s1[j - 1]) + a)//2 if j > 0 else 0)
            r1 = min(c.cut[1], b + mg, (b + int(s0[j + 1]))//2 if j + 1 < len(s0) else c.nfft)
            sigs = _region(c, a, b, r0, r1, Signal, _on, _dof, min_snr)
            # (read again a window on; a region's first time a fraction of one, set by where it is, so the turns
            # spread over the window)
            wait = refresh or 0
            if rec is None and refresh:
                wait = refresh//2 + (a*7919) % max(1, refresh//2)
        if state is not None:
            kept.append(dict(a=a, b=b, lvl=lvl, sig=sigs, due=now + wait))
        out += _copies(sigs)
    if state is not None:
        state["levels"] = kept
    return out

ofdm_pilots

OFDM pilot patterns, blind: which cells of the time-frequency grid carry known values, and the lattice they form

o = rp.analysis.spectrum.waveform.ofdm(x, Fs)                 # (or waveform.classify(x, Fs).ofdm): Tu, CP, comb
p = rp.analysis.spectrum.ofdm_pilots.discover(x, Fs, o)       # or tu=, tcp= when known
print(p)    # e.g. "OFDM 1024 x 1/4 CP, 601 used subcarriers: pattern every 4 symbols; scattered pilots every 12th
            #  subcarrier, moving 3 a symbol; 45 continual pilots; pilots 2.5 dB over data"
p.mask      # (period, K) bool: pilot cells by symbol in the period and subcarrier; p.empty: cells never used
g = rp.analysis.spectrum.ofdm_pilots.grid(x, Fs, tu, tcp)     # the grid itself: g.Y (symbols, K), g.on, g.k

The grid: x is resampled so that Tu is a power-of-2 FFT; each symbol's start is the peak of its cyclic-prefix correlation, searched a little either side of where the last one said (so a longer first CP in a slot, LTE's, is followed); the fractional carrier offset is the correlation's phase; the FFT window starts a quarter of the CP early. Subcarriers from the first to the last within floor_db of the signal's plateau are kept; symbols far under the strongest are off (TDD, bursts).

Pilots are cells whose value is known, so a pilot cell is the same (or follows a sequence that repeats) from one period of the pattern to the next, and data cells are not: Y[t, k] Y[t + L, k] summed over t keeps its phase at a pilot cell and averages away at a data cell. The lag L that repeats the most power (each subcarrier's autocorrelation along time, by FFT, the magnitudes summed over subcarriers) is the pattern's period (the smallest lag within share of the strongest: DVB-T's scattered pilots 4 symbols, a sequence that changes every symbol and repeats each frame its frame, LTE's cell reference signal 140). At that lag every cell's coherence |sum Y Y| / sum |Y|^2 over its symbols in the period is near 1 for a pilot and about 1/sqrt(n) for data: over max(coherence, 5/sqrt(n)) is a pilot. Then: scattered rows (symbols in the period) whose pilots are equally spaced: the spacing, and the offset's step a symbol continual subcarriers that are pilots in nearly every symbol empty cells with almost no power in every period (guard bands, DC, the gaps of a comb) boost pilot over data power Rows (symbols in the period) are decided as a whole: a lattice of subcarriers (spacing D, offset o) whose coherence stands over the row's (a t-statistic less what the best of D offsets reaches by chance, holding across the band, not in one block: a broadcast channel repeating its content is no lattice), strong alone or weaker with the spacing most rows have; or the whole symbol known (its median coherence high: a preamble, a sync or sounding symbol); single cells only where enough periods make one cell's coherence telling (irregular continual pilots). Limits: a long period needs many periods: an 84 ms record of LTE TDD (7 frames of 140 symbols) gives its known symbols and most of its reference-signal rows (spacing 6, offsets alternating by 3), not all. The pattern is read relative to the first kept subcarrier (an integer carrier offset shifts it); a common phase that wanders over the lag (phase noise, a symbol clock off by ppm over a long lag) weakens the coherence (the per-symbol common phase is taken out against the previous period first).

Classes:

Name Description
Grid

grid: Y (symbols, K) complex cells (kept subcarriers only), k (K,) their FFT bins (0 = the carrier, signed),

Pilots

discover: period (symbols), mask (period, K) pilot cells, empty (period, K) unused cells, coherence (period,

Functions:

Name Description
grid

The OFDM time-frequency grid of baseband x at Fs (see the module): Grid. tu, tcp: useful symbol and CP (s)

discover

The pilot pattern of an OFDM signal x (see the module). o: rpps.analysis.spectrum.waveform.ofdm's result (tu and tcp are

Grid

Grid(**kw)

grid: Y (symbols, K) complex cells (kept subcarriers only), k (K,) their FFT bins (0 = the carrier, signed), starts (symbols,) each symbol's start (samples at fs), on (symbols,) bool, N (FFT size), ncp (CP samples at fs), fs (the resampled rate), cfo (Hz: the fractional offset taken out), rho (symbols,) each CP correlation

Source code in src/rpps/analysis/spectrum/ofdm_pilots.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

Pilots

Pilots(**kw)

discover: period (symbols), mask (period, K) pilot cells, empty (period, K) unused cells, coherence (period, K), scattered [(row, offset, spacing, count)], step (offset change a symbol of the scattered lattice, None), spacing (its subcarrier spacing), continual (kept-subcarrier indices), boost_db, lags [(lag, score)] strongest first, grid (Grid), lattices {row: (spacing, offset, t)}: each row's pilot lattice (spacing 1: the whole symbol known)

Source code in src/rpps/analysis/spectrum/ofdm_pilots.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

grid

grid(x, Fs, tu, tcp, floor_db=10.0, off_db=10.0, max_symbols=None)

The OFDM time-frequency grid of baseband x at Fs (see the module): Grid. tu, tcp: useful symbol and CP (s)

Source code in src/rpps/analysis/spectrum/ofdm_pilots.py
def grid(x, Fs, tu, tcp, floor_db=10.0, off_db=10.0, max_symbols=None):
    """The OFDM time-frequency grid of baseband x at Fs (see the module): Grid. tu, tcp: useful symbol and CP (s)"""
    x = np.asarray(x, dtype=np.complex128)
    N = 1 << int(np.ceil(np.log2(tu*Fs - 1e-6)))
    fs = N/tu
    if abs(fs - Fs) > 1e-9*Fs:
        x = interpolate(x, np.arange(int(len(x)*fs/Fs) - 8)*Fs/fs)
    ncp = max(1, int(round(tcp*fs)))
    Ns = N + ncp
    rho, s = _cp_metric(x, N, ncp)
    if len(rho) < 2*Ns:
        raise ValueError("fewer than two symbols")
    # the first symbol: the strongest peak in the first two periods
    n0 = int(np.argmax(rho[:2*Ns]))
    n0 = n0 % Ns if n0 >= Ns and rho[n0 % Ns] > 0.5*rho[n0] else n0
    d = max(2, int(0.02*N))
    starts, rhos = [], []
    n = n0
    while n + Ns + d < len(rho) and (max_symbols is None or len(starts) < max_symbols):
        lo, hi = max(0, n - d), min(len(rho), n + d + 1)
        k = lo + int(np.argmax(rho[lo:hi]))
        # follow the peak only when it is clear; else keep time
        if rho[k] > 0.3:
            n = k
        starts.append(n)
        rhos.append(float(rho[n]))
        n += Ns
    starts = np.array(starts)
    rhos = np.array(rhos)
    good = rhos > 0.3
    starts = _smooth_starts(starts, good)
    ang = np.angle(np.sum(s[starts[good]])) if good.any() else 0.0
    f = -ang/(2*np.pi*N) # cycles a sample
    cfo = f*fs
    win = starts + ncp - ncp//4
    win = win[win + N <= len(x)]
    idx = win[:, None] + np.arange(N)[None, :]
    seg = x[idx]*np.exp(-2j*np.pi*f*idx)
    Y = np.fft.fftshift(np.fft.fft(seg, axis=1), axes=1)/np.sqrt(N)
    bins = np.arange(N) - N//2
    pw_sym = np.mean(np.abs(Y)**2, axis=1)
    on = pw_sym > np.max(pw_sym)*10**(-off_db/10)
    pk = np.mean(np.abs(Y[on])**2, axis=0)
    live = pk > 1e-6*pk.max() # resampling leaves bins outside the capture's band (nearly) empty
    top = np.percentile(pk[live], 95)
    used = pk > top*10**(-floor_db/10) # within floor_db of the signal's plateau
    if not used.any():
        raise ValueError("no subcarriers over the floor")
    a, b = np.flatnonzero(used)[[0, -1]]
    keep = np.arange(a, b + 1) # contiguous: nulls inside the band (DC, comb gaps) stay, they are part of the pattern
    return Grid(Y=Y[:, keep], k=bins[keep], starts=win, on=on, N=N, ncp=ncp, fs=fs, cfo=cfo, rho=rhos[:len(win)])

discover

discover(x, Fs, o=None, tu=None, tcp=None, max_lag=None, share=0.6, row_coherence=0.6, min_t=7.0, weak_t=3.5, max_spacing=24, max_symbols=4000)

The pilot pattern of an OFDM signal x (see the module). o: rpps.analysis.spectrum.waveform.ofdm's result (tu and tcp are taken from it; a pilot comb's symbol is comb x its lag, with the CP of the system it names), else tu and tcp (s). max_lag: longest pattern period searched (symbols; default a quarter of the symbols, at most 320)

Source code in src/rpps/analysis/spectrum/ofdm_pilots.py
def discover(x, Fs, o=None, tu=None, tcp=None, max_lag=None, share=0.6, row_coherence=0.6, min_t=7.0, weak_t=3.5, max_spacing=24,
             max_symbols=4000):
    """The pilot pattern of an OFDM signal x (see the module). o: rpps.analysis.spectrum.waveform.ofdm's result (tu and tcp are
    taken from it; a pilot comb's symbol is comb x its lag, with the CP of the system it names), else tu and tcp (s).
    max_lag: longest pattern period searched (symbols; default a quarter of the symbols, at most 320)"""
    if tu is None:
        if o is None:
            from . import waveform
            o = waveform.ofdm(x, Fs)
            if o is None:
                raise ValueError("not OFDM (rpps.analysis.spectrum.waveform.ofdm found no cyclic prefix)")
        tu, tcp = _symbol_of(o)
    g = grid(x, Fs, tu, tcp, max_symbols=max_symbols)
    Y = g.Y/np.sqrt(np.mean(np.abs(g.Y[g.on])**2))
    T, K = Y.shape
    max_lag = max_lag or max(2, min(320, T//4))
    sc = _lag_scores(Y, g.on, max_lag)
    # data alone: each subcarrier's sum of T products of random phase is ~sqrt(T) of the T magnitudes'
    base = 1/np.sqrt(max(int(g.on.sum()), 1))
    order = np.argsort(-sc[1:]) + 1
    lags = [(int(L), float(sc[L])) for L in order[:8]]
    top = sc[order[0]]
    if top < 3*base:
        return Pilots(period=None, mask=np.zeros((1, K), bool), empty=np.zeros((1, K), bool),
                      coherence=np.zeros((1, K)), scattered=[], step=None, spacing=None, continual=np.array([], int),
                      boost_db=None, lags=lags, grid=g, lattices={})
    P = int(min(L for L in range(1, max_lag + 1) if sc[L] >= share*top and sc[L] > 3*base))
    Yc = _common_phase(Y, P, g.on)
    num = np.zeros((P, K), np.complex128)
    den = np.zeros((P, K))
    pw = np.zeros((P, K))
    cnt = np.zeros(P)
    for t in range(T - P):
        r = t % P
        if g.on[t] and g.on[t + P]:
            num[r] += Yc[t + P]*np.conj(Yc[t])
            den[r] += 0.5*(np.abs(Yc[t])**2 + np.abs(Yc[t + P])**2)
            pw[r] += np.abs(Yc[t])**2
            cnt[r] += 1
    rows = cnt > 0
    coh = np.where(den > 0, np.abs(num)/np.maximum(den, 1e-30), 0)
    pw = pw/np.maximum(cnt, 1)[:, None]
    level = np.median(pw[rows]) if rows.any() else 0.0
    empty = (pw < 0.05*level) & rows[:, None]
    # single cells: only where enough periods make a cell's coherence alone telling (irregular continual pilots)
    thr = np.maximum(0.9, 5/np.sqrt(np.maximum(cnt, 1)))[:, None]
    mask = (coh > thr) & ~empty & rows[:, None]
    lattices, fits = {}, {}
    for r in np.flatnonzero(rows):
        live = ~empty[r]
        c = coh[r]
        if live.sum() < 8:
            continue
        cl = c[live]
        if np.median(cl) > row_coherence: # a whole symbol known (a preamble, a sync or sounding symbol)
            mask[r] |= live
            lattices[r] = (1, 0, 99.0)
            continue
        lat = _lattice(c, live, max_spacing)
        if lat is not None and lat[2] >= weak_t:
            fits[r] = lat
    # a row's lattice counts when it is strong alone, or weaker but with the spacing most rows found (or a divisor of
    # it, or a multiple: two lattices of one pattern in a symbol read as one at half the spacing, LTE's)
    if fits:
        Ds = [D for D, _, _ in fits.values()]
        common = max(set(Ds), key=Ds.count)
        for r, (D, o, t) in fits.items():
            if t >= min_t or common % D == 0 or D % common == 0:
                k = np.arange(K)
                on_lat = (k % D == o) & ~empty[r]
                hit = np.flatnonzero(on_lat & (coh[r] > 0.5*np.median(coh[r][on_lat])))
                if len(hit):
                    on_lat &= (k >= hit[0]) & (k <= hit[-1]) # between the first and last that hold
                mask[r] |= on_lat
                lattices[r] = (D, o, t)
    nrow = max(int(rows.sum()), 1)
    continual = np.flatnonzero(mask[rows].sum(axis=0) >= 0.9*nrow)
    scat = [(int(r), int(o), int(D), int(np.sum(mask[r]))) for r, (D, o, t) in sorted(lattices.items()) if D >= 2]
    spacing = step = None
    if scat:
        sps = [x[2] for x in scat]
        spacing = max(set(sps), key=sps.count)
        rs = [x for x in scat if x[2] == spacing]
        # the offset's change from one pilot symbol to the next, per symbol between them
        steps = [((b[1] - a[1]) % spacing, b[0] - a[0]) for a, b in zip(rs, rs[1:])]
        one = [d for d, gap in steps if gap == 1]
        if one:
            step = max(set(one), key=one.count)
    data = ~mask & ~empty & rows[:, None]
    boost = None
    if mask.any() and data.any():
        boost = float(10*np.log10(pw[mask].mean()/pw[data].mean()))
    return Pilots(period=P, mask=mask, empty=empty, coherence=coh, scattered=scat, step=step, spacing=spacing,
                  continual=continual, boost_db=boost, lags=lags, grid=g, lattices=lattices)

pencil

Spectral lines from short records: the matrix pencil (Hua & Sarkar 1990)

lines = rp.analysis.spectrum.pencil.lines(x, Fs)         # [(freq Hz, amplitude, damping /s), ...] strongest first

An FFT resolves lines 1/T apart (T the record) and smears each over its window. A sum of K exponentials x[n] = sum a_k z_k^n has a Hankel matrix of rank K, the Vandermonde structure of the z_k; the matrix pencil takes the z_k from it directly (eigenvalues of Y1^+ Y0, Y0 and Y1 the matrix without its last and first columns, through the K principal singular vectors), so two lines a fraction of 1/T apart are told apart and each frequency is found to far finer than a bin: FSK tones in a short burst, a pilot beside a carrier, cyclic lines of a short capture. K comes from the singular values (those over floor of the largest), or is given.

Functions:

Name Description
lines

Exponentials in x: [(frequency Hz, amplitude (complex), damping 1/s (0 for a steady line))], strongest first.

lines

lines(x, Fs, K=None, L=None, floor=0.05, max_samples=4096)

Exponentials in x: [(frequency Hz, amplitude (complex), damping 1/s (0 for a steady line))], strongest first. K: how many (default: the singular values over floor of the largest). L: the pencil parameter (default n/3)

Source code in src/rpps/analysis/spectrum/pencil.py
def lines(x, Fs, K=None, L=None, floor=0.05, max_samples=4096):
    """Exponentials in x: [(frequency Hz, amplitude (complex), damping 1/s (0 for a steady line))], strongest first.
    K: how many (default: the singular values over `floor` of the largest). L: the pencil parameter (default n/3)"""
    x = np.asarray(x, dtype=np.complex128)[:max_samples]
    n = len(x)
    L = n//3 if L is None else int(L)
    if n < 8 or not 1 <= L < n - 1:
        raise ValueError("too few samples")
    Y = np.lib.stride_tricks.sliding_window_view(x, L + 1) # (n - L) x (L + 1) Hankel
    U, s, Vh = np.linalg.svd(Y, full_matrices=False)
    if K is None:
        K = int(np.sum(s > floor*s[0]))
    K = max(1, min(K, L))
    V = Vh[:K].T # (L + 1) x K: Y's rows, sums of the vectors (z^0 .. z^L), are in the span of these
    V0, V1 = V[:-1], V[1:]
    z = np.linalg.eigvals(np.linalg.pinv(V0) @ V1)
    # amplitudes by least squares on the Vandermonde of the z
    Z = z[None, :]**np.arange(n)[:, None]
    a, *_ = np.linalg.lstsq(Z, x, rcond=None)
    f = np.angle(z)/(2*np.pi)*Fs
    damp = -np.log(np.maximum(np.abs(z), 1e-300))*Fs
    order = np.argsort(-np.abs(a))
    return [(float(f[i]), complex(a[i]), float(damp[i])) for i in order]

psd

Functions:

Name Description
psd

Perform Power Spectral Density

vbw_calc

Convert Hz to gaussian sigma

vbw

Perform gaussian smoothing

psd

psd(samps, Fs: float = 1, vbw_hz=None)

Perform Power Spectral Density

Source code in src/rpps/analysis/spectrum/psd.py
def psd(samps, Fs: float = 1, vbw_hz=None):
    """Perform Power Spectral Density"""
    N = len(samps)
    y = np.abs(np.fft.fft(samps))**2 / (N*Fs)
    y = np.fft.fftshift(10.0*np.log10(y))
    if vbw_hz is not None:
        smooth = vbw_calc(N, Fs, vbw_hz)
        y = vbw(y, smooth)
    return y

vbw_calc

vbw_calc(N: int, Fs: float, vbw_hz: float)

Convert Hz to gaussian sigma

Source code in src/rpps/analysis/spectrum/psd.py
def vbw_calc(N: int, Fs: float, vbw_hz: float):
    """Convert Hz to gaussian sigma"""
    return vbw_hz/(Fs / N)

vbw

vbw(samps, smooth: float)

Perform gaussian smoothing

Source code in src/rpps/analysis/spectrum/psd.py
def vbw(samps, smooth: float):
    """Perform gaussian smoothing"""
    return gaussian.gaussian(samps, gaussian.fwhm2sigma(smooth))

scf

Spectral coherence over all cycle frequencies (FFT accumulation), the significant ones, and blind FRESH filtering

table = rp.analysis.spectrum.scf.cycle_frequencies(x, Fs)              # [(alpha Hz, coherence, conjugate), ...] significant
f, a, c = rp.analysis.spectrum.scf.coherence(x, Fs)                     # every (f, alpha) point
y, w = rp.analysis.spectrum.scf.fresh(x, Fs, ref, shifts=(-125e3, 0, 125e3), train=slice(0, len(ref)))

rpps.analysis.spectrum.cyclic tests chosen nonlinearities (|x|^2, x^M) for lines; that sees the strongest signal's rate and carrier. The spectral correlation function S_x^a(f) = E[X(f + a/2) X*(f - a/2)] at every cycle frequency a shows every cyclostationary signal in the band at once, each by its own pattern of cycle frequencies (rates, carriers, and their sums): the way to see signals that share a band. One computes it over all (f, a); here by the FFT accumulation method (Roberts, Brown & Loomis 1991), every pair of channels' product transformed over time, as rpps.analysis.spectrum.cyclic.scf. Normalized by the two channels' power, the spectral coherence is near 0 for noise and up to 1 for a feature, whatever the power: thresholded, it is a blind table of cycle frequencies (the CSP Blog's "spectral coherence and blind estimation of significant cycle frequencies"). Conjugate: E[X(f + a/2) X(a/2 - f)], the cycle frequencies of x^2: twice a carrier, and that plus and minus the rate, for BPSK / OQPSK / MSK-like signals.

fresh: a frequency-shift filter (Gardner 1993) sums filtered copies of x shifted by multiples of a signal's cycle frequencies, the spectral redundancy of a band-limited cyclostationary signal; an interferer overlapping it in frequency but with other cycle frequencies does not share that redundancy and can be taken out, which no filter of x alone can do. The weights are trained by least squares on a stretch where the wanted signal is known: a preamble, or the signal rpps.analysis.modulation.cancel regenerates from decisions (decision-directed). (Blind weights, by self-coherence restoral (Agee, Schell & Gardner 1990), need reference branches that are not shifts of the same copies: with one sensor that is not done here.)

Functions:

Name Description
coherence

Spectral coherence by the FFT accumulation method (as rpps.analysis.spectrum.cyclic.scf): (f Hz, alpha Hz, |coherence|) over

cycle_frequencies

Significant cycle frequencies: [(alpha Hz, coherence, conjugate)] best first, non-conjugate a > 0 only (it is

fresh

A frequency-shift filter for the signal reference is a stretch of (a known preamble, training, or what

coherence

coherence(x, Fs, nfft=64, frames=None, hop=None, conjugate=False)

Spectral coherence by the FFT accumulation method (as rpps.analysis.spectrum.cyclic.scf): (f Hz, alpha Hz, |coherence|) over the points each channel pair is responsible for. |C| = |S^a(f)| / sqrt(S(f + a/2) S(f - a/2)), each channel's own power the denominator, so 0 <= |C| <= 1. conjugate: X(f + a/2) X(a/2 - f), the cycle frequencies of x^2. Silence (zero power) has coherence 0; samples that are not finite are a ValueError

Source code in src/rpps/analysis/spectrum/scf.py
def coherence(x, Fs, nfft=64, frames=None, hop=None, conjugate=False):
    """Spectral coherence by the FFT accumulation method (as rpps.analysis.spectrum.cyclic.scf): (f Hz, alpha Hz, |coherence|) over
    the points each channel pair is responsible for. |C| = |S^a(f)| / sqrt(S(f + a/2) S(f - a/2)), each channel's own power
    the denominator, so 0 <= |C| <= 1. conjugate: X(f + a/2) X(a/2 - f), the cycle frequencies of x^2. Silence (zero
    power) has coherence 0; samples that are not finite are a ValueError"""
    x = np.asarray(x, dtype=np.complex128)
    if not np.all(np.isfinite(x)):
        raise ValueError("coherence: the samples are not all finite (NaN or inf)")
    hop = nfft//4 if hop is None else hop
    P = (len(x) - nfft)//hop + 1 if frames is None else frames
    P = int(2**int(np.log2(max(P, 2))))
    if (P - 1)*hop + nfft > len(x):
        raise ValueError("too few samples for the frames asked")
    idx = np.arange(nfft)[None, :] + hop*np.arange(P)[:, None]
    X = np.fft.fftshift(np.fft.fft(x[idx]*np.hamming(nfft), axis=1), axes=1)
    k = np.arange(-nfft//2, nfft//2)
    X = X*np.exp(-2j*np.pi*k[None, :]*hop*np.arange(P)[:, None]/nfft)
    w = np.hamming(P)[:, None]
    power = np.sum(w*np.abs(X)**2, axis=0)/np.sum(w) # each channel's, weighted as the products are: |C| <= 1
    power = power + 1e-3*power.max() # an empty channel (outside every signal) would make 0/0 coherences
    fk = k*Fs/nfft
    q = np.arange(-P//2, P//2)*Fs/(hop*P)
    keep = np.abs(q) <= Fs/(2*nfft)
    ff, aa, cc = [], [], []
    for a in range(nfft):
        prod = X[:, a:a + 1]*(X if conjugate else np.conj(X))*w # X(f1) X(f2): alpha = f1 + f2; X(f1) X*(f2): f1 - f2
        Z = np.fft.fftshift(np.fft.fft(prod, axis=0), axes=0)/np.sum(w)
        Z = Z[keep]
        alpha = fk[a] + (fk[None, :] if conjugate else -fk[None, :]) + q[keep][:, None]
        f = (fk[a] + (-fk[None, :] if conjugate else fk[None, :]))/2 + 0*q[keep][:, None]
        den = np.sqrt(power[a]*power[None, :])
        c = np.divide(np.abs(Z), den, out=np.zeros(Z.shape), where=den > 0) # (0 where there is no power at all)
        ff.append(f.ravel()); aa.append(alpha.ravel()); cc.append(c.ravel())
    return np.concatenate(ff), np.concatenate(aa), np.concatenate(cc)

cycle_frequencies

cycle_frequencies(x, Fs, nfft=64, conjugate=None, pfa=0.001, merge=None)

Significant cycle frequencies: [(alpha Hz, coherence, conjugate)] best first, non-conjugate a > 0 only (it is symmetric) and a = 0 left out. The threshold is where noise alone would exceed it with probability pfa over all the points (coherence of noise: Rayleigh, its scale from the median of all points). merge: Hz within which points are one cycle frequency (default Fs/nfft)

Source code in src/rpps/analysis/spectrum/scf.py
def cycle_frequencies(x, Fs, nfft=64, conjugate=None, pfa=1e-3, merge=None):
    """Significant cycle frequencies: [(alpha Hz, coherence, conjugate)] best first, non-conjugate a > 0 only (it is
    symmetric) and a = 0 left out. The threshold is where noise alone would exceed it with probability pfa over all the
    points (coherence of noise: Rayleigh, its scale from the median of all points). merge: Hz within which points are one
    cycle frequency (default Fs/nfft)"""
    out = []
    for conj in ((False, True) if conjugate is None else (conjugate,)):
        f, a, c = coherence(x, Fs, nfft, conjugate=conj)
        n = len(c)
        merge_ = Fs/nfft if merge is None else merge # a feature shows in neighbouring channel pairs that far off
        # noise's coherence is Rayleigh: its scale from the median of all points; P(c > t) = exp(-t^2 / (2 s^2)), n points
        s = np.median(c)/np.sqrt(2*np.log(2))
        # (15% over Rayleigh's: measured on noise, the window over frames makes the tail heavier, and the points correlate)
        thr = TAIL*s*np.sqrt(2*np.log(n/pfa))
        sel = c > thr
        if not conj:
            sel &= (a > merge_) # a = 0 is the spectrum itself; negative a mirrors positive
        order = np.argsort(-c[sel])
        taken = []
        for av, cv in zip(a[sel][order], c[sel][order]):
            if all(abs(av - t) > merge_ for t, _ in taken):
                taken.append((float(av), float(cv)))
        out += [(t, cv, conj) for t, cv in taken]
    return sorted(out, key=lambda t: -t[1])

fresh

fresh(x, Fs, reference, shifts, taps=16, conj_shifts=(), train=None, reg=1e-06)

A frequency-shift filter for the signal reference is a stretch of (a known preamble, training, or what rpps.analysis.modulation.cancel regenerates from decisions): the least-squares weights over x's copies shifted by shifts (Hz; multiples of the wanted signal's cycle frequencies, e.g. -Rs, 0, Rs) and, for signals with conjugate features, conj(x) shifted by conj_shifts. train: the samples (a slice or index array) the reference covers (default all). Returns (the filtered signal over all of x, the weights). With shifts (0,) it is an ordinary Wiener filter; the shifted copies are what let it take out an interferer overlapping the signal (Gardner 1993)

Source code in src/rpps/analysis/spectrum/scf.py
def fresh(x, Fs, reference, shifts, taps=16, conj_shifts=(), train=None, reg=1e-6):
    """A frequency-shift filter for the signal `reference` is a stretch of (a known preamble, training, or what
    rpps.analysis.modulation.cancel regenerates from decisions): the least-squares weights over x's copies shifted by `shifts` (Hz;
    multiples of the wanted signal's cycle frequencies, e.g. -Rs, 0, Rs) and, for signals with conjugate features, conj(x)
    shifted by `conj_shifts`. train: the samples (a slice or index array) the reference covers (default all). Returns
    (the filtered signal over all of x, the weights). With shifts (0,) it is an ordinary Wiener filter; the shifted copies
    are what let it take out an interferer overlapping the signal (Gardner 1993)"""
    X = _branches(x, tuple(shifts), taps, Fs, tuple(conj_shifts))
    d = np.asarray(reference, dtype=np.complex128)
    sel = np.arange(len(d)) if train is None else np.arange(len(x))[train]
    A = X[sel]
    R = A.conj().T @ A
    R += reg*np.trace(R).real/len(R)*np.eye(len(R))
    w = np.linalg.solve(R, A.conj().T @ d[:len(sel)])
    return X @ w, w

separate

Two signals of equal power on one channel, separated: each one's carrier and timing, then both symbol streams

p = rp.analysis.spectrum.separate.estimate(x, Fs, baud, "qpsk")     # two Params: carrier (Hz), timing (s), complex gain
r = rp.analysis.spectrum.separate.separate(x, Fs, baud, "qpsk")     # (or params=p) r.symbols[0], r.symbols[1], r.evm

A paired carrier (two transmitters sharing a frequency, "carrier in carrier") at equal power is beyond cancellation: each is the other's interference at 0 dB, so neither can be demodulated first. What still tells them apart is their own carrier offset, timing and phase:

carriers x^M of an M-PSK signal has a line at M f_i, each signal its own (the cross terms of the two fall elsewhere): the two strongest lines near the middle of the x^M spectrum are M f_1 and M f_2 timing the M-th power of a shaped PSK signal also pulses once a symbol: lines at M f_i +- baud, whose phase over the centre line's is -2 pi baud tau_i (each signal's own, read at its own lines); the half-symbol ambiguity of a symmetric pulse is settled by which of tau and tau + T/2 gives the more PSK-like matched-filter output gains each signal's phase (mod 2 pi / M) from its centre line (a^M times a positive sum), its amplitude half the matched filter's power, then both refitted from decisions, slowly varying (a running mean over smooth symbols, which takes up a carrier estimate a little off)

Then both streams are matched-filtered on their own grids, z_i[k], and what each picks up of the other is c_ij(k, m) = A_j RC((m T + tau_j) - (k T + tau_i)) exp(j 2 pi (f_j - f_i) t_km) (the raised-cosine overlap of the pulses, turned by the carrier difference). Detection is a sequence estimate over both streams at once (the "paired carrier" receiver): the symbols of both, merged in time order, each output z[n] mostly the sum of its own symbol and its two neighbours of the other signal, so a Viterbi search over states (u[n-1], u[n]) (M^2 of them) scores every output exactly; the further neighbours (RC tails) are taken out with the previous pass's decisions, and the gains refitted, iterations times.

Limits: equal or comparable rates, both of the same PSK. estimate needs the two carriers resolved in the x^M spectrum: apart by more than about 4 / (M x the record's length) (measured: 20 Hz apart from 0.16 s of QPSK is separated without a symbol error at 15 dB, 5 Hz is not). Closer carriers need params from elsewhere (a known offset, a longer record); the detector then works on timing and phase differences alone, but a stretch where the two coincide in timing and phase as well is genuinely ambiguous. Signal 0 is the lower carrier.

Classes:

Name Description
Params

One signal's: cfo (Hz), tau (s: a symbol centre), gain (complex), line (its x^M line over the spectrum's median)

Separation

separate: symbols [s0, s1] (decided, on each one's grid), soft [s0, s1] (corrected matched-filter outputs with

Functions:

Name Description
estimate

Both signals' parameters (see the module): [Params, Params], the lower carrier first. search: the largest

separate

Both symbol streams of two overlapping signals (see the module): Separation

Params

Params(**kw)

One signal's: cfo (Hz), tau (s: a symbol centre), gain (complex), line (its x^M line over the spectrum's median)

Source code in src/rpps/analysis/spectrum/separate.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

Separation

Separation(**kw)

separate: symbols [s0, s1] (decided, on each one's grid), soft [s0, s1] (corrected matched-filter outputs with the other signal taken out), params [Params, Params], evm [e0, e1], iterations

Source code in src/rpps/analysis/spectrum/separate.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

estimate

estimate(x, Fs, baud, mod='qpsk', beta=0.35, search=None)

Both signals' parameters (see the module): [Params, Params], the lower carrier first. search: the largest carrier offset (Hz) looked at (default baud/4)

Source code in src/rpps/analysis/spectrum/separate.py
def estimate(x, Fs, baud, mod="qpsk", beta=0.35, search=None):
    """Both signals' parameters (see the module): [Params, Params], the lower carrier first. search: the largest
    carrier offset (Hz) looked at (default baud/4)"""
    x = np.asarray(x, dtype=np.complex128)
    pts = _points(mod)
    M = len(pts) if len(pts) <= 8 else 4
    n = len(x)
    nfft = 1 << int(np.ceil(np.log2(n)))
    y = x**M
    Y = np.fft.fft(y, nfft)
    P = np.abs(Y)**2
    f = np.fft.fftfreq(nfft, 1/Fs)
    search = baud/4 if search is None else search
    med = np.median(P)
    near = np.flatnonzero(np.abs(f) <= M*search)
    loc = near[(P[near] >= P[near - 1]) & (P[near] >= P[(near + 1) % nfft])]
    loc = loc[np.argsort(-P[loc])]
    peaks = []
    for i in loc:
        if all(abs(f[i] - f[j]) > 4*Fs/nfft for j in peaks):
            peaks.append(i)
        if len(peaks) == 2:
            break
    if len(peaks) < 2:
        raise ValueError("fewer than two carrier lines in x^M")
    t = np.arange(n)/Fs
    out = []
    for i in sorted(peaks, key=lambda j: f[j]):
        a, b, c = P[i - 1], P[i], P[(i + 1) % nfft]
        den = a - 2*b + c
        fm = f[i] + (0.5*(a - c)/den if den else 0.0)*Fs/nfft # M f_i
        L0 = np.sum(y*np.exp(-2j*np.pi*fm*t))
        Lp = np.sum(y*np.exp(-2j*np.pi*(fm + baud)*t))
        Lm = np.sum(y*np.exp(-2j*np.pi*(fm - baud)*t))
        # the periodic part's coefficient at +baud over 0 is real for a symmetric pulse: its phase is -2 pi baud tau
        ang = np.angle(Lp*np.conj(L0)) - np.angle(Lm*np.conj(L0)) # both sides, the pulse's own sign cancelling
        tau = (-ang/2/(2*np.pi*baud)) % (1/baud)
        cfo = fm/M
        best = None
        for tt in (tau, (tau + 0.5/baud) % (1/baud)):
            n0, cnt = _grid(x, Fs, baud, tt)
            z = _mf(x, Fs, baud, beta, cfo, tt, n0, min(cnt, 4000))
            q = np.abs(np.mean((z/np.sqrt(np.mean(np.abs(z)**2)))**M))
            if best is None or q > best[0]:
                best = (q, tt, z)
        _, tau, z = best
        # the line is a^M (the same for every point of M-PSK) times the pulse's M-th power summed (> 0): the phase
        # of this signal alone, mod 2 pi / M (the matched filter's own z^M is the two signals' cross terms as much)
        ph = (np.angle(L0) - np.angle(pts[0]**M))/M
        amp = np.sqrt(np.mean(np.abs(z)**2)/2) # equal power: half of the matched filter's output each (refitted later)
        out.append(Params(cfo=float(cfo), tau=float(tau), gain=amp*np.exp(1j*ph), line=float(b/med)))
    return out

separate

separate(x, Fs, baud, mod='qpsk', beta=0.35, params=None, iterations=4, smooth=256, taps=6)

Both symbol streams of two overlapping signals (see the module): Separation

Source code in src/rpps/analysis/spectrum/separate.py
def separate(x, Fs, baud, mod="qpsk", beta=0.35, params=None, iterations=4, smooth=256, taps=6):
    """Both symbol streams of two overlapping signals (see the module): Separation"""
    x = np.asarray(x, dtype=np.complex128)
    pts = _points(mod)
    ps = params or estimate(x, Fs, baud, mod, beta)
    T = 1/baud
    Z, tk = [], []
    for p in ps:
        n0, cnt = _grid(x, Fs, baud, p.tau)
        Z.append(_mf(x, Fs, baud, beta, p.cfo, p.tau, n0, cnt))
        tk.append(p.tau + (n0 + np.arange(cnt))*T)
    # the merged sequence, in time order
    sig = np.concatenate((np.zeros(len(tk[0]), int), np.ones(len(tk[1]), int)))
    idx = np.concatenate((np.arange(len(tk[0])), np.arange(len(tk[1]))))
    tt = np.concatenate(tk)
    order = np.argsort(tt, kind="stable")
    sig, idx, tt = sig[order], idx[order], tt[order]
    z = np.concatenate(Z)[order]
    L = len(z)
    cf = np.array([ps[0].cfo, ps[1].cfo])
    # coupling of merged symbol p into observation n (other signal only), for p = n - taps .. n + taps
    offs = np.arange(-taps, taps + 1)
    P = np.clip(np.arange(L)[:, None] + offs[None, :], 0, L - 1)
    valid = ((np.arange(L)[:, None] + offs[None, :]) >= 0) & ((np.arange(L)[:, None] + offs[None, :]) < L) & \
        (sig[P] != sig[:, None])
    W = _rc((tt[P] - tt[:, None])/T, beta)*np.exp(2j*np.pi*(cf[sig[P]] - cf[sig][:, None])*(tt[P] + tt[:, None])/2)*valid
    gains = [np.full(len(tk[i]), ps[i].gain, np.complex128) for i in range(2)]
    dec = np.zeros(L, np.complex128) # previous pass's decisions (none on the first)
    centre = taps
    for it in range(1, iterations + 1):
        g = np.where(sig == 0, gains[0][np.minimum(idx, len(tk[0]) - 1)], gains[1][np.minimum(idx, len(tk[1]) - 1)])
        GW = W*g[P] # with the coupled symbol's gain
        wl, wr = GW[:, centre - 1], GW[:, centre + 1]
        far = GW.copy()
        far[:, centre - 1:centre + 2] = 0
        resid = np.sum(far*dec[P], axis=1) if it > 1 else np.zeros(L, np.complex128)
        u = _viterbi(z, g, wl, wr, resid, pts)
        dec = pts[u]
        # gains, refitted from the decisions with everything else they hear taken out: a running mean
        clean = z - np.sum(GW*dec[P], axis=1)
        for i in range(2):
            sel = sig == i
            gi = clean[sel]*np.conj(dec[sel])/np.abs(dec[sel])**2
            ker = np.ones(smooth)/smooth
            gains[i] = np.convolve(gi, ker, mode="same")/np.convolve(np.ones(len(gi)), ker, mode="same")
    g = np.where(sig == 0, gains[0][np.minimum(idx, len(tk[0]) - 1)], gains[1][np.minimum(idx, len(tk[1]) - 1)])
    other = np.sum(W*g[P]*dec[P], axis=1)
    y = (z - other)/g
    syms, soft, evm = [], [], []
    for i in range(2):
        sel = sig == i
        yi = y[sel][np.argsort(idx[sel])]
        di = dec[sel][np.argsort(idx[sel])]
        soft.append(yi)
        syms.append(di)
        evm.append(float(np.sqrt(np.mean(np.abs(yi - di)**2)/np.mean(np.abs(pts)**2))))
    return Separation(symbols=syms, soft=soft, params=list(ps), evm=evm, iterations=iterations)

signal

Classes:

Name Description
Signal

A signal found in a spectrum

Burst

A Signal on part of the time

Survey

The signals found in a capture (a list of Signal, by frequency), and the spectrum they came from

Functions:

Name Description
welch

Averaged periodogram (Hann window), fftshifted. Returns (power per bin, number of averages)

noise_floor

Robust noise floor [dB]: median, then median of what is within margin dB above it (signals drop out)

measure_band

A band given by hand (a channel plan, a band a user typed) measured as find_signals measures what it finds: a

find_signals

The signals in a capture: rpps.analysis.spectrum.find.find (how it works is there), as a Survey of Signal sorted

survey

Look at a source (rp.source.File, Device) or an array, and find the signals in it

reject_spur_bauds

Drop baud estimates that are really a line in the capture, not the signal's symbol rate

Signal

Signal(mid, width, bottom, height, snr=None, *, lo=None, hi=None, power=None, peak_freq=None, duty=None, resolved=True, Fs=None, cf=0.0, bin_hz=None, clipped=False)

A signal found in a spectrum

mid: centre [Hz, from the capture's centre], freq: centre [Hz] absolute (cf + mid) width: occupied bandwidth [Hz] (the span holding occupied of its power), lo/hi: its edges [Hz from the capture's centre] bottom: noise floor [dB] (global), height: peak above the floor [dB], snr: in-band power over noise power in that band [dB] power: total in-band power [dB], peak_freq: strongest bin [Hz from the capture's centre] carrier, cn0: its power without the band's noise [dBFS], C/N0 [dB-Hz] duty: fraction of the time it is on (1: continuous, less: bursty) resolved: there were enough bins across it to trust the edges. False means read more samples clipped: it runs into the edge of the capture's band, so its width and centre are only what is inside baud_est / baud_strength: symbol rate from the |x|^2 line of the channelized signal (None: no clear line) holds: how many other signals stand on it (a transponder's pedestal, or a carrier with a narrower signal on it: which one, the spectrum can't tell; its own symbol-rate line can). over: the one it stands on, when it stands on one t0/t1, bursts: when it is on score: dB over the threshold that found it id: its number, kept from survey to survey by Survey.match stale, seen: a Finder's: not found in the last block, kept (its hold) as last seen; when it was last found [s] Fs, cf, bin_hz: the capture's rates and the spectrum's resolution A signal on only part of the time is a Burst.

Methods:

Name Description
channel

The filters that bring this signal to baseband at about oversample times its width

esn0_db

Es/N0 [dB] from the in-band SNR: the noise in the signal's width (snr) is that density times width, the

estimate_baud

Fill baud_est from samples of the capture (this signal is channelized first)

Attributes:

Name Type Description
carrier

The carrier's power [dB of the samples' |x|^2: dBFS where |x| = 1 is full scale]: power less the noise in

cn0

C/N0 [dB-Hz]: the carrier over the noise density, snr over the band's width (None without snr)

Source code in src/rpps/analysis/spectrum/signal.py
def __init__(self, mid, width, bottom, height, snr=None, *, lo=None, hi=None, power=None, peak_freq=None,
             duty=None, resolved=True, Fs=None, cf=0.0, bin_hz=None, clipped=False):
    self.mid = mid
    self.width = width
    self.bottom = bottom
    self.height = height
    self.snr = snr
    self.lo = mid - width/2 if lo is None else lo
    self.hi = mid + width/2 if hi is None else hi
    self.power = power
    self.peak_freq = mid if peak_freq is None else peak_freq
    self.duty = duty
    self.resolved = resolved
    self.clipped = clipped
    self.Fs, self.cf, self.bin_hz = Fs, cf, bin_hz
    self.baud_est = None
    self.baud_strength = 0.0
    self.holds = 0
    self.id = None
    self.t0 = self.t1 = None # when it is on [s from the capture's start]; bursts: [(t0, t1)], None when steady
    self.bursts = None
    self.over = None         # the signal it stands on (a pedestal, a carrier it jams), or None
    self.score = None        # dB over the threshold that found it
    self.stale = False       # (a Finder's: not found this block, kept as last seen)
    self.seen = None         # (a Finder's: when it was last found [s from the stream's start])
carrier property
carrier

The carrier's power [dB of the samples' |x|^2: dBFS where |x| = 1 is full scale]: power less the noise in its band (None without snr)

cn0 property
cn0

C/N0 [dB-Hz]: the carrier over the noise density, snr over the band's width (None without snr)

channel
channel(oversample=4.0, guard=1.3, atten_db=50.0)

The filters that bring this signal to baseband at about oversample times its width

Shift + multi-stage decimation (rp.signal.channelize), then a sharp filter at the low rate to drop the neighbours the decimation lets through: passband to guard*width/2 (the pulse skirts reach past the 99% width). Returns Channel(front, Fs, decimation, delay, settle): block + channel.front.

Source code in src/rpps/analysis/spectrum/signal.py
def channel(self, oversample=4.0, guard=1.3, atten_db=50.0):
    """The filters that bring this signal to baseband at about `oversample` times its width

    Shift + multi-stage decimation (rp.signal.channelize), then a sharp filter at the low rate to drop the neighbours
    the decimation lets through: passband to `guard`*width/2 (the pulse skirts reach past the 99% width).
    Returns Channel(front, Fs, decimation, delay, settle): `block + channel.front`.
    """
    from ...signal.filters import low_pass_kaiser
    from ...signal import channelize as _channel
    from ...base import Pipeline
    if self.Fs is None:
        raise ValueError("This signal doesn't know its capture's Fs: build it from rp.analysis.survey or find_signals")
    front, Fs, D = _channel(self.mid, self.width, self.Fs, oversample)
    if self.width*guard < Fs:
        sel = low_pass_kaiser(0.5*self.width*guard, 0.2*self.width, atten_db, Fs)
        front = Pipeline(front, sel)
    from ...base import Data
    delay = (Data(np.zeros(1, np.complex64), Fs=self.Fs) + front).meta.delay # (a stream of its own: front holds no state)
    return Channel(front, Fs, D, delay, int(np.ceil(2*delay*Fs)))
esn0_db
esn0_db(baud=None)

Es/N0 [dB] from the in-band SNR: the noise in the signal's width (snr) is that density times width, the symbol energy is the power over the symbol rate, so Es/N0 = snr + 10log10(width/baud). baud defaults to baud_est. The spectrum can't tell signal from noise inside the band, so this is the guide, the measured one (rp.sync.quality.measure on the locked symbols) the answer

Source code in src/rpps/analysis/spectrum/signal.py
def esn0_db(self, baud=None):
    """Es/N0 [dB] from the in-band SNR: the noise in the signal's width (snr) is that density times width, the
    symbol energy is the power over the symbol rate, so Es/N0 = snr + 10log10(width/baud). `baud` defaults to
    baud_est. The spectrum can't tell signal from noise inside the band, so this is the guide, the measured one
    (rp.sync.quality.measure on the locked symbols) the answer"""
    baud = baud or self.baud_est
    if baud is None or self.snr is None:
        return None
    return self.snr + 10*np.log10(self.width/baud)
estimate_baud
estimate_baud(samps, min_strength=4.0)

Fill baud_est from samples of the capture (this signal is channelized first)

Source code in src/rpps/analysis/spectrum/signal.py
def estimate_baud(self, samps, min_strength=4.0):
    """Fill baud_est from samples of the capture (this signal is channelized first)"""
    from ...sync.rate import find_baud
    from ...base import Data
    ch = self.channel()
    x = (Data(np.asarray(samps), Fs=self.Fs) + ch.front).data
    if len(x) < 512:
        return None
    baud, strength = find_baud(x, ch.Fs)
    self.baud_strength = strength
    self.baud_est = baud if strength >= min_strength else None
    return self.baud_est

Burst

Burst(mid, width, bottom, height, snr=None, *, lo=None, hi=None, power=None, peak_freq=None, duty=None, resolved=True, Fs=None, cf=0.0, bin_hz=None, clipped=False)

Bases: Signal

A Signal on part of the time

bursts: [(t0, t1)] in seconds, in what was looked at, duty (the fraction on), last (the latest burst), period (the median start to start [s], None under 3 bursts)

Methods:

Name Description
of

sig as a Burst (the same object, its class changed)

Source code in src/rpps/analysis/spectrum/signal.py
def __init__(self, mid, width, bottom, height, snr=None, *, lo=None, hi=None, power=None, peak_freq=None,
             duty=None, resolved=True, Fs=None, cf=0.0, bin_hz=None, clipped=False):
    self.mid = mid
    self.width = width
    self.bottom = bottom
    self.height = height
    self.snr = snr
    self.lo = mid - width/2 if lo is None else lo
    self.hi = mid + width/2 if hi is None else hi
    self.power = power
    self.peak_freq = mid if peak_freq is None else peak_freq
    self.duty = duty
    self.resolved = resolved
    self.clipped = clipped
    self.Fs, self.cf, self.bin_hz = Fs, cf, bin_hz
    self.baud_est = None
    self.baud_strength = 0.0
    self.holds = 0
    self.id = None
    self.t0 = self.t1 = None # when it is on [s from the capture's start]; bursts: [(t0, t1)], None when steady
    self.bursts = None
    self.over = None         # the signal it stands on (a pedestal, a carrier it jams), or None
    self.score = None        # dB over the threshold that found it
    self.stale = False       # (a Finder's: not found this block, kept as last seen)
    self.seen = None         # (a Finder's: when it was last found [s from the stream's start])
of classmethod
of(sig)

sig as a Burst (the same object, its class changed)

Source code in src/rpps/analysis/spectrum/signal.py
@classmethod
def of(cls, sig):
    """sig as a Burst (the same object, its class changed)"""
    sig.__class__ = cls
    return sig

Survey

Survey(signals=(), Fs=1.0, cf=0.0, nfft=0, K=0, freq=None, db=None, floor=0.0, head=None)

Bases: list

The signals found in a capture (a list of Signal, by frequency), and the spectrum they came from

Fs, cf: the capture's rates. nfft, K, bin_hz: the spectrum's size, averages and resolution freq, db: the spectrum [Hz from the centre, dB], floor: its noise floor [dB] head: the samples the survey looked at (a Device can't rewind: feed these first)

Methods:

Name Description
pick

One signal. near: closest to this offset from the capture's centre [Hz], freq: closest to this absolute

match

Carry signal ids over from the survey before this one of the same band (frame to frame): ids are a signal's

plot

Draw the spectrum with every signal shaded and numbered. Returns the axes

choose

Show the survey and wait for a click (or a number key) on the signal to process. Returns the Signal

Source code in src/rpps/analysis/spectrum/signal.py
def __init__(self, signals=(), Fs=1.0, cf=0.0, nfft=0, K=0, freq=None, db=None, floor=0.0, head=None):
    super().__init__(signals)
    self.Fs, self.cf, self.nfft, self.K = Fs, cf, nfft, K
    self.bin_hz = Fs/nfft if nfft else 0.0
    self.freq, self.db, self.floor, self.head = freq, db, floor, head
    self.lost = []       # [(Signal, surveys since seen)]: what `match` remembers of signals that went missing
    self.next_id = None  # The id `match` gives the next new signal (ids are never reused)
pick
pick(near=None, freq=None, index=None, strongest=False)

One signal. near: closest to this offset from the capture's centre [Hz], freq: closest to this absolute frequency [Hz], index: by position, strongest: highest in-band SNR, not total power, which a wide pedestal under the carriers would win (also the default for one argument less)

Source code in src/rpps/analysis/spectrum/signal.py
def pick(self, near=None, freq=None, index=None, strongest=False):
    """One signal. near: closest to this offset from the capture's centre [Hz], freq: closest to this absolute
    frequency [Hz], index: by position, strongest: highest in-band SNR, not total power, which a wide pedestal under the
    carriers would win (also the default for one argument less)"""
    if not len(self):
        raise ValueError("No signals to pick from")
    if index is not None:
        return self[index]
    if freq is not None:
        return min(self, key=lambda s: abs(s.freq - freq))
    if near is not None:
        return min(self, key=lambda s: abs(s.mid - near))
    return max(self, key=lambda s: s.snr if s.snr is not None else s.height)
match
match(previous, near=0.5, ratio=(0.75, 4 / 3), hold=8)

Carry signal ids over from the survey before this one of the same band (frame to frame): ids are a signal's own, stable however others come and go.

A signal is the earlier one whose centre is within near of its width and whose width is within ratio of its own (the closest such); each earlier signal is matched once. One that went missing (not found for a survey or a few: too weak for a moment) is remembered for hold surveys and gets its id back when it returns. A new signal gets an id never used before in the chain of surveys, so a signal appearing never renumbers the others. Sets Signal.id in place (and lost, next_id for the next match) and returns self

Source code in src/rpps/analysis/spectrum/signal.py
def match(self, previous, near=0.5, ratio=(0.75, 4/3), hold=8):
    """Carry signal ids over from the survey before this one of the same band (frame to frame): ids are a signal's
    own, stable however others come and go.

    A signal is the earlier one whose centre is within `near` of its width and whose width is within `ratio` of its own
    (the closest such); each earlier signal is matched once. One that went missing (not found for a survey or a few:
    too weak for a moment) is remembered for `hold` surveys and gets its id back when it returns. A new signal gets an
    id never used before in the chain of surveys, so a signal appearing never renumbers the others. Sets Signal.id in
    place (and `lost`, `next_id` for the next match) and returns self"""
    known = [(p, 0) for p in previous if p.id is not None] + list(getattr(previous, "lost", []))
    nxt = getattr(previous, "next_id", None)
    if nxt is None:
        nxt = max((p.id for p, _ in known), default=-1) + 1
    taken = set()
    order = sorted(self, key=lambda s: -s.snr if s.snr is not None else -s.height) # Strongest choose first
    cand = [[] for _ in order]
    if known and order: # (the pairs near enough and of about the width, at once)
        pf = np.array([p.freq for p, _ in known], float)
        pw = np.array([p.width for p, _ in known], float)
        sf = np.array([s.freq for s in order], float)[:, None]
        sw = np.array([s.width for s in order], float)[:, None]
        with np.errstate(divide="ignore", invalid="ignore"):
            r = sw/pw[None, :]
        ok = (np.abs(pf[None, :] - sf) <= near*sw) & (ratio[0] <= r) & (r <= ratio[1])
        cand = [np.flatnonzero(row).tolist() for row in ok]
    for s, cs in zip(order, cand):
        best = None
        for j in cs:
            p, age = known[j]
            if p.id in taken:
                continue
            d = abs(p.freq - s.freq)
            if best is None or (age, d) < best[0]:
                best = ((age, d), p) # (one seen in the last survey before one remembered)
        if best is None:
            s.id, nxt = nxt, nxt + 1
        else:
            s.id = best[1].id
            taken.add(s.id)
    self.lost = [(p, age + 1) for p, age in known if p.id not in taken and age + 1 <= hold]
    self.next_id = nxt
    return self
plot
plot(ax=None, chosen=None)

Draw the spectrum with every signal shaded and numbered. Returns the axes

Source code in src/rpps/analysis/spectrum/signal.py
def plot(self, ax=None, chosen=None):
    """Draw the spectrum with every signal shaded and numbered. Returns the axes"""
    from ...viz.plots.survey import survey as _plot
    return _plot(ax, self, chosen)
choose
choose()

Show the survey and wait for a click (or a number key) on the signal to process. Returns the Signal

Without an interactive backend (CI, a script run headless) it can't ask: the strongest signal is taken and said so.

Source code in src/rpps/analysis/spectrum/signal.py
def choose(self):
    """Show the survey and wait for a click (or a number key) on the signal to process. Returns the Signal

    Without an interactive backend (CI, a script run headless) it can't ask: the strongest signal is taken and said so.
    """
    import matplotlib
    import matplotlib.pyplot as plt
    if not len(self):
        raise ValueError("No signals to choose from")
    backend = matplotlib.get_backend().lower()
    try:
        from matplotlib.backends import backend_registry, BackendFilter
        headless = backend in backend_registry.list_builtin(BackendFilter.NON_INTERACTIVE)
    except ImportError: # Matplotlib before 3.9
        headless = backend in matplotlib.rcsetup.non_interactive_bk
    if headless:
        sig = self.pick(strongest=True)
        print(f"No interactive backend ({backend}): taking the strongest signal, {sig.describe()}")
        return sig
    fig, ax = plt.subplots(layout="constrained")
    self.plot(ax)
    ax.set_title("Click a signal (or press its number) to process it")
    picked = []
    def hit(sel):
        picked.append(sel)
        self.plot(ax, sel)
        fig.canvas.draw_idle()
    def on_click(ev):
        if ev.inaxes is ax and ev.xdata is not None:
            x = ev.xdata*1e6 - self.cf # The axis is MHz, absolute
            inside = [s for s in self if s.lo <= x <= s.hi]
            hit(min(inside or self, key=lambda s: abs(s.mid - x)))
    def on_key(ev):
        if ev.key and ev.key.isdigit() and int(ev.key) < len(self):
            hit(self[int(ev.key)])
    fig.canvas.mpl_connect("button_press_event", on_click)
    fig.canvas.mpl_connect("key_press_event", on_key)
    plt.show(block=False)
    while not picked and plt.fignum_exists(fig.number):
        plt.pause(0.05)
    if not picked:
        raise RuntimeError("The survey was closed without choosing a signal")
    plt.pause(0.3) # Show the choice
    plt.close(fig)
    return picked[0]

welch

welch(samps, Fs: float = 1, nfft: int = 4096, overlap: float = 0.5)

Averaged periodogram (Hann window), fftshifted. Returns (power per bin, number of averages)

Source code in src/rpps/analysis/spectrum/signal.py
def welch(samps, Fs: float = 1, nfft: int = 4096, overlap: float = 0.5):
    """Averaged periodogram (Hann window), fftshifted. Returns (power per bin, number of averages)"""
    seg, wp = _segments(samps, nfft, overlap)
    return np.fft.fftshift(seg.sum(axis=0)/(len(seg)*wp*Fs)), len(seg)

noise_floor

noise_floor(db, iters=4, margin=3.0, start=None)

Robust noise floor [dB]: median, then median of what is within margin dB above it (signals drop out)

start: where to begin instead of the median. A band mostly full of signal has a median inside the signals; starting from a low level makes the floor the quiet part, wherever the signals are

Source code in src/rpps/analysis/spectrum/signal.py
def noise_floor(db, iters=4, margin=3.0, start=None):
    """Robust noise floor [dB]: median, then median of what is within `margin` dB above it (signals drop out)

    start: where to begin instead of the median. A band mostly full of signal has a median inside the signals; starting
    from a low level makes the floor the quiet part, wherever the signals are
    """
    floor = np.median(db) if start is None else start
    for _ in range(iters):
        sel = db < floor + margin
        floor = np.median(db[sel])
    return floor

measure_band

measure_band(samps, Fs, freq, bw, cf=0.0, nfft=None, edge=0.005)

A band given by hand (a channel plan, a band a user typed) measured as find_signals measures what it finds: a Signal with power, SNR, height, peak and duty filled in, so typed and found signals compare alike

freq: the band's centre [Hz, absolute: cf + offset], bw: its width [Hz], cf: the capture's centre frequency. The noise is the capture's floor (find's, per bin); the band is cut to the capture's edges (clipped).

Source code in src/rpps/analysis/spectrum/signal.py
def measure_band(samps, Fs, freq, bw, cf=0.0, nfft=None, edge=0.005):
    """A band given by hand (a channel plan, a band a user typed) measured as find_signals measures what it finds: a
    Signal with power, SNR, height, peak and duty filled in, so typed and found signals compare alike

    freq: the band's centre [Hz, absolute: cf + offset], bw: its width [Hz], cf: the capture's centre frequency.
    The noise is the capture's floor (find's, per bin); the band is cut to the capture's edges (clipped)."""
    from .find import _nfft_for, fit_floor, spectrogram
    samps = np.asarray(samps)
    nfft = _nfft_for(len(samps)) if nfft is None else int(nfft)
    P, hop = spectrogram(samps, Fs, nfft, 0.5)
    fit = fit_floor(P, hop, edge)
    A = P.mean(axis=0, dtype=np.float64)
    bin_hz = Fs/nfft
    mid = freq - cf
    e0 = int(np.clip(np.floor((mid - bw/2)/bin_hz + nfft/2), 0, nfft - 1))
    e1 = int(np.clip(np.ceil((mid + bw/2)/bin_hz + nfft/2) - 1, e0, nfft - 1))
    clipped = mid - bw/2 < -Fs/2 or mid + bw/2 > Fs/2
    z = A[e0:e1+1]/fit.floor[e0:e1+1]
    n = e1 - e0 + 1
    snr = 10*np.log10(max(float(np.sum(z - 1.0)), 1e-30)/n)
    # Duty: the band's power frame by frame over the noise; halfway from the noise to its mean divides on from off. Too
    # weak or narrow to tell the swing from the estimate's own scatter: no answer
    on = (P[:, e0:e1+1]/fit.floor[None, e0:e1+1]).mean(axis=1)
    mean_p = float(on.mean())
    duty = float(np.mean(on > (1.0 + mean_p)/2)) if mean_p - 1.0 > 4*mean_p*np.sqrt(2/n) else None
    band = A[e0:e1+1]
    return Signal(((e0 + e1 + 1)/2 - nfft/2)*bin_hz, n*bin_hz, float(np.median(10*np.log10(fit.floor[e0:e1+1]))),
                  float(10*np.log10(max(float(z.max()), 1e-30))), float(snr), lo=(e0 - nfft/2)*bin_hz,
                  hi=(e1 + 1 - nfft/2)*bin_hz, power=float(10*np.log10(band.sum()*bin_hz + 1e-30)),
                  peak_freq=float((e0 + int(np.argmax(band)) - nfft/2)*bin_hz), duty=duty, resolved=n >= 8,
                  clipped=clipped, Fs=Fs, cf=cf, bin_hz=bin_hz)

find_signals

find_signals(samps, Fs: float = 1, nfft=None, cf=0.0, pfa=0.001, edge=0.005, drop_db=10.0, min_bins=1, min_across=8, nested=True, **retired)

The signals in a capture: rpps.analysis.spectrum.find.find (how it works is there), as a Survey of Signal sorted by frequency, ids 0, 1... in that order

pfa: expected false boxes in a capture of pure noise; nfft: FFT size [N/16, up to 65536]; cf: the capture's centre frequency [Hz], for Signal.freq; edge: fraction of the band at each end not looked at (the receiver's roll-off is also found); drop_db: a carrier's edges are this far under its level (or halfway to what is beside it); min_bins: narrowest signal; min_across: bins across under which its edges aren't trusted (Signal.resolved); nested: keep the boxes that hold other signals (a pedestal, a carrier a narrower one jams: Signal.holds). False: only what stands on them The thresholds of the rules this replaced (min_snr_db, gap, occupied, min_band_snr_db, edges, edge_db, split_db) are taken for one release with a DeprecationWarning, and do nothing: pfa sets what the detection lets through.

Source code in src/rpps/analysis/spectrum/signal.py
def find_signals(samps, Fs: float = 1, nfft=None, cf=0.0, pfa=1e-3, edge=0.005, drop_db=10.0, min_bins=1,
                 min_across=8, nested=True, **retired):
    """The signals in a capture: rpps.analysis.spectrum.find.find (how it works is there), as a Survey of Signal sorted
    by frequency, ids 0, 1... in that order

    pfa: expected false boxes in a capture of pure noise; nfft: FFT size [N/16, up to 65536]; cf: the capture's centre
    frequency [Hz], for Signal.freq; edge: fraction of the band at each end not looked at (the receiver's roll-off is
    also found); drop_db: a carrier's edges are this far under its level (or halfway to what is beside it); min_bins: narrowest signal; min_across: bins across under which its
    edges aren't trusted (Signal.resolved); nested: keep the boxes that hold other signals (a pedestal, a carrier a
    narrower one jams: Signal.holds). False: only what stands on them
    The thresholds of the rules this replaced (min_snr_db, gap, occupied, min_band_snr_db, edges, edge_db, split_db) are taken
    for one release with a DeprecationWarning, and do nothing: `pfa` sets what the detection lets through."""
    import warnings
    from .find import find
    bad = [k for k in retired if k not in _RETIRED]
    if bad:
        raise TypeError(f"find_signals() got unexpected keyword arguments {bad}")
    if retired:
        warnings.warn(f"find_signals: {sorted(retired)} no longer do anything (the finder's thresholds come from pfa); "
                      "they go in the next release", DeprecationWarning, stacklevel=2)
    sv = find(samps, Fs, cf=cf, nfft=nfft, pfa=pfa, edge=edge, drop_db=drop_db, min_bins=min_bins, min_across=min_across)
    if not nested:
        kept = [s for s in sv if not s.holds]
        for t in kept:
            if t.over is not None and t.over.holds:
                t.over = None
        sv[:] = kept
        for i, s in enumerate(sv):
            s.id = i
    return sv

survey

survey(source, Fs=None, cf=None, samples=2 ** 17, more=2 ** 20, baud=True, **kw)

Look at a source (rp.source.File, Device) or an array, and find the signals in it

how many samples to read. More means a finer spectrum, so close neighbours stay apart and the edges

are right, whatever block size the receive chain will use later

more: if some signal is too narrow for its bins, read up to this many (once) and look again baud: also estimate each signal's symbol rate (Signal.baud_est) The rest (pfa, drop_db, ...) is for find_signals. Returns a Survey; Survey.head is what was read.

Source code in src/rpps/analysis/spectrum/signal.py
def survey(source, Fs=None, cf=None, samples=2**17, more=2**20, baud=True, **kw):
    """Look at a source (rp.source.File, Device) or an array, and find the signals in it

    samples: how many samples to read. More means a finer spectrum, so close neighbours stay apart and the edges
        are right, whatever block size the receive chain will use later
    more: if some signal is too narrow for its bins, read up to this many (once) and look again
    baud: also estimate each signal's symbol rate (Signal.baud_est)
    The rest (pfa, drop_db, ...) is for find_signals. Returns a Survey; Survey.head is what was read.
    """
    if hasattr(source, "peek"):
        Fs = source.Fs if Fs is None else Fs
        cf = source.cf if cf is None else cf
        head = source.peek(samples)
        Fs, cf = (source.Fs if Fs is None else Fs), (source.cf if cf is None else cf) # A device settles on its own
    else:
        if Fs is None:
            raise ValueError("An array needs Fs")
        head, cf = np.asarray(source), (0.0 if cf is None else cf)
    sv = find_signals(head, Fs, cf=cf, **kw)
    if more and hasattr(source, "peek") and len(head) < more and any(not s.resolved for s in sv):
        bigger = source.peek(more)
        if len(bigger) > len(head):
            head = bigger
            sv = find_signals(head, Fs, cf=cf, **kw)
    sv.head = head
    if baud:
        for s in sv:
            try:
                s.estimate_baud(head)
            except Exception: # No estimate is not a failed survey
                pass
        reject_spur_bauds(sv)
    return sv

reject_spur_bauds

reject_spur_bauds(signals, tol=0.005, min_count=3, spread=1.5)

Drop baud estimates that are really a line in the capture, not the signal's symbol rate

A symbol rate above the signal's width can't be (width is at least the symbol rate). A rate found again and again on signals of different widths is a spur of the capture (a clock coupling into every signal's |x|^2); it, and its half multiples, are dropped from every signal of this capture. Signals sharing a rate and width are carriers of one service and keep it.

Source code in src/rpps/analysis/spectrum/signal.py
def reject_spur_bauds(signals, tol=0.005, min_count=3, spread=1.5):
    """Drop baud estimates that are really a line in the capture, not the signal's symbol rate

    A symbol rate above the signal's width can't be (width is at least the symbol rate). A rate found again and again
    on signals of different widths is a spur of the capture (a clock coupling into every signal's |x|^2); it, and
    its half multiples, are dropped from every signal of this capture. Signals sharing a rate and width are carriers
    of one service and keep it.
    """
    sigs = [s for s in signals if s.baud_est]
    for s in sigs:
        if s.baud_est > 1.1*s.width:
            s.baud_est = None
    sigs = [s for s in sigs if s.baud_est]
    spurs = []
    for s in sigs:
        like = [t for t in sigs if abs(t.baud_est - s.baud_est) <= tol*s.baud_est]
        if len(like) >= min_count and max(t.width for t in like)/min(t.width for t in like) > spread:
            spurs.append(s.baud_est)
    if spurs:
        base = float(np.median(spurs))
        for s in sigs:
            n = s.baud_est/(base/2)
            if abs(n - round(n)) <= 2*tol*n and round(n) >= 1:
                s.baud_est = None
    return signals

waveform

What kind of waveform a signal is, when it isn't a single linearly modulated carrier: tones, OFDM, bursts

w = rp.analysis.spectrum.waveform.classify(x, Fs)    # x: the signal at baseband (rp.signal.baseband / Signal.channel)
print(w)                                    # e.g. "OFDM 15 kHz subcarriers ... LTE / NR 15 kHz, normal CP; bursts ..."
Each test is cheap and says why it holds

tones: nearly all the power in a few lines narrower than a few Hz (a beacon, a pilot, an unmodulated carrier; two tones beat, and the beat looks like a symbol rate to the cyclostationary search) ofdm: the cyclic prefix repeats the end of each symbol, so the signal correlates with itself at the useful symbol length Tu (1/subcarrier spacing), about Tcp/(Tu+Tcp) of its power; x(t)x*(t+Tu) then pulses once a symbol, at 1/(Tu+Tcp). Many subcarriers add up to a Gaussian (E|x|^4/E|x|^2^2 near 2), which tells OFDM from a single carrier whose frame repeats (a preamble and pilots correlate at the frame length too). (Tu, Tcp) names the system: SYSTEMS bursts: the power switches on and off; the period of the switching (a TDD frame, a TDMA slot) envelope: E|x|^4/E|x|^2^2: 1 for a constant envelope (FM, FSK, CPM, a carrier), 1.3-1.7 for filtered PSK, 2 for noise or OFDM

Classes:

Name Description
Tones

tones: lines [(Hz from the centre, share of the power)], strongest first; share: of all of it, in them

OFDM

ofdm: tu, tcp (s), strength (the correlation at Tu: about tcp/(tu+tcp) at a high SNR), ratio (over other lags),

Bursts

bursts: duty (fraction of the time on), period (s, None if the switching isn't periodic), on (s a period)

Waveform

classify: tones, ofdm, bursts (each None when not), envelope (E|x|^4/E|x|^2^2)

Functions:

Name Description
envelope

E|x|^4/E|x|^2^2: 1 constant envelope, about 1.3-1.7 filtered PSK, 2 Gaussian (noise, OFDM, many carriers)

autocorr

|sum x(n+L) x*(n)| / sum |x|^2 for every lag L >= 0 (by FFT)

tones

Lines holding share of the power, at most max_lines of them, each within width_bins bins: Tones, or None.

ofdm

OFDM in baseband samples x at Fs: OFDM, or None (no lag stands out, no symbol period, or not Gaussian)

on_samples

The samples of x inside its bursts (a boolean mask): those every window of the smoothed power over them is on,

on_off

Whether the power switches on and off: Bursts, or None (steady, or too weak to tell). smooth: the power is averaged

classify

Tones, OFDM, bursts and the envelope of baseband samples x at Fs (see the module): a Waveform

Tones

Tones(lines, share, resolution)

tones: lines [(Hz from the centre, share of the power)], strongest first; share: of all of it, in them

Source code in src/rpps/analysis/spectrum/waveform.py
def __init__(self, lines, share, resolution):
    self.lines, self.share, self.resolution = lines, share, resolution

OFDM

OFDM(**kw)

ofdm: tu, tcp (s), strength (the correlation at Tu: about tcp/(tu+tcp) at a high SNR), ratio (over other lags), line (the symbol-rate line over its floor), envelope, systems [(name, misfit)] that fit, best first. comb: when the lag found repeats (correlating at 2x and 3x it too), it isn't the symbol but a pilot comb's period inside symbols: every comb-th subcarrier used, so the symbol is comb x tu (systems then fit that); None for plain OFDM

Source code in src/rpps/analysis/spectrum/waveform.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))

Bursts

Bursts(duty, period, on)

bursts: duty (fraction of the time on), period (s, None if the switching isn't periodic), on (s a period)

Source code in src/rpps/analysis/spectrum/waveform.py
def __init__(self, duty, period, on):
    self.duty, self.period, self.on = duty, period, on

Waveform

Waveform(tones=None, ofdm=None, bursts=None, envelope=None)

classify: tones, ofdm, bursts (each None when not), envelope (E|x|^4/E|x|^2^2)

Attributes:

Name Type Description
kind

"tones", "ofdm", "constant envelope", or None (nothing here says what it is)

Source code in src/rpps/analysis/spectrum/waveform.py
def __init__(self, tones=None, ofdm=None, bursts=None, envelope=None):
    self.tones, self.ofdm, self.bursts, self.envelope = tones, ofdm, bursts, envelope
kind property
kind

"tones", "ofdm", "constant envelope", or None (nothing here says what it is)

envelope

envelope(x)

E|x|^4/E|x|^2^2: 1 constant envelope, about 1.3-1.7 filtered PSK, 2 Gaussian (noise, OFDM, many carriers)

Source code in src/rpps/analysis/spectrum/waveform.py
def envelope(x):
    """E|x|^4/E|x|^2^2: 1 constant envelope, about 1.3-1.7 filtered PSK, 2 Gaussian (noise, OFDM, many carriers)"""
    a2 = np.abs(np.asarray(x))**2
    return float(np.mean(a2**2)/np.mean(a2)**2)

autocorr

autocorr(x)

|sum x(n+L) x*(n)| / sum |x|^2 for every lag L >= 0 (by FFT)

Source code in src/rpps/analysis/spectrum/waveform.py
def autocorr(x):
    """|sum x(n+L) x*(n)| / sum |x|^2 for every lag L >= 0 (by FFT)"""
    n = len(x)
    X = np.fft.fft(x, 2*n)
    r = np.fft.ifft(np.abs(X)**2)[:n]
    return np.abs(r)/np.real(r[0])

tones

tones(x, Fs, share=0.9, max_lines=4, width_bins=2)

Lines holding share of the power, at most max_lines of them, each within width_bins bins: Tones, or None. The resolution is Fs/len(x): a long stretch tells a carrier from a narrow modulated signal

Source code in src/rpps/analysis/spectrum/waveform.py
def tones(x, Fs, share=0.9, max_lines=4, width_bins=2):
    """Lines holding `share` of the power, at most `max_lines` of them, each within `width_bins` bins: Tones, or None.
    The resolution is Fs/len(x): a long stretch tells a carrier from a narrow modulated signal"""
    x = np.asarray(x, dtype=np.complex128)
    n = len(x)
    if n < 256:
        return None
    P = np.abs(np.fft.fft(x*np.hanning(n)))**2
    total = P.sum()
    f = np.fft.fftfreq(n, 1/Fs)
    left, lines = P.copy(), []
    for _ in range(max_lines):
        k = int(np.argmax(left))
        idx = np.arange(k - width_bins - 1, k + width_bins + 2) % n # The Hann window spreads a line over 3 bins
        lines.append((float(f[k]), float(left[idx].sum()/total)))
        left[idx] = 0.0
        got = sum(s for _, s in lines)
        if got >= share:
            keep = [(fr, s) for fr, s in lines if s > 0.02*got]
            return Tones(keep, got, Fs/n)
        if lines[-1][1] < 0.02: # The rest is spread: not lines
            break
    return None

ofdm

ofdm(x, Fs, tu_min=2e-06, tu_max=0.005, min_ratio=8.0, min_envelope=1.8, max_samples=2 ** 21, max_rate_line=8.0)

OFDM in baseband samples x at Fs: OFDM, or None (no lag stands out, no symbol period, or not Gaussian)

tu_min/tu_max: useful symbol lengths searched. min_ratio: the correlation at Tu over the median of the other lags. max_rate_line: a |x|^2 line this far over its floor (rpps.sync.find_baud) is a single carrier's symbol rate

Source code in src/rpps/analysis/spectrum/waveform.py
def ofdm(x, Fs, tu_min=2e-6, tu_max=5e-3, min_ratio=8.0, min_envelope=1.8, max_samples=2**21, max_rate_line=8.0):
    """OFDM in baseband samples x at Fs: OFDM, or None (no lag stands out, no symbol period, or not Gaussian)

    tu_min/tu_max: useful symbol lengths searched. min_ratio: the correlation at Tu over the median of the other lags.
    max_rate_line: a |x|^2 line this far over its floor (rpps.sync.find_baud) is a single carrier's symbol rate"""
    x = np.asarray(x[:max_samples], dtype=np.complex128)
    x = x - x.mean()
    n = len(x)
    env = envelope(x)
    lo, hi = max(int(tu_min*Fs), 8), min(int(tu_max*Fs), n//4)
    if env < min_envelope or hi <= lo + 8:
        return None
    # A single carrier has a symbol-rate line in |x|^2 (near its bandwidth); OFDM's subcarriers have none there
    from ...sync.rate import find_baud
    if find_baud(x[:2**18], Fs)[1] >= max_rate_line:
        return None
    r = autocorr(x)
    floor = float(np.median(r[lo:hi]))
    # The band's own correlation falls from 1 at lag 0 over about 1/bandwidth, longer for a sharp edge (a signal cut by
    # the capture's band edge rings): search from where it has fallen to the floor
    near = np.nonzero(r[lo:hi] < 3*floor)[0]
    if not len(near):
        return None
    lo += int(near[0])
    k = int(np.argmax(r[lo:hi])) + lo
    peak = float(r[k])
    if peak < min_ratio*floor:
        return None
    # A prefix peak is isolated; the band shape's own correlation near zero lag falls smoothly
    side = np.concatenate((r[max(lo, int(k*0.75)):max(lo, int(k*0.9))], r[int(k*1.1):min(n, int(k*1.25))]))
    if len(side) and peak < min_ratio*np.median(side):
        return None
    a, b, c = r[k - 1], r[k], r[k + 1]
    L = k + (0.5*(a - c)/(a - 2*b + c) if a - 2*b + c else 0.0)
    tu = L/Fs
    # The symbol period: the line of x(t) x*(t+Tu) between 1/(1.5 Tu) and 1/(1.003 Tu). Its phase is constant (the
    # carrier offset over Tu), so the line is at +-1/Ts: both sides are added
    Li = int(round(L))
    g = x[Li:]*np.conj(x[:-Li])
    m = 4*len(g)
    G = np.abs(np.fft.fft(g - g.mean(), m))
    G = G + G[(-np.arange(m)) % m]
    f = np.fft.fftfreq(m, 1/Fs)
    band = np.nonzero((f > 1/(1.5*tu)) & (f < 1/(1.003*tu)))[0]
    if not len(band):
        return None
    kk = band[np.argmax(G[band])]
    line = float(G[kk]/np.median(G[band]))
    if line < 6:
        return None
    tcp = 1/f[kk] - tu
    # A cyclic prefix correlates at Tu only; a comb (every m-th subcarrier used) repeats m times within its symbol, and
    # correlates at 2x and 3x the lag too. Its symbol is m x the lag, and the prefix found is no prefix
    comb = None
    if 2*Li + 2 < n and r[2*Li - 2:2*Li + 3].max() > COMB*peak:
        for m in range(2, 9):
            if any(abs(stu*1e-6 - m*tu)/(m*tu) < 0.01 for _, stu, _ in SYSTEMS):
                comb = m
                break
        else:
            comb = 0
    if comb is None and not 0.005 < tcp/tu < 0.4: # Not a prefix: a frame that repeats
        return None
    sy = []
    for name, stu, scp in SYSTEMS:
        if comb:
            e = abs(stu*1e-6 - comb*tu)/(comb*tu)
            if e < 0.01:
                sy.append((name.split(",")[0] + f", pilots on every {_nth(comb)} subcarrier", e))
            continue
        e_tu, e_cp = abs(stu*1e-6 - tu)/tu, abs(scp*1e-6 - tcp)/tu
        if e_tu < 0.01 and e_cp < 0.012:
            sy.append((name, e_tu + e_cp))
    sy = sorted(dict(sorted(sy, key=lambda t: -t[1])).items(), key=lambda t: t[1])
    return OFDM(tu=tu, tcp=tcp, strength=peak, ratio=peak/floor, line=line, envelope=env, systems=sy,
                comb=comb if comb else None)

on_samples

on_samples(x, Fs, smooth=2e-06, contrast=10.0)

The samples of x inside its bursts (a boolean mask): those every window of the smoothed power over them is on, so a filtered signal's dips between symbols stay in and the bursts' edges stay out. All of x when it doesn't switch

Source code in src/rpps/analysis/spectrum/waveform.py
def on_samples(x, Fs, smooth=2e-6, contrast=10.0):
    """The samples of x inside its bursts (a boolean mask): those every window of the smoothed power over them is on,
    so a filtered signal's dips between symbols stay in and the bursts' edges stay out. All of x when it doesn't switch"""
    g = _gate(x, Fs, smooth, contrast)
    if g is None:
        return np.ones(len(x), bool)
    on, w = g
    c = np.concatenate(([0], np.cumsum(on)))
    i = np.arange(w - 1, len(on)) # sample i is in windows i-w+1 .. i: all on
    m = np.zeros(len(x), bool)
    m[i] = c[i + 1] - c[i - w + 1] == w
    return m

on_off

on_off(x, Fs, smooth=2e-06, contrast=10.0, min_off=0.03)

Whether the power switches on and off: Bursts, or None (steady, or too weak to tell). smooth: the power is averaged over this long, and over 32 samples at least; contrast: the on level over the off level needed (power ratio); min_off: the least time off. The period (None when the bursts are not regular enough: autocorrelation under 0.5) is found from 0.5 ms to half of the record

Source code in src/rpps/analysis/spectrum/waveform.py
def on_off(x, Fs, smooth=2e-6, contrast=10.0, min_off=0.03):
    """Whether the power switches on and off: Bursts, or None (steady, or too weak to tell). smooth: the power is averaged
    over this long, and over 32 samples at least; contrast: the on level over the off level needed (power ratio);
    min_off: the least time off. The
    period (None when the bursts are not regular enough: autocorrelation under 0.5) is found from 0.5 ms to half of
    the record"""
    g = _gate(x, Fs, smooth, contrast)
    if g is None:
        return None
    on, _w = g
    duty = float(on.mean())
    if duty > 1 - min_off:
        return None
    dec = max(1, int(Fs*10e-6)) # The pattern at 100 kS/s is enough to find a period of a millisecond or more
    o = on[:len(on)//dec*dec].reshape(-1, dec).mean(1)
    o = o - o.mean()
    fs2 = Fs/dec
    r = autocorr(o) if len(o) > 8 else np.zeros(1)
    r = r*len(r)/np.maximum(len(r) - np.arange(len(r)), 1) # Per lag over the overlap: a long lag has fewer terms to sum
    # The period: a peak past the autocorrelation's first dip (before it, the lags inside one burst, which are always
    # near 1), from 0.5 ms to half the record (two periods; at most 0.5 s: frames of a satellite TDMA network)
    lo_, hi_ = int(0.5e-3*fs2), min(len(r)//2, int(0.5*fs2))
    period = None
    if hi_ > lo_ + 2:
        d = np.diff(r[:hi_])
        dip = int(np.argmax(d > 0)) if (d > 0).any() else hi_
        start = max(lo_, dip)
        if start < hi_ - 2: # A true peak (not the range's end), the earliest within 10% of the highest (not a multiple)
            seg = r[start:hi_]
            peaks = np.flatnonzero((seg[1:-1] >= seg[:-2]) & (seg[1:-1] >= seg[2:])) + 1
            if len(peaks):
                top = seg[peaks].max()
                k = start + int(peaks[np.argmax(seg[peaks] >= 0.9*top)])
                if r[k] > 0.5:
                    period = k/fs2
    return Bursts(duty, period, duty*period if period else None)

classify

classify(x, Fs)

Tones, OFDM, bursts and the envelope of baseband samples x at Fs (see the module): a Waveform

Source code in src/rpps/analysis/spectrum/waveform.py
def classify(x, Fs):
    """Tones, OFDM, bursts and the envelope of baseband samples x at Fs (see the module): a Waveform"""
    x = np.asarray(x)
    if len(x) < 256:
        return Waveform()
    t = tones(x, Fs)
    b = None if t is not None else on_off(x, Fs) # Tones beat: their envelope swings without switching off
    o = None if t is not None else ofdm(x, Fs)
    # A burst's on and off move the envelope statistic: judge it over the on part only, by the smoothed power (a
    # threshold on each sample's would drop filtered PSK's dips between symbols, and call it constant envelope)
    on = x if b is None else x[on_samples(x, Fs)]
    return Waveform(t, o, b, envelope(on) if len(on) > 64 else None)