Skip to content

Wave

rpps.wave

Waveform layer: streaming stages between symbols and samples (data + stage)

Shape     symbols to samples, each symbol carrying a pulse (rp.signal.filters.load("pulse/..."): the definitions)
Matched   the pulse's matched filter
Stagger   offset one rail by part of a symbol (O-QPSK)
FM        a shaped level signal to a phase-continuous frequency-modulated one (FSK, GFSK, GMSK, C4FM)
FMDemod   its quadrature discriminator
demod     FM, AM or SSB audio from one block, no state, with FM deviation, AM depth and SINAD
loops     second class: AMDemod with its mean as a per-sample loop (the same output; a C++ kernel)

The pulses are definitions (config/pulse: halfsine, gaussian, rrc, rect), loaded by rp.signal.filters.load:

qpsk = rp.symbol.load("psk/qpsk")
wave = bits * qpsk + rp.wave.Shape(8, rp.signal.filters.load("pulse/halfsine/halfsine")) + rp.wave.Stagger()   # O-QPSK

Wave pairs

A profile's wave step runs as written on receive and inverted on transmit:

Step Receive (as written) Transmit (inverted)
shape, symbol pulse (rrc, rc, halfsine, rect) wave.Matched(pulse), unit gain at the instants wave.Shape(sps, pulse), polyphase
shape, frequency pulse (gaussian, FSK rect) none (the fm discriminator) wave.Shape(sps, pulse)
stagger Stagger("i", delay) Stagger("q", delay)
fm FMDemod + integrate over the symbol FM(h, step)
ofdm remove CP + FFT IFFT + CP

Whether a pulse is a symbol or a frequency pulse is the pulse definition's kind, not the profile's.

Modules:

Name Description
analog

Analog demodulation, carrier modulation to baseband: AM envelope and SSB as stream stages (FM is FMDemod), and demod,

fm
loops

Demodulation as per-sample loops (second class): AMDemod with its running mean run sample by sample, in the C++

ofdm
shape

Pulse shaping and its matched filter: the wave pair of a symbol pulse (rpps.wave, Wave pairs)

stagger

analog

Analog demodulation, carrier modulation to baseband: AM envelope and SSB as stream stages (FM is FMDemod), and demod, one block at a time with its measurements (FM deviation, AM depth, SINAD)

Classes:

Name Description
AMDemod

Envelope detector: |x| with the carrier (DC) removed by a slow running mean (alpha: how fast the mean follows, the

SSBDemod

Single sideband: keeps bw Hz of the upper (or lower) side of the carrier at 0 Hz and returns the audio (real)

Measurements

What demod measured on its block

Functions:

Name Description
demod

Demodulate one block of analog signal, centred at 0 Hz, and measure it: for a display that wants each frame on its own

AMDemod

AMDemod(alpha=0.001)

Bases: Stage

Envelope detector: |x| with the carrier (DC) removed by a slow running mean (alpha: how fast the mean follows, the fraction of the gap closed per sample); AMDemod(alpha=None) keeps the envelope as it is (on-off keying, pulse position: the levels themselves carry the bits)

Source code in src/rpps/wave/analog.py
def __init__(self, alpha=1e-3):
    self.alpha = alpha

SSBDemod

SSBDemod(bw=2800.0, sideband='usb', taps=201)

Bases: FIR

Single sideband: keeps bw Hz of the upper (or lower) side of the carrier at 0 Hz and returns the audio (real)

audio = baseband + rp.wave.SSBDemod(2800, "usb")

Source code in src/rpps/wave/analog.py
def __init__(self, bw=2800.0, sideband="usb", taps=201):
    if sideband not in ("usb", "lsb"):
        raise ValueError("sideband must be usb or lsb")
    self.bw, self.sideband, self.n = bw, sideband, taps | 1

Measurements

Measurements(kind, **kw)

What demod measured on its block

kind: fm, pm, am, usb or lsb. power_db: power in the channel (bw) [dB] offset_hz: FM and PM's carrier offset from 0 Hz (FM: the mean instantaneous frequency, PM: the slope of the phase); None for the others deviation_hz / deviation_rms_hz: FM peak (99.9th percentile) and rms deviation from that mean phase_dev_rad / phase_dev_rms_rad: PM peak (99.9th percentile) and rms phase deviation [rad] depth: AM modulation depth, (max - min)/(max + min) of the envelope (0.1th and 99.9th percentiles) tone_hz / sinad_db: the audio's strongest tone, and the power of everything over everything but it, when one tone holds most of the audio (a test tone); None otherwise

Source code in src/rpps/wave/analog.py
def __init__(self, kind, **kw):
    self.kind = kind
    for k in self.__slots__[1:]:
        setattr(self, k, kw.get(k))

demod

demod(x, Fs, kind='fm', bw=None, audio_bw=None)

Demodulate one block of analog signal, centred at 0 Hz, and measure it: for a display that wants each frame on its own (the stream stages FMDemod, AMDemod and SSBDemod carry state and filter delay from block to block instead)

kind: "fm", "pm", "am", "usb" or "lsb". bw: the channel [Hz] (default: FM 200 kHz, PM 25 kHz, AM 10 kHz, SSB 2.8 kHz; capped at Fs) audio_bw: the audio kept [Hz] (default: FM 15 kHz, PM and AM bw/2, SSB bw) Returns (audio, audio_Fs, Measurements). audio is float32 in the signal's own units: FM the frequency deviation [Hz], PM the phase deviation [rad] (unwrapped, the carrier's offset and phase taken out), AM the envelope over the carrier less one (1.0 is 100% modulation), SSB the real signal. audio_Fs = Fs/D, the whole decimation D that keeps audio_bw with some room. A channel as wide as Fs, and audio as wide as Fs/2, are not filtered (the whole span shown); complex64 samples are worked in single precision (PM's unwrapped phase in double: a long ramp would lose its resolution).

Source code in src/rpps/wave/analog.py
def demod(x, Fs, kind="fm", bw=None, audio_bw=None):
    """Demodulate one block of analog signal, centred at 0 Hz, and measure it: for a display that wants each frame on its own
    (the stream stages `FMDemod`, `AMDemod` and `SSBDemod` carry state and filter delay from block to block instead)

    kind: "fm", "pm", "am", "usb" or "lsb". bw: the channel [Hz] (default: FM 200 kHz, PM 25 kHz, AM 10 kHz, SSB 2.8 kHz;
    capped at Fs)
    audio_bw: the audio kept [Hz] (default: FM 15 kHz, PM and AM bw/2, SSB bw)
    Returns (audio, audio_Fs, Measurements). audio is float32 in the signal's own units: FM the frequency deviation [Hz],
    PM the phase deviation [rad] (unwrapped, the carrier's offset and phase taken out), AM the envelope over the carrier
    less one (1.0 is 100% modulation), SSB the real signal. audio_Fs = Fs/D, the whole
    decimation D that keeps audio_bw with some room.
    A channel as wide as Fs, and audio as wide as Fs/2, are not filtered (the whole span shown); complex64 samples are
    worked in single precision (PM's unwrapped phase in double: a long ramp would lose its resolution).
    """
    if kind not in ("fm", "pm", "am", "usb", "lsb"):
        raise ValueError(f"kind must be fm, pm, am, usb or lsb, not {kind!r}")
    x = np.asarray(x)
    if x.dtype != np.complex64:
        x = x.astype(np.complex128)
    if len(x) < 2:
        raise ValueError(f"{len(x)} samples: nothing to demodulate")
    bw = min(float(bw or {"fm": 200e3, "pm": 25e3, "am": 10e3}.get(kind, 2800.0)), Fs)
    audio_bw = min(float(audio_bw or {"fm": 15e3, "pm": bw/2, "am": bw/2}.get(kind, bw)), Fs/2)
    m = Measurements(kind)
    if kind in ("usb", "lsb"):
        y = _band(x, Fs, 0.0, bw) if kind == "usb" else _band(x, Fs, -bw, 0.0)
        m.power_db = float(10*np.log10(np.mean(np.abs(y)**2) + 1e-30))
        audio = y.real
    else:
        y = _band(x, Fs, -bw/2, bw/2)
        m.power_db = float(10*np.log10(np.mean(np.abs(y)**2) + 1e-30))
        if kind == "fm":
            f = discriminate(y, Fs)
            m.offset_hz = float(np.mean(f))
            audio = f - m.offset_hz
            m.deviation_hz = float(np.percentile(np.abs(audio), 99.9))
            m.deviation_rms_hz = float(np.sqrt(np.mean(audio**2)))
        elif kind == "pm":
            ph = np.unwrap(np.angle(y).astype(np.float64))
            n = np.arange(len(ph))
            slope, icpt = np.polyfit(n, ph, 1) # The carrier: its offset (a phase ramp) and its phase
            m.offset_hz = float(slope*Fs/(2*np.pi))
            audio = ph - (slope*n + icpt)
            m.phase_dev_rad = float(np.percentile(np.abs(audio), 99.9))
            m.phase_dev_rms_rad = float(np.sqrt(np.mean(audio**2)))
        else:
            env = np.abs(y)
            lo, hi = np.percentile(env, (0.1, 99.9))
            m.depth = float((hi - lo)/(hi + lo)) if hi + lo > 0 else 0.0
            carrier = float(np.mean(env))
            audio = env/carrier - 1 if carrier > 0 else env
        audio = _band_real(audio, Fs, audio_bw)
    D = max(1, int(Fs // (2.5*audio_bw)))
    audio = audio[::D].astype(np.float32)
    m.tone_hz, m.sinad_db = _tone(audio, Fs/D)
    return audio, Fs/D, m

fm

Classes:

Name Description
FM

Frequency modulator: a shaped level signal becomes a constant-envelope signal whose frequency follows it. The phase is

FMDemod

Quadrature FM demodulator as a stream stage: the last sample carries across blocks

Functions:

Name Description
discriminate

Instantaneous frequency between samples, arg(x[n] conj(x[n-1])): radians a sample, or Hz given the sample rate Fs.

fm_gain

The FMDemod gain that gives back the levels FM(h, step) was fed at sps samples per symbol

FM

FM(h=0.5, step=2.0, deviation=None)

Bases: Stage

Frequency modulator: a shaped level signal becomes a constant-envelope signal whose frequency follows it. The phase is continuous across samples and blocks, so FSK, GFSK, GMSK, 4FSK and C4FM are this and a pulse

levels + Zeros(sps) + pulse + FM(h)          # a held level a is a tone of a*h/step cycles per symbol

h: modulation index, the frequency spacing of neighbouring levels in cycles per symbol (0.5: MSK; BLE 0.5; 4FSK C4FM 1/3...). step: the distance between neighbouring levels of the signal (2 for levels -1 +1 or -3 -1 +1 +3). The signal must be at meta.sps >= 1 samples per symbol, and real; its pulse should leave a held level at unit gain (rp.signal.filters shaping rect, gaussian). deviation: analog FM instead (broadcast, voice): a level of 1.0 is this many Hz off the carrier, whatever the symbol rate (FM(deviation=75e3); the matching FMDemod(deviation=75e3) gives the levels back).

Source code in src/rpps/wave/fm.py
def __init__(self, h=0.5, step=2.0, deviation=None):
    self.h, self.level_step = float(h), float(step) # not `step`: that is the Stage method
    self.deviation = None if deviation is None else float(deviation)

FMDemod

FMDemod(gain=0.5, deviation=None)

Bases: Stage

Quadrature FM demodulator as a stream stage: the last sample carries across blocks

gain: what one radian per sample becomes (fm_gain gives the one that returns FM's levels); or deviation: Hz that become a level of 1.0 (analog FM: FMDemod(deviation=75e3)), worked out from the sample rate when it runs

Source code in src/rpps/wave/fm.py
def __init__(self, gain=0.5, deviation=None):
    self.gain = gain
    self.deviation = None if deviation is None else float(deviation)

discriminate

discriminate(x, Fs=None)

Instantaneous frequency between samples, arg(x[n] conj(x[n-1])): radians a sample, or Hz given the sample rate Fs. len(x) - 1 values (FMDemod carries the last sample across blocks)

Source code in src/rpps/wave/fm.py
def discriminate(x, Fs=None):
    """Instantaneous frequency between samples, arg(x[n] conj(x[n-1])): radians a sample, or Hz given the sample rate Fs.
    len(x) - 1 values (`FMDemod` carries the last sample across blocks)"""
    x = np.asarray(x)
    w = np.angle(x[1:]*np.conj(x[:-1]))
    return w if Fs is None else w*Fs/(2*np.pi)

fm_gain

fm_gain(h, sps, step=2.0)

The FMDemod gain that gives back the levels FM(h, step) was fed at sps samples per symbol

Source code in src/rpps/wave/fm.py
def fm_gain(h, sps, step=2.0):
    """The `FMDemod` gain that gives back the levels `FM(h, step)` was fed at `sps` samples per symbol"""
    return -step*sps/(2*np.pi*h)

loops

Demodulation as per-sample loops (second class): AMDemod with its running mean run sample by sample, in the C++ kernel when it is built (rpps._native.am_demod) and a Python loop otherwise

The first-class rpps.wave.AMDemod runs the same mean as an IIR section with no loop over the samples; this gives the same output to rounding.

Classes:

Name Description
AMDemod

Envelope detector: |x| with the carrier (DC) removed by a slow running mean (alpha: how fast the mean follows, the

AMDemod

AMDemod(alpha=0.001)

Bases: Stage

Envelope detector: |x| with the carrier (DC) removed by a slow running mean (alpha: how fast the mean follows, the fraction of the gap closed per sample), updated sample by sample; AMDemod(alpha=None) keeps the envelope

Source code in src/rpps/wave/loops.py
def __init__(self, alpha=1e-3):
    self.alpha = alpha

ofdm

Classes:

Name Description
OFDMTx

IFFT and cyclic prefix: n_fft carrier values per OFDM symbol in (see rp.symbol.Carriers), n_fft + n_cp samples out.

OFDMRx

Cyclic prefix off, then the FFT: samples starting on an OFDM symbol's prefix in, n_fft carrier values per OFDM symbol

OFDMTx

OFDMTx(n_fft=64, n_cp=16)

Bases: Stage

IFFT and cyclic prefix: n_fft carrier values per OFDM symbol in (see rp.symbol.Carriers), n_fft + n_cp samples out. A partial OFDM symbol waits in the stage for the rest

Source code in src/rpps/wave/ofdm.py
def __init__(self, n_fft=64, n_cp=16):
    self.n_fft, self.n_cp = int(n_fft), int(n_cp)

OFDMRx

OFDMRx(n_fft=64, n_cp=16)

Bases: Stage

Cyclic prefix off, then the FFT: samples starting on an OFDM symbol's prefix in, n_fft carrier values per OFDM symbol out (one value per carrier: symbols). Finding where the OFDM symbols start is sync's job

Source code in src/rpps/wave/ofdm.py
def __init__(self, n_fft=64, n_cp=16):
    self.n_fft, self.n_cp = int(n_fft), int(n_cp)

shape

Pulse shaping and its matched filter: the wave pair of a symbol pulse (rpps.wave, Wave pairs)

The pulses themselves are definitions (config/pulse, built by rp.signal.filters.load("pulse/...")); these apply them:

Shape(sps, pulse)   transmit: `sps` samples a symbol, each symbol carrying the pulse (zero stuffing and the pulse, in
                    polyphase form, so the zeros are never multiplied: the same output as `Zeros(sps) + pulse`)
Matched(pulse)      receive: the pulse time-reversed and conjugated, scaled so that pulse and matched filter give a
                    symbol back at the amplitude it was sent (unit=False: the taps as they are, an integrate-and-dump)

It does not choose the sampling instant: that is timing recovery (rpps.sync.time).

Classes:

Name Description
Shape

Symbols to sps samples a symbol, each carrying pulse (an FIR stage, a pulse definition)

Matched

The matched filter of pulse (an FIR stage): its taps reversed and conjugated, divided by sum |h|^2 when unit

Shape

Shape(sps, pulse)

Bases: Interpolate

Symbols to sps samples a symbol, each carrying pulse (an FIR stage, a pulse definition)

Source code in src/rpps/wave/shape.py
def __init__(self, sps, pulse):
    super().__init__(int(sps), pulse)

Matched

Matched(pulse, unit=True)

Bases: FIR

The matched filter of pulse (an FIR stage): its taps reversed and conjugated, divided by sum |h|^2 when unit (the peak of pulse * matched filter), so a symbol of 1 comes back as 1

Source code in src/rpps/wave/shape.py
def __init__(self, pulse, unit=True):
    self.pulse, self.unit = pulse, bool(unit)

stagger

Classes:

Name Description
Stagger

Offset one rail of a complex signal by a part of a symbol: the stagger of O-QPSK

Stagger

Stagger(rail='q', delay=0.5)

Bases: Stage

Offset one rail of a complex signal by a part of a symbol: the stagger of O-QPSK

tx = symbols + Zeros(sps) + halfsine + Stagger()             # Q half a symbol after I
rx = samples + Stagger(rail="i") + ...                       # I delayed to line up with Q again

A carrier phase offset mixes I into Q while Q is still late, so take it off the staggered signal before Stagger(rail="i") (a loop that works on the aligned symbols is too late).

rail: which of "q" (imaginary part) or "i" (real part) is delayed. delay: symbols, 0.5 for O-QPSK; delay * samples per symbol must be a whole number. The delayed rail is zero for the first samples and its last ones stay held in the stage: a stream that ends has them still inside (a receiver delaying I loses nothing it needs)

Source code in src/rpps/wave/stagger.py
def __init__(self, rail="q", delay=0.5):
    if rail not in ("i", "q"):
        raise ValueError(f"rail must be 'i' or 'q', not {rail!r}")
    self.rail, self.delay = rail, float(delay)