Skip to content

Sync

rpps.sync

Sync: estimate something unknown about the data and correct or align it, at whatever representation it can be separated

Its estimates go to stream.est[name], never into the data. Block estimation and block-rate tracking are first class; per-sample loops are second class.

First class: block estimation, tracked across windows

Estimate from a window with block operations (FFTs, correlation, least squares), then a slow loop run once per window (track: critically damped second order, wide while it pulls in, coasting through gated windows) carries each parameter and its rate across windows and gates outliers; the correction is evaluated per item.

Estimates Operator Profile method
symbol timing time.OerderMeyr: square-law, cubic interpolation; follows a clock 200 ppm off timing: oerder_meyr (default)
symbol timing, the matched filter fused in time.MatTrack: the matched filter's energy maximum (MatRRC), read only at the instants; on a GPU too timing: mat
carrier frequency and phase phase.MPower: M-th power of the phase, FFT acquisition carrier: mpower (default)
channel equalize.BlockLS: least squares per window against decisions; blind=True: constant modulus by least squares until the eye opens equalize: ls (default), "blind": true
OFDM timing and frequency CPSync: from the cyclic prefix
carrier phase per frame PilotPhase (pilot blocks), phase.FFCarrier (Viterbi & Viterbi) carrier: pilots, carrier: ff
spectral inversion Inversion, inversion.sense (known symbols turning backwards) inversion
frame starts FrameSync (a preamble and the best word of a header code; or named alternatives, Zadoff-Chu sets, a word mid-burst, real levels, what the match says: word, scale, cfo, esn0, modulation), Delimiter (a word among bits) frame, delimit
alignment on bits Align (markers, patterns, polarity), Puncture (puncture phase) align, puncture
modulation (PSK, QAM, APSK), rate, roll-off, offset Acquire (detect once; roll-off: rate.find_rolloff), Lock (a snapshot: Lock.find, lock.update; contiguous blocks joined: lock.follow); code phase and Doppler: acquire_code
channel code, bit map, alignment AcquireFEC
bursts Burst splits a stream into bursts, BurstTx places them; Bursts on many carriers, placed in a burst time plan (rpps.plan) whose origin it acquires and tracks, PlanTx places them by one; Preamble finds each one's preamble (attach_tx(): its PreambleTx) burst, preamble
a pilot tone ToneLock (FM stereo's 19 kHz, ATSC's pilot)

Rules for feedforward estimators:

  1. Windows sit at absolute stream positions ([k*W, k*W + L), history carried between blocks), so output does not depend on how the stream is cut.
  2. Drifting parameters are tracked across windows, not held per window (a free-running SDR is 10-20 ppm off and wanders), and the correction is evaluated per sample.
  3. Windows are set in time, not symbols: oscillator phase wanders in time (cycle slips at 8 ms windows, none at 2 ms).
  4. Latency is declared in stream.est[name]["latency"] (seconds), not added to meta.delay, the group delay.

A profile's sync steps name what is estimated (carrier, timing, equalize, frame) and get the first-class method; another is chosen by name in defaults: {"timing": {"method": "mat"}}. A new estimator is registered with rp.profile.steps.register_sync_method.

Second class: per-sample loops

loops (rpps.sync.loops) holds them, for signals and conditions block estimation does not suit, as references and for comparison: loops.MM (Mueller & Muller, Gardner), loops.TLL (a timing locked loop around a detector from loops.ted: ted="zx" zero crossing, "el" early-late), loops.Costas (M-PSK, or any constellation's points), loops.AGC, loops.PeakAGC, loops.Squelch, the adaptive equalizers loops.LMS and loops.CMA. Profiles reach them by name (timing: mm, gardner, timing: {"method": "tll", "ted": "el"}, carrier: costas, agc: loop, equalize: lms, cma). Their loop filter is loops.pll.PILoop (gains from a bandwidth: loops.pll.loop_gains).

Known, measured, detected

  • time.Known: timing that is given, not estimated (a loopback, a source whose timing is known); fuses the matched filter before it (timing: known).
  • On a GPU (rpps._accel.device(), CUDA or ROCm/HIP; numpy without one), by "device": true in a step's sync settings: time.MatTrack (timing: mat: the held samples filtered and read at the instants on the device, windows measured a group at a time) and FrameSync (frame: the preamble metric, and the header words ranked in one matrix product). Both agree with their numpy paths to single-precision rounding: the same frames, the same symbols to 1e-4.
  • detect, Detection, rate.find_baud: the feed-forward estimates Acquire runs (rate, timing, modulation, offset, phase); blind analysis uses them too.
  • quality: Es/N0, Eb/N0 and EVM of locked symbols, once (measure), over a window (Track) or on the stream (Monitor, {"sync": "quality"}); each symbol's error (errors) and an analyser's error summary (summary: EVM, MER, magnitude and phase error, IQ offset, gain imbalance, quadrature error).

AcquireFEC does for the code what Acquire does for the modulation: on timed, carrier-corrected symbols it finds the configured code, bit map and alignment (analysis.identify: convolutional codes, RS behind a Forney interleaver, HDLC, block codes), names the profile that decodes it, then tracks by re-encoding once per window and putting carrier turns and symbol slips right; est["fec"].rx() decodes. With blind=True the blind tools (rpps.analysis) run when no definition fits; what they find is a Guess, a definition that decodes once saved.

Modules:

Name Description
acquire

Acquisition: symbol rate, timing, modulation, frequency offset and phase from baseband samples: once (detect), as

acquire_fec

AcquireFEC: which code timed symbols carry, found as the stream arrives (the scans are in rpps.analysis.identify)

agc

Automatic gain control, with no loop over samples

align
burst

Per-burst acquisition: cut a stream of samples into the bursts that rise out of its noise floor

code_acquire
equalize

Equalizers: symbols + rp.sync.equalize.BlockLS(qpsk) solves the taps per window

frame

Frame sync: where frames start (rpps.sync)

inversion

Spectral inversion (a stream conjugated) found by known symbols turning backwards, and undone (rpps.sync)

kernels

Batch kernels of the sync operators: PilotLine of PilotPhase

ofdm

OFDM symbol timing and fractional carrier frequency from the cyclic prefix (van de Beek, Sandell & Borjesson 1997)

pilots
plan

Bursts on many carriers, placed in a burst time plan (rpps.plan): the return link of an MF-TDMA network

preamble

A preamble at the start of a burst: where it is, and the carrier offset its repetition gives

puncture
quality

Signal quality of recovered symbols: Es/N0, Eb/N0, EVM, measured once (measure), over a running window (Track)

rate

Symbol rate estimates: the |x|^2 cyclostationary line on samples (find_baud), the rate of symbols (find_rate), the

squelch

Squelch: detects that a signal is present, and gates the stream on it

tone

A phase-locked tone: the oscillator a pilot sets (FM stereo's 19 kHz, ATSC's pilot), and the signal mixed with it

track

Block-rate tracking (rpps.sync): a slow loop run once per window over the window estimates

acquire

Acquisition: symbol rate, timing, modulation, frequency offset and phase from baseband samples: once (detect), as snapshots of separate blocks (Lock: a display that seeks, pauses and retunes) and as the stream arrives (Acquire)

Everything here is feed-forward: symbol rate and timing from the matrix matched filter, frequency/phase from the M-th power of the symbols, modulation from the likelihood of the corrected symbols under each candidate constellation.

The likelihood needs the noise. Fitted per candidate (each its own variance, the points at the symbols' rms, noise included), a denser constellation explains noise better, so at low SNR the densest candidate won (noise alone was named 32APSK, QPSK at 4 dB 64QAM): the generalised likelihood's known bias to higher orders. So each candidate is scored at its own Es/N0 from the symbols' moments (rpps.sync.quality.m2m4: what that candidate's kurtosis says the signal and noise are; the quasi-hybrid likelihood test), unless the fit's own winner reads over FIT_MIN dB: there the fit is right and M2M4 fades (for QAM), so the fit; at the caller's Es/N0 when it gives one (esn0=, from a known sequence: rpps.sync.quality.from_sequence on a Zadoff-Chu). It needs nothing but the symbols. With the rate given, BPSK is named 7 dB lower, QPSK from 1.75 dB (it was 4.75), 32QAM and the APSKs 1.75 dB lower; 64QAM's 10 dB is honest now (tools/modclass_bench.py).

min_evidence makes detect say it doesn't know (mod None, the leader in best) rather than name a guess: when the leader doesn't beat Gaussian noise of the same power by NULL_MARGIN nats in all (Detection.over_noise: is there a constellation at all), or doesn't lead the runner-up by min_evidence nats (Detection.evidence: which one). 10 nats never named noise; it named 8PSK as 16PSK and 16QAM as 64QAM now and then at 8 dB, and at 0-4 dB names 9-22%.

Classes:

Name Description
Detection

Result of detect. Acquire stamps it on its blocks: meta.det

Lock

A signal's symbols, as a snapshot: found once by a full search (Lock.find), then followed block by block

Acquire

Detect as soon as the signal is there, then keep refining as the stream grows

Functions:

Name Description
symmetry

Order M of the rotational symmetry of a point set (the M-th power removes the modulation)

candidates

Load candidate constellations from config/constellation: {name: unit-rms points}. Each is read once per config

turned_candidates

Turned candidates.

correct

Feed-forward frequency + phase correction for a candidate. Returns (symbols, cfo cycles/symbol, phase); a carrier

drift

The phase curvature c (radians a symbol^2) a drifting carrier leaves on symbols y.

score

Mean log-likelihood per symbol of unit-rms y under equiprobable points with Gaussian noise: the variance fitted

score_all

Scores of {name: (corrected unit-rms symbols, points)} and how they were made: at the caller's esn0 ("given"); each

null_score

score of unit-rms y as Gaussian noise of the same power (complex, unit variance)

track_timing

Refine sps from the drift of the best timing between the start and end of x. Returns (sps, tau)

detect

Find symbol rate, timing, modulation, frequency offset and phase from baseband samples

onset

Where a signal comes on in x. The first block whose power reaches level of the median block's (0 when the

Detection

Detection(**kw)

Result of detect. Acquire stamps it on its blocks: meta.det

strength of the symbol-rate line the rate came from, over its local floor (noise peaks at about 3-4; a rate

taken from a weaker line is a guess)

beta: the roll-off of the matched filter that scored best; rolloff: the spectrum's (rate.find_rolloff), when measured mod: the modulation, None when detect was asked for min_evidence and the evidence is short (best the leader) how: how the candidates were scored: "given" (at the caller's esn0, given), "moments" (each at its M2M4 Es/N0) or "fit" (each its own variance). null: the score of Gaussian noise of the symbols' power (see over_noise) drift: the carrier's frequency rate over the symbols searched, Hz/s (a Doppler rate; 0.0 when none stands out: drift), taken off before the symbols were scored

Attributes:

Name Type Description
margin

Score lead of the detected modulation over the runner-up

evidence

Total log-likelihood lead of the leader over the runner-up (nats): margin times symbols

over_noise

Total log-likelihood lead of the leader over Gaussian noise of the same power (nats): a constellation at all

Source code in src/rpps/sync/acquire.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw.get(k))
margin property
margin

Score lead of the detected modulation over the runner-up

evidence property
evidence

Total log-likelihood lead of the leader over the runner-up (nats): margin times symbols

over_noise property
over_noise

Total log-likelihood lead of the leader over Gaussian noise of the same power (nats): a constellation at all

Lock

A signal's symbols, as a snapshot: found once by a full search (Lock.find), then followed block by block (update) without searching again. Nothing is held between blocks, and they need not be consecutive, so a display that seeks, pauses or changes channel gets an answer for every frame:

lk = rp.sync.Lock.find(x, Fs)               # raises rp.errors.NoLock(reason) when there is nothing to lock to
lk = lk.update(x_next)                      # same modulation and roll-off; timing, rate and cfo followed
lk.symbols, lk.quality.esn0_db, lk.stale    # stale: the signal is not the one found, search again
lk = lk.refine(x_longer)                    # the rate searched again on more signal (Acquire, as history grows)
lk = lk.follow(x_after, at=pos)             # the block right after this one: its symbols join on with no slip

det: the Detection for this block (rate, timing on its lattice from x[0], cfo, phase, gain, modulation) found: the Detection of the full search the lock started from symbols: matched-filtered, frequency and phase corrected, unit rms, at centres (sample positions in the block) points: the constellation (unit rms). quality: rpps.sync.quality.Quality of the symbols stale: why the lock no longer fits (Es/N0 fell drop_db below the search's, the rate moved more than drift from it, or one of the search's RECHECK runners-up now fits better), None while it does x: the block the lock is of (after follow, with the end of the one before that the filter needs) end: the stream position just past x, when at gave where x starts (None otherwise)

What an analyser shows of the block: decisions(), errors() and summary() (rpps.sync.quality: EVM, MER, IQ offset, gain imbalance, quadrature error), derotated() (x as the symbols see it), matched(up) (the matched filter between the symbols: eye diagrams) and reference() (the ideal waveform of the decided symbols)

Methods:

Name Description
find

Search x for a signal: its symbol rate, modulation, roll-off, timing, cfo and phase (detect)

update

The same signal in a new block x (anywhere in the stream: consecutive or not): timing and rate followed from

follow

The block right after this lock's (contiguous: its first sample follows the last of x), its symbols joining

refine

The search again on more of the signal (x: a longer stretch), its modulation and roll-off kept: the rate is

decisions

The nearest constellation point to each symbol (unit rms, as points)

errors

Each symbol's error against its decision: rpps.sync.quality.Errors (vector; evm_pct and mag_pct as a percentage

summary

An analyser's error summary of the symbols: rpps.sync.quality.Summary (EVM rms and peak, MER, magnitude and

derotated

x with the carrier offset and phase taken out and scaled as the symbols are (their matched filter at centres

matched

The matched filter's output between the symbols, up points a symbol: (t, z). t: time in symbols from the

reference

The ideal waveform of the block: the decided symbols through the root raised cosine pulse at centres, on x's

find classmethod
find(x, Fs, names=None, betas=None, span=8, baud=None, lock=5.0, min_samples=1024, drop_db=6.0, drift=0.002, at=None, esn0=None, min_evidence=None)

Search x for a signal: its symbol rate, modulation, roll-off, timing, cfo and phase (detect)

names / betas: candidate modulations and roll-offs (default: candidates(), and as detect chooses them) baud: the symbol rate when known: no rate search and no line needed lock: symbol-rate line strength needed over its local floor (noise peaks at about 3-4); None takes any line min_samples: fewer samples are not searched (the rate search goes down to Fs/16: at least 64 symbols) drop_db / drift: when update calls the lock stale (an Es/N0 drop [dB], a relative rate change) esn0 / min_evidence: as detect (a known Es/N0; how sure the modulation must be: NoLock when it isn't, or when the samples hold no symbol-rate correlation) at: the stream position of x[0], when known: follow then checks the next block is the one right after Raises NoLock (reason, line) when x is too short or has no clear symbol rate

Source code in src/rpps/sync/acquire.py
@classmethod
def find(cls, x, Fs, names=None, betas=None, span=8, baud=None, lock=5.0, min_samples=1024,
         drop_db=6.0, drift=2e-3, at=None, esn0=None, min_evidence=None):
    """Search x for a signal: its symbol rate, modulation, roll-off, timing, cfo and phase (`detect`)

    names / betas: candidate modulations and roll-offs (default: candidates(), and as `detect` chooses them)
    baud: the symbol rate when known: no rate search and no line needed
    lock: symbol-rate line strength needed over its local floor (noise peaks at about 3-4); None takes any line
    min_samples: fewer samples are not searched (the rate search goes down to Fs/16: at least 64 symbols)
    drop_db / drift: when `update` calls the lock stale (an Es/N0 drop [dB], a relative rate change)
    esn0 / min_evidence: as `detect` (a known Es/N0; how sure the modulation must be: NoLock when it isn't, or
        when the samples hold no symbol-rate correlation)
    at: the stream position of x[0], when known: `follow` then checks the next block is the one right after
    Raises NoLock (reason, line) when x is too short or has no clear symbol rate"""
    x = cls._samples(x, min_samples, f"the search needs {min_samples}")
    with cls._numbers():
        line = None
        if not baud:
            baud, line = find_baud(x, Fs)
            if lock is not None and not line >= lock:
                raise NoLock(f"no symbol rate (line {line:.1f}, needs {lock:g}): a carrier, or noise?", line)
            if not 0 < baud <= Fs/1.5: # (find_baud searches up to there: 1.5 samples a symbol)
                raise NoLock(f"no symbol rate (the strongest line is at {baud:.6g} Bd): a carrier, or noise?", line)
        det = detect(x, Fs, names, betas, span, baud=baud, esn0=esn0, min_evidence=min_evidence)
        det.line = line
        if det.mod is None:
            raise NoLock(f"modulation unclear: {det.best} leads by {det.evidence:.0f} nats (needs {min_evidence:g})"
                         if det.over_noise >= NULL_MARGIN else
                         f"nothing like a constellation: {det.over_noise:.0f} nats over Gaussian noise", line)
        lk = cls._make(x, Fs, det, candidates([det.mod])[det.mod], span, det, drop_db, drift)
    return cls._made(lk, x, det, at)
update
update(x, rounds=1, recheck=True, at=None)

The same signal in a new block x (anywhere in the stream: consecutive or not): timing and rate followed from this lock's (track_timing, rounds times), cfo and phase measured afresh, no search. Returns a new Lock; raises NoLock when x holds too few symbols

recheck: score the other modulations the search tried on these symbols (the same matched filter output), and call the lock stale when one fits better by RECHECK_MARGIN: at low SNR a change of modulation can cost less Es/N0 than drop_db. at: the stream position of x[0], when known (for follow)

Source code in src/rpps/sync/acquire.py
def update(self, x, rounds=1, recheck=True, at=None):
    """The same signal in a new block x (anywhere in the stream: consecutive or not): timing and rate followed from
    this lock's (`track_timing`, `rounds` times), cfo and phase measured afresh, no search. Returns a new Lock;
    raises NoLock when x holds too few symbols

    recheck: score the other modulations the search tried on these symbols (the same matched filter output), and
    call the lock stale when one fits better by RECHECK_MARGIN: at low SNR a change of modulation can cost less Es/N0
    than `drop_db`. at: the stream position of x[0], when known (for `follow`)"""
    x = self._samples(x)
    d = self.det
    with self._numbers():
        sps, tau = track_timing(x, d.sps, d.beta, self.span, rounds)
        det = Detection(mod=d.mod, baud=self.Fs/sps, sps=sps, beta=d.beta, tau=tau, M=d.M, scores=self.found.scores,
                        line=self.found.line, rolloff=self.found.rolloff)
        lk = self._make(x, self.Fs, det, self.points, self.span, self.found, self.drop_db, self.drift, recheck)
    return self._made(lk, x, det, at)
follow
follow(x, at=None, rounds=1, recheck=True)

The block right after this lock's (contiguous: its first sample follows the last of x), its symbols joining on to these with no symbol dropped or repeated: the first is the one after the last here, the timing, rate, carrier offset and phase carried on (the phase on the branch of its M-fold symmetry that continues this one's, so the decisions keep their rotation). Concatenating the symbols of a chain of follows gives the sequence one update over the joined record would (each block's estimates its own). Returns a new Lock, whose x starts with the end of this one's that the matched filter needs

the stream position of x[0]. When both this lock's end and at are known and differ, the blocks are not

contiguous: NoLock (start again with update). Stale (stale) also when the timing moved more than MAX_STEP of a symbol between the blocks: a slip is likely, so the joined symbols can't be trusted

Raises NoLock when x holds too few symbols

Source code in src/rpps/sync/acquire.py
def follow(self, x, at=None, rounds=1, recheck=True):
    """The block right after this lock's (contiguous: its first sample follows the last of `x`), its symbols joining
    on to these with no symbol dropped or repeated: the first is the one after the last here, the timing, rate,
    carrier offset and phase carried on (the phase on the branch of its M-fold symmetry that continues this one's, so
    the decisions keep their rotation). Concatenating the symbols of a chain of follows gives the sequence one
    `update` over the joined record would (each block's estimates its own). Returns a new Lock, whose `x` starts with
    the end of this one's that the matched filter needs

    at: the stream position of x[0]. When both this lock's `end` and `at` are known and differ, the blocks are not
        contiguous: NoLock (start again with `update`). Stale (`stale`) also when the timing moved more than
        MAX_STEP of a symbol between the blocks: a slip is likely, so the joined symbols can't be trusted
    Raises NoLock when x holds too few symbols"""
    x = self._samples(x)
    if at is not None and self.end is not None and int(at) != self.end:
        raise NoLock(f"not the next block: it starts at {int(at)}, this one ended at {self.end} "
                     f"({int(at) - self.end:+d} samples)")
    d = self.det
    sps = d.sps
    nxt = self.centres[-1] + sps # the next symbol instant, in this x's positions
    keep = max(0, int(np.floor(nxt - self.span*sps - 6)))
    j = np.concatenate((self.x[keep:], x))
    c0 = nxt - keep
    with self._numbers():
        sps2, tau = track_timing(j, sps, d.beta, self.span, rounds)
        step = (tau - c0 + sps2/2) % sps2 - sps2/2 # the measured lattice nearest the predicted instant
        det = Detection(mod=d.mod, baud=self.Fs/sps2, sps=sps2, beta=d.beta, tau=c0 + step, M=d.M,
                        scores=self.found.scores, line=self.found.line, rolloff=self.found.rolloff)
        # The carrier phase predicted at the first new symbol, len(centres) symbols after this lock's first
        phase = d.phase + 2*np.pi*d.cfo/d.baud*len(self.centres)
        lk = self._make(j, self.Fs, det, self.points, self.span, self.found, self.drop_db, self.drift, recheck,
                        first=c0 + step, phase=phase)
    lk = self._made(lk, j, det)
    lk.end = None if self.end is None else self.end + len(x)
    if at is not None:
        lk.end = int(at) + len(x)
    if lk.stale is None and abs(step) > self.MAX_STEP*sps2:
        lk.stale = f"the timing moved {step/sps2:+.2f} symbols between the blocks: a slip is likely"
    return lk
refine
refine(x, baud=None)

The search again on more of the signal (x: a longer stretch), its modulation and roll-off kept: the rate is searched afresh (or baud, when known), so an estimate made on few samples is corrected however far off it was, which update, following, can't. The result is the lock's new reference (found). Raises NoLock as find

Source code in src/rpps/sync/acquire.py
def refine(self, x, baud=None):
    """The search again on more of the signal (x: a longer stretch), its modulation and roll-off kept: the rate is
    searched afresh (or `baud`, when known), so an estimate made on few samples is corrected however far off it was,
    which `update`, following, can't. The result is the lock's new reference (`found`). Raises NoLock as `find`"""
    x = self._samples(x)
    with self._numbers():
        det = detect(x, self.Fs, [self.det.mod], (self.det.beta,), self.span, baud=baud)
        det.scores = self.found.scores # (only the kept modulation was scored)
        lk = self._make(x, self.Fs, det, self.points, self.span, det, self.drop_db, self.drift)
    return self._made(lk, x, det)
decisions
decisions()

The nearest constellation point to each symbol (unit rms, as points)

Source code in src/rpps/sync/acquire.py
def decisions(self):
    """The nearest constellation point to each symbol (unit rms, as `points`)"""
    return decide(self.symbols, self.points)
errors
errors()

Each symbol's error against its decision: rpps.sync.quality.Errors (vector; evm_pct and mag_pct as a percentage of the constellation's rms; phase_deg)

Source code in src/rpps/sync/acquire.py
def errors(self):
    """Each symbol's error against its decision: rpps.sync.quality.Errors (vector; evm_pct and mag_pct as a percentage
    of the constellation's rms; phase_deg)"""
    return errors(self.symbols, self.points)
summary
summary()

An analyser's error summary of the symbols: rpps.sync.quality.Summary (EVM rms and peak, MER, magnitude and phase error, IQ offset, gain imbalance, quadrature error)

Source code in src/rpps/sync/acquire.py
def summary(self):
    """An analyser's error summary of the symbols: rpps.sync.quality.Summary (EVM rms and peak, MER, magnitude and
    phase error, IQ offset, gain imbalance, quadrature error)"""
    return summary(self.symbols, self.points)
derotated
derotated()

x with the carrier offset and phase taken out and scaled as the symbols are (their matched filter at centres gives about symbols; exactly for no carrier offset, the offset turning inside the filter otherwise)

Source code in src/rpps/sync/acquire.py
def derotated(self):
    """x with the carrier offset and phase taken out and scaled as the symbols are (their matched filter at `centres`
    gives about `symbols`; exactly for no carrier offset, the offset turning inside the filter otherwise)"""
    return self.x*self._turn(np.arange(len(self.x)))
matched
matched(up=1, exact=False)

The matched filter's output between the symbols, up points a symbol: (t, z). t: time in symbols from the first symbol instant (centres[0]); z: the output corrected as the symbols are, z[::up] being symbols. From the first symbol to the last; the eye diagram of the block is z against t modulo a symbol or two.

The filter runs once over the block, at its sample rate, and its output (band-limited) is read between the samples by a 12-tap windowed sinc (rpps.math.interp.fractional): about 1e-3 rms of the symbols' scale from the filter's own rows (a few 1e-3 at most, at 2 samples a symbol), the instants exact. exact: the filter itself at every point (its matrix, one row a point: slow for a dense eye)

Source code in src/rpps/sync/acquire.py
def matched(self, up=1, exact=False):
    """The matched filter's output between the symbols, `up` points a symbol: (t, z). t: time in symbols from the
    first symbol instant (centres[0]); z: the output corrected as the symbols are, z[::up] being `symbols`. From the
    first symbol to the last; the eye diagram of the block is z against t modulo a symbol or two.

    The filter runs once over the block, at its sample rate, and its output (band-limited) is read between the samples
    by a 12-tap windowed sinc (rpps.math.interp.fractional): about 1e-3 rms of the symbols' scale from the filter's own
    rows (a few 1e-3 at most, at 2 samples a symbol), the instants exact. exact: the filter itself at every point (its matrix, one row a point: slow for a dense eye)"""
    up = int(up)
    if up < 1:
        raise ValueError("matched: up is a whole number of points a symbol, 1 or more")
    d, c = self.det, self.centres
    pos = c[0] + np.arange((len(c) - 1)*up + 1)*(d.sps/up)
    pos[::up] = c # (the instants themselves, to the last bit)
    if exact:
        z = np.empty(len(pos), np.complex128)
        step = max(1, 2**20//int(2*self.span*d.sps + 2)) # Rows of the filter matrix a time
        for a in range(0, len(pos), step):
            p = pos[a:a + step]
            z[a:a + step] = matrix_mf(self.x, p, d.sps, d.beta, self.span)*self._turn(p)
        return (pos - c[0])/d.sps, z
    from ..signal.filters import rrc_pulse
    from ..math.interp import fractional_edge
    L = int(np.ceil(self.span*d.sps))
    h = rrc_pulse(np.arange(-L, L + 1)/d.sps, d.beta)
    h /= np.sqrt(np.sum(h**2))
    x = np.asarray(self.x, dtype=np.complex128)
    n = len(x) + len(h) - 1
    if len(h) > 64: # by FFT
        N = 1 << int(np.ceil(np.log2(n)))
        y = np.fft.ifft(np.fft.fft(x, N)*np.fft.fft(h, N))[:n]
    else:
        y = np.convolve(x, h)
    # y[i]: the filter's output at sample i - L of x (zeros beyond x); read at pos
    z = fractional_edge(y.astype(np.complex64), pos + L, 12).astype(np.complex128)*self._turn(pos)
    z[::up] = self.symbols
    return (pos - c[0])/d.sps, z
reference
reference()

The ideal waveform of the block: the decided symbols through the root raised cosine pulse at centres, on x's samples, scaled and turned as derotated() (compare the two). Zero where no symbol of the lock reaches (the ends of x hold symbols the lock has not)

Source code in src/rpps/sync/acquire.py
def reference(self):
    """The ideal waveform of the block: the decided symbols through the root raised cosine pulse at `centres`, on x's
    samples, scaled and turned as `derotated()` (compare the two). Zero where no symbol of the lock reaches (the
    ends of x hold symbols the lock has not)"""
    from .time.mat import _rrc_rows
    d, c = self.det, self.centres
    dec = self.decisions()
    S = self.span*d.sps
    lags = np.arange(int(np.ceil(2*S)) + 2)
    r = np.zeros(len(self.x), np.complex128)
    step = max(1, 2**20//len(lags))
    for a in range(0, len(c), step):
        cc = c[a:a + step]
        j0 = np.ceil(cc - S).astype(np.int64)
        w = _rrc_rows(j0 - cc, lags, d.sps, d.beta)
        w /= np.sqrt(np.sum(w**2, axis=1, keepdims=True))
        idx = j0[:, None] + lags
        ok = (idx >= 0) & (idx < len(r))
        np.add.at(r, idx[ok], (dec[a:a + step, None]*w)[ok])
    return r

Acquire

Acquire(lock=5.0, max_wait=2 ** 17, history=2 ** 16, names=None, betas=None, min_samples=1024, baud=None)

Bases: Stage

Detect as soon as the signal is there, then keep refining as the stream grows

The matrix matched filter and the likelihood only need a few hundred symbols, so there is no fixed wait: blocks are held only until the symbol-rate line is significant (lock times the local floor, noise peaks at about 3-4). Then everything held is released at once, and the estimates are re-run on the growing history so baud and cfo tighten, up to history samples.

Every decision is made on the stream's first P samples at fixed P (min_samples, then doubling), never on whatever has arrived, so how the stream is cut into blocks changes nothing: a block that passes one or more of those positions has them run in order. The modulation and roll-off are searched again in full at each position until two in a row agree (a first decision on a few thousand samples at low SNR can be wrong, and refining would keep it); after that, refinements retest only them, which is much cheaper. A block carries the detection made by its end (meta.det). At the stream's end (flush) what has not settled is decided on the whole stream.

Calibrates meta.sps (to the detected one), so following stages get the fractional sps.

lock: symbol-rate line strength required to detect max_wait: samples after which to detect regardless min_samples: samples held before the first try, whatever the line: the rate search goes down to Fs/16, so this is at least 64 symbols (a narrow signal decimated far, a carrier, gives a few samples a block, and a line in a few hundred samples is no rate) baud: the symbol rate when known (a channel plan, rpps.analysis.spectrum.cyclic): no waiting for a line, no rate search

Source code in src/rpps/sync/acquire.py
def __init__(self, lock=5.0, max_wait=2**17, history=2**16, names=None, betas=None, min_samples=1024,
             baud=None):
    self.baud = baud
    self.min_samples = min_samples
    self.lock = lock
    self.max_wait = max_wait
    self.history = history
    self.names = names
    self.betas = betas

symmetry

symmetry(points, tol=0.001, max_order=16)

Order M of the rotational symmetry of a point set (the M-th power removes the modulation)

Source code in src/rpps/sync/acquire.py
def symmetry(points, tol=1e-3, max_order=16):
    """Order M of the rotational symmetry of a point set (the M-th power removes the modulation)"""
    pts = np.asarray(points)
    for M in range(max_order, 1, -1):
        rot = pts * np.exp(2j*np.pi/M)
        if all(np.min(np.abs(rot[i] - pts)) < tol for i in range(len(pts))):
            return M
    return 1

candidates

candidates(names=None)

Load candidate constellations from config/constellation: {name: unit-rms points}. Each is read once per config search path (a Lock rechecks them every block: finding the files would cost more than scoring them)

Source code in src/rpps/sync/acquire.py
def candidates(names=None):
    """Load candidate constellations from config/constellation: {name: unit-rms points}. Each is read once per config
    search path (a Lock rechecks them every block: finding the files would cost more than scoring them)"""
    from .. import symbol  # Late: symbol imports after sync
    from .. import _config
    where = _config.state()
    if names is None: # The PSK, QAM and APSK families' own point sets: a child (a labelling, rotation or radii of a parent)
        names = _CANDIDATES.get((where, None))                             # is not another modulation
        if names is None:
            have = symbol.ls(blind=True)
            names = _CANDIDATES[(where, None)] = tuple(
                n for g in GROUPS for n in have.get(g, [])
                if "extends" not in _config.read_raw(_config.find("constellation", f"{g}/{n}")))
    out = {}
    for name in names:
        pts = _CANDIDATES.get((where, name))
        if pts is None:
            pts = np.asarray(symbol.load_or_generate(name).points, dtype=np.complex128)
            pts = pts / np.sqrt(np.mean(np.abs(pts)**2))
            pts.flags.writeable = False
            _CANDIDATES[(where, name)] = pts
        out[name] = pts
    return out

turned_candidates

turned_candidates(names)

Turned candidates.

{(name, map): unit-rms points} of each constellation names gives, as defined (map None) and as each of its maps that turns the points uses them (map: that map's name, "DVB-S2"): what symbols whose carrier phase a known word set are scored against (rp.sync.FrameSync's classify), where a turned set is another constellation

Source code in src/rpps/sync/acquire.py
def turned_candidates(names):
    """Turned candidates.

    {(name, map): unit-rms points} of each constellation `names` gives, as defined (map None) and as each of its maps
    that turns the points uses them (map: that map's name, "DVB-S2"): what symbols whose carrier phase a known word set
    are scored against (rp.sync.FrameSync's classify), where a turned set is another constellation"""
    from .. import symbol
    from .. import _config
    where, out = _config.state(), {}
    for name in names:
        hit = _CANDIDATES.get((where, name, "turned"))
        if hit is None:
            c = symbol.load_or_generate(name)
            hit = {}
            for m in [None] + c.turned:
                pts = c._base*np.exp(1j*m.turn) if m is not None else c._base
                pts = np.asarray(pts, dtype=np.complex128)/np.sqrt(np.mean(np.abs(pts)**2))
                pts.flags.writeable = False
                hit[(name, None if m is None else m._comment)] = pts
            _CANDIDATES[(where, name, "turned")] = hit
        out.update(hit)
    return out

correct

correct(y, pts, M, pad=4)

Feed-forward frequency + phase correction for a candidate. Returns (symbols, cfo cycles/symbol, phase); a carrier drifting over y (a Doppler rate: the frequency moving along) is taken off too (drift)

Source code in src/rpps/sync/acquire.py
def correct(y, pts, M, pad=4):
    """Feed-forward frequency + phase correction for a candidate. Returns (symbols, cfo cycles/symbol, phase); a carrier
    drifting over y (a Doppler rate: the frequency moving along) is taken off too (`drift`)"""
    n = len(y)
    cfo = 0.0
    if M > 1:
        spec = np.abs(np.fft.fft(y**M * np.hanning(n), pad*n))
        k, d = peak(spec, circular=True)
        f = (k + d)/(pad*n)
        cfo = (f - (1 if f > 0.5 else 0))/M
    y1 = y * np.exp(-2j*np.pi*cfo*np.arange(n))
    phase = 0.0
    if M > 1:
        c, w = drift(y1, M, offset=True)
        if c:
            t = np.arange(n) - (n - 1)/2
            y1 = y1*np.exp(-1j*(c*t**2 + w*t))
            cfo += w/(2*np.pi)
        phase = (np.angle(np.sum(y1**M)) - np.angle(np.mean(pts**M)))/M
    return y1 * np.exp(-1j*phase), cfo, phase

drift

drift(y, M, blocks=32, min_block=64, sigmas=4.0, segments=8, min_segment=256, offset=False)

The phase curvature c (radians a symbol^2) a drifting carrier leaves on symbols y.

phase(t) = c (t - centre)^2 after a frequency is taken off: the frequency moves 2c radians a symbol^2 (a Doppler rate, a drifting oscillator). Coarse, from the M-th power's frequency in each of segments segments (an FFT peak each, unambiguous within +-1/(2M) cycles a symbol, whatever the phase does between them): the line through them; then fine, from the M-th power's phase in blocks blocks (at least min_block symbols each), unwrapped by 2 pi / M, a quadratic least-squares fit, on the symbols the coarse drift was taken off. Each counts only when sigmas standard errors off 0 (a steady carrier's segments and blocks only scatter); 0.0 with neither. offset: (c, w), w the frequency (radians a symbol) still on y about its centre, which an FFT over a drifting carrier places off (its peak smeared)

Source code in src/rpps/sync/acquire.py
def drift(y, M, blocks=32, min_block=64, sigmas=4.0, segments=8, min_segment=256, offset=False):
    """The phase curvature c (radians a symbol^2) a drifting carrier leaves on symbols y.

    phase(t) = c (t - centre)^2 after a frequency is taken off: the frequency moves 2c radians a symbol^2 (a Doppler
    rate, a drifting oscillator).
    Coarse, from the M-th power's frequency in each of `segments` segments (an FFT peak each, unambiguous within
    +-1/(2M) cycles a symbol, whatever the phase does between them): the line through them; then fine, from the M-th
    power's phase in `blocks` blocks (at least `min_block` symbols each), unwrapped by 2 pi / M, a quadratic
    least-squares fit, on the symbols the coarse drift was taken off. Each counts only when `sigmas` standard errors off
    0 (a steady carrier's segments and blocks only scatter); 0.0 with neither. offset: (c, w), w the frequency (radians a
    symbol) still on y about its centre, which an FFT over a drifting carrier places off (its peak smeared)"""
    n = len(y)
    centre = (n - 1)/2
    u = y/np.maximum(np.abs(y), 1e-30)
    c = w = 0.0
    L = n//segments
    if L >= min_segment:
        f, t = [], []
        for k in range(segments):
            z = u[k*L:(k + 1)*L]**M
            spec = np.abs(np.fft.fft(z*np.hanning(L), 4*L))
            i, d = peak(spec, circular=True)
            v = (i + d)/(4*L)
            f.append(((v + 0.5) % 1.0 - 0.5)/M) # cycles a symbol
            t.append((k + 0.5)*L - centre)
        f, t = np.asarray(f), np.asarray(t)
        f = np.unwrap(f*2*np.pi*M)/(2*np.pi*M) # (a frequency moving across 1/(2M) wraps: unwrapped)
        A = np.stack((t, np.ones(len(t))), axis=1)
        coef, *_ = np.linalg.lstsq(A, f, rcond=None)
        r = f - A @ coef
        se = np.sqrt(max(float(np.sum(r**2))/max(len(t) - 2, 1), 1e-300)*np.linalg.pinv(A.T @ A)[0, 0])
        if abs(coef[0]) > sigmas*se:
            c, w = float(np.pi*coef[0]), float(2*np.pi*coef[1]) # (2 pi (a/2) t^2: a the slope in cycles a symbol^2)
            u = u*np.exp(-1j*(c*(np.arange(n) - centre)**2 + w*(np.arange(n) - centre)))
    B = max(min_block, n//blocks)
    k = n//B
    if k < 6:
        return (c, w) if offset else c
    s = (u[:k*B]**M).reshape(k, B).sum(axis=1)
    ph = np.unwrap(np.angle(s))/M
    t = (np.arange(k) + 0.5)*B - centre
    A = np.stack((t**2, t, np.ones(k)), axis=1)
    coef, *_ = np.linalg.lstsq(A, ph, rcond=None)
    r = ph - A @ coef
    var = float(np.sum(r**2))/max(k - 3, 1)
    se = float(np.sqrt(max(var*np.linalg.pinv(A.T @ A)[0, 0], 1e-300)))
    if abs(coef[0]) > sigmas*se:
        c, w = c + float(coef[0]), w + float(coef[1])
    return (c, w) if offset else c

score

score(y, pts, iters=8, esn0=None)

Mean log-likelihood per symbol of unit-rms y under equiprobable points with Gaussian noise: the variance fitted (EM), or, given esn0 (dB), the points scaled to the signal's share of the power and the noise the rest

Source code in src/rpps/sync/acquire.py
def score(y, pts, iters=8, esn0=None):
    """Mean log-likelihood per symbol of unit-rms y under equiprobable points with Gaussian noise: the variance fitted
    (EM), or, given esn0 (dB), the points scaled to the signal's share of the power and the noise the rest"""
    return _score(y, pts, iters, esn0)[0]

score_all

score_all(ycs, esn0=None)

Scores of {name: (corrected unit-rms symbols, points)} and how they were made: at the caller's esn0 ("given"); each fitting its own variance when the fit's winner reads over FIT_MIN dB ("fit"); else each at its own M2M4 Es/N0 ("moments")

Source code in src/rpps/sync/acquire.py
def score_all(ycs, esn0=None):
    """Scores of {name: (corrected unit-rms symbols, points)} and how they were made: at the caller's esn0 ("given"); each
    fitting its own variance when the fit's winner reads over FIT_MIN dB ("fit"); else each at its own M2M4 Es/N0
    ("moments")"""
    if esn0 is not None:
        return {n: score(y, p, esn0=esn0) for n, (y, p) in ycs.items()}, "given"
    fits = {n: _score(y, p) for n, (y, p) in ycs.items()}
    fit = {n: f[0] for n, f in fits.items()}
    var = fits[max(fit, key=fit.get)][1] # per axis, unit-rms y: signal 1 - 2 var
    if 10*np.log10(max(1 - 2*var, 1e-12)/(2*var)) > FIT_MIN:
        return fit, "fit"
    return {n: score(y, p, esn0=m2m4(y, p)) for n, (y, p) in ycs.items()}, "moments"

null_score

null_score(y)

score of unit-rms y as Gaussian noise of the same power (complex, unit variance)

Source code in src/rpps/sync/acquire.py
def null_score(y):
    """`score` of unit-rms y as Gaussian noise of the same power (complex, unit variance)"""
    return float(-np.mean(np.abs(y)**2) - np.log(np.pi))

track_timing

track_timing(x, sps, beta, span=8, rounds=2)

Refine sps from the drift of the best timing between the start and end of x. Returns (sps, tau)

A rate a little off makes the timing walk across x: the walk between its first and last eighth (at least 60 symbols each) corrects sps, rounds times. The walk is seen modulo a symbol, so sps must be right to within about sps/(2 len(x)) relative (40 ppm for 60000 samples at 4 sps): a lock follows a clock, a search gets close first. tau is on the absolute lattice tau + k*sps from x[0]. x too short for two such parts keeps sps.

Source code in src/rpps/sync/acquire.py
def track_timing(x, sps, beta, span=8, rounds=2):
    """Refine sps from the drift of the best timing between the start and end of x. Returns (sps, tau)

    A rate a little off makes the timing walk across x: the walk between its first and last eighth (at least 60 symbols each)
    corrects sps, `rounds` times. The walk is seen modulo a symbol, so sps must be right to within about sps/(2 len(x))
    relative (40 ppm for 60000 samples at 4 sps): a lock follows a clock, a search gets close first. tau is on the absolute
    lattice tau + k*sps from x[0]. x too short for two such parts keeps sps."""
    n = len(x)
    seg = max(n//8, int(60*sps))
    if seg*2 < n:
        for _ in range(rounds):
            a, _e = best_tau(x, sps, beta, span, 0, seg)
            b, _e = best_tau(x, sps, beta, span, n-seg, n)
            drift = (b - a + sps/2) % sps - sps/2 # Timing moved by this much...
            sps += drift/((n - seg)/sps) # ...over this many symbols
    tau, _e = best_tau(x, sps, beta, span)
    return sps, tau

detect

detect(x, Fs, names=None, betas=None, span=8, baud=None, esn0=None, min_evidence=None)

Find symbol rate, timing, modulation, frequency offset and phase from baseband samples

x: complex baseband at Fs, with the signal of interest centred and filtered names: candidate modulations, default candidates()'s (the PSK, QAM and APSK definitions) betas: RRC roll-offs to try; None: BETAS and the standard roll-off nearest the spectrum's (rate.find_rolloff: the likelihood can't tell 0.05 from 0.15, the edges can), which rolloff records baud: the symbol rate when already known (a channel plan, rpps.analysis.spectrum.cyclic): timing refines it, no search esn0: the Es/N0 when known (rpps.sync.quality.from_sequence on a known sequence): every candidate is scored at it min_evidence: nats the winner must lead the runner-up by in all (Detection.evidence), with it NULL_MARGIN over Gaussian noise (Detection.over_noise), or mod is None and best holds the leader (see the module) Returns a Detection; its tau is relative to x[0].

Source code in src/rpps/sync/acquire.py
def detect(x, Fs, names=None, betas=None, span=8, baud=None, esn0=None, min_evidence=None):
    """Find symbol rate, timing, modulation, frequency offset and phase from baseband samples

    x: complex baseband at Fs, with the signal of interest centred and filtered
    names: candidate modulations, default `candidates()`'s (the PSK, QAM and APSK definitions)
    betas: RRC roll-offs to try; None: BETAS and the standard roll-off nearest the spectrum's (rate.find_rolloff: the
        likelihood can't tell 0.05 from 0.15, the edges can), which `rolloff` records
    baud: the symbol rate when already known (a channel plan, rpps.analysis.spectrum.cyclic): timing refines it, no search
    esn0: the Es/N0 when known (rpps.sync.quality.from_sequence on a known sequence): every candidate is scored at it
    min_evidence: nats the winner must lead the runner-up by in all (Detection.evidence), with it NULL_MARGIN over
        Gaussian noise (Detection.over_noise), or mod is None and `best` holds the leader (see the module)
    Returns a Detection; its tau is relative to x[0].
    """
    cands = candidates(names)
    baud0, line = (float(baud), None) if baud else find_baud(x, Fs)
    rolloff = None
    if betas is None:
        rolloff = find_rolloff(x, Fs, baud0)[0] if baud0 > 0 else None
        betas = tuple(sorted(set(BETAS) | ({nearest_rolloff(rolloff)} if rolloff is not None else set())))
    best = None
    for beta in betas:
        sps, tau = track_timing(x, Fs/baud0, beta, span)
        c = centres_in(len(x), tau + np.ceil((span*sps + 5 - tau)/sps)*sps, sps, span)
        y = matrix_mf(x, c, sps, beta, span)
        gain = np.sqrt(np.mean(np.abs(y)**2))
        y = y / gain
        ycs, fits = {}, {}
        for name, pts in cands.items():
            M = symmetry(pts)
            yc, cfo, phase = correct(y, pts, M)
            ycs[name] = (yc, pts)
            fits[name] = (M, cfo, phase)
        scores, how = score_all(ycs, esn0)
        top = max(scores, key=scores.get)
        if best is None or scores[top] > best[0]:
            M, cfo, phase = fits[top]
            q = measure(correct(y, cands[top], M)[0], cands[top])
            baud = Fs/sps
            c = drift(y*np.exp(-2j*np.pi*cfo*np.arange(len(y))), M) if M > 1 else 0.0
            best = (scores[top], Detection(
                mod=top, baud=baud, sps=sps, beta=beta, tau=tau,
                cfo=cfo*baud, phase=phase, M=M, gain=gain,
                scores=scores, n=len(y), esn0=q.esn0_db, ebn0=q.ebn0_db, line=line,
                best=top, how=how, given=esn0, null=null_score(y), rolloff=rolloff,
                drift=float(2*c/(2*np.pi)*baud**2) # (cycles a symbol^2 at baud^2: Hz/s)
            ))
    det = best[1]
    if min_evidence is not None and (det.over_noise < NULL_MARGIN or det.evidence < min_evidence):
        det.mod = None
    return det

onset

onset(x, block=ONSET_BLOCK, level=ONSET_LEVEL)

Where a signal comes on in x. The first block whose power reaches level of the median block's (0 when the first does, or when x is short). A stretch of nothing or of noise well under the signal at x's start is left out of an estimate made on x (a burst, a carrier switched on after the recording started); at low SNR the noise before the signal is not that far under it, and x is taken whole. A signal on for under half of x is not found this way (the median is the noise's): a later, longer x finds it

Source code in src/rpps/sync/acquire.py
def onset(x, block=ONSET_BLOCK, level=ONSET_LEVEL):
    """Where a signal comes on in x. The first block whose power reaches `level` of the median block's (0 when the
    first does, or when x is short). A stretch of nothing or of noise well under the signal at x's start is left out of
    an estimate made on x (a burst, a carrier switched on after the recording started); at low SNR the noise before the
    signal is not that far under it, and x is taken whole. A signal on for under half of x is not found this way (the
    median is the noise's): a later, longer x finds it"""
    x = np.asarray(x)
    k = len(x)//block
    if k < 4:
        return 0
    p = (np.abs(x[:k*block])**2).reshape(k, block).mean(axis=1)
    on = np.flatnonzero(p >= level*np.median(p))
    return int(on[0])*block if len(on) else 0

acquire_fec

AcquireFEC: which code timed symbols carry, found as the stream arrives (the scans are in rpps.analysis.identify)

Classes:

Name Description
AcquireFEC

Identify the code the symbols carry, then turn them to the map its decoder uses

AcquireFEC

AcquireFEC(window=2 ** 14, skip=2048, max_wait=2 ** 18, names=None, blind=False, check=4096, relock=4.0, name='fec', min_line=5.0)

Bases: Stage

Identify the code the symbols carry, then turn them to the map its decoder uses

rx = front + rp.sync.Acquire() + rp.sync.time.Mat() + rp.sync.phase.FFCarrier() + rp.sync.AcquireFEC()
out = blk + rx
fec = out.stream.est.get("fec")           # an rpps.analysis.identify.CodeDetection, once there is one
dec = fec.rx()                             # once fec.complete: the decoder (a profile runner), bits = dec(out)

Takes timed, carrier-corrected symbols (after phase.FFCarrier, with the modulation from Acquire in meta.det) and gives the same symbols, turned and conjugated so the decoder's map is the right one (the carrier phase has an M-fold ambiguity, and the IQ sense is unknown). Codes are the configured ones (rpps.analysis.identify.identify).

Acquisition: symbols are held until skip + window have arrived, and the code is identified on those window (at absolute positions, so the result is the same however the stream was cut). While more symbols could tell more (a window shorter than the scans use, or Reed-Solomon behind a Viterbi, which needs ~100 codewords) the window doubles, up to max_wait symbols. A stream that ends first (meta.flush) is decided on every symbol held past skip, blind tools included, so a short capture gets the same look a long one does. Acquire can decide again before it settles (another modulation, or a rate more than REDECIDED off): what was held, taken at the old one, is dropped and the acquisition starts over from that block, skip again. Then what was held is released from the window on (from a codeword start for a block code; the skip symbols before it, where the sync before this was settling, are dropped). Tracking (convolutional codes): every check symbols the output is re-encoded through the code on the decoder's map. A mismatch above relock times the one at acquisition means a slip: the carrier by a turn, or the symbol timing by a symbol (the code's puncture phase moves). Every turn and alignment is tried on that window; it goes on with the one the code fits, turned, and with symbols dropped so the decoder after it keeps its alignment. slips counts them.

Its estimate is stream.est[name]: the CodeDetection (found False when nothing was, with its report). While it is still acquiring it holds the answer so far with complete False (before any, found False and n the symbols held so far): a code found then may still gain the layers inside it, so a decoder is best built once complete, which it is once the stage stops looking. names: only these convolutional definitions. blind: also look for unknown codes (a Guess, never decoded), unless the rate came from a symbol-rate line weaker than min_line over its floor (Acquire took it anyway: a guess; None: always)

Source code in src/rpps/sync/acquire_fec.py
def __init__(self, window=2**14, skip=2048, max_wait=2**18, names=None, blind=False, check=4096, relock=4.0, name="fec",
             min_line=5.0):
    self.window, self.skip, self.max_wait = int(window), int(skip), int(max_wait)
    self.names, self.blind, self.min_line = names, blind, min_line
    self.check, self.relock, self.name = int(check), float(relock), name

agc

Automatic gain control, with no loop over samples

AGC: the level by block estimation (rpps.sync's first class): each window's level (the mean of log|x|, or of |x|), the gain that brings it to target at the window's centre, a line between centres evaluated per sample. PeakAGC: the gain from a peak that is followed at once and decays, in closed form.

Classes:

Name Description
PeakAGC

Gain from the peak: |x| is followed instantly upward and decays by decay per sample, and the signal is scaled so

AGC

Gain that brings the signal's level to target, by block estimation

PeakAGC

PeakAGC(target=1.0, decay=0.999, floor=1e-06)

Bases: Stage

Gain from the peak: |x| is followed instantly upward and decays by decay per sample, and the signal is scaled so that peak sits at target. For bursts and on-off keying (Mode S pulses, OOK): the first pulse of a burst sets the level, where an average is still settling. decay 0.999 at 2 MS/s holds a peak for about a millisecond.

The peak p[n] = max(|x[n]|, decay p[n-1]) is d^n max_(k<=n)(|x[k]| d^-k): in logs a running maximum (np.maximum.accumulate), no loop over the samples, the same peak to rounding.

Source code in src/rpps/sync/agc.py
def __init__(self, target=1.0, decay=0.999, floor=1e-6):
    if not 0 < decay <= 1:
        raise ValueError(f"PeakAGC: decay in (0, 1], not {decay}")
    self.target, self.decay, self.floor = float(target), float(decay), float(floor)

AGC

AGC(target=1.0, *, window=0.0001, min_samples=64, log=True, min_gain=0.0, max_gain=np.inf, init=1.0, name='agc')

Bases: Stage

Gain that brings the signal's level to target, by block estimation

block + rp.sync.AGC(1.0)

First class (rpps.sync). Windows sit at absolute stream positions, window seconds (at least min_samples). Each window's level is exp(mean log|x|) (log, the default: a level that does not depend on the signal's shape) or mean |x|, and its gain log(target / level) is put at the window's centre; between centres the log gain is a straight line, evaluated per sample: no steps at window edges and no loop over the samples. A level step settles within a window, with no overshoot after it (a gain is not a drift: nothing carries a rate on). A window of zeros (a gap) keeps the gain before it. The gain is held to [min_gain, max_gain]. Until a window with signal has been seen, samples pass at init. Latency: a window and a half (a sample waits for the centre of the window after it). Estimates in stream.est[name]: gain, level, latency (seconds).

Source code in src/rpps/sync/agc.py
def __init__(self, target=1.0, *, window=1e-4, min_samples=64, log=True, min_gain=0.0, max_gain=np.inf, init=1.0,
             name="agc"):
    # (keywords only: a loop's `mu` given in second place would otherwise be taken for a window)
    self.target, self.window, self.min_samples, self.log = float(target), window, int(min_samples), bool(log)
    self.min, self.max, self.init, self.name = float(min_gain), float(max_gain), float(init), name

align

Classes:

Name Description
Align

Align a bit stream on a marker that repeats every period units, and resolve its polarity

Align

Align(period, markers=None, pattern=None, unit=8, acquire=None, threshold=0.9, misses=3, polarity=True, name='align', start='any', publish=False)

Bases: BitStage

Align a bit stream on a marker that repeats every period units, and resolve its polarity

aligned = coded_bits + rp.sync.Align(period=204, pattern=[0xB8] + [0x47]*7)   # DVB-S after Viterbi
aligned = bits + rp.sync.Align(period=64, markers=(0x7E,))                     # any of a set, every period

Takes channel or data bits, as LLRs or hard bits, and gives the same form back, starting on a marker and with the polarity put right (LLRs negated, bits inverted). This is sync on bits: block estimation, then tracking at the block rate.

What starts each period is either markers: a set of unit values, any of which may start any period, or pattern: what starts each period in turn, repeating: a value, or a set of values, per period. DVB-S sends 0x47 and, every eighth packet, 0xB8. As a set those two cannot tell the polarity (inverted, one is the other); as a pattern they can, and the pattern's phase is found too.

Acquisition: once enough periods are in, every bit offset, pattern phase and polarity is scored by the fraction of periods that start as expected, and the best one locks if it reaches threshold. Otherwise the oldest period is dropped and it tries again as more arrives. What comes before lock is dropped (counted). Tracking: each whole period goes out as it completes, and its start is checked. After misses periods in a row that don't start as expected, the lock is given up and acquisition starts again from there.

period: units per period. unit: bits per unit (8: bytes, most significant bit first). acquire: periods to score, at least one whole pattern. start: "any" period, or "pattern": the output starts on the pattern's first position (a frame of periods: DVB-S energy dispersal restarts every 8 packets). publish: each period out is a frame start, {"frame": k} published from it (rpps.base.control), so a header after it reads one period at a time (DVB-S's transport packets). Its estimates are in stream.est[name].

Attributes:

Name Type Description
span

Bits in one period

Source code in src/rpps/sync/align.py
def __init__(self, period, markers=None, pattern=None, unit=8, acquire=None, threshold=0.9, misses=3, polarity=True,
             name="align", start="any", publish=False):
    if start not in ("any", "pattern"):
        raise ValueError(f"start is 'any' or 'pattern', not {start!r}")
    self.start, self.publish = start, bool(publish)
    if (markers is None) == (pattern is None):
        raise ValueError("give markers (any of a set) or pattern (one per period), not both")
    self.period, self.unit = int(period), int(unit)
    rows = [markers] if pattern is None else list(pattern)
    self._allowed = np.zeros((len(rows), 1 << self.unit), dtype=bool) # [pattern position, unit value]: expected?
    for i, r in enumerate(rows):
        self._allowed[i, np.atleast_1d(np.asarray(r, dtype=np.int64))] = True
    self.length = len(rows)
    acquire = max(8, 2*self.length) if acquire is None else int(acquire)
    self.acquire, self.threshold, self.misses = int(acquire), float(threshold), int(misses)
    self.polarity, self.name = bool(polarity), name
    self._w = 1 << np.arange(self.unit - 1, -1, -1) # Unit value from its bits, first bit most significant
span property
span

Bits in one period

burst

Per-burst acquisition: cut a stream of samples into the bursts that rise out of its noise floor

for b in src(65536) + rp.sync.Burst(win=8, min_s=60e-6, max_s=3e-3) + rx:   # rx runs on each burst on its own
    print(b.meta.pos, len(b))

data + Burst() gives a list: the bursts that ended in this block, each a Data of its own stream (the stages after it start over on every burst: loops, timing and frame sync acquire each packet fresh), placed at its absolute position in the source (meta.pos, and meta.time_of when the source has a time). Blocks and Pipeline run what follows on every burst. A burst still open at the end of a block waits for the blocks that end it; the stream's end closes it.

The detector: the mean power of windows of win samples, at absolute positions (independent of the block cut), against factor times the noise floor. The floor is taken from the noise windows alone, of those seen so far (the last history): their mean m is the fixed point of m = mean(windows below quietm), climbed to from the quietest window, so it stops at the lowest cluster of window powers (the noise) however many windows the bursts fill; the floor is the percentile of the windows below quietm. Bursts may follow one another as closely as the air allows: the floor needs some quiet windows, not most of them (a signal with no gap of a window at all is one burst). Windows of exact zeros (padding, a clean synthetic signal's gaps) join the noise windows as the quietest of them: a few do not move the floor, but once they are percentile% of the noise windows the floor is 0, and any power is a burst (a clean signal's bursts are all found; a noisy capture padded with that many zeros is one burst). For one flushed block of a whole capture this is a batch rule: every window of the capture sets the floor. A stream's first settle windows are decided together, once they are all in (or the stream ends): a floor taken from the first few windows alone would be a burst's own level.

The rest of the burst code: rpps.sync.plan (bursts on many carriers, placed in a time plan), rpps.profile.burst (a profile's burst step), rpps.analysis.burst (bursts demodulated blind; plans learned and checked: its docstring maps it all).

Classes:

Name Description
Burst

Bursts of a stream of samples, each a block of its own stream (see the module)

BurstTx

The transmit side of Burst: bursts placed on one stream of samples, each where its start puts it

Burst

Burst(factor=6.0, win=100, min_s=0.0, max_s=None, percentile=20, history=1 << 17, settle=512, quiet=3.0)

Bases: Pipe

Bursts of a stream of samples, each a block of its own stream (see the module)

factor: how far above the noise floor a window's power is to be part of a burst win: samples per window (the time resolution of the burst edges) min_s, max_s: shortest and longest burst kept [s] (max_s None: any length); a longer one is dropped, and its samples are not held past max_s percentile: of the noise windows' powers, the noise floor; quiet: how far above their mean a window may be and still count as noise; history: windows the floor is taken over (taken again once a 16th of them are new: one block is the batch rule exactly, a long stream does not sort its history every block); settle: windows at the stream's start held until the floor has them all Estimates go in the stream's est["burst"]: the floor, bursts emitted, too short, too long.

Methods:

Name Description
split

The bursts that end in this block (a list of Data)

floor

The noise floor of window powers e (see the module)

Source code in src/rpps/sync/burst.py
def __init__(self, factor=6.0, win=100, min_s=0.0, max_s=None, percentile=20, history=1 << 17, settle=512, quiet=3.0):
    if win < 1 or factor <= 0 or quiet <= 2:
        raise ValueError("Burst: win is at least 1 sample, factor positive, quiet above 2 (below it the floor sinks to 0)")
    self.factor, self.win, self.min_s, self.max_s = float(factor), int(win), float(min_s), max_s
    self.percentile, self.history, self.settle, self.quiet = percentile, int(history), int(settle), float(quiet)
split
split(data)

The bursts that end in this block (a list of Data)

Source code in src/rpps/sync/burst.py
def split(self, data):
    """The bursts that end in this block (a list of Data)"""
    meta = data.meta
    st = meta.state_of(self)
    x = np.asarray(data.data)
    if st.pos is None:
        st.pos, st.rest = meta.pos, x[:0]
    buf = np.concatenate((st.rest, x)) if len(st.rest) else x
    pos0, win = st.pos, self.win # buf[0] is at absolute position pos0, a window boundary
    nw = len(buf)//win
    if len(st.hist) == 0 and nw < self.settle and not data.flush: # The start: wait for enough windows to set the floor
        st.rest = buf
        return []
    used = nw*win
    st.rest = buf[used:] if not data.flush else buf[:0] # (a partial window at the end of the stream is dropped)
    st.pos = pos0 + used
    out = []
    if nw:
        e = (np.abs(buf[:used].astype(np.complex128))**2).reshape(nw, win).mean(axis=1)
        st.hist = np.concatenate((st.hist, e))[-self.history:]
        st.new += nw
        if st.floor is None or st.new*16 >= len(st.hist):
            st.floor, st.new = self.floor(st.hist), 0
        floor = st.floor
        st.est["floor"] = floor
        on = e > self.factor*floor
        d = np.diff(np.r_[int(st.on), on.astype(int)])
        edges = sorted([(int(i)*win, True) for i in np.nonzero(d == 1)[0]] + [(int(i)*win, False) for i in np.nonzero(d == -1)[0]])
        for at, rise in edges:
            if rise:
                st.start, st.held, st.n_held, st.long = pos0 + at, [], 0, False
                st.on = True
            else:
                self._take(st, buf, pos0, at, meta.Fs)
                out += self._close(st, data, pos0 + at)
        if st.on: # Still open at the end of the block: hold what it has so far
            self._take(st, buf, pos0, used, meta.Fs)
    if data.flush and st.on: # The end of the stream ends the burst
        out += self._close(st, data, st.pos)
    meta.stream.est["burst"] = dict(st.est)
    return out
floor
floor(e)

The noise floor of window powers e (see the module)

Source code in src/rpps/sync/burst.py
def floor(self, e):
    """The noise floor of window powers `e` (see the module)"""
    zeros = int(np.count_nonzero(e <= 0))
    s = np.sort(e[e > 0])
    if not len(s):
        return 0.0
    cs = np.cumsum(s)
    m, n = s[0], 1
    least = max(4, len(s)//100) # A cluster of fewer windows is a few quiet outliers, not the noise (a narrow channel's
    for _ in range(1000):       # windows hold few independent samples: a dip of a tenth comes now and then)
        n = max(int(np.searchsorted(s, self.quiet*m)), 1) # m grows by at least quiet/2 a step while below the noise
        m2 = cs[n - 1]/n                                  # (quiet > 2), then settles
        if m2 <= m*(1 + 1e-9):
            if n >= least or n >= len(s):
                break
            m = s[n] # (past the outliers: climb on from the next window)
            continue
        m = m2
    return float(np.percentile(np.r_[np.zeros(zeros), s[:n]], self.percentile))

BurstTx

BurstTx(Fs=None, gap_s=0.0, ramp_s=0.0, hop=None)

Bases: Pipe

The transmit side of Burst: bursts placed on one stream of samples, each where its start puts it

btx = rp.sync.BurstTx(gap_s=1e-3)
btx.add(burst)                       # a Data of samples, one whole burst (its own stream, flushed)
btx.add(burst, at=0.004, freq=-3e6)  # at 4 ms from the stream's start, 3 MHz below its centre
out = btx.take()                     # the samples no later burst can reach any more; take(flush=True): the rest

One BurstTx makes one output stream (it holds it: a profile's transmit runner builds its own). Bursts come in the order of their starts. A burst's start is at [s from the stream's first sample], else the end of the burst before plus gap_s (the first: gap_s from 0). The stream ends gap_s after the last burst's end, as it began.

Per burst: its first and last ramp_s raised by a raised cosine (the power ramps of a burst transmitter; 0: switched), resampled to the stream's rate Fs (None: the first burst's rate) by a rational polyphase filter, and moved freq Hz from the stream's centre (None: the next of hop, cycled, or 0) by an oscillator running from the stream's first sample (every burst on one carrier has the phase of one continuous carrier). Bursts may overlap: they add (carriers of an MF-TDMA network share a slot; a burst may also start inside the one before).

sent: (start sample, samples, freq) of every burst added. take(flush=True) ends the stream: the next add starts a new one (as reset()), its at from that stream's start, and sent its record.

Methods:

Name Description
reset

Start a new stream

add

Place one whole burst (a Data of samples). Its samples come out of take

take

The samples up to the last burst's start (no burst added later reaches before it), as a block of the output

Source code in src/rpps/sync/burst.py
def __init__(self, Fs=None, gap_s=0.0, ramp_s=0.0, hop=None):
    if gap_s < 0 or ramp_s < 0:
        raise ValueError("BurstTx: gap_s and ramp_s are not negative")
    if Fs is not None and Fs <= 0:
        raise ValueError("BurstTx: Fs is positive")
    self.Fs, self.gap_s, self.ramp_s = Fs, float(gap_s), float(ramp_s)
    self.hop = None if hop is None else [float(f) for f in hop]
    if self.hop is not None and not self.hop:
        raise ValueError("BurstTx: hop is a list of offsets [Hz], not empty")
    self.reset()
reset
reset()

Start a new stream

Source code in src/rpps/sync/burst.py
def reset(self):
    """Start a new stream"""
    self._Fs, self._cf, self._sps = self.Fs, None, None
    self._buf, self._base = np.zeros(0, np.complex128), 0 # Samples not handed out yet, from absolute position _base
    self._start, self._end = None, 0 # The last burst's start and end
    self._stream = None
    self._ended = False # Flushed: the next burst starts a new stream
    self.sent = []
add
add(burst, at=None, freq=None)

Place one whole burst (a Data of samples). Its samples come out of take

Source code in src/rpps/sync/burst.py
def add(self, burst, at=None, freq=None):
    """Place one whole burst (a Data of samples). Its samples come out of `take`"""
    if self._ended:
        self.reset()
    x = np.asarray(burst.data).astype(np.complex128)
    Fs_in = burst.meta.Fs
    if self._Fs is None:
        self._Fs = Fs_in
    if self._cf is None:
        self._cf, self._sps = burst.meta.cf, burst.meta.sps*self._Fs/Fs_in
    Fs = self._Fs
    if freq is None:
        freq = self.hop[len(self.sent) % len(self.hop)] if self.hop else 0.0
    if abs(freq) >= Fs/2:
        raise ValueError(f"BurstTx: {freq:g} Hz is outside the stream ({Fs:g} Hz)")
    x = self._resample(self._ramp(x, Fs_in), Fs_in, Fs)
    start = int(round(at*Fs)) if at is not None else (self._end if self.sent else 0) + int(round(self.gap_s*Fs))
    if at is not None and at < 0:
        raise ValueError("BurstTx: at is from the stream's start, not before it")
    if self._start is not None and start < self._start - self._lag_samples():
        raise ValueError(f"BurstTx: bursts come in the order of their starts ({start} is before {self._start})")
    if start < self._base:
        raise ValueError(f"BurstTx: sample {start} was handed out already (the stream is out to {self._base})")
    if freq:
        x = x*np.exp(2j*np.pi*freq/Fs*(start + np.arange(len(x))))
    need = start + len(x) - self._base
    if need > len(self._buf):
        self._buf = np.concatenate((self._buf, np.zeros(need - len(self._buf), np.complex128)))
    self._buf[start - self._base:need] += x
    self._start = start if self._start is None else max(self._start, start)
    self._end = max(self._end, start + len(x))
    self.sent.append((start, len(x), float(freq)))
take
take(flush=False)

The samples up to the last burst's start (no burst added later reaches before it), as a block of the output stream; flush: all of them and the gap after the last burst, ending the stream

Source code in src/rpps/sync/burst.py
def take(self, flush=False):
    """The samples up to the last burst's start (no burst added later reaches before it), as a block of the output
    stream; flush: all of them and the gap after the last burst, ending the stream"""
    from ..base.data import Data
    if self._Fs is None:
        raise ValueError("BurstTx: no burst added yet")
    if flush:
        end = max(self._end + int(round(self.gap_s*self._Fs)), self._base)
        if end - self._base > len(self._buf):
            self._buf = np.concatenate((self._buf, np.zeros(end - self._base - len(self._buf), np.complex128)))
    else:
        end = max(self._start - self._lag_samples(), self._base) if self._start is not None else self._base
    n = end - self._base
    out, self._buf, self._base = self._buf[:n], self._buf[n:], end
    d = Data(out.astype(np.complex64), flush=flush, Fs=self._Fs, sps=self._sps, cf=self._cf, stream=self._stream)
    self._stream = d.stream
    self._ended = flush
    return d

code_acquire

Functions:

Name Description
acquire_code

Find where a spreading code starts in a signal, and its frequency offset: the parallel code-phase search

noise_threshold

The ratio to the mean that the largest of cells noise-only powers, each summed over periods, exceeds with probability pfa

acquire_code

acquire_code(x, code: Code, sps=1, index=0, Fs=None, doppler=(0.0,), periods=None, threshold=None, pfa=0.001)

Find where a spreading code starts in a signal, and its frequency offset: the parallel code-phase search

For each trial frequency the signal is mixed down, every code period is correlated with the sequence at all delays at once (FFT), and the powers of the periods are added. Power is added, not amplitude, so data modulated on the code (a bit flip, a differential phase change) does not cancel it. A peak that stands out of the rest is the signal.

x: complex samples at sps samples per chip. index: which sequence of a set. Fs: sample rate, needed for doppler. doppler: trial frequency offsets [Hz]; each can only be found to within about 1/(period) Hz, so space them by half that periods: how many whole code periods to use (default all there are) threshold: the peak's ratio to the mean power of the other delays that counts as locked. Default: what noise alone exceeds, in the best of all the (frequency, delay) cells and periods tried, with probability pfa (the sum of P periods' noise power is gamma distributed; its tail is taken from the Wilson-Hilferty approximation)

Returns offset (samples into x where a code period starts: give it to Despread), doppler [Hz], metric (peak / mean of the other delays at the best frequency), threshold, locked, and power (frequencies, delays) for plotting

Source code in src/rpps/sync/code_acquire.py
def acquire_code(x, code: Code, sps=1, index=0, Fs=None, doppler=(0.0,), periods=None, threshold=None, pfa=1e-3):
    """Find where a spreading code starts in a signal, and its frequency offset: the parallel code-phase search

    For each trial frequency the signal is mixed down, every code period is correlated with the sequence at all
    delays at once (FFT), and the powers of the periods are added. Power is added, not amplitude, so data modulated on the
    code (a bit flip, a differential phase change) does not cancel it. A peak that stands out of the rest is the signal.

    x: complex samples at `sps` samples per chip. index: which sequence of a set. Fs: sample rate, needed for `doppler`.
    doppler: trial frequency offsets [Hz]; each can only be found to within about 1/(period) Hz, so space them by half that
    periods: how many whole code periods to use (default all there are)
    threshold: the peak's ratio to the mean power of the other delays that counts as locked. Default: what noise alone
        exceeds, in the best of all the (frequency, delay) cells and periods tried, with probability `pfa` (the
        sum of P periods' noise power is gamma distributed; its tail is taken from the Wilson-Hilferty approximation)

    Returns offset (samples into x where a code period starts: give it to Despread), doppler [Hz], metric (peak / mean
    of the other delays at the best frequency), threshold, locked, and `power` (frequencies, delays) for plotting"""
    x = np.asarray(x, dtype=np.complex128)
    sps = int(sps)
    L = code.length*sps
    P = len(x)//L if periods is None else int(periods)
    if P < 1 or P*L > len(x):
        raise ValueError(f"{len(x)} samples is not {max(P, 1)} period(s) of {L}")
    doppler = np.atleast_1d(np.asarray(doppler, dtype=float))
    if np.any(doppler != 0) and Fs is None:
        raise ValueError("Fs is needed to search frequency offsets")
    ref = np.repeat(code[index], sps)
    fref = np.conj(np.fft.fft(ref))
    blocks = x[:P*L]
    power = np.empty((len(doppler), L))
    t = np.arange(P*L)
    for k, f in enumerate(doppler):
        mixed = blocks*np.exp(-2j*np.pi*f*t/Fs) if f else blocks
        c = np.fft.ifft(np.fft.fft(mixed.reshape(P, L), axis=1)*fref, axis=1) # c[p, d]: period p against the code delayed by d
        power[k] = (np.abs(c)**2).sum(axis=0)
    k, d = np.unravel_index(np.argmax(power), power.shape)
    rest = np.delete(power[k], d)
    metric = float(power[k, d]/max(rest.mean(), 1e-30))
    if threshold is None:
        threshold = noise_threshold(P, power.size, pfa)
    return SimpleNamespace(offset=int(d), doppler=float(doppler[k]), metric=metric, threshold=float(threshold), locked=metric >= threshold, power=power)

noise_threshold

noise_threshold(periods, cells, pfa=0.001)

The ratio to the mean that the largest of cells noise-only powers, each summed over periods, exceeds with probability pfa

Source code in src/rpps/sync/code_acquire.py
def noise_threshold(periods, cells, pfa=1e-3):
    """The ratio to the mean that the largest of `cells` noise-only powers, each summed over `periods`, exceeds with probability pfa"""
    dof = 2*periods # the power of a complex Gaussian is chi-square with 2 degrees of freedom; a sum of P of them, 2P
    z = NormalDist().inv_cdf(1 - pfa/cells)
    return (1 - 2/(9*dof) + z*np.sqrt(2/(9*dof)))**3

equalize

Equalizers: symbols + rp.sync.equalize.BlockLS(qpsk) solves the taps per window

The taps carry across blocks, so any block length gives the same stream. The per-symbol adaptive equalizers (second class) are rp.sync.loops.LMS and rp.sync.loops.CMA.

Classes:

Name Description
BlockLS

Equalize symbols by least squares over each window, decision directed, with the taps carried from window to window

Functions:

Name Description
symmetry

(M, E[a^M]) for the smallest M whose moment E[a^M] is not zero: the constellation's rotational symmetry (2 BPSK,

BlockLS

BlockLS(constellation, taps=7, window=0.001, min_symbols=1024, iters=3, blend=0.5, gate=0.5, name='equalizer', blind=False, blind_iters=8)

Bases: Stage

Equalize symbols by least squares over each window, decision directed, with the taps carried from window to window

symbols = timed + carrier + rp.sync.equalize.BlockLS(rp.symbol.load("QPSK"), taps=7)

First class (rpps.sync): block estimation, where loops.LMS and loops.CMA adapt per symbol. Windows sit at absolute stream positions, window seconds (at least min_symbols). On each, the taps w (symbol spaced, centred: output n uses inputs n - taps//2 .. n + taps//2) solve min |X w - d|^2, d the constellation points nearest to X w, iters times; the window's solution is blended with the last (blend of the old: the tracking across windows), and that is the filter for the window. It starts as a pass-through and normalizes the power to the constellation's. A window that is noise only would pull the taps anywhere: gate is the least fraction of decisions within half the minimum distance for a window to update the taps. Latency: a window and taps//2 symbols (est: latency).

blind=True: a window whose decisions fail the gate (an eye the channel has closed, before any decision is right) is solved without decisions, by block least squares constant modulus (LS-CMA, Agee): blind_iters times, the targets are the outputs y pushed onto the constellation's modulus (R y/|y|, R^2 = E|a|^4/E|a|^2), and w solves min |X w - R y/|y||^2 with the same normal equations. The modulus does not see the phase: the taps are turned by the constellation's M-th power phase (M its rotational symmetry: 2 BPSK, 4 QPSK/QAM, 8 8PSK) and, of the M rotations left, the one nearest the taps before, so windows blend alike. The window is then refined decision directed (when its decisions pass the gate within dmin/4, not dmin/2: a dense constellation's own spread lands within dmin/2 of a point pi/4 of the time, eye open or not); the M-fold ambiguity is left to what follows (a frame word, differential coding). est: mode, "decided" or "blind" (the last window's).

Source code in src/rpps/sync/equalize.py
def __init__(self, constellation, taps=7, window=1e-3, min_symbols=1024, iters=3, blend=0.5, gate=0.5, name="equalizer",
             blind=False, blind_iters=8):
    if taps < 1 or taps % 2 == 0:
        raise ValueError("taps is an odd number")
    self.points = np.asarray(constellation.points, dtype=np.complex128)
    self.dmin = float(constellation.min_distance)
    self.taps, self.window, self.min_symbols = int(taps), window, min_symbols
    self.iters, self.blend, self.gate, self.name = int(iters), float(blend), float(gate), name
    self.blind, self.blind_iters = bool(blind), int(blind_iters)
    a2 = np.mean(np.abs(self.points)**2)
    self.modulus = float(np.sqrt(np.mean(np.abs(self.points)**4)/a2))
    self.order, self.moment = symmetry(self.points)

symmetry

symmetry(points, most=12)

(M, E[a^M]) for the smallest M whose moment E[a^M] is not zero: the constellation's rotational symmetry (2 BPSK, 4 QPSK and square QAM, 8 8PSK); (0, 0) when none up to most (a constellation with no phase to read)

Source code in src/rpps/sync/equalize.py
def symmetry(points, most=12):
    """(M, E[a^M]) for the smallest M whose moment E[a^M] is not zero: the constellation's rotational symmetry (2 BPSK,
    4 QPSK and square QAM, 8 8PSK); (0, 0) when none up to `most` (a constellation with no phase to read)"""
    p = np.asarray(points, dtype=np.complex128)
    scale = np.mean(np.abs(p))
    for m in range(1, most + 1):
        mom = np.mean(p**m)
        if abs(mom) > 1e-6*scale**m:
            return m, complex(mom)
    return 0, 0j

frame

Frame sync: where frames start (rpps.sync)

FrameSync   symbols: correlate a known preamble (DVB-S2 SOF), give each frame from its preamble to the next one,
            with the carrier phase the preambles measured taken off
Delimiter   bits: find the word that comes before each frame (802.11b SFD, a CCSDS ASM), give the bits after it (or
            the frame from its word on), for a fixed or a controlled length, with the polarity put right

Both publish {"frame": k} at each frame start (rp.base.control.publish), so a profile can drive the steps after them frame by frame (a header that reads the frame's start), and say where each frame came from (rp.base.control.anchor).

Classes:

Name Description
FrameSync

Find frames by a known preamble among timed symbols, and give them whole and the right way round

Delimiter

Find frames in a bit stream by the word that comes before each one (a start-of-frame delimiter), give the bits

Functions:

Name Description
word_errors

The most bit errors a match of an n_bits word may have while random bits stay under false_alarm matches over

FrameSync

FrameSync(preamble, words=None, threshold=None, max_length=None, name='frame', pending=False, device=False, before=0, length=None, segments=1, scale=False, classify=None, margin=0.1, min_symbols=64, polarity=True, cfo=False, count=None, memory=32)

Bases: Stage

Find frames by a known preamble among timed symbols, and give them whole and the right way round

frames = symbols + rp.sync.FrameSync(preamble)          # preamble: the known symbols, complex
frames = symbols + rp.sync.FrameSync(sof, words)        # then one of a set of known continuations (DVB-S2 PLS)
frames = levels + rp.sync.FrameSync({"bs_voice": a, "bs_data": b}, before=54, length=132, scale=True)  # DMR

Block estimation: the normalised correlation with the preamble, |c| / sqrt(E_window E_preamble) (1 for a perfect match), peaks above threshold and the largest within a preamble's length. With words (M, n): the n symbols after the preamble are one of M known words (a short header code), and the metric takes the best of them, in phase with the preamble, over the whole L + n symbols: random data then hardly ever passes, where a short preamble alone would every few frames (DVB-S2: 26 SOF symbols, then 64 PLS symbols from 128 words: random 8PSK data stays under 0.41, a header at -2 dB Es/N0 is over 0.5 99 times in 100; threshold 0.5 by default with words, 0.6 without). Each frame goes out when the next preamble is found (or the stream is flushed), from its preamble to the next, turned back by the carrier phase: a line from the phase its preamble measured to the next one's (block-rate tracking of a slowly turning carrier; a residual frequency is for the pilots to take off). A frame longer than max_length symbols is cut there. A unique word known as bits (a long one after demodulation, before the FEC) is found here rather than among bits when the carrier leaves an M-fold ambiguity: its phase is measured, so a frame turned by 90 degrees is put right too (a bit search only corrects an inversion). pending: the preamble comes later (set_template), as a profile makes it from such a word. Over L symbols random data correlates about 1/sqrt(L) (0.05 for a 400-symbol word), so a long word may use a threshold well under the default.

the symbols, or alternatives of one length: {name: symbols} or {name: (symbols, {field: value})} (sync

words that say what follows: DMR's voice / data, base / mobile; Zadoff-Chu roots and shifts). Each is correlated; the best names the frame, published as word with its fields, for controls to drive steps by.

before, length: the frame starts before symbols ahead of its preamble (a sync word mid-burst) and is length symbols long (a controlled parameter too: a header says it); without a length a frame runs to the next one. segments: the preamble correlated in that many parts, added without their phases: a carrier offset turns a long word (a Zadoff-Chu sequence moves its peak with it) and a coherent sum over the whole word loses it (a burst's own offset, 3 kHz at 512 kBd, turns a 64-symbol word by 145 degrees). "auto": one part a 16 symbols, at most 4 (1 with header words): what a profile's frame step on a word takes unless it says. count: frames to find in a stream, then no more searching (None: all; a burst's runner: 1, as data later in the burst can pass for the word). cfo: take the carrier frequency its preamble measured off each frame too (within +-1/L cycles a symbol: a larger offset is for a carrier step before), not only its phase. "track": the frequency tracked over the frames instead, data-aided (Luise and Reggiannini over each frame's known symbols, the preamble and the word it matched, summed over the last memory frames or so, weighted down by age, started again when a frame's own estimate is over 4 of its standard deviations off: an offset taken off upstream mid-stream; unambiguous within +-2/(L + n) cycles a symbol), and refined by the phase from one preamble to the next (the turns between them from the tracked frequency once it is 3 standard deviations off 0, else none, as without it; what that leaves of the tracked frequency is published as cfo_left, for pilots closer together to take off: rpps.sync.PilotPhase): below an M-th power's SNR gate the offset is not taken off before, and a frame's own known symbols measure it too poorly to resolve pilots far apart (DVB-S2 at 6 dB Es/N0: 90 known symbols a frame, pilot blocks 1476 apart). Published as cfo (cycles a symbol). scale: divide each frame by the gain its preamble measured, so levels come out as the preamble's (4FSK +-1, +-3). Real levels (a discriminator's output) stay real: the phase is a polarity, a frame upside down is turned over. polarity: an inverted (turned) match counts (an unknown carrier phase, a discriminator of unknown sense); False: only matches in phase, where the sense is known and alternatives are each other inverted (DMR voice / data). classify: constellation names; each frame's symbols after its preamble are scored against them (rpps.sync.acquire) at the Es/N0 the preamble measured, and the best published as modulation (when it leads by margin nats a symbol over at least min_symbols; otherwise the last one stays, reported), with mapping: the name of the map whose turned points fit (the preamble set the phase: DVB-S2 8PSK is told from 8PSK), None for the points as defined.

Each frame start publishes {"frame": k, "metric", "phase", "scale", "esn0" (dB: the frame's power less the noise the residual after its preamble measured, over that noise), "cfo" (cycles a symbol, from the phase between the preamble's halves; complex input), "word" and its fields (alternatives), "modulation" and "mapping" (classify)}. Estimates in stream.est[name]: the same of the last frame.

Methods:

Name Description
set_template

The known symbols that start each frame, or {name: symbols or (symbols, fields)} of one length (a profile makes

Source code in src/rpps/sync/frame.py
def __init__(self, preamble, words=None, threshold=None, max_length=None, name="frame", pending=False, device=False,
             before=0, length=None, segments=1, scale=False, classify=None, margin=0.1, min_symbols=64, polarity=True,
             cfo=False, count=None, memory=32):
    if preamble is None and not pending:
        raise ValueError("FrameSync: a preamble, or pending=True (set_template gives it later)")
    if pending and words is not None:
        raise ValueError("FrameSync: words follow a preamble given now, not a pending one")
    self.preamble, self.L, self._ep = None, 0, 0.0
    self.pres, self.names, self.fields = None, None, None
    self._auto = segments == "auto" # (resolved when the preamble is known: its length says)
    self.segments = 1 if self._auto else int(segments)
    if self.segments < 1:
        raise ValueError("FrameSync: segments >= 1")
    if preamble is not None:
        self.set_template(preamble)
    self.words = None if words is None else np.conj(np.asarray(words, dtype=np.complex128)) # (M, n), conjugated
    self.n = 0 if words is None else self.words.shape[1]
    self._words_ri = None if words is None else np.stack((self.words.real.T, -self.words.imag.T), axis=1).reshape(2*self.n, -1).astype(np.float32) # (re, -im) pairs
    self._words_t = None if words is None else np.ascontiguousarray(self._words_ri.T) # (words, 2n) for the C++ kernel
    self.threshold = float(threshold if threshold is not None else (0.6 if words is None else 0.5))
    self.name = name
    self.max_length = None if max_length is None else int(max_length)
    self.device, self._xp = bool(device), None # device: the metric on the GPU of rpps._accel.device() (numpy without one)
    self.before = int(before)
    if self.before < 0:
        raise ValueError("FrameSync: before >= 0 (symbols of the frame ahead of its preamble)")
    self.length = None
    self.control(length=length)
    self.scale = bool(scale)
    self.classify = None if not classify else list(classify)
    self.margin, self.min_symbols = float(margin), int(min_symbols)
    self.polarity = bool(polarity)
    if cfo not in (True, False, "track"):
        raise ValueError(f"FrameSync: cfo True, False or 'track', not {cfo!r}")
    self.cfo = cfo if cfo == "track" else bool(cfo)
    self.memory = float(memory)
    self.count = None if count is None else int(count)
    self._check()
set_template
set_template(preamble, first=0, span=None)

The known symbols that start each frame, or {name: symbols or (symbols, fields)} of one length (a profile makes them from words, through its own transmit side down to the symbol mapping: rpps.profile.Profile._template; first and span are unused, the symbols being one a sample)

Source code in src/rpps/sync/frame.py
def set_template(self, preamble, first=0, span=None):
    """The known symbols that start each frame, or {name: symbols or (symbols, fields)} of one length (a profile makes
    them from words, through its own transmit side down to the symbol mapping: rpps.profile.Profile._template; first
    and span are unused, the symbols being one a sample)"""
    if isinstance(preamble, dict):
        items = list(preamble.items())
    else:
        items = [(None, preamble)]
    names, pres, fields = [], [], []
    for k, v in items:
        f = {}
        if isinstance(v, tuple):
            v, f = v
        names.append(k)
        pres.append(np.asarray(v, dtype=np.complex128).reshape(-1))
        fields.append(dict(f))
    if not pres or not len(pres[0]):
        raise ValueError("FrameSync: an empty preamble")
    if len({len(p) for p in pres}) != 1:
        raise ValueError(f"FrameSync: alternatives of one length, not {sorted({len(p) for p in pres})}")
    self.pres, self.names, self.fields = np.stack(pres), names, fields
    if getattr(self, "_auto", False):
        words = getattr(self, "words", None) is not None
        self.segments = 1 if words else min(4, max(1, len(pres[0])//16))
    self.preamble = self.pres[0]
    self.L = len(self.preamble)
    self._eps = np.sum(np.abs(self.pres)**2, axis=1)
    self._ep = float(self._eps[0])
    bounds = np.linspace(0, self.L, min(self.segments, self.L) + 1).round().astype(int)
    self._segs = [(int(a), int(b)) for a, b in zip(bounds[:-1], bounds[1:])]
    if hasattr(self, "words"):
        self._check()

Delimiter

Delimiter(word, bits=None, order='msb', errors=0, name='delimiter', length=None, keep=False, polarity=False)

Bases: BitStage

Find frames in a bit stream by the word that comes before each one (a start-of-frame delimiter), give the bits after it

frames = bits + rp.sync.Delimiter(word=0xF3A0, bits=16, order="lsb")      # 802.11b SFD, sent LSB first
frames = bits + rp.sync.Delimiter(0x1ACFFC1D, 32, length=8160, keep=True) # CCSDS: the ASM and its frame, whole

word: the delimiter's value, bits long, sent most (order "msb") or least significant bit first; or the bits themselves (an array, in the order sent), or a sequence definition of type word (rp.sequence.load). errors: bit errors a match may have (word_errors gives the most a false-alarm rate allows; a word longer than 64 bits is matched by FFT correlation). length: bits in a frame after the word; after them the frame is over and the search starts again (also a controlled parameter: a header says how long its frame is); unknown, the bits pass until the next delimiter. keep: give each frame from its word on (so a rp.code.Marker after it can strip and check the word) rather than from the bit after it. polarity: match the inverted word too, and give such a frame inverted back (LLRs negated), for links whose sense an unknown carrier phase can flip. Takes hard bits or LLRs, gives the same. Estimates in stream.est[name]: frames found, polarity of the last.

Source code in src/rpps/sync/frame.py
def __init__(self, word, bits=None, order="msb", errors=0, name="delimiter", length=None, keep=False, polarity=False):
    from ..sequence.word import Word, word_bits
    self.word = word.bits if isinstance(word, Word) else word_bits(word, bits, order)
    self.n, self.errors, self.name = len(self.word), int(errors), name
    self.length = None if length is None else int(length)
    self.keep, self.polarity = bool(keep), bool(polarity)

word_errors

word_errors(n_bits, false_alarm=1e-06, positions=1, polarity=False)

The most bit errors a match of an n_bits word may have while random bits stay under false_alarm matches over positions places searched (a frame's bits, when the search restarts every frame): the largest e with positions * P(Binomial(n_bits, 1/2) <= e) (twice that with polarity, the inverted word matched too) under it. -1 when even an exact match is too likely (a short word over many places). A 32-bit ASM searched over a CCSDS frame (8160 places) allows 1 at 1e-3; an 800-bit word (100 bytes) 314 at 1e-9, so its own channel errors hardly ever matter

Source code in src/rpps/sync/frame.py
def word_errors(n_bits, false_alarm=1e-6, positions=1, polarity=False):
    """The most bit errors a match of an `n_bits` word may have while random bits stay under `false_alarm` matches over
    `positions` places searched (a frame's bits, when the search restarts every frame): the largest e with
    positions * P(Binomial(n_bits, 1/2) <= e) (twice that with `polarity`, the inverted word matched too) under it.
    -1 when even an exact match is too likely (a short word over many places). A 32-bit ASM searched over a CCSDS frame
    (8160 places) allows 1 at 1e-3; an 800-bit word (100 bytes) 314 at 1e-9, so its own channel errors hardly ever matter"""
    from math import log
    from ..math.prob import log_binom_half_cdf
    n = int(n_bits)
    budget = log(false_alarm) - log(max(1, int(positions))) - (log(2) if polarity else 0.0)
    ok = np.nonzero(np.atleast_1d(log_binom_half_cdf(n, np.arange(n + 1))) <= budget)[0]
    return int(ok[-1]) if len(ok) else -1

inversion

Spectral inversion (a stream conjugated) found by known symbols turning backwards, and undone (rpps.sync)

A high-side LO or I and Q swapped anywhere on the way conjugates a stream.

symbols + rp.sync.Inversion(rp.symbol.load_header("dvbs2_pl").preamble)      # {"sync": "inversion", "header": ...}

Conjugated, everything turns clockwise. That is not a bit map: random data on a constellation the same conjugated (every PSK, QAM, APSK) looks the same either way, so only a known sequence that turns (steps not all 0 / 180 degrees) or a code on a standard's map (CodeDetection.inverted) tells. sense(z, known): the symbol steps z[n] conj(z[n-1]) against the sequence's, forwards and conjugated; differential, so before carrier sync.

Classes:

Name Description
Inversion

Spectral inversion of timed symbols by a known sequence that turns; conjugates them back

Functions:

Name Description
handed

Whether a sequence turns (a step not 0 or 180 degrees): only then does it tell the senses apart

sense

Whether symbols z are inverted, by a known sequence in them: True, False, None (not found, or it doesn't turn)

Inversion

Inversion(known, window=4096, threshold=0.7, evidence=3.0, hold=2 ** 16, name='inversion')

Bases: Stage

Spectral inversion of timed symbols by a known sequence that turns; conjugates them back

Windows of window symbols at absolute positions: each match over threshold (forwards or backwards) adds Re(forward) - Re(backward) to a score held within +-2 evidence (about +-2 a pi/2-BPSK word). The sense is decided at +-evidence and changes only at the other: a stray match never flips it. Windows wait up to hold symbols for the first decision, then go out as received. Each goes out in the sense known when it was searched (held ones in the first decision's): the output is the input one for one, however cut. Publishes {"inverted"} where the sense is decided or changes; est[name]: inverted, score, matches, windows, latency. Real levels pass (their polarity is a frame sync's).

Source code in src/rpps/sync/inversion.py
def __init__(self, known, window=4096, threshold=0.7, evidence=3.0, hold=2**16, name="inversion"):
    if not handed(known):
        raise ValueError("Inversion: the known sequence never turns (steps of 0 or 180 degrees only): it looks the same conjugated")
    self.known = np.asarray(known, dtype=np.complex128).reshape(-1)
    self.ref = _steps(self.known)
    self.window, self.threshold, self.evidence = int(window), float(threshold), float(evidence)
    self.hold, self.name = int(hold), name
    if self.window < 1:
        raise ValueError("Inversion: window >= 1")

handed

handed(known)

Whether a sequence turns (a step not 0 or 180 degrees): only then does it tell the senses apart

Source code in src/rpps/sync/inversion.py
def handed(known):
    """Whether a sequence turns (a step not 0 or 180 degrees): only then does it tell the senses apart"""
    return bool(np.any(np.abs(_steps(known).imag) > 1e-6))

sense

sense(z, known, threshold=0.6, top=8)

Whether symbols z are inverted, by a known sequence in them: True, False, None (not found, or it doesn't turn)

The top strongest matches over threshold vote: True when they turn backwards

Source code in src/rpps/sync/inversion.py
def sense(z, known, threshold=0.6, top=8):
    """Whether symbols z are inverted, by a known sequence in them: True, False, None (not found, or it doesn't turn)

    The `top` strongest matches over `threshold` vote: True when they turn backwards"""
    if not handed(known):
        return None
    m = _matches(z, _steps(known), threshold)
    if m is None or not len(m[3]):
        return None
    up, down, size, peaks = m
    best = peaks[np.argsort(-size[peaks])[:top]]
    return bool(np.sum(down[best].real) > np.sum(up[best].real))

kernels

Batch kernels of the sync operators: PilotLine of PilotPhase

Checked row for row against the operator run frame by frame (tests/unit/parallel/test_batch_kernels.py); they use only what numpy and cupy share, so xp can be either (rpps.parallel)

Classes:

Name Description
PilotLine

The carrier phase of each frame from its pilot blocks, taken off: a least-squares line through the phase of every block (and

PilotLine

PilotLine(starts, total, length, value, lead, name='pilot_line', left=0.0)

Bases: Kernel

The carrier phase of each frame from its pilot blocks, taken off: a least-squares line through the phase of every block (and through lead, a position where it is known to be 0), per row. Symbols past the frame pass unchanged, a frame cut short as it is. starts: where the blocks start in a frame, total: its length with the pilots; left: a frequency (cycles a symbol) taken off from lead first (PilotPhase's)

Source code in src/rpps/sync/kernels.py
def __init__(self, starts, total, length, value, lead, name="pilot_line", left=0.0):
    self.starts, self.total, self.length, self.value, self.lead = np.asarray(starts, np.int64), int(total), int(length), complex(value), lead
    self.left = float(left)
    self.name = f"line:{name}"
    pos = [float(s) + self.length/2 for s in self.starts]
    self.pos = np.array(([float(lead)] if lead is not None else []) + pos)

ofdm

OFDM symbol timing and fractional carrier frequency from the cyclic prefix (van de Beek, Sandell & Borjesson 1997)

Classes:

Name Description
CPSync

OFDM symbols found by their cyclic prefix: samples in, the same samples out from the start of a symbol (its prefix),

CPSync

CPSync(n_fft=64, n_cp=16, window=0.001, min_symbols=16, snr=10.0, bw=0.25, gate=4.0, name='ofdm')

Bases: Stage

OFDM symbols found by their cyclic prefix: samples in, the same samples out from the start of a symbol (its prefix), whole symbols of n_fft + n_cp, with the fractional carrier frequency offset taken off. wave.OFDMRx follows it

carriers = samples + rp.sync.CPSync(64, 16) + rp.wave.OFDMRx(64, 16)

First class (rpps.sync): block estimation over windows at absolute stream positions, window seconds (at least min_symbols OFDM symbols). In a window, the correlation of every sample with the one n_fft later, summed over a prefix's length and folded over the window's symbols, peaks where the prefixes start: gamma(t) = sum r[k] r*[k + N] over the prefix at t. The ML metric |gamma(t)| - rho * energy(t)/2 (rho = snr/(snr + 1)) takes the timing; the angle of gamma there is the carrier frequency, -angle/(2 pi) of a subcarrier spacing (|offset| under half a spacing: an integer offset is for the pilots or a preamble). Both are tracked across windows (rpps.sync.track): timing modulo a symbol, so a clock some ppm off is followed, the output keeping whole symbols by dropping or repeating one prefix sample when the tracked start moves by one; the frequency taken off is a phase line evaluated per sample. A window whose peak is weaker than gate (|gamma| against the prefix's energy: 1 for a clean signal, about 1/sqrt(symbols) on noise) is skipped and the loops coast: the gate is on the metric against what noise gives (|gamma| / energy times sqrt(symbols * prefix): about 1 on noise, and its peak over the L candidate starts about sqrt(2 ln L)), so it holds for any window length. Estimates in stream.est[name]: timing (samples into a symbol), cfo (subcarrier spacings), metric, latency.

Source code in src/rpps/sync/ofdm.py
def __init__(self, n_fft=64, n_cp=16, window=1e-3, min_symbols=16, snr=10.0, bw=0.25, gate=4.0, name="ofdm"):
    self.N, self.cp = int(n_fft), int(n_cp)
    self.window, self.min_symbols, self.rho = window, int(min_symbols), snr/(snr + 1.0)
    self.bw, self.gate, self.name = bw, gate, name

pilots

Classes:

Name Description
PilotEqualizer

Equalize OFDM carriers from their pilots: n_fft carrier values per OFDM symbol in, the same with the channel removed

PilotPhase

Carrier phase over each frame from its pilot blocks: a line through the phases they measure, taken off the frame

PilotEqualizer

PilotEqualizer(carriers, taps=None, max_taps=16)

Bases: Stage

Equalize OFDM carriers from their pilots: n_fft carrier values per OFDM symbol in, the same with the channel removed

The channel seen on the pilots of each OFDM symbol is fitted with a short impulse response (least squares, taps long), and every carrier is divided by that response's frequency response. A multipath channel shorter than the prefix and a constant phase offset come off. Block estimation, one OFDM symbol at a time.

Which OFDM symbol a block starts on (the pilots' sign alternates) comes from its absolute stream position, so any block cut gives the same output.

carriers: the rp.symbol.Carriers layout. taps: channel length (default 3/4 of the pilots, at most max_taps)

Source code in src/rpps/sync/pilots.py
def __init__(self, carriers, taps=None, max_taps=16):
    self.carriers = carriers
    k = np.asarray(carriers.pilots)
    self.order = np.argsort(k)
    self.pk = k[self.order]
    self.pb = carriers.bins(self.pk)
    n = carriers.n_fft
    L = taps or max(1, min(max_taps, (3*len(self.pk))//4))
    lags = np.arange(L)
    fit = np.linalg.pinv(np.exp(-2j*np.pi*np.outer(self.pk, lags)/n)) # pilot response -> impulse response
    all_k = np.arange(n)
    self.response = np.exp(-2j*np.pi*np.outer(all_k, lags)/n) @ fit # pilot response -> response on every bin

PilotPhase

PilotPhase(slot=90, every=16, length=36, value=(1 + 1j) / np.sqrt(2), slots=None, pilots=True, lead=None, name='pilots', left=0.0)

Bases: Stage

Carrier phase over each frame from its pilot blocks: a line through the phases they measure, taken off the frame

payload = symbols + rp.sync.PilotPhase(slots=360)       # DVB-S2: blocks of 36 pilots after every 16 slots of 90

Block estimation per frame, data-aided: the phase of each pilot block (the mean of the symbols times the conjugate pilot value) at its centre, unwrapped in order, and a least-squares line through them (and through lead: a position before the payload where the phase is known to be 0, the frame's preamble once a frame sync took its phase off). A frame is held until it is whole. left: a frequency (cycles a symbol) known to be on the frame still, taken off from lead first (a control: FrameSync's cfo_left, the part of a tracked frequency its preambles, far apart, could not place), so the blocks' phases are unwrapped about it. Without pilots, or before a profile says how the frame is laid out (slots, pilots), the symbols pass unchanged (left too: with nothing to check it by, it is not taken off). Frames start where a profile applies a change (rpps.profile.control), or at the start of the stream. Estimates in stream.est[name]: the last frame's phase line (phase at the start, per symbol).

Methods:

Name Description
kernel

The batch carrier fit, for the frame layout params set (without one, or without pilots, the symbols pass)

Source code in src/rpps/sync/pilots.py
def __init__(self, slot=90, every=16, length=36, value=(1 + 1j)/np.sqrt(2), slots=None, pilots=True, lead=None,
             name="pilots", left=0.0):
    self.slot, self.every, self.length, self.value = int(slot), int(every), int(length), complex(value)
    self.slots, self.pilots, self.lead, self.name = slots, bool(pilots), lead, name
    self.left = float(left)
    self._start = True
kernel
kernel(params, how)

The batch carrier fit, for the frame layout params set (without one, or without pilots, the symbols pass)

Source code in src/rpps/sync/pilots.py
def kernel(self, params, how):
    """The batch carrier fit, for the frame layout `params` set (without one, or without pilots, the symbols pass)"""
    from .kernels import PilotLine
    if params:
        self.control(**params)
    if self.slots is None or not self.pilots:
        return PilotLine([], 0, self.length, self.value, None, self.name) # the symbols pass
    from ..symbol.frame import pilot_layout
    total, starts = pilot_layout(self.slots, self.pilots, self.slot, self.every, self.length)
    return PilotLine(starts, total, self.length, self.value, self.lead, self.name, self.left)

plan

Bursts on many carriers, placed in a burst time plan (rpps.plan): the return link of an MF-TDMA network

for b in src(1 << 16) + rp.sync.Bursts(carriers=[{"freq": -1e6, "width": 600e3}, {"freq": 0, "width": 600e3}]):
    print(b.ctx["burst"])          # {"carrier": 0, "freq": -1e6, "start": 0.0123}

bursts = rp.sync.Bursts(plan=rp.plan.load("demo/mftdma"))   # the plan's carriers; each burst labelled with its place

Detection comes first: each carrier is brought to baseband (rpps.signal.channelize) and cut into the bursts that rise out of its own noise floor (rpps.sync.Burst), at absolute positions, so a capture with no plan still gives its bursts, and a plan learned from them (rpps.analysis.burst) or told by a forward link (rpps.plan) places them:

  • plan: each burst is labelled with its window (superframe, frame, slot, tx type, assignment) and the fields of its tx type (what a profile's controls drive per burst). A burst no window explains is given unlabelled, and counted.
  • the plan's time in the capture, origin (plan clock ticks at the capture's first sample): given (from a forward link's clock reference, rpps.plan), or acquired. Acquiring is block estimation: each detected burst votes for the origins that would put it on a slot of its carrier; the most voted, once lock bursts agree on it (to tol), is taken, and then tracked burst by burst (rpps.sync.track, its rate the clock offset between the network and the capture). The precise start of each burst comes back from the preamble its profile found (feedback, which a profile's burst runner calls): energy edges only seed it, as they smear at low SNR.
  • gate: "energy" (default) or "plan": once the origin is locked, cut every window the plan gives (assigned ones, when the plan has assignments) whether its energy stands out or not, margin seconds either side.

Each burst is a Data of its own stream (the steps after it start over), at the carrier's rate, its first sample at its position in the carrier's stream; ctx["burst"] holds its fields: carrier (index), freq (Hz from the capture's centre), start (seconds from the capture's first sample), and with a plan its window's fields. sps (or a carrier's own) with its rate brings each carrier to exactly that many samples a symbol (decimated by a whole factor, the rest resampled: a capture at any rate), so one profile serves carriers of several rates. Estimates in est["bursts"]: per carrier the floor and bursts, the origin, its rate, locked, labelled and unlabelled counts.

The rest of the burst code: rpps.sync.burst (one carrier's bursts by energy), rpps.profile.burst (a profile's burst step), rpps.analysis.burst (bursts demodulated blind; plans learned and checked: its docstring maps it all).

Classes:

Name Description
Bursts
PlanTx

Bursts placed by a plan: each burst's fields name its window (sequence, superframe, frame, slot; or window),

Bursts

Bursts(carriers=None, plan=None, origin=None, gate='energy', tol=None, lock=8, margin=None, oversample=3.0, bw=0.25, sps=None, pad=None, **burst)

Bases: Pipe

Methods:

Name Description
control

A plan, or its time in the capture, from what a forward link says (rpps.plan): the origin seeds the tracker,

split

The bursts that end in this block, on every carrier, in order of their starts (a list of Data)

feedback

A burst's precise start [s from the capture's first sample], from its preamble: the tracked origin follows

Source code in src/rpps/sync/plan.py
def __init__(self, carriers=None, plan=None, origin=None, gate="energy", tol=None, lock=8, margin=None,
             oversample=3.0, bw=0.25, sps=None, pad=None, **burst):
    if carriers is None and plan is None:
        raise ValueError("Bursts: the carriers, or a plan that has them")
    if gate not in ("energy", "plan"):
        raise ValueError(f"Bursts: gate is energy or plan, not {gate!r}")
    self.carriers = None if carriers is None else [dict(c) for c in carriers]
    self.plan, self.origin, self.gate = plan, origin, gate
    self.tol, self.lock, self.margin, self.oversample, self.bw = tol, int(lock), margin, float(oversample), float(bw)
    self.sps = None if sps is None else int(sps)
    self.pad = pad # Seconds kept either side of an energy burst (its edges sit under its pulse's tails); None: 16
    # symbols where the rate is known, else 4 windows
    self.burst = dict(burst)
    Burst(**self.burst) # (checked now)
control
control(plan=None, origin=None)

A plan, or its time in the capture, from what a forward link says (rpps.plan): the origin seeds the tracker, which the bursts' preambles still refine (the forward link's clock does not know the path to this receiver)

Source code in src/rpps/sync/plan.py
def control(self, plan=None, origin=None):
    """A plan, or its time in the capture, from what a forward link says (rpps.plan): the origin seeds the tracker,
    which the bursts' preambles still refine (the forward link's clock does not know the path to this receiver)"""
    if plan is not None:
        self.plan = plan
    if origin is not None:
        self.origin = float(origin)
        self._reseed = True
split
split(data)

The bursts that end in this block, on every carrier, in order of their starts (a list of Data)

Source code in src/rpps/sync/plan.py
def split(self, data):
    """The bursts that end in this block, on every carrier, in order of their starts (a list of Data)"""
    st = data.meta.state_of(self)
    x = np.asarray(data.data)
    out = []
    for i, ch in enumerate(st.chans):
        inner = Data(x, Fs=data.meta.Fs, sps=data.meta.sps, cf=data.meta.cf, stream=ch.stream)
        inner.flush = data.flush
        y = inner + ch.chan
        ch.Fs, ch.delay = y.meta.Fs, y.meta.delay
        self._hold(ch, y)
        pad = self._pad(ch)
        warm = int(np.ceil(2*ch.delay*ch.Fs)) + 1 - (y.meta.pos - ch.held0) # The filters' start: not cut (the
        if warm > 0: # cutter would take those near-silent samples for its noise floor); it starts after them
            k = min(warm, len(y))
            m = y.meta.fork()
            m.pos = y.meta.pos + k
            y = type(y)(np.asarray(y.data)[k:], y.CAT, y.DT, dict(y.ctx), m, y.REP)
        for b in y + ch.cut:
            for a, n in self._split(st, ch, b.meta.pos, len(b)):
                start = a/ch.Fs - ch.delay # (seconds from the capture's first sample)
                f = self._label(st, i, ch, {"carrier": i, "freq": ch.freq, "start": start}, n/ch.Fs)
                if not f.get("_dup"):
                    ch.pending.append((a - pad, a + n + pad, f))
        cs = y.meta.state_of(ch.cut) # (the energy cutter's: a burst still open holds the history from its start)
        ch.open = None
        if cs is not None and getattr(cs, "pos", None) is not None and not len(cs.hist): # still settling: all it holds
            ch.open = cs.pos
        elif cs is not None and getattr(cs, "on", False) and cs.start is not None:
            ch.open = cs.start
        if self.gate == "plan" and self._locked(st):
            ch.pending += self._windows(st, i, ch, data.flush)
    if st.waiting and (self._locked(st) or data.flush): # The bursts before the origin was found: placed now
        for i, f, dur in st.waiting:
            f.pop("_wait", None)
            if self._locked(st):
                f.update(self._label(st, i, st.chans[i], {k: f[k] for k in ("carrier", "freq", "start")}, dur))
            else:
                st.unlabelled += 1
        st.waiting = []
    for ch in st.chans:
        out += self._emit(ch, data.flush)
    out.sort(key=lambda o: o[0])
    bursts = []
    for start, f, b in out:
        if f.get("_dup"):
            continue
        b.ctx["burst"] = {k: v for k, v in f.items() if not k.startswith("_")}
        b.ctx["burst_window"] = f.get("_window")
        bursts.append(b)
    data.meta.stream.est["bursts"] = {"carriers": [{"freq": ch.freq} for ch in st.chans], "origin": self._origin(st),
                                      "rate": st.tr.rate, "locked": self._locked(st), "labelled": st.labelled,
                                      "unlabelled": st.unlabelled}
    return bursts
feedback
feedback(meta, ctx, start)

A burst's precise start [s from the capture's first sample], from its preamble: the tracked origin follows it (a profile's burst runner calls this, with the burst's ctx, with what its frame sync found). The preambles of a superframe make one measurement (their median, at their median time): a block estimate the tracker takes once a superframe, as bursts on several carriers come at once

Source code in src/rpps/sync/plan.py
def feedback(self, meta, ctx, start):
    """A burst's precise start [s from the capture's first sample], from its preamble: the tracked origin follows
    it (a profile's burst runner calls this, with the burst's ctx, with what its frame sync found). The preambles of
    a superframe make one measurement (their median, at their median time): a block estimate the tracker takes once a
    superframe, as bursts on several carriers come at once"""
    st = meta.state_of(self)
    w = (ctx or {}).get("burst_window")
    if self.plan is None or w is None or not st.tr.started:
        return
    dur = self.plan.sequences[w.sequence].duration
    pred = self._origin(st, start)
    st.fb.append((start, pred + track.wrap(w.burst - start*self.plan.clock - pred, dur)))
    if start - st.fb[0][0] >= dur/self.plan.clock:
        t = np.array([a for a, _ in st.fb])
        o = np.array([b for _, b in st.fb])
        track.update(st.tr, float(np.median(o)), float(np.median(t)), period=dur, bw=self.bw)
        st.fb = []

PlanTx

PlanTx(plan, origin=0.0, cf=0.0, Fs=None, ramp_s=0.0)

Bases: BurstTx

Bursts placed by a plan: each burst's fields name its window (sequence, superframe, frame, slot; or window), and it goes where the plan puts it: at its burst start, freq its carrier, from the plan's time origin (clock ticks at the output's first sample) and the output's centre frequency cf

tx = rp.sync.PlanTx(plan, origin=0, cf=14e9, Fs=8e6)
tx.place(burst, {"superframe": 3, "frame": 0, "slot": 7})

Methods:

Name Description
where

(at [s], freq [Hz from the centre], window) of a burst whose fields name its window

Source code in src/rpps/sync/plan.py
def __init__(self, plan, origin=0.0, cf=0.0, Fs=None, ramp_s=0.0):
    super().__init__(Fs, 0.0, ramp_s)
    self.plan, self.origin, self.cf = plan, float(origin), float(cf)
    # Bursts on several carriers start together, and each is placed so that its first symbol (not its pulse's tail) is
    # on its slot: a BTU held back lets one go a little before another
    self.lag = max((ft.btu_duration for ft in plan.frame_types.values()), default=0)/plan.clock
where
where(fields)

(at [s], freq [Hz from the centre], window) of a burst whose fields name its window

Source code in src/rpps/sync/plan.py
def where(self, fields):
    """(at [s], freq [Hz from the centre], window) of a burst whose fields name its window"""
    p = self.plan
    f = dict(fields or {})
    seq = int(f.get("sequence", next(iter(p.sequences))))
    s = p.sequences[seq]
    count = int(f["superframe"])
    k = (count - s.count) % (1 << 16)
    t0 = s.start + k*s.duration
    ws = [w for w in p.windows(t0, t0 + s.duration, sequences=[seq])
          if w.superframe == count and w.frame == int(f["frame"]) and w.slot == int(f["slot"])]
    if not ws:
        raise ValueError(f"PlanTx: no window for {f} in {p.name}")
    w = ws[0]
    return (w.burst - self.origin)/p.clock, w.freq - self.cf, w

preamble

A preamble at the start of a burst: where it is, and the carrier offset its repetition gives

bursts = src(65536) + rp.sync.Burst(win=100, min_s=30e-6)
for b in bursts + rp.sync.Preamble(ltf_symbol, repeat=64, offset=-192, correct=True):  # 802.11a/g: STF start, CFO off
    ...

Found once per stream: a stream is one burst after rp.sync.Burst. Until it is found the samples are held (up to search samples of candidate starts, or the stream's end); then the output starts at the preamble (plus offset), placed at its absolute position, and the rest of the stream passes. Not found: nothing comes out, and est[name]["found"] is False.

Classes:

Name Description
Preamble

Find a burst's preamble: a known waveform, or a repeated one (Schmidl & Cox)

PreambleTx

The transmit side of a Preamble (Preamble.attach_tx()): its template put before a stream

Preamble

Preamble(template=None, repeat=None, window=None, search=None, gate=0.5, offset=0, correct=False, name='preamble', first=0, pending=False, span=None)

Bases: Stage

Find a burst's preamble: a known waveform, or a repeated one (Schmidl & Cox)

the preamble's samples at the stream's rate (an 802.11 LTF symbol, an LTE PSS); its start is where the

normalized correlation |sum x t*| / sqrt(sum |x|^2 sum |t|^2) (1: the template exactly, scaled and turned) is highest, if at least gate. A template that repeats in the preamble matches each copy: give all the copies (802.11's two LTF symbols). A carrier offset turns the preamble over its length and lowers the metric: about sinc(offset x length / Fs) (40 kHz over 128 samples at 20 MS/s: 0.89). None: the repetition alone finds it, Schmidl & Cox's C over window samples at lag repeat: among the starts where |C|/P reaches gate, the first where |C| is at its plateau (97% of its peak; |C|/P alone rises before the window is all in the preamble)

repeat: the preamble repeats after this many samples (802.11 STF 16, LTF 64): the carrier offset is the angle of the repetition, -angle(sum x[n] x*[n + repeat]) Fs / (2 pi repeat), over window samples from the start found (default: the template's length). correct: take that offset off the output search: candidate starts examined (None: the whole stream, which then waits for its end). offset: the output starts this many samples after the preamble's start (negative: before it; 802.11 STF before the LTF) A real stream (an FSK discriminator's output) is matched by the correlation coefficient: the template and the stream's window with their means taken off (a carrier offset there is a constant), positive only. The offset, the level b of the fit x = a template + b over the match, is est["level"]; correct takes it off the output. first: the template's sample at its first symbol's peak; span: its samples up to the tail its pulses leave (its symbols times the samples a symbol; None: all of it); pending: the template comes later (set_template: a profile makes it from its own transmit side). attach_tx(): the transmit side, which sends this template (PreambleTx). Estimates in stream.est[name]: found, pos (absolute), metric, cfo [Hz] (with repeat), and where the symbols are: first (the absolute sample of the first symbol's peak), delay and Fs (the group delay and rate there; known timing with an anchor places its grid by them).

Methods:

Name Description
set_template

The waveform to find, its sample at the first symbol's peak, and its samples up to its pulses' tail

attach_tx

The transmit side: a PreambleTx that sends this preamble's template (the one set now or later)

Source code in src/rpps/sync/preamble.py
def __init__(self, template=None, repeat=None, window=None, search=None, gate=0.5, offset=0, correct=False, name="preamble",
             first=0, pending=False, span=None):
    if template is None and not pending and (repeat is None or window is None):
        raise ValueError("Preamble: a template, or a repetition (repeat=lag, window=samples) to find")
    self.repeat, self.search, self.gate, self.offset = repeat, search, float(gate), int(offset)
    self._window = window
    self.correct, self.name = correct, name
    self.template, self.first, self.window, self.span = None, 0, None, None
    if template is not None:
        self.set_template(template, first, span)
    else:
        self.window = None if window is None else int(window)
set_template
set_template(template, first=0, span=None)

The waveform to find, its sample at the first symbol's peak, and its samples up to its pulses' tail

Source code in src/rpps/sync/preamble.py
def set_template(self, template, first=0, span=None):
    """The waveform to find, its sample at the first symbol's peak, and its samples up to its pulses' tail"""
    t = np.asarray(template)
    if t.dtype.kind == "c" and np.max(np.abs(t.imag), initial=0.0) <= 1e-6*np.max(np.abs(t), initial=1.0):
        t = t.real # (real levels made from complex points: BPSK)
    self.template = t.astype(np.complex128) if t.dtype.kind == "c" else t.astype(np.float64)
    self.first = int(first)
    self.span = len(self.template) if span is None else int(span)
    if not 0 <= self.span <= len(self.template):
        raise ValueError("Preamble: span is within the template")
    self.window = int(self._window) if self._window is not None else len(self.template)
attach_tx
attach_tx()

The transmit side: a PreambleTx that sends this preamble's template (the one set now or later)

Source code in src/rpps/sync/preamble.py
def attach_tx(self):
    """The transmit side: a PreambleTx that sends this preamble's template (the one set now or later)"""
    return PreambleTx(self)

PreambleTx

PreambleTx(preamble)

Bases: Stage

The transmit side of a Preamble (Preamble.attach_tx()): its template put before a stream

The stream starts with the template, the stream's own samples from its span on (the preamble's symbols), the tail its pulses leave added to them: for linear steps (pulse shaping) exactly the waveform of the preamble's symbols and the stream's sent as one. The template is the Preamble's when the stream starts (a profile sets it after building).

Source code in src/rpps/sync/preamble.py
def __init__(self, preamble):
    self.preamble = preamble

puncture

Classes:

Name Description
Puncture

Find where a punctured convolutional code's puncture pattern starts, and start the stream there

Puncture

Puncture(code, window=4000, name='puncture', max_windows=8, rotations=None)

Bases: BitStage

Find where a punctured convolutional code's puncture pattern starts, and start the stream there

aligned = llrs + rp.sync.Puncture(rp.code.load("conv/k7_171_133/3_4")) + ...   # then Viterbi

Block estimation on channel bits: windows of window coded bits at fixed stream positions, each offset into the puncture period tried on one by decoding it and coding the decision again; the right offset reproduces what was received (only channel errors differ), a wrong one does not. rotations: the constellation's turns as bit transforms (rp.symbol.mapping.bit_rotations: the carrier's M-fold phase left by an M-th power estimate) tried with every offset; the one found is applied to everything after. The first window where the best hypothesis's mismatch is under DECISIVE of the best one not equivalent to it (within EQUIVALENT: a code that decodes inverted bits too) decides (the stream's start is where the timing and carrier before were settling: there every offset decodes badly, and the pick was chance); after max_windows the best summed over them. The bits before the offset are dropped, once; after that the stream passes through. Its estimate is in stream.est[name] (offset, the mismatch rate at each offset in the window that decided, windows).

Source code in src/rpps/sync/puncture.py
def __init__(self, code, window=4000, name="puncture", max_windows=8, rotations=None):
    self.code, self.window, self.name = code, int(window), name
    self.period = puncture_period(code)
    self.max_windows = int(max_windows)
    self.rotations = list(rotations) if rotations else [None]
    self.k = len(self.rotations[0][0]) if self.rotations[0] is not None else 1

quality

Signal quality of recovered symbols: Es/N0, Eb/N0, EVM, measured once (measure), over a running window (Track) or on the stream (Monitor, a stage that publishes it); each symbol's error (errors) and an analyser's error summary (summary: EVM, MER, magnitude and phase error, IQ offset, gain imbalance, quadrature error)

The symbols must be locked (timing, frequency, phase and gain corrected) so they sit on the constellation points. The noise is found the way detection finds it: the variance of Gaussian clusters around equiprobable points, by EM (rp.math.prob.mixture_variance), which stays right when the clusters touch and the nearest point is sometimes wrong.

Before anything is locked, three estimates need no constellation and no noise floor measured apart (each an SNR), and a fourth needs only a constellation to assume (m2m4(y, points): the symbols' second and fourth moments under that constellation's kurtosis, no decisions; rpps.sync.detect scores each candidate at its own):

  • from_sequence(y, ref): from a known sequence in the signal. With a CAZAC one (rp.sequence.zadoff_chu: LTE/NR PSS, PRACH, SRS), the circular correlation of one received period with it has one peak (the channel, multipath taps included within guard) and noise alone at every other lag: signal and noise from the same correlation, in band. Any other known sequence, aligned: the least-squares gain and its residual.
  • cyclic(x, sps): from the signal's own cyclostationarity, in band. Shifted by -1/2T and +1/2T, the two copies of a linearly modulated signal correlate (its spectral correlation at alpha = 1/T); noise doesn't. Where both copies carry signal (the roll-off's overlap) they are fully coherent whatever the pulse: per frequency (Sa - N0)(Sb - N0) = |C|^2, and one N0 is fitted to that over the overlap. Es is the folded spectrum over the signal's band less N0. The roll-off (which bins are the overlap) comes from fitting an RRC's correlation shape, and is given too. Any colour of noise outside the signal's band is irrelevant, and nothing but the symbol rate (searched +-2%) and independent symbols is assumed: a stream whose symbols aren't yet random (an interleaver filling from zero) reads low. Above about 15 dB the window's smoothing takes the coherence down and it reads low (17-19 at 20 dB), still high. None: no correlation found; noise alone reads None or under -3 dB (100 of 100 blocks).
  • blind(x, sps): from the band the signal leaves empty: the eigenvalues of the covariance of L-sample windows. The signal takes at most 2/sps of them (roll-off <= 1, MDL finds how many), the rest are the noise. Precise in white noise, but noise a front-end filter has shaped is not white: where some passband noise shows past the signal the eigenvalues are not flat and it says None, but where the filter's edge is right at the signal's band all it sees is the stopband, flat, and it reads 26-38 dB high. Use it only where the noise is white across Fs.

Measured (2026-11-23, error mean / std in dB; cyclic and blind on 2048 symbols at 4 sps, roll-off 0.35):

Es/N0                     -10          -5           0            10           20           noise through a front-end filter
from_sequence, ZC 63      -0.3 / 3.0                +0.1 / 1.1                +0.15 / 0.6  within 0.5
from_sequence, ZC 839      0.0 / 0.7                 0.0 / 0.3                 0.0 / 0.16
cyclic (RRC 0.2-0.5)      unusable     -0.2..-1.5   -0.1..-0.3   -0.1..-0.5   -1.1..-2.8   the same as white
                                       / 0.7-1.3    / 0.2-0.6    / 0.1-0.3    / 0.1-0.2
blind                     None         -0.2 / 0.3   -0.0 / 0.2   +0.0 / 0.1   +0.0 / 0.04  None, or 26-38 dB high

Classes:

Name Description
Quality

Es/N0, Eb/N0 and friends of a set of symbols (see measure)

SNR

A signal-to-noise estimate before anything is locked (from_sequence, blind)

Errors

Per symbol, against the nearest point (see errors): vector = y - ideal; evm_pct = |vector|, mag_pct = |y| - |ideal|

Summary

A vector signal analyser's error summary of locked symbols (see summary)

Track

Running Es/N0 estimate over the last history symbols: update(block) returns the current Quality (None until enough)

Monitor

Es/N0, Eb/N0 and EVM of the locked symbols going by, published to meta.stream.est[name] as a Quality (None until

Functions:

Name Description
measure

Es/N0, Eb/N0 and EVM of locked symbols y around the constellation points

m2m4

Es/N0 (dB) of symbols y were they of the constellation points, from their second and fourth moments alone

from_sequence

SNR of samples y carrying the known sequence ref (one sample per element, sps samples a symbol for esn0)

cyclic

Es/N0 of samples of one linearly modulated signal (RRC, any roll-off) from its spectral correlation at the symbol

blind

SNR of oversampled samples of one signal, from the band it leaves empty (see the module). None when it can't tell

decide

The nearest of points to each of y

errors

The error of each symbol of y (locked: corrected and at the constellation's scale) against the nearest of points.

summary

EVM, MER, magnitude and phase error, IQ offset, gain imbalance and quadrature error of locked symbols y against

Quality

Quality(esn0_db, ebn0_db, snr_db, evm_pct, sigma, bits, rate, n)

Es/N0, Eb/N0 and friends of a set of symbols (see measure)

esn0_db: symbol energy over noise density. ebn0_db: bit energy over noise density (uncoded, or the information bits of a code with rate). snr_db: signal over noise power in the sample bandwidth (None without sps). evm_pct: rms error vector against the nearest point, as a percentage of the rms symbol. sigma: noise per real axis (unit-rms symbols). n: symbols used.

Source code in src/rpps/sync/quality.py
def __init__(self, esn0_db, ebn0_db, snr_db, evm_pct, sigma, bits, rate, n):
    self.esn0_db, self.ebn0_db, self.snr_db = esn0_db, ebn0_db, snr_db
    self.evm_pct, self.sigma, self.bits, self.rate, self.n = evm_pct, sigma, bits, rate, n

SNR

SNR(**kw)

A signal-to-noise estimate before anything is locked (from_sequence, blind)

snr_db: signal over noise power per sample. esn0_db: per symbol (snr_db + 10 log10 sps). noise_var: noise power per sample (complex). gain: the complex channel gain (from_sequence). delay: the lag of the peak (from_sequence, periodic). dims: the signal's eigenvalues out of L (blind). beta: the fitted roll-off, sps: the samples a symbol the correlation was strongest at (cyclic). n: samples used.

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

Errors

Errors(ideal, vector, evm_pct, mag_pct, phase_deg)

Per symbol, against the nearest point (see errors): vector = y - ideal; evm_pct = |vector|, mag_pct = |y| - |ideal| (both as a percentage of the constellation's rms, as a vector signal analyser normalises them); phase_deg = the angle from ideal to y [degrees] (0 where the ideal is the origin)

Source code in src/rpps/sync/quality.py
def __init__(self, ideal, vector, evm_pct, mag_pct, phase_deg):
    self.ideal, self.vector, self.evm_pct, self.mag_pct, self.phase_deg = ideal, vector, evm_pct, mag_pct, phase_deg

Summary

Summary(**kw)

A vector signal analyser's error summary of locked symbols (see summary)

evm_rms_pct, evm_peak_pct (at symbol evm_peak_at); mer_db: ideal symbol power over error power; mag_err_rms_pct, phase_err_rms_deg; from a fit of the symbols as kI I + kQ Q + c on the ideal points' I and Q: iq_offset_db: |c| over the rms of the rest [dB] (floored at -200); gain_imbalance_db: |kI| / |kQ| [dB], I over Q; quad_error_deg: the angle between the I and Q axes less 90 [degrees] (positive: more than 90 apart). The last two are None for a constellation on one line (BPSK, ASK). n: symbols

Source code in src/rpps/sync/quality.py
def __init__(self, **kw):
    for k in self.__slots__:
        setattr(self, k, kw[k])

Track

Track(points, bits=None, rate=1.0, history=4096, minimum=256)

Running Es/N0 estimate over the last history symbols: update(block) returns the current Quality (None until enough)

Source code in src/rpps/sync/quality.py
def __init__(self, points, bits=None, rate=1.0, history=4096, minimum=256):
    self.points, self.bits, self.rate = points, bits, rate
    self.history, self.minimum = history, minimum
    self.buf = np.zeros(0, dtype=np.complex64)

Monitor

Monitor(points=None, bits=None, rate=1.0, history=4096, minimum=256, name='quality')

Bases: Stage

Es/N0, Eb/N0 and EVM of the locked symbols going by, published to meta.stream.est[name] as a Quality (None until minimum symbols): the symbols pass unchanged. The constellation is points, or the detected one (meta.det, from Acquire) when none is given. A profile names it {"sync": "quality"}.

Source code in src/rpps/sync/quality.py
def __init__(self, points=None, bits=None, rate=1.0, history=4096, minimum=256, name="quality"):
    self.points = None if points is None else np.asarray(points, dtype=np.complex128)
    self.bits, self.rate, self.history, self.minimum, self.name = bits, rate, int(history), int(minimum), name

measure

measure(y, points, bits=None, rate=1.0, sps=None)

Es/N0, Eb/N0 and EVM of locked symbols y around the constellation points

bits: bits per symbol (default log2 of the number of points). rate: code rate, if the bits are information bits of a code (Eb/N0 is per information bit). sps: samples per symbol of the data they were taken from, for snr_db.

Source code in src/rpps/sync/quality.py
def measure(y, points, bits=None, rate=1.0, sps=None):
    """Es/N0, Eb/N0 and EVM of locked symbols `y` around the constellation `points`

    bits: bits per symbol (default log2 of the number of points). rate: code rate, if the bits are information bits
    of a code (Eb/N0 is per information bit). sps: samples per symbol of the data they were taken from, for snr_db.
    """
    y = np.asarray(y)
    pts = np.asarray(points, dtype=np.complex128)
    pts = pts/np.sqrt(np.mean(np.abs(pts)**2))
    if len(y) < 8:
        raise ValueError("Need at least 8 symbols")
    y = y/np.sqrt(np.mean(np.abs(y)**2))
    for _ in range(3): # The rms includes the noise, so the signal is a little smaller than a point: fit its amplitude
        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
    var = mixture_variance(d2) # Per real axis
    esn0 = 10*np.log10(1/(2*var))
    bits = float(np.log2(len(pts))) if bits is None else bits
    ebn0 = esn0 - 10*np.log10(bits*rate)
    snr = None if sps is None else esn0 - 10*np.log10(max(sps, 1.0))
    evm = 100*np.sqrt(np.mean(np.min(d2, axis=1)))
    return Quality(float(esn0), float(ebn0), None if snr is None else float(snr), float(evm), float(np.sqrt(var)), bits, rate, len(y))

m2m4

m2m4(y, points)

Es/N0 (dB) of symbols y were they of the constellation points, from their second and fourth moments alone (Pauluzzi and Beaulieu, 2000): M2 = S + N, M4 = k S^2 + 4 S N + 2 N^2 with k = E|p|^4 of the unit-rms points (1 for any PSK; under 2 for any digital constellation), so S = sqrt((2 M2^2 - M4)/(2 - k)). No decisions, no carrier phase, no pulse: rpps.sync.detect scores each candidate at its own. It fades for QAM at high SNR. Clamped to -30..60 dB

Source code in src/rpps/sync/quality.py
def m2m4(y, points):
    """Es/N0 (dB) of symbols y were they of the constellation `points`, from their second and fourth moments alone
    (Pauluzzi and Beaulieu, 2000): M2 = S + N, M4 = k S^2 + 4 S N + 2 N^2 with k = E|p|^4 of the unit-rms points (1 for
    any PSK; under 2 for any digital constellation), so S = sqrt((2 M2^2 - M4)/(2 - k)). No decisions, no carrier phase,
    no pulse: rpps.sync.detect scores each candidate at its own. It fades for QAM at high SNR. Clamped to -30..60 dB"""
    y = np.asarray(y)
    pts = np.asarray(points, dtype=np.complex128)
    k = float(np.mean(np.abs(pts)**4)/np.mean(np.abs(pts)**2)**2)
    a2 = np.abs(y)**2
    M2, M4 = float(np.mean(a2)), float(np.mean(a2**2))
    S = np.sqrt(max(2*M2**2 - M4, 0.0)/(2 - k)) if k < 2 else 0.0
    return float(np.clip(10*np.log10(max(S, 1e-30)/max(M2 - S, 1e-30)), -30.0, 60.0))

from_sequence

from_sequence(y, ref, periodic=True, guard=2, sps=1.0)

SNR of samples y carrying the known sequence ref (one sample per element, sps samples a symbol for esn0)

y is one period of a CAZAC sequence (rp.sequence.zadoff_chu) at any cyclic shift and carrier phase, as an

OFDM symbol or a cyclic-prefixed preamble gives it: the peak of the circular correlation and the guard lags each side of it are the signal (the channel's taps), every other lag noise alone. Needs len(y) == len(ref).

otherwise: y and ref aligned; the least-squares gain, and the residual as the noise.

Source code in src/rpps/sync/quality.py
def from_sequence(y, ref, periodic=True, guard=2, sps=1.0):
    """SNR of samples `y` carrying the known sequence `ref` (one sample per element, `sps` samples a symbol for esn0)

    periodic: y is one period of a CAZAC sequence (rp.sequence.zadoff_chu) at any cyclic shift and carrier phase, as an
        OFDM symbol or a cyclic-prefixed preamble gives it: the peak of the circular correlation and the `guard` lags
        each side of it are the signal (the channel's taps), every other lag noise alone. Needs len(y) == len(ref).
    otherwise: y and ref aligned; the least-squares gain, and the residual as the noise."""
    y = np.asarray(y, dtype=np.complex128)
    ref = np.asarray(ref, dtype=np.complex128)
    N = len(ref)
    if len(y) != N or N < 8:
        raise ValueError(f"from_sequence needs y as long as ref (at least 8): {len(y)} and {N}")
    ref = ref/np.sqrt(np.mean(np.abs(ref)**2))
    if periodic:
        if 2*guard + 1 >= N//2:
            raise ValueError(f"guard {guard} leaves too few noise lags in {N}")
        c = np.fft.ifft(np.fft.fft(y)*np.conj(np.fft.fft(ref))) # c[k] = mean_n y[n] conj(ref[n - k])
        p = np.abs(c)**2
        k = int(np.argmax(p))
        taps = (k + np.arange(-guard, guard + 1)) % N
        off = np.ones(N, bool)
        off[taps] = False
        lag = float(np.mean(p[off])) # E|c|^2 of a noise lag: noise_var / N
        sig = float(np.sum(p[taps])) - len(taps)*lag
        noise = lag*N
        gain, delay = complex(c[k]), k
    else:
        gain = complex(np.vdot(ref, y)/N)
        noise = float(np.sum(np.abs(y - gain*ref)**2)/(N - 1))
        sig, delay = abs(gain)**2, None
    snr = _db(sig, noise)
    return SNR(snr_db=snr, esn0_db=snr + 10*np.log10(sps), noise_var=noise, gain=gain, delay=delay, n=N)

cyclic

cyclic(x, sps, nseg=None, search=0.02, step=0.005)

Es/N0 of samples of one linearly modulated signal (RRC, any roll-off) from its spectral correlation at the symbol rate (see the module). None when there is no correlation to fit; esn0_db inf when N0 came out <= 0 (high SNR).

x: complex samples, the signal centred; sps: samples a symbol (more than 1.25). nseg: the Welch segment (default about 32 bins a symbol rate). search / step: the cyclic frequency is looked for within +-search of 1/sps (relative) in these steps, the strongest correlation kept: a rate a few tenths of a percent off turns the two copies half a cycle apart over a segment and the correlation, and Es with it, fades (sps in the result: the rate it was found at)

Source code in src/rpps/sync/quality.py
def cyclic(x, sps, nseg=None, search=0.02, step=0.005):
    """Es/N0 of samples of one linearly modulated signal (RRC, any roll-off) from its spectral correlation at the symbol
    rate (see the module). None when there is no correlation to fit; esn0_db inf when N0 came out <= 0 (high SNR).

    x: complex samples, the signal centred; sps: samples a symbol (more than 1.25). nseg: the Welch segment (default
    about 32 bins a symbol rate). search / step: the cyclic frequency is looked for within +-search of 1/sps (relative)
    in these steps, the strongest correlation kept: a rate a few tenths of a percent off turns the two copies half a
    cycle apart over a segment and the correlation, and Es with it, fades (sps in the result: the rate it was found at)"""
    x = np.asarray(x, dtype=np.complex128)
    if sps <= 1.25:
        return None
    nseg = int(nseg or 2**int(np.ceil(np.log2(32*sps))))
    if len(x) < 8*nseg:
        return None
    best = None
    for rel in np.arange(-search, search + step/2, step) if search else (0.0,):
        s = sps/(1 + rel)
        f, Sa, Sb, X, K = _shifted_spectra(x, s, nseg)
        e = np.sum(np.abs(X)**2 - Sa*Sb/(K/1.9))
        if best is None or e > best[0]:
            best = (e, s, f, Sa, Sb, X, K)
    _, sps, f, Sa, Sb, X, K = best
    band, T = _templates(nseg, float(round(sps, 6)))
    f, Sa, Sb, X = f[band], Sa[band], Sb[band], X[band]
    C2 = np.abs(X)**2 - _VAR*Sa*Sb/K # noise alone leaves |X|^2 of about this
    norms = np.sum(T**2, axis=1)
    es2 = np.maximum(T @ C2/np.where(norms > 0, norms, 1), 0.0) # least squares Es^2 for each roll-off
    resid = np.sum((C2[None, :] - es2[:, None]*T)**2, axis=1)
    resid[norms == 0] = np.inf
    i = int(np.argmin(resid))
    if es2[i] <= 0:
        return None
    beta = float(_BETAS[i])
    N = _coherent_noise(Sa[np.abs(f) < beta/2], Sb[np.abs(f) < beta/2], C2[np.abs(f) < beta/2])
    # Es: the folded spectrum over the signal's band, less the noise (f + 1/2T in the band for Sa, f - 1/2T for Sb)
    Es = (np.sum(Sa[f < beta/2] - N) + np.sum(Sb[f > -beta/2] - N))/len(f)
    esn0 = float(10*np.log10(Es/N)) if N > 0 and Es > 0 else np.inf if Es > 0 else -np.inf
    return SNR(snr_db=esn0 - 10*np.log10(sps), esn0_db=esn0, beta=beta, sps=float(sps), n=len(x))

blind

blind(x, sps, L=32, max_samples=16384, flat=FLAT)

SNR of oversampled samples of one signal, from the band it leaves empty (see the module). None when it can't tell

x: complex samples, the signal centred; sps: samples a symbol (at least 1.3). L: the window, eigenvalues of its covariance; max_samples: the most used. flat: how flat the noise eigenvalues must be (geometric over arithmetic mean)

Source code in src/rpps/sync/quality.py
def blind(x, sps, L=32, max_samples=16384, flat=FLAT):
    """SNR of oversampled samples of one signal, from the band it leaves empty (see the module). None when it can't tell

    x: complex samples, the signal centred; sps: samples a symbol (at least 1.3). L: the window, eigenvalues of its
    covariance; max_samples: the most used. flat: how flat the noise eigenvalues must be (geometric over arithmetic mean)"""
    x = np.asarray(x, dtype=np.complex128)[:max_samples]
    n = len(x) - L + 1
    if sps < 1.3 or n < 8*L:
        return None
    W = np.lib.stride_tricks.sliding_window_view(x, L)
    lam = np.sort(np.linalg.eigvalsh(W.T @ W.conj()/n))[::-1].clip(min=1e-30) # (L, L) covariance, largest first
    kmax = min(int(np.ceil(2*L/sps)), L - 4) # the signal's band: at most (1 + roll-off)/sps <= 2/sps of the samples
    best, k = np.inf, 0
    for j in range(kmax + 1): # MDL (Wax and Kailath), j signal eigenvalues
        t = lam[j:]
        mdl = -n*len(t)*(np.mean(np.log(t)) - np.log(np.mean(t))) + 0.5*j*(2*L - j)*np.log(n)
        if mdl < best:
            best, k = mdl, j
    if k == 0:
        return None
    t = lam[k:] # the noise: every eigenvalue past the signal's
    if np.exp(np.mean(np.log(t)))/np.mean(t) < flat:
        return None
    noise = float(np.mean(t))
    snr = _db(float(np.mean(lam)) - noise, noise)
    return SNR(snr_db=snr, esn0_db=snr + 10*np.log10(sps), noise_var=noise, dims=k, n=len(x))

decide

decide(y, points)

The nearest of points to each of y

Source code in src/rpps/sync/quality.py
def decide(y, points):
    """The nearest of `points` to each of y"""
    pts = np.asarray(points)
    y = np.asarray(y)
    return pts[np.argmin(np.abs(y[:, None] - pts[None, :]), axis=1)]

errors

errors(y, points)

The error of each symbol of y (locked: corrected and at the constellation's scale) against the nearest of points. Returns Errors (arrays of len(y))

Source code in src/rpps/sync/quality.py
def errors(y, points):
    """The error of each symbol of y (locked: corrected and at the constellation's scale) against the nearest of `points`.
    Returns Errors (arrays of len(y))"""
    y = np.asarray(y, dtype=np.complex128)
    pts = np.asarray(points, dtype=np.complex128)
    rms = float(np.sqrt(np.mean(np.abs(pts)**2))) or 1.0
    d = decide(y, pts)
    e = y - d
    ph = np.where(np.abs(d) > 0, np.degrees(np.angle(y*np.conj(d))), 0.0)
    return Errors(d, e, 100*np.abs(e)/rms, 100*(np.abs(y) - np.abs(d))/rms, ph)

summary

summary(y, points)

EVM, MER, magnitude and phase error, IQ offset, gain imbalance and quadrature error of locked symbols y against the nearest of points (Summary). Like an analyser, the decisions are the reference: at low SNR, where some are wrong, the errors read low

Source code in src/rpps/sync/quality.py
def summary(y, points):
    """EVM, MER, magnitude and phase error, IQ offset, gain imbalance and quadrature error of locked symbols y against
    the nearest of `points` (Summary). Like an analyser, the decisions are the reference: at low SNR, where some are
    wrong, the errors read low"""
    y = np.asarray(y, dtype=np.complex128)
    if len(y) < 8:
        raise ValueError("Need at least 8 symbols")
    E = errors(y, points)
    d, e = E.ideal, E.vector
    k = int(np.argmax(E.evm_pct))
    with np.errstate(divide="ignore"):
        mer = 10*np.log10(np.sum(np.abs(d)**2)/np.sum(np.abs(e)**2)) if np.any(e) else np.inf
    I, Q = d.real, d.imag
    planar = np.std(I) > 1e-9 and np.std(Q) > 1e-9 and abs(np.corrcoef(I, Q)[0, 1]) < 0.99
    A = np.stack([I, Q, np.ones(len(y))], axis=1) if planar else np.stack([d, np.ones(len(y))], axis=1)
    coef = np.linalg.lstsq(A.astype(np.complex128), y, rcond=None)[0]
    c = coef[-1]
    rest = A[:, :-1] @ coef[:-1]
    off = 20*np.log10(max(abs(c)/max(float(np.sqrt(np.mean(np.abs(rest)**2))), 1e-300), 1e-10))
    gi = qe = None
    if planar:
        kI, kQ = coef[0], coef[1]
        gi = float(20*np.log10(abs(kI)/abs(kQ)))
        qe = float((np.degrees(np.angle(kQ/kI)) - 90 + 180) % 360 - 180)
    return Summary(evm_rms_pct=float(np.sqrt(np.mean(E.evm_pct**2))), evm_peak_pct=float(E.evm_pct[k]), evm_peak_at=k,
                   mer_db=float(mer), mag_err_rms_pct=float(np.sqrt(np.mean(E.mag_pct**2))),
                   phase_err_rms_deg=float(np.sqrt(np.mean(E.phase_deg**2))), iq_offset_db=float(off),
                   gain_imbalance_db=gi, quad_error_deg=qe, n=len(y))

rate

Symbol rate estimates: the |x|^2 cyclostationary line on samples (find_baud), the rate of symbols (find_rate), the pulse's roll-off from the spectrum (find_rolloff)

Functions:

Name Description
find_baud

Find the symbol rate from IQ samples using the |x|^2 cyclostationary line

find_rate

Find symbol rate (as a fraction of the sample rate) from IQ samples

raised_cosine_psd

The power spectrum of RRC-shaped symbols (|RRC|^2, a raised cosine) at frequencies f [Hz], 1 in the flat part

nearest_rolloff

The standard roll-off (ROLLOFFS) nearest a measured one

find_rolloff

The roll-off of an RRC-shaped signal from its spectrum: (beta, residual)

find_baud

find_baud(x, Fs, lo=None, hi=None, pad=4)

Find the symbol rate from IQ samples using the |x|^2 cyclostationary line

lo/hi: search range in Hz [Fs/16, Fs/2.5] returns (baud, strength). Strength is the line over the local floor, a few is noise. Under 2.5 samples a symbol the line is at Fs/2.5 or above, and at 2 |x|^2 aliases it onto Fs/2: with the default range and no line over CLEAR_LINE, x is interpolated to twice its rate (in frequency) and Fs/2.5 to Fs/1.5 searched there too, its line taken when clear, stronger and no wider than the signal (16QAM at exactly 2 samples a symbol read a noise peak as its rate)

Source code in src/rpps/sync/rate.py
def find_baud(x, Fs, lo=None, hi=None, pad=4):
    """Find the symbol rate from IQ samples using the |x|^2 cyclostationary line

    lo/hi: search range in Hz [Fs/16, Fs/2.5]
    returns (baud, strength). Strength is the line over the local floor, a few is noise.
    Under 2.5 samples a symbol the line is at Fs/2.5 or above, and at 2 |x|^2 aliases it onto Fs/2: with the default
    range and no line over CLEAR_LINE, x is interpolated to twice its rate (in frequency) and Fs/2.5 to Fs/1.5 searched
    there too, its line taken when clear, stronger and no wider than the signal (16QAM at exactly 2 samples a symbol read a noise peak as its rate)
    """
    n = len(x)
    if n < 256:
        return 0.0, 0.0
    got = _line(x, Fs, Fs/16 if lo is None else lo, Fs/2.5 if hi is None else hi, pad)
    if hi is None and got[1] < CLEAR_LINE:
        X = np.fft.fft(np.asarray(x, dtype=np.complex128))
        h = n//2
        Z = np.zeros(2*n, np.complex128)
        Z[:h], Z[2*n - (n - h):] = X[:h], X[h:]
        up = _line(np.fft.ifft(Z), 2*Fs, Fs/2.5, Fs/1.5, pad)
        # Clear on its own (a weak true line beats noise up there), and a signal as wide as such a rate: a narrow one
        # shows lines at Fs/2 that are no rate of its (a channel's own filtering)
        if up[1] >= CLEAR_LINE and up[1] > got[1] and _width(X, Fs) >= 0.7*up[0]:
            return up
    return got

find_rate

find_rate(syms)

Find symbol rate (as a fraction of the sample rate) from IQ samples

Source code in src/rpps/sync/rate.py
def find_rate(syms):
    """Find symbol rate (as a fraction of the sample rate) from IQ samples"""
    return find_baud(syms, 1.0)[0]

raised_cosine_psd

raised_cosine_psd(f, baud, beta)

The power spectrum of RRC-shaped symbols (|RRC|^2, a raised cosine) at frequencies f [Hz], 1 in the flat part

Source code in src/rpps/sync/rate.py
def raised_cosine_psd(f, baud, beta):
    """The power spectrum of RRC-shaped symbols (|RRC|^2, a raised cosine) at frequencies f [Hz], 1 in the flat part"""
    a = np.abs(np.asarray(f, dtype=np.float64))/baud
    lo, hi = (1 - beta)/2, (1 + beta)/2
    out = np.where(a <= lo, 1.0, 0.0)
    if beta > 0:
        mid = (a > lo) & (a < hi)
        out = np.where(mid, 0.5*(1 + np.cos(np.pi/beta*(a - lo))), out)
    return out

nearest_rolloff

nearest_rolloff(beta)

The standard roll-off (ROLLOFFS) nearest a measured one

Source code in src/rpps/sync/rate.py
def nearest_rolloff(beta):
    """The standard roll-off (ROLLOFFS) nearest a measured one"""
    return min(ROLLOFFS, key=lambda r: abs(r - beta))

find_rolloff

find_rolloff(x, Fs, baud, cfo=0.0, nfft=None, grid=ROLLOFF_GRID)

The roll-off of an RRC-shaped signal from its spectrum: (beta, residual)

A Welch spectrum of x (the signal at cfo Hz from x's centre, baud symbols a second, some floor beside it) fitted by a raised cosine of each beta in grid plus a flat floor, each by least squares in its level and floor; the beta whose fit leaves the least (residual: its rms over the signal's level). It measures the composite edge: a transponder or receiver filter that steepens the edges reads as a smaller beta than the pulse's. Matched-filter likelihoods can't tell 0.05 from 0.15 (rpps.sync.detect names 0.15 for both); the edges can: 8192 symbols at 10 dB read 0.05, 0.10, 0.20, 0.35 as 0.068, 0.109, 0.201, 0.39 (+-0.01 .. 0.05), each nearest its own of ROLLOFFS.

Source code in src/rpps/sync/rate.py
def find_rolloff(x, Fs, baud, cfo=0.0, nfft=None, grid=ROLLOFF_GRID):
    """The roll-off of an RRC-shaped signal from its spectrum: (beta, residual)

    A Welch spectrum of x (the signal at `cfo` Hz from x's centre, `baud` symbols a second, some floor beside it) fitted
    by a raised cosine of each beta in `grid` plus a flat floor, each by least squares in its level and floor; the beta
    whose fit leaves the least (residual: its rms over the signal's level). It measures the composite edge: a transponder
    or receiver filter that steepens the edges reads as a smaller beta than the pulse's. Matched-filter likelihoods can't
    tell 0.05 from 0.15 (rpps.sync.detect names 0.15 for both); the edges can: 8192 symbols at 10 dB read 0.05, 0.10,
    0.20, 0.35 as 0.068, 0.109, 0.201, 0.39 (+-0.01 .. 0.05), each nearest its own of ROLLOFFS."""
    x = np.asarray(x)
    if nfft is None: # bins of a 64th of the rate or finer (a 0.05 edge is 3 of them; finer bins average fewer segments
        nfft = int(min(2**16, 2**np.ceil(np.log2(64*Fs/baud)), max(64, 2**np.floor(np.log2(max(len(x)//8, 64))))))
    n = len(x)//nfft*nfft
    if n == 0:
        return None, None
    w = np.hanning(nfft)
    P = np.mean(np.abs(np.fft.fft(x[:n].reshape(-1, nfft)*w, axis=1))**2, axis=0)
    f = np.fft.fftfreq(nfft, 1/Fs) - cfo
    f = (f + Fs/2) % Fs - Fs/2
    use = np.abs(f) < min(0.8*baud, 0.5*Fs) # the signal and its edges, with a little floor
    f, P = f[use], P[use]
    best = (np.inf, None)
    for beta in grid:
        h = raised_cosine_psd(f, baud, beta)
        A = np.stack((h, np.ones_like(h)), axis=1)
        coef, *_ = np.linalg.lstsq(A, P, rcond=None)
        r = float(np.sqrt(np.mean((A @ coef - P)**2))/max(coef[0], 1e-30))
        if r < best[0]:
            best = (r, float(beta))
    return best[1], best[0]

squelch

Squelch: detects that a signal is present, and gates the stream on it

Classes:

Name Description
Squelch

Silence the signal while it is quieter than threshold_db (power, dB re 1.0), with hysteresis

Functions:

Name Description
gate

Hysteresis: open where level > hi, closed where level <= lo, else as at the sample before (was_open before the

Squelch

Squelch(threshold_db=-40.0, hysteresis_db=3.0, alpha=0.01)

Bases: Stage

Silence the signal while it is quieter than threshold_db (power, dB re 1.0), with hysteresis

The level follows a running average of the power (alpha of the gap a sample, from the first sample on: an IIR section), so a brief dip doesn't close it. It opens where the level is over the open threshold, closes where it is at or under the close one, and in between stays as it was: the last of those events, carried forward (no loop over the samples).

Source code in src/rpps/sync/squelch.py
def __init__(self, threshold_db=-40.0, hysteresis_db=3.0, alpha=0.01):
    self.open_db = threshold_db
    self.close_db = threshold_db - hysteresis_db
    self.alpha = alpha

gate

gate(level, lo, hi, was_open=False)

Hysteresis: open where level > hi, closed where level <= lo, else as at the sample before (was_open before the first): each sample takes the last decisive one's state

Source code in src/rpps/sync/squelch.py
def gate(level, lo, hi, was_open=False):
    """Hysteresis: open where level > hi, closed where level <= lo, else as at the sample before (`was_open` before the
    first): each sample takes the last decisive one's state"""
    level = np.asarray(level)
    up, down = level > hi, level <= lo
    decisive = up | down
    last = np.maximum.accumulate(np.where(decisive, np.arange(len(level)), -1)) if len(level) else np.zeros(0, int)
    return np.where(last >= 0, up[np.maximum(last, 0)], bool(was_open))

tone

A phase-locked tone: the oscillator a pilot sets (FM stereo's 19 kHz, ATSC's pilot), and the signal mixed with it

Classes:

Name Description
ToneLock

Lock an oscillator to a steady tone near f0 Hz, and mix the stream with its harmonic

ToneLock

ToneLock(f0, win=16384, kp=0.4, ki=0.05, harmonic=1, min_level=0.0, lock_level=0.0, lock_err=0.5, min_part=0.25, history=4096)

Bases: Stage

Lock an oscillator to a steady tone near f0 Hz, and mix the stream with its harmonic

A block-rate PLL: every win samples (windows at absolute positions, so the block cut does not matter) the tone's phase is measured against the oscillator, which then corrects its phase (kp) and frequency (ki). Output, from the oscillator as it was over each window: complex input: x exp(-j h phase), the tone (h = 1) moved to DC (ATSC: the pilot locks the carrier) real input: 2 x cos(h phase), a product detector at the harmonic (FM stereo: h = 2, the L-R subcarrier at 38 kHz)

min_level: below this tone level the loop holds (a station with no pilot leaves noise there); lock_level and lock_err [rad] decide locked. min_part: at the stream's end, a last window this full still corrects. The state: level (the tone's amplitude: 2|z| for a real input, |z| for complex), err [rad], locked, and the last history windows' errs and levels.

Source code in src/rpps/sync/tone.py
def __init__(self, f0, win=16384, kp=0.4, ki=0.05, harmonic=1, min_level=0.0, lock_level=0.0, lock_err=0.5,
             min_part=0.25, history=4096):
    if win < 1:
        raise ValueError("ToneLock: win is at least one sample")
    self.f0, self.win, self.kp, self.ki, self.harmonic = float(f0), int(win), kp, ki, harmonic
    self.min_level, self.lock_level, self.lock_err, self.min_part, self.history = min_level, lock_level, lock_err, min_part, history

track

Block-rate tracking (rpps.sync): a slow loop run once per window over the window estimates

A first-class estimator measures a parameter on each window (block estimation); this carries the parameter and its rate from window to window, gating outliers, so a drifting clock or carrier is followed without a staircase: the value at any position is at(t), a line through the last update. It is a critically damped second-order loop: each window's error (measured minus predicted, wrapped to the parameter's period) moves the value by 2*bw of itself and the rate by bw**2 of it per window. bw is the loop's natural frequency in radians per window: smaller is quieter, larger follows faster drift.

The state is a SimpleNamespace (new()), kept in the estimating stage's stream state, so a re-run can copy it.

Functions:

Name Description
new

A tracker that has seen nothing: started False until the first update

wrap

x wrapped to [-period/2, period/2)

at

The tracked value at position t (any position: the correction is evaluated per item, not per window)

line_phasor

exp(-j (phi0 + rate i)) for i in 0 .. length-1: a phase line turned into a phasor with no exponential per item. Each

line_parts

(starts, local) of line_phasor: item i's phasor is starts[i // len(local)]*local[i % len(local)] (a device kernel

update

A window's measurement (modulo period when given) at position t, its centre. rate: a measured rate to start from

miss

A window gated out: the tracker coasts on its rate

windows

Hold x and give each window ready: (a0, b, seg) for stream positions [a0, b) of [kW, (k+1)W). On a flush the

keep

Let go of the items held before stream position pos (at most all of them)

new

new()

A tracker that has seen nothing: started False until the first update

Source code in src/rpps/sync/track.py
def new():
    """A tracker that has seen nothing: `started` False until the first update"""
    return SimpleNamespace(started=False, value=0.0, rate=0.0, at=0.0, windows=0, missed=0)

wrap

wrap(x, period)

x wrapped to [-period/2, period/2)

Source code in src/rpps/sync/track.py
def wrap(x, period):
    """x wrapped to [-period/2, period/2)"""
    return (x + period/2) % period - period/2

at

at(tr, t)

The tracked value at position t (any position: the correction is evaluated per item, not per window)

Source code in src/rpps/sync/track.py
def at(tr, t):
    """The tracked value at position t (any position: the correction is evaluated per item, not per window)"""
    return tr.value + tr.rate*(t - tr.at)

line_phasor

line_phasor(phi0, rate, length)

exp(-j (phi0 + rate i)) for i in 0 .. length-1: a phase line turned into a phasor with no exponential per item. Each block of about sqrt(length) items is one start phasor times the same short vector of exponentials, so it costs two multiplications an item and about 2 sqrt(length) exponentials, and agrees with the direct exponential to about 1e-14

Source code in src/rpps/sync/track.py
def line_phasor(phi0, rate, length):
    """exp(-j (phi0 + rate i)) for i in 0 .. length-1: a phase line turned into a phasor with no exponential per item. Each
    block of about sqrt(length) items is one start phasor times the same short vector of exponentials, so it costs two
    multiplications an item and about 2 sqrt(length) exponentials, and agrees with the direct exponential to about 1e-14"""
    if length <= 0:
        return np.zeros(0, np.complex128)
    starts, local = line_parts(phi0, rate, length)
    return (starts[:, None]*local[None, :]).reshape(-1)[:length]

line_parts

line_parts(phi0, rate, length)

(starts, local) of line_phasor: item i's phasor is starts[i // len(local)]*local[i % len(local)] (a device kernel reads the line this way, the exponentials made on the host in double)

Source code in src/rpps/sync/track.py
def line_parts(phi0, rate, length):
    """(starts, local) of `line_phasor`: item i's phasor is starts[i // len(local)]*local[i % len(local)] (a device kernel
    reads the line this way, the exponentials made on the host in double)"""
    block = max(16, int(max(length, 1)**0.5))
    nb = -(-max(length, 1)//block)
    return np.exp(-1j*(phi0 + rate*block*np.arange(nb))), np.exp(-1j*rate*np.arange(block))

update

update(tr, measured, t, period=None, bw=0.25, rate=None)

A window's measurement (modulo period when given) at position t, its centre. rate: a measured rate to start from

Source code in src/rpps/sync/track.py
def update(tr, measured, t, period=None, bw=0.25, rate=None):
    """A window's measurement (modulo `period` when given) at position t, its centre. rate: a measured rate to start from"""
    if not tr.started:
        tr.started, tr.value, tr.at = True, float(measured), float(t)
        tr.rate = 0.0 if rate is None else float(rate)
        tr.windows, tr.missed = 1, 0
        return 0.0
    dt = t - tr.at
    pred = at(tr, t)
    e = measured - pred
    if period is not None:
        e = wrap(e, period)
    tr.value, tr.at = pred + 2*bw*e, float(t)
    if dt > 0:
        tr.rate += bw*bw*e/dt
    tr.windows += 1
    tr.missed = 0
    return float(e)

miss

miss(tr, t)

A window gated out: the tracker coasts on its rate

Source code in src/rpps/sync/track.py
def miss(tr, t):
    """A window gated out: the tracker coasts on its rate"""
    if tr.started:
        tr.value, tr.at = at(tr, t), float(t)
        tr.missed += 1

windows

windows(st, x, meta, W)

Hold x and give each window ready: (a0, b, seg) for stream positions [a0, b) of [kW, (k+1)W). On a flush the last, partial window comes too. st carries buf (the items held from position base), base, k and W: None until the first block sets them. Afterwards call keep(st, pos) to let go of what lies before pos

Source code in src/rpps/sync/track.py
def windows(st, x, meta, W):
    """Hold x and give each window ready: (a0, b, seg) for stream positions [a0, b) of [k*W, (k+1)*W). On a flush the
    last, partial window comes too. `st` carries `buf` (the items held from position `base`), `base`, `k` and `W`:
    None until the first block sets them. Afterwards call `keep(st, pos)` to let go of what lies before pos"""
    if st.base is None:
        st.base, st.W, st.k = meta.pos, W, meta.pos//W
    st.buf = np.concatenate((st.buf, np.asarray(x, dtype=st.buf.dtype)))
    end = st.base + len(st.buf)
    while True:
        a, b = st.k*st.W, (st.k + 1)*st.W
        if b > end:
            if not (meta.flush and a < end):
                return
            b = end
        a0 = max(a, st.base)
        yield a0, b, st.buf[a0 - st.base:b - st.base]
        st.k += 1
        if b >= end:
            return

keep

keep(st, pos)

Let go of the items held before stream position pos (at most all of them)

Source code in src/rpps/sync/track.py
def keep(st, pos):
    """Let go of the items held before stream position pos (at most all of them)"""
    pos = min(max(pos, st.base), st.base + len(st.buf))
    st.buf, st.base = st.buf[pos - st.base:], pos

rpps.sync.loops

Second class: per-sample loops (rpps.sync)

Each updates its estimate once a sample or a symbol, carrying it from one to the next. Block estimation tracked across windows (rpps.sync's first class) replaces them in the profiles and examples; they stay for signals and conditions it does not suit, as references, and for comparison. Each runs in the C++ kernels when they are built (rpps._native), with its Python loop as the reference. Their loop filter is pll.PILoop, its gains from a noise bandwidth (pll.loop_gains).

Loop Estimates First-class counterpart
MM symbol timing: Mueller & Muller (ted="mm", decisions) or Gardner ("gardner"), interpolated per symbol time.OerderMeyr, time.MatTrack
TLL symbol timing: a PI loop (pll.PILoop) around a detector from ted (zero crossing, early-late) time.OerderMeyr, time.MatTrack
Costas carrier phase and frequency, per symbol: M-PSK, or decisions on any constellation's points phase.MPower, phase.DDCarrier
AGC the gain, sample by sample (mu, linear or in logs) rpps.sync.AGC (the level per window)
PeakAGC the peak, followed and decayed sample by sample rpps.sync.PeakAGC (closed form, the same output)
Squelch whether a signal is there, the level followed sample by sample rpps.sync.Squelch (an IIR section, the same output)
LMS equalizer taps, per symbol: least mean squares against training, then decisions equalize.BlockLS
CMA equalizer taps, per symbol: constant modulus, blind equalize.BlockLS (blind=True)

Modules:

Name Description
agc

Automatic gain control as per-sample loops

costas

The Costas loop: carrier phase and frequency followed per symbol (rpps.sync.loops)

equalize

Adaptive equalizers, updated symbol by symbol (second class): symbols + rp.sync.loops.CMA(11), rp.sync.loops.LMS

mm

Mueller & Muller and Gardner timing recovery: a per-symbol loop (rpps.sync.loops)

pll

Phase Locked Loop helpers

squelch

Squelch as a per-sample loop: the level and the gate decided sample by sample

ted

Timing error detectors: the error a timing loop (rpps.sync.loops.TLL) steers by, from samples around a symbol's instant

tll

Timing locked loop: a per-symbol loop around a timing error detector (rpps.sync.loops.ted)

agc

Automatic gain control as per-sample loops

R = reference level

x[n] = input signal z[n] = a[n-1] * x[n] controlled output e[n] = R - |z[n]| (linear) or log(R) - log|z[n]| (log) a[n] = a[n-1] + mu * e[n] (linear) or a[n-1] * exp(mu * e[n]) (log)

The gain is carried across blocks, so any block length gives the same stream. The first-class rpps.sync.AGC measures the level per window instead; rpps.sync.PeakAGC is PeakAGC here in closed form (the same output).

Classes:

Name Description
PeakAGC

Gain from the peak, followed sample by sample: |x| is followed instantly upward and decays by decay per sample,

AGC

Feedback AGC: block + rp.sync.loops.AGC(1.0, 0.01)

PeakAGC

PeakAGC(target=1.0, decay=0.999, floor=1e-06)

Bases: Stage

Gain from the peak, followed sample by sample: |x| is followed instantly upward and decays by decay per sample, and the signal is scaled so that peak sits at target

Source code in src/rpps/sync/loops/agc.py
def __init__(self, target=1.0, decay=0.999, floor=1e-6):
    self.target, self.decay, self.floor = float(target), float(decay), float(floor)

AGC

AGC(target=1.0, mu=0.01, log=True, min_gain=0.0, max_gain=np.inf, init=1.0)

Bases: Stage

Feedback AGC: block + rp.sync.loops.AGC(1.0, 0.01)

target: output amplitude R mu: loop rate (per sample). Larger tracks faster and ripples more log: adapt the gain in the log domain, so the loop speed doesn't depend on the signal level max_gain/min_gain: limits on the gain

Source code in src/rpps/sync/loops/agc.py
def __init__(self, target=1.0, mu=0.01, log=True, min_gain=0.0, max_gain=np.inf, init=1.0):
    self.target = target
    self.mu = mu
    self.log = log
    self.min = min_gain
    self.max = max_gain
    self.init = init

costas

The Costas loop: carrier phase and frequency followed per symbol (rpps.sync.loops)

Classes:

Name Description
Costas

Costas loop: symbols + rp.sync.loops.Costas.from_bandwidth(0.02, order=4). Settings live here, freq and pha live in meta.state_of(costas)

Costas

Costas(alpha, beta, order=2, offset=0.0, points=None)

Bases: Stage

Costas loop: symbols + rp.sync.loops.Costas.from_bandwidth(0.02, order=4). Settings live here, freq and pha live in meta.state_of(costas)

The error is normalized by the symbol amplitude, so alpha/beta don't depend on signal level

alpha, beta: proportional and integral gain (see from_bandwidth) order: 2 (BPSK), 4 (QPSK, points at 45 degrees) or any M >= 3 for M-PSK with a point at offset radians points: any constellation's points instead (APSK, QAM): the error is the angle to the nearest one, the loop decision directed (in Python: the C++ kernel knows M-PSK only); order is then len(points)

Methods:

Name Description
from_bandwidth

Loop gains from a noise bandwidth normalised to the symbol rate (0.01-0.05 typical)

Source code in src/rpps/sync/loops/costas.py
def __init__(self, alpha, beta, order=2, offset=0.0, points=None):
    """alpha, beta: proportional and integral gain (see `from_bandwidth`)
    order: 2 (BPSK), 4 (QPSK, points at 45 degrees) or any M >= 3 for M-PSK with a point at `offset` radians
    points: any constellation's points instead (APSK, QAM): the error is the angle to the nearest one, the loop
    decision directed (in Python: the C++ kernel knows M-PSK only); `order` is then len(points)"""
    self.alpha = alpha
    self.beta = beta
    if points is not None:
        self.err_func = _oPoints(points)
        order = len(np.ravel(points))
    elif order == 2:
        self.err_func = _o2
    elif order == 4:
        self.err_func = _o4
    elif order >= 3:
        self.err_func = _oM(order, offset)
    else:
        raise ValueError(f"Costas order must be 2 or more, got {order}")
    self.order = int(order)
    self.offset = float(offset)
    self._builtin = self.err_func if points is None else None # points, or a replaced err_func, run in Python
from_bandwidth classmethod
from_bandwidth(bw, order=2, damping=0.7071, offset=0.0, points=None)

Loop gains from a noise bandwidth normalised to the symbol rate (0.01-0.05 typical)

Source code in src/rpps/sync/loops/costas.py
@classmethod
def from_bandwidth(cls, bw, order=2, damping=0.7071, offset=0.0, points=None):
    """Loop gains from a noise bandwidth normalised to the symbol rate (0.01-0.05 typical)"""
    from .pll import loop_gains
    return cls(*loop_gains(bw, damping), order=order, offset=offset, points=points)

equalize

Adaptive equalizers, updated symbol by symbol (second class): symbols + rp.sync.loops.CMA(11), rp.sync.loops.LMS

Each makes one output per symbol from sps input samples per symbol (1, or 2 for a fractionally spaced equalizer). The taps carry across blocks, so any block length gives the same stream. First class: rp.sync.equalize.BlockLS, the taps solved by least squares per window (blind, by least squares constant modulus, until the eye opens).

Classes:

Name Description
CMA

Constant modulus algorithm: blind, for constant-envelope modulations (PSK, FSK) -- it fixes ISI but not rotation

LMS

Least mean squares against a training sequence for the first symbols, then against the nearest point of

CMA

CMA(taps=11, mu=0.005, sps=None, modulus=1.0)

Bases: _Equalizer

Constant modulus algorithm: blind, for constant-envelope modulations (PSK, FSK) -- it fixes ISI but not rotation

modulus: the symbol amplitude it steers towards (1.0)

Source code in src/rpps/sync/loops/equalize.py
def __init__(self, taps=11, mu=0.005, sps=None, modulus=1.0):
    super().__init__(taps, mu, sps)
    self.R = modulus**2

LMS

LMS(taps=11, mu=0.01, sps=None, points=None, training=None)

Bases: _Equalizer

Least mean squares against a training sequence for the first symbols, then against the nearest point of points (decision directed). Needs a carrier that is already locked

eq = rp.sync.loops.LMS(11, points=rp.symbol.load("QPSK").points, training=known_symbols)

With neither, the constellation is the detected one (meta.det, see rp.sync.Acquire), so after the carrier correction: ... + rp.sync.phase.FFCarrier() + rp.sync.loops.LMS(7, 0.002).

Source code in src/rpps/sync/loops/equalize.py
def __init__(self, taps=11, mu=0.01, sps=None, points=None, training=None):
    super().__init__(taps, mu, sps)
    self.points = None if points is None else np.asarray(points, dtype=np.complex64)
    self.training = None if training is None else np.asarray(training, dtype=np.complex64)

mm

Mueller & Muller and Gardner timing recovery: a per-symbol loop (rpps.sync.loops)

Classes:

Name Description
MM

Mueller & Muller timing recovery

MM

MM(alpha=0.3, est=0.0, interp=32, biphase=False, ted='mm')

Bases: Stage

Mueller & Muller timing recovery

The whole block is interpolated once, then the optimal sample is picked from the interpolated block. The timing estimate is kept in [0, 1) (fractional sample offset); its integer part is moved into the input index.

Settings live here, the loop state (est, history...) lives in meta.state_of(mm).

"mm" (Mueller & Muller, decision directed) or "gardner" (needs no decisions, works for any modulation,

wants at least 2 samples per symbol)

biphase: Biphase (Manchester) symbols, after their matched filter, have two power peaks per symbol and M&M is happy at the weaker one. Use early-late on power, and hop half a symbol if the other peak is stronger.

Source code in src/rpps/sync/loops/mm.py
def __init__(self, alpha=0.3, est=0.0, interp=32, biphase=False, ted="mm"):
    if ted not in ("mm", "gardner"):
        raise ValueError(f"ted must be mm or gardner, not {ted!r}")
    self.ted = ted
    self.alpha = alpha
    self.est = est # Initial estimate
    self.interp = up.Sinc(interp)
    self.biphase = biphase

pll

Phase Locked Loop helpers

Composed of: - Error detector, (eD[n]), error detector output - Loop filter, (eF[n]), filter output - Generator, (eC[n]), estimate - Accumulator - eC[n] = (eC[n-1] + K0 * eF[n-1] mod [max])

loop_gains designs the filter from a bandwidth, which is how Costas and the timing loops should be tuned; PILoop is the filter.

Classes:

Name Description
PILoop

Proportional-integral loop filter: eF[n] = KpeD[n] + (sum of KieD)

Functions:

Name Description
loop_gains

Proportional and integral gains (alpha, beta) of a second order loop

K_fs

(Kp, Ki) for a loop of noise bandwidth Bn [Hz] running at Fs [Hz]

K_sr

(Kp, Ki) for a loop of noise bandwidth Bn [Hz] that updates once per symbol (sr: symbol rate [Hz])

PILoop

PILoop(Kp, Ki)

Proportional-integral loop filter: eF[n] = KpeD[n] + (sum of KieD)

Source code in src/rpps/sync/loops/pll.py
def __init__(self, Kp, Ki):
    self.Kp = Kp
    self.Ki = Ki
    self.integ = 0.0

loop_gains

loop_gains(bw, damping=0.7071, Kd=1.0, K0=1.0)

Proportional and integral gains (alpha, beta) of a second order loop

bw: loop noise bandwidth, normalised to the rate the loop runs at (0.01-0.05 is typical: 1-5 % of the rate) damping: damping factor (1/sqrt(2); 0.5-2.0) Kd: detector gain, K0: generator gain

Source code in src/rpps/sync/loops/pll.py
def loop_gains(bw, damping=0.7071, Kd=1.0, K0=1.0):
    """Proportional and integral gains (alpha, beta) of a second order loop

    bw: loop noise bandwidth, normalised to the rate the loop runs at (0.01-0.05 is typical: 1-5 % of the rate)
    damping: damping factor (1/sqrt(2); 0.5-2.0)
    Kd: detector gain, K0: generator gain
    """
    theta = bw/(damping + 1/(4*damping))
    den = 1 + 2*damping*theta + theta**2
    return 4*damping*theta/den/(Kd*K0), 4*theta**2/den/(Kd*K0)

K_fs

K_fs(Kd, K0, Df, Bn, Fs)

(Kp, Ki) for a loop of noise bandwidth Bn [Hz] running at Fs [Hz]

Source code in src/rpps/sync/loops/pll.py
def K_fs(Kd, K0, Df, Bn, Fs):
    """(Kp, Ki) for a loop of noise bandwidth Bn [Hz] running at Fs [Hz]"""
    Kp = (1/(Kd*K0)) * ((4*Df)/(Df+(1/(4*Df)))) * (Bn/Fs)
    Ki = (1/(Kd*K0)) * (4/(Df+(1/(4*Df)))**2) * (Bn/Fs)**2
    return Kp, Ki

K_sr

K_sr(Kd, K0, Df, Bn, sr, sps)

(Kp, Ki) for a loop of noise bandwidth Bn [Hz] that updates once per symbol (sr: symbol rate [Hz])

Source code in src/rpps/sync/loops/pll.py
def K_sr(Kd, K0, Df, Bn, sr, sps):
    """(Kp, Ki) for a loop of noise bandwidth Bn [Hz] that updates once per symbol (sr: symbol rate [Hz])"""
    Kp = (1/(Kd*K0*sps)) * ((4*Df)/(Df+(1/(4*Df)))) * (Bn/sr)
    Ki = (1/(Kd*K0*sps**2)) * (4/(Df+(1/(4*Df)))**2) * (Bn/sr)**2
    return Kp, Ki

squelch

Squelch as a per-sample loop: the level and the gate decided sample by sample

Classes:

Name Description
Squelch

Silence the signal while it is quieter than threshold_db (power, dB re 1.0), with hysteresis

Squelch

Squelch(threshold_db=-40.0, hysteresis_db=3.0, alpha=0.01)

Bases: Stage

Silence the signal while it is quieter than threshold_db (power, dB re 1.0), with hysteresis

The level follows a running average of the power, updated sample by sample, so a brief dip doesn't close it. The same output as rpps.sync.Squelch, which runs the average as an IIR section.

Source code in src/rpps/sync/loops/squelch.py
def __init__(self, threshold_db=-40.0, hysteresis_db=3.0, alpha=0.01):
    self.open_db = threshold_db
    self.close_db = threshold_db - hysteresis_db
    self.alpha = alpha

ted

Timing error detectors: the error a timing loop (rpps.sync.loops.TLL) steers by, from samples around a symbol's instant

Both need no decisions and no carrier (non-data aided) and at least 2 samples a symbol. Positive: the instant is early (the loop moves it later). Decision-directed Mueller & Muller is part of rpps.sync.loops.MM.

Functions:

Name Description
zx

Zero crossing (Gardner): early and late the instants of two symbols in a row, mid the sample half way between

el

Early-late: at the symbol's instant, before and after half a symbol either side (the slope of |z|^2 there)

zx

zx(early, mid, late)

Zero crossing (Gardner): early and late the instants of two symbols in a row, mid the sample half way between

Source code in src/rpps/sync/loops/ted.py
def zx(early, mid, late):
    """Zero crossing (Gardner): `early` and `late` the instants of two symbols in a row, `mid` the sample half way between"""
    return np.real(mid*(np.conj(early) - np.conj(late)))

el

el(before, at, after)

Early-late: at the symbol's instant, before and after half a symbol either side (the slope of |z|^2 there)

Source code in src/rpps/sync/loops/ted.py
def el(before, at, after):
    """Early-late: `at` the symbol's instant, `before` and `after` half a symbol either side (the slope of |z|^2 there)"""
    return np.real(at*(np.conj(after) - np.conj(before)))

tll

Timing locked loop: a per-symbol loop around a timing error detector (rpps.sync.loops.ted)

Classes:

Name Description
TLL

Symbol timing by a timing locked loop: samples at sps in (after their matched filter), one symbol each out

TLL

TLL(sps=None, bw=0.01, damping=0.7071, name='timing', ted='zx')

Bases: Stage

Symbol timing by a timing locked loop: samples at sps in (after their matched filter), one symbol each out

symbols = matched + rp.sync.loops.TLL(sps=4, bw=0.01)

Second class (rpps.sync): a loop updated once per symbol. Each symbol is interpolated at its instant, and a timing error detector (ted: "zx", zero crossing (Gardner), on the symbol before it, the sample half way and this one; "el", early-late, on the samples half a symbol either side of this one) gives the timing error, which a proportional-integral loop filter (rpps.sync.loops.pll.PILoop, from bw as a fraction of the symbol rate) turns into the next instant. Needs no decisions and no carrier, so it runs before carrier recovery. Any sps over 1, fractional too, and any block cut. Estimates in stream.est[name]: the timing phase (samples) and the loop's rate correction.

Source code in src/rpps/sync/loops/tll.py
def __init__(self, sps=None, bw=0.01, damping=0.7071, name="timing", ted="zx"):
    if ted not in DETECTORS:
        raise ValueError(f"TLL: ted {ted!r}, one of {sorted(DETECTORS)}")
    self.sps, self.bw, self.damping, self.name, self.ted = sps, bw, damping, name, ted

rpps.sync.phase

Carrier frequency and phase, by block estimation (rpps.sync): MPower (M-th power: FFT acquisition, then per-window phase, tracked), DDCarrier / decided.follow (from decisions, any constellation: APSK, QAM), FFCarrier (Viterbi & Viterbi, per frame)

Modules:

Name Description
decided

Carrier phase from decisions, by block estimation tracked across windows: any constellation (APSK, QAM, PSK)

ff
mpower

decided

Carrier phase from decisions, by block estimation tracked across windows: any constellation (APSK, QAM, PSK)

Symbols are cut into windows of window at absolute positions. Each window is turned back by the phase the tracker (rpps.sync.track) predicts for it, and its residual is the angle of sum y conj(d), d the nearest point to y (the window's amplitude matched to the points' first), twice: the second time decided on symbols already closer to their points. The tracker carries phase and frequency to the next window, so the correction is a line per symbol and a frequency offset is followed. No loop over symbols: one per window.

Decisions are right only near the points: the phase has to start within half the points' closest angular spacing (16APSK's outer ring: 15 degrees), so this follows a carrier a preamble or a word has taken off, as a Costas loop on the same points would; it does not acquire one (MPower does, for M-fold symbols). follow(y, points) corrects a whole array; DDCarrier is the stream stage.

Classes:

Name Description
DDCarrier

Carrier phase and frequency from decisions on any constellation, block estimation tracked across windows

Functions:

Name Description
decide

The nearest of points to each of y

residual

The phase of y against its own decisions (its amplitude matched to the points'), refined iters times

follow

y (symbols, one each, a carrier near 0 already) with the phase its decisions show taken off: DDCarrier over the

DDCarrier

DDCarrier(points, window=32, bw=0.25, name='carrier')

Bases: Stage

Carrier phase and frequency from decisions on any constellation, block estimation tracked across windows

symbols + rp.sync.phase.DDCarrier(rp.symbol.load("apsk/dvbs2_16apsk", rate="2/3").points)

First class (rpps.sync); see the module. Symbols in (one a symbol), the same out. window symbols a window, bw the tracker's (rpps.sync.track), wide for the first windows while it pulls in. 32 symbols: on 16APSK with a drifting, noisy phase, 64 slipped a rotation once in 40 runs while the rate was being learned, 32 never. Latency: a window. Estimates in stream.est[name]: phase (rad), frequency (cycles a symbol), latency (symbols).

Source code in src/rpps/sync/phase/decided.py
def __init__(self, points, window=32, bw=0.25, name="carrier"):
    self.points = np.asarray(points, dtype=np.complex128).ravel()
    self.window, self.bw, self.name = int(window), bw, name
    if self.window < 2:
        raise ValueError("DDCarrier: a window of 2 symbols at least")

decide

decide(y, points)

The nearest of points to each of y

Source code in src/rpps/sync/phase/decided.py
def decide(y, points):
    """The nearest of `points` to each of y"""
    pts = np.asarray(points, dtype=np.complex128).ravel()
    flat = np.asarray(y).reshape(-1)
    out = np.empty(len(flat), np.complex128)
    for a in range(0, len(flat), CHUNK):
        u = flat[a:a + CHUNK]
        out[a:a + CHUNK] = pts[np.argmin(np.abs(u[:, None] - pts[None, :]), axis=1)]
    return out.reshape(np.shape(y))

residual

residual(y, points, iters=2)

The phase of y against its own decisions (its amplitude matched to the points'), refined iters times

Source code in src/rpps/sync/phase/decided.py
def residual(y, points, iters=2):
    """The phase of y against its own decisions (its amplitude matched to the points'), refined `iters` times"""
    pts = np.asarray(points, dtype=np.complex128).ravel()
    scale = np.sqrt(np.mean(np.abs(pts)**2)/max(float(np.mean(np.abs(y)**2)), 1e-30))
    e = 0.0
    for _ in range(iters):
        u = y*np.exp(-1j*e)
        e += float(np.angle(np.sum(u*np.conj(decide(u*scale, pts)))))
    return e

follow

follow(y, points, window=32, bw=0.25)

y (symbols, one each, a carrier near 0 already) with the phase its decisions show taken off: DDCarrier over the whole array

Source code in src/rpps/sync/phase/decided.py
def follow(y, points, window=32, bw=0.25):
    """y (symbols, one each, a carrier near 0 already) with the phase its decisions show taken off: `DDCarrier` over the
    whole array"""
    from ...base.data import Data
    y = np.asarray(y)
    if len(y) == 0:
        return y.astype(np.complex128)
    return np.asarray((Data(y.astype(np.complex64), sps=1, flush=True) + DDCarrier(points, window, bw)).data).astype(np.complex128)

ff

Classes:

Name Description
FFCarrier

Feed-forward carrier correction for M-fold symmetric (PSK) symbols. No loop

FFCarrier

FFCarrier(window=64)

Bases: Stage

Feed-forward carrier correction for M-fold symmetric (PSK) symbols. No loop

Takes the modulation order M, the constellation phase, the frequency offset and the gain from the detection in Meta (meta.det). Then per symbol: frequency: phase-continuous oscillator at the detected offset phase: Viterbi & Viterbi, the angle of the sum of y^M over the last window symbols, divided by M amplitude: the detected gain

window: symbols averaged for the phase. Longer is quieter, shorter follows drift better

Source code in src/rpps/sync/phase/ff.py
def __init__(self, window=64):
    self.window = window

mpower

Classes:

Name Description
MPower

Carrier frequency and phase of M-fold symmetric symbols by the M-th power, block estimation tracked across windows

Functions:

Name Description
offset_of

The angle of a constellation's mean point^M: what MPower takes off as offset

MPower

MPower(order=4, offset=0.0, window=0.001, min_symbols=1024, bw=0.25, gate=3.0, relock=4, name='carrier', device=False, acquire=16384)

Bases: Stage

Carrier frequency and phase of M-fold symmetric symbols by the M-th power, block estimation tracked across windows

symbols = timed + rp.sync.phase.MPower(order=4, offset=np.pi)     # QPSK at 45 degrees: its points^4 are -1

First class (rpps.sync). Windows sit at absolute stream positions, window seconds (at least min_symbols). The first window that shows the carrier acquires it: the FFT of y^M (zero padded) gives the frequency, |f| < 1/(2M) cycles per symbol, and the phase at its centre. After that each window measures the residual phase of y turned back by the tracked line, (angle(sum u^M) - offset) / M with u = y e^{-j phase} / |y|, and a block-rate loop (rpps.sync.track) carries phase and frequency on, so the correction is a line per symbol, with no staircase and no slips while the drift stays inside the loop. A window whose M-th power line is weaker than gate (its SNR: noise alone is about 1) is skipped; after relock of those in a row the carrier is acquired again from the FFT, its phase on the branch (of the M) nearest the line held till then, so the correction carries on without a jump. Acquiring wants gate more than the best of the FFT's N frequencies reaches on noise, sqrt(2 ln N): at an Es/N0 where the M-th power is lost in noise (DVB-S2 under 0 dB with M = 8) nothing is acquired and the symbols pass, for a preamble and pilots to take the phase. acquire: a line one window can't show is tried on the last acquire symbols together, once every that many windows (fixed positions): DVB-S2 at 8 dB under M = 8 wants about 8000. Tracking does the same: a window under the gate holds the line, and the last acquire symbols are measured together at those positions, so a carrier a window can't show is still tracked (each long measurement is one update; only a long one missing counts towards relock) rather than acquired again and again.

The phase is known modulo 2 pi / M: a preamble, a differential code or a polarity search takes the rest. order: M (a profile may change it with the modulation, live). offset: the angle of the constellation's mean point^M (0 for BPSK, 8PSK, and DVB-S2's pi/2-BPSK under M = 8; pi for QPSK at 45 degrees under M = 4). Until it acquires, symbols pass unchanged. Estimates in stream.est[name]: frequency (cycles per symbol), phase, SNR, latency (seconds). device: each window's measurement and correction on the GPU of rpps._accel.device() (CuPy, CUDA or ROCm/HIP; the host without one), the samples going up once a block; acquiring (an FFT, rarely) stays on the host, and the tracking is the host's, window by window.

Source code in src/rpps/sync/phase/mpower.py
def __init__(self, order=4, offset=0.0, window=1e-3, min_symbols=1024, bw=0.25, gate=3.0, relock=4, name="carrier",
             device=False, acquire=16384):
    self.order, self.offset, self.window, self.min_symbols = int(order), float(offset), window, min_symbols
    self.bw, self.gate, self.relock, self.name, self.device = bw, gate, relock, name, bool(device)
    self.acquire = int(acquire)

offset_of

offset_of(constellation, order)

The angle of a constellation's mean point^M: what MPower takes off as offset

Source code in src/rpps/sync/phase/mpower.py
def offset_of(constellation, order):
    """The angle of a constellation's mean point^M: what MPower takes off as `offset`"""
    pts = np.asarray(constellation.points)
    return float(np.angle(np.mean(pts**order)))

rpps.sync.time

Symbol timing: where to sample, by block estimation (rpps.sync). OerderMeyr (the square-law line, tracked across windows), MatTrack (the matched filter fused in and evaluated only at the instants, timing from its energy maximum, tracked across windows; on a GPU too), Mat (matrix matched filter, per block), Known when the timing is given

Modules:

Name Description
known

Known timing: the symbol instants given, not estimated (a profile's timing: known)

mat
matrack

MatTrack: the matched filter and symbol timing in one, tracked across windows (a profile's timing: mat)

om

known

Known timing: the symbol instants given, not estimated (a profile's timing: known)

Classes:

Name Description
Known

Timing that is known, not estimated (a loopback, a source whose timing is given): one sample per symbol at the pulse

Known

Known(sps, anchor=None)

Bases: Stage

Timing that is known, not estimated (a loopback, a source whose timing is given): one sample per symbol at the pulse peaks, which the group delay so far (meta.delay) places. Tracks the absolute input index of the next peak, so any block cut gives the same output.

With a matched filter fused in (fuse, which a profile does for the filter just before it) the filter is evaluated only at those instants, a dot product of its taps with the signal per symbol: sps times less work than filtering every sample and keeping every sps-th, the same symbols. The estimators that need the filter's output at every sample (Oerder & Meyr) have nothing to fuse

anchor: the name of a preamble (rpps.sync.Preamble) in the stream's estimates: the grid starts at its first symbol's peak, moved by the group delay added since (a burst's own timing; until the preamble is found nothing comes out)

Methods:

Name Description
fuse

Take over a matched filter (a FIR stage): this stage then also filters, at the instants it samples

Source code in src/rpps/sync/time/known.py
def __init__(self, sps, anchor=None):
    self.sps = sps
    self.anchor = anchor
    self.matched = None
fuse
fuse(matched)

Take over a matched filter (a FIR stage): this stage then also filters, at the instants it samples

Source code in src/rpps/sync/time/known.py
def fuse(self, matched):
    """Take over a matched filter (a FIR stage): this stage then also filters, at the instants it samples"""
    self.matched = matched

mat

Classes:

Name Description
Mat

Matrix matched filter and symbol timing

Functions:

Name Description
matrix_mf

Matched filter + symbol sampling as a (banded) matrix: y = W @ x

fits

Which centres have their whole matched-filter support in n samples (what matrix_mf reads)

centres_in

Symbol centres t0 + k*sps whose whole support fits in n samples

best_tau

Symbol timing in [0, sps) maximising the matched-filter output energy, from x[lo:hi]

Mat

Mat(beta=None, span=8, track=0.1)

Bases: Stage

Matrix matched filter and symbol timing

Needs meta.det (see rpps.sync.detect) for beta and the timing offset. Symbols are taken from a lattice t_next + k*sps in the (fractional) sps of Meta, then the lattice is nudged by a block-wise energy-maximum estimate (track = fraction of it applied) to follow the clock.

beta/span/track: settings; beta None takes the detected one.

Source code in src/rpps/sync/time/mat.py
def __init__(self, beta=None, span=8, track=0.1):
    self.beta = beta
    self.span = span
    self.track = track

matrix_mf

matrix_mf(x, centres, sps, beta=0.2, span=8)

Matched filter + symbol sampling as a (banded) matrix: y = W @ x

W[i, j] = rrc((j - centres[i]) / sps), so symbols are taken at any fractional instant and sps may be fractional. Only the 2spansps columns that matter are built per row. x[centres +/- span*sps] must exist (fits; IndexError otherwise). Weights have unit energy per row. Complex x runs in C++ when the kernels are loaded (rpps._native.matrix_mf: the rows computed and applied in one pass, never stored); the code below is the reference it agrees with to rounding.

Source code in src/rpps/sync/time/mat.py
def matrix_mf(x, centres, sps, beta=0.2, span=8):
    """Matched filter + symbol sampling as a (banded) matrix: y = W @ x

    W[i, j] = rrc((j - centres[i]) / sps), so symbols are taken at any fractional instant
    and sps may be fractional. Only the 2*span*sps columns that matter are built per row.
    x[centres +/- span*sps] must exist (`fits`; IndexError otherwise). Weights have unit energy per row.
    Complex x runs in C++ when the kernels are loaded (rpps._native.matrix_mf: the rows computed and applied in one
    pass, never stored); the code below is the reference it agrees with to rounding.
    """
    native = _accel.native
    if native is not None and isinstance(x, np.ndarray) and x.dtype in (np.complex64, np.complex128):
        return native.matrix_mf(np.ascontiguousarray(x), np.ascontiguousarray(centres, dtype=np.float64), float(sps),
                                float(beta), float(span))
    S = span * sps
    j0 = np.ceil(centres - S).astype(np.int64)
    lags = np.arange(int(np.ceil(2*S)) + 2)
    if len(j0) and (j0.min() < 0 or j0.max() + len(lags) > len(x)): # (numpy would wrap a negative index round)
        raise IndexError("matrix_mf: a symbol's support runs outside x")
    idx = j0[:, None] + lags
    w = _rrc_rows(j0 - np.asarray(centres, dtype=np.float64), lags, sps, beta)
    w /= np.sqrt(np.sum(w**2, axis=1, keepdims=True))
    return np.sum(w * x[idx], axis=1)

fits

fits(centres, n, sps, span=8)

Which centres have their whole matched-filter support in n samples (what matrix_mf reads)

Source code in src/rpps/sync/time/mat.py
def fits(centres, n, sps, span=8):
    """Which centres have their whole matched-filter support in n samples (what matrix_mf reads)"""
    S = span*sps
    j0 = np.ceil(np.asarray(centres, dtype=np.float64) - S)
    return (j0 >= 0) & (j0 + int(np.ceil(2*S)) + 2 <= n)

centres_in

centres_in(n, t0, sps, span=8)

Symbol centres t0 + k*sps whose whole support fits in n samples

Source code in src/rpps/sync/time/mat.py
def centres_in(n, t0, sps, span=8):
    """Symbol centres t0 + k*sps whose whole support fits in n samples"""
    last = n - span*sps - 5
    if last < t0:
        return np.zeros(0)
    return t0 + sps*np.arange(int((last - t0)//sps) + 1)

best_tau

best_tau(x, sps, beta=0.2, span=8, lo=0, hi=None, grid=16)

Symbol timing in [0, sps) maximising the matched-filter output energy, from x[lo:hi]

The symbol lattice is tau + k*sps in absolute sample index, so results from different segments of x are comparable. Returns (tau, mean |y|^2)

The matched filter runs once, as a convolution; its output is band-limited, so each of the grid candidate timings reads it at its own symbol instants with a 12-tap windowed sinc (math.interp.fractional: -56 dB at 2 samples a symbol), in chunks. A segment too short for the convolution's edges takes the filter matrix for each candidate (_best_tau_rows), which gives the same answer.

Source code in src/rpps/sync/time/mat.py
def best_tau(x, sps, beta=0.2, span=8, lo=0, hi=None, grid=16):
    """Symbol timing in [0, sps) maximising the matched-filter output energy, from x[lo:hi]

    The symbol lattice is tau + k*sps in absolute sample index, so results from different
    segments of x are comparable. Returns (tau, mean |y|^2)

    The matched filter runs once, as a convolution; its output is band-limited, so each of the `grid` candidate timings
    reads it at its own symbol instants with a 12-tap windowed sinc (math.interp.fractional: -56 dB at 2 samples a
    symbol), in chunks. A segment too short for the convolution's edges takes the filter matrix for each candidate
    (`_best_tau_rows`), which gives the same answer.
    """
    hi = len(x) if hi is None else hi
    L = int(np.ceil(span*sps))
    if hi - lo < 4*L + 8*sps:
        return _best_tau_rows(x, sps, beta, span, lo, hi, grid)
    h = rrc_pulse(np.arange(-L, L + 1)/sps, beta)
    h /= np.sqrt(np.sum(h**2))
    z = np.convolve(np.asarray(x[lo:hi], dtype=np.complex128), h, mode="valid") # z[i]: output at sample lo + L + i
    z = z.astype(np.complex64) # (the interpolator's native path; its error is far above single precision's)
    taps = 2*REACH
    t0, t1 = lo + L + REACH, lo + L + len(z) - REACH - 1 # Absolute positions the interpolator reads whole
    taus = np.arange(grid)*sps/grid
    ks = [np.arange(np.ceil((t0 - tau)/sps), np.ceil((t1 - tau)/sps)) for tau in taus]
    pos = np.concatenate([tau + k*sps for tau, k in zip(taus, ks)]) - (lo + L)
    count = np.array([len(k) for k in ks], dtype=np.float64)
    which = np.repeat(np.arange(grid), [len(k) for k in ks])
    energy = np.zeros(grid)
    for a in range(0, len(pos), TAU_CHUNK):
        y = fractional(z, pos[a:a + TAU_CHUNK], taps)
        energy += np.bincount(which[a:a + TAU_CHUNK], weights=(y.real.astype(np.float64)**2 + y.imag.astype(np.float64)**2),
                              minlength=grid)
    energy = np.divide(energy, count, out=np.zeros(grid), where=count > 0)
    g, d = peak(energy, circular=True, log=False)
    return ((g + d)*sps/grid) % sps, float(energy[g])

matrack

MatTrack: the matched filter and symbol timing in one, tracked across windows (a profile's timing: mat)

Classes:

Name Description
MatTrack

Matched filter and symbol timing in one: samples at sps in (before their matched filter, which a profile fuses in

MatTrack

MatTrack(sps=None, window=0.001, min_symbols=2048, bw=0.25, delta=None, grid=16, gate=0.02, relock=4, group=16, device=False, name='timing')

Bases: Stage

Matched filter and symbol timing in one: samples at sps in (before their matched filter, which a profile fuses in from the step before: fuse), one symbol each out. The matched filter is evaluated only at the instants read, a dot product of its taps with the samples at the four around each instant, cubic-interpolated: what filtering every sample and interpolating (Matched + OerderMeyr) gives there, sps times less filtering.

symbols = samples + rp.sync.time.MatTrack(sps=4, pulse=rrc)           # or a profile's {"timing": {"method": "mat"}}

The timing is a matrix matched filter's (as Mat, MatRRC): no decisions, no per-sample loop. Each window (window seconds, at least min_symbols symbols, at absolute stream positions) measures the filter's energy at the predicted instants and delta samples either side; the parabola's vertex is the timing error, and the block-rate loop (rpps.sync.track) carries the phase and the clock's rate on. The first window acquires the phase from grid phases a symbol (the energy's maximum), as does a window after relock misses; a window without a maximum is a miss (noise, a gap between bursts), the loop coasting through it.

Once the loop has settled (group windows), windows go in groups of group at fixed stream positions, each measured at the instants the loop predicted at its group's start, so a group is one batch of work (one launch on a device) and any block cut gives the same symbols; delta (default a quarter symbol) sets the range a measurement reads, which a settled loop stays well inside of over a group. device: the evaluation on the GPU of rpps._accel.device() (CuPy, CUDA or ROCm/HIP; numpy without one): only the samples go up and the symbols down. Estimates in stream.est[name]: phase (samples), ppm, windows, missed, latency (seconds).

Methods:

Name Description
fuse

Take over a matched filter (a FIR stage, the profile's wave shape receive side): it is evaluated here

Source code in src/rpps/sync/time/matrack.py
def __init__(self, sps=None, window=1e-3, min_symbols=2048, bw=0.25, delta=None, grid=16, gate=0.02, relock=4, group=16,
             device=False, name="timing"):
    self.sps, self.window, self.min_symbols, self.bw, self.delta = sps, window, min_symbols, bw, delta
    self.grid, self.gate, self.relock, self.group, self.device, self.name = int(grid), gate, int(relock), int(group), bool(device), name
    self.matched = None
fuse
fuse(matched)

Take over a matched filter (a FIR stage, the profile's wave shape receive side): it is evaluated here

Source code in src/rpps/sync/time/matrack.py
def fuse(self, matched):
    """Take over a matched filter (a FIR stage, the profile's `wave shape` receive side): it is evaluated here"""
    self.matched = matched

om

Classes:

Name Description
OerderMeyr

Symbol timing by square-law block estimation (Oerder & Meyr), tracked across windows: samples at sps in (after

OerderMeyr

OerderMeyr(sps=None, window=0.001, min_symbols=2048, bw=0.25, gate=2.0, name='timing', clock=True, device=False)

Bases: Stage

Symbol timing by square-law block estimation (Oerder & Meyr), tracked across windows: samples at sps in (after their matched filter), one symbol each out

symbols = matched + rp.sync.time.OerderMeyr()

First class (rpps.sync). Windows sit at absolute stream positions [kW, (k+1)W): W is window seconds, at least min_symbols symbols (the square-law line is weak: at roll-off 0.2 it is about 3% of the power, so it wants a few thousand samples). Each window's timing phase is the angle of sum |x[n]|^2 exp(-j 2 pi n / sps), and a block-rate loop (rpps.sync.track) carries the phase and the clock's rate (ppm: the transmitter's clock fast by that much) from window to window, so a clock some ppm off is followed and each symbol's instant comes from the line, not a step per window. A window whose line is weaker than gate (its SNR, |X| / sum|x|^2 * sqrt(n): noise alone is about 1) is skipped, the loop coasting through it (a gap between bursts). Symbols are interpolated from the samples (cubic, or a windowed sinc under 4 samples a symbol: rpps._effort.interp_taps); any sps from 1, fractional too (under 2: a 30 MBd carrier in 50 MS/s), and any block cut.

Latency: a window, as latency (seconds) in stream.est[name] with the phase, the rate (ppm) and the line's SNR. Nothing comes out before the first window that passes the gate. device: each window's sums and symbols on the GPU of rpps._accel.device() (CuPy, CUDA or ROCm/HIP; the host without one), the samples going up once a block; the tracking is the host's, window by window (under 4 samples a symbol the upsampled window is made on the host).

Source code in src/rpps/sync/time/om.py
def __init__(self, sps=None, window=1e-3, min_symbols=2048, bw=0.25, gate=2.0, name="timing", clock=True, device=False):
    self.sps, self.window, self.min_symbols, self.bw, self.gate, self.name = sps, window, min_symbols, bw, gate, name
    self.device = bool(device)
    self.clock = bool(clock) # False: the phase only, no clock rate (a burst a few windows long: two windows' phases