Skip to content

Signal

rpps.signal

Conditioning: samples to samples, without knowing what signal they carry

filters FIR/IIR design, windows, frequency shifts, the polyphase channelizer, pulse shaping sample sample-rate changes: decimation, interpolation, rational resampling channelize bring one signal of a wider capture to baseband at a few times its width FFTBank many signals of one capture to baseband at once, each at its own width, from one FFT per hop channel the simulated medium between transmitter and receiver: AWGN, offsets, multipath, fading DCBlock, Deemphasis, Conjugate conditioning: DC removal, FM de-emphasis, spectral inversion loops second class: DCBlock and Deemphasis as per-sample loops (the same output; C++ kernels)

Modules:

Name Description
channel

Channel impairments as stages, to test a receiver against: signal + rp.signal.channel.AWGN(10) + rp.signal.channel.CFO(300)

channelize
condition

Conditioning: DC removal, FM de-emphasis, spectral inversion

fftbank

FFTBank: many channels of one capture, each at its own width and rate, from one FFT per hop

loops

Conditioning as per-sample loops (second class): the recursions DCBlock and Deemphasis run sample by sample, in

channel

Channel impairments as stages, to test a receiver against: signal + rp.signal.channel.AWGN(10) + rp.signal.channel.CFO(300)

Every stage carries its state (noise generator, oscillator phase, fading) in the stream, so the result doesn't depend on how the signal is cut into blocks. Seeds make a run repeatable.

Classes:

Name Description
AWGN

Additive white gaussian noise at a signal-to-noise ratio

CFO

Carrier frequency offset [Hz]: an oscillator whose phase carries across blocks (the centre frequency is not touched)

PhaseOffset

Constant phase rotation [rad]

Gain

Amplitude gain in dB

TimingOffset

Fractional-sample delay (windowed sinc, carried across blocks)

ClockDrift

Sample clock error [ppm]: the receiver samples slightly fast (positive) or slow. Rates in Meta are untouched

Multipath

Static multipath: a tap at each delay (in samples, whole numbers) with a complex gain

Fading

Flat fading by a sum of sinusoids (Jakes): Rayleigh, or Rician with k_db (line of sight over scattered power)

AWGN

AWGN(snr_db=None, esn0_db=None, ebn0_db=None, bits_per_symbol=1, power=1.0, seed=None)

Bases: Stage

Additive white gaussian noise at a signal-to-noise ratio

Give one of

snr_db: signal power over noise power in the sample bandwidth esn0_db: symbol energy over noise density: the SNR plus 10*log10(sps) (needs sps on the data) ebn0_db: bit energy over noise density (needs bits_per_symbol)

power: the signal power the SNR refers to (1.0 for the unit-power constellations). None measures each block

Methods:

Name Description
snr_db

The SNR [dB] in the sample bandwidth at this sps

Source code in src/rpps/signal/channel.py
def __init__(self, snr_db=None, esn0_db=None, ebn0_db=None, bits_per_symbol=1, power=1.0, seed=None):
    if sum(v is not None for v in (snr_db, esn0_db, ebn0_db)) != 1:
        raise ValueError("Give exactly one of snr_db, esn0_db, ebn0_db")
    self.snr, self.esn0, self.ebn0, self.bps = snr_db, esn0_db, ebn0_db, bits_per_symbol
    self.power, self.seed = power, seed
snr_db
snr_db(sps)

The SNR [dB] in the sample bandwidth at this sps

Source code in src/rpps/signal/channel.py
def snr_db(self, sps):
    """The SNR [dB] in the sample bandwidth at this sps"""
    if self.snr is not None:
        return self.snr
    esn0 = self.esn0 if self.esn0 is not None else self.ebn0 + 10*np.log10(self.bps)
    return esn0 - 10*np.log10(max(sps, 1.0))

CFO

CFO(fo)

Bases: ShiftFreq

Carrier frequency offset [Hz]: an oscillator whose phase carries across blocks (the centre frequency is not touched)

Source code in src/rpps/signal/filters/shift.py
def __init__(self, fo):
    self.fo = fo

PhaseOffset

PhaseOffset(phase)

Bases: Stage

Constant phase rotation [rad]

Source code in src/rpps/signal/channel.py
def __init__(self, phase):
    self.phase = phase

Gain

Gain(db)

Bases: Stage

Amplitude gain in dB

Source code in src/rpps/signal/channel.py
def __init__(self, db):
    self.gain = 10**(db/20)

TimingOffset

TimingOffset(delay, taps=21)

Bases: ShiftTime

Fractional-sample delay (windowed sinc, carried across blocks)

Source code in src/rpps/signal/filters/shift.py
def __init__(self, delay, taps=21):
    pulse = np.arange(taps) - (taps-1)/2
    pulse = np.sinc(pulse - delay) # calc filter taps
    pulse *= np.hamming(taps)
    pulse /= np.sum(pulse)  # unity gain
    self.pulse = pulse

ClockDrift

ClockDrift(ppm)

Bases: Stage

Sample clock error [ppm]: the receiver samples slightly fast (positive) or slow. Rates in Meta are untouched

Source code in src/rpps/signal/channel.py
def __init__(self, ppm):
    self.ppm = ppm

Multipath

Multipath(gains, delays)

Bases: FIR

Static multipath: a tap at each delay (in samples, whole numbers) with a complex gain

Source code in src/rpps/signal/channel.py
def __init__(self, gains, delays):
    n = int(max(delays)) + 1
    taps = np.zeros(n, dtype=np.complex64)
    for g, d in zip(gains, delays):
        taps[int(d)] += g
    self.taps = taps

Fading

Fading(doppler_hz, paths=24, k_db=None, seed=None)

Bases: Stage

Flat fading by a sum of sinusoids (Jakes): Rayleigh, or Rician with k_db (line of sight over scattered power)

doppler_hz: the maximum Doppler shift. The fading has unit mean power, so it doesn't change the average level

Source code in src/rpps/signal/channel.py
def __init__(self, doppler_hz, paths=24, k_db=None, seed=None):
    self.fd, self.paths, self.seed = doppler_hz, paths, seed
    self.k = None if k_db is None else 10**(k_db/10)

channelize

Classes:

Name Description
Channelize

channelize as one stage: one channel of the capture to baseband, designed from the stream's sample rate when the

Functions:

Name Description
channelize

Filter stages that bring a signal to baseband at about oversample times its width

baseband

A channel of a whole capture at baseband, in one call: (samples, Fs_out). freq: the channel's centre relative to the

Channelize

Channelize(freq, width, oversample=3.0)

Bases: Stage

channelize as one stage: one channel of the capture to baseband, designed from the stream's sample rate when the first block arrives (a profile does not know the capture's rate)

narrow = wide + rp.signal.Channelize(freq=-250e3, width=200e3)      # Fs out about 3 x 200 kHz

freq: the channel's centre relative to the capture's [Hz]; width: its bandwidth [Hz]

Source code in src/rpps/signal/channelize.py
def __init__(self, freq, width, oversample=3.0):
    self.freq, self.width, self.oversample = float(freq), float(width), float(oversample)

channelize

channelize(mid, width, Fs, oversample=3.0, max_taps=401, largest=16)

Filter stages that bring a signal to baseband at about oversample times its width

Decimates in several stages, each with an anti-alias filter just sharp enough for its own rate, so a 100 kHz signal in a 100 MS/s capture needs a few short filters rather than one of thousands of taps. Returns (pipeline, Fs_out, total decimation): block + pipeline. State carries across consecutive blocks of a stream.

Source code in src/rpps/signal/channelize.py
def channelize(mid, width, Fs, oversample=3.0, max_taps=401, largest=16):
    """Filter stages that bring a signal to baseband at about `oversample` times its width

    Decimates in several stages, each with an anti-alias filter just sharp enough for its own rate, so
    a 100 kHz signal in a 100 MS/s capture needs a few short filters rather than one of thousands of taps.
    Returns (pipeline, Fs_out, total decimation): `block + pipeline`. State carries across consecutive blocks of a stream.
    """
    from .sample.down import Decimate  # Late: sample imports filters
    D = max(1, int(Fs/(oversample*width)))
    while D > 1 and max(_factors(D, largest)) > largest:
        D -= 1
    stages = [ShiftFreq(-mid)]
    fs = Fs
    edge = 0.5*width*1.05 # Passband edge
    for f in _factors(D, largest):
        out = fs/f
        stop = out - 0.5*width*1.05 # What would alias onto the passband
        trans = stop - edge
        taps = int(np.ceil(3.3*fs/trans)) | 1 if trans > 0 else max_taps
        taps = int(np.clip(taps, 15, max_taps)) | 1
        stages.append(low_pass(taps, 0.5*(edge + stop), fs))
        stages.append(Decimate(f))
        fs = out
    from ..base import Pipeline
    return Pipeline(*stages), fs, D

baseband

baseband(x, Fs, freq, width, oversample=3.0)

A channel of a whole capture at baseband, in one call: (samples, Fs_out). freq: the channel's centre relative to the capture's centre [Hz]; width: its bandwidth [Hz]. The stages of channelize run once over x, flushed, and their group delay is taken off, so output sample k is the channel at input time k/Fs_out

Source code in src/rpps/signal/channelize.py
def baseband(x, Fs, freq, width, oversample=3.0):
    """A channel of a whole capture at baseband, in one call: (samples, Fs_out). freq: the channel's centre relative to the
    capture's centre [Hz]; width: its bandwidth [Hz]. The stages of `channelize` run once over x, flushed, and their group
    delay is taken off, so output sample k is the channel at input time k/Fs_out"""
    from ..base import Data
    pipe, Fs_out, D = channelize(freq, width, Fs, oversample)
    out = Data(np.asarray(x), Fs=Fs, flush=True) + pipe
    lag = int(round(out.delay*Fs_out))
    return np.asarray(out.data)[lag:], Fs_out

condition

Conditioning: DC removal, FM de-emphasis, spectral inversion

Classes:

Name Description
DCBlock

Removes the DC offset (a one pole high pass: y[n] = x[n] - x[n-1] + r*y[n-1]), an IIR section

Deemphasis

FM broadcast de-emphasis: a one pole low pass with time constant tau (75 us in the Americas, 50 us elsewhere), an

Conjugate

Spectral inversion of a complex signal: x -> conj(x), so a capture whose I and Q were swapped (or taken from the

DCBlock

DCBlock(r=0.999)

Bases: Stage

Removes the DC offset (a one pole high pass: y[n] = x[n] - x[n-1] + r*y[n-1]), an IIR section

Source code in src/rpps/signal/condition.py
def __init__(self, r=0.999):
    self.r = r
    self._iir = IIR([[1.0, -1.0, 0.0, 1.0, -r, 0.0]])

Deemphasis

Deemphasis(tau=7.5e-05)

Bases: Stage

FM broadcast de-emphasis: a one pole low pass with time constant tau (75 us in the Americas, 50 us elsewhere), an IIR section at the stream's rate

Source code in src/rpps/signal/condition.py
def __init__(self, tau=75e-6):
    self.tau = tau

Conjugate

Bases: Stage

Spectral inversion of a complex signal: x -> conj(x), so a capture whose I and Q were swapped (or taken from the lower sideband of a mixer) comes out the right way round. Inverting the spectrum at the symbol level instead is a constellation map ("R090 inverted"); this does it on the samples, before any sync

fftbank

FFTBank: many channels of one capture, each at its own width and rate, from one FFT per hop

bank = rp.signal.FFTBank(Fs, [(mid, width), ...])      # Hz from the capture's centre, Hz wide
for blk in src(16384):
    outs = bank.step(blk.data)                        # [samples at bank.Fs_out[k]] per channel, baseband
outs = bank.flush()                                   # the rest, the end of the stream

Overlap-save on a fixed grid from the start of the stream (so the output does not depend on how the input is cut): every hop input samples one FFT of n samples (the hop and overlap on each side). Each channel takes only the bins around its centre, weighted by a smooth mask (flat to guard x width / 2, a raised-cosine skirt transition x width wide), and an inverse FFT of n / D of them gives its samples decimated by D directly: D the largest power of two that keeps oversample x width. The bin grid's rounding of the centre is put right with a phase ramp continuous across hops, so a channel comes out at exactly mid. A signal_profile over twenty channels filters the capture once, where a shift and decimation per channel (rp.signal.channelize) went over every sample once a channel.

The mask is zero phase (no delay); n is chosen so the skirt spans at least min_bins bins (its impulse response stays inside the overlap), for the narrowest channel. active in step skips channels nobody reads any more.

Classes:

Name Description
FFTBank

Channels (mid, width) [Hz] of a capture at Fs: step(x) -> [baseband samples per channel]. Fs_out[k], D[k]

FFTBank

FFTBank(Fs, channels, oversample=4.0, guard=1.3, transition=0.2, min_bins=16, max_n=2 ** 21)

Channels (mid, width) [Hz] of a capture at Fs: step(x) -> [baseband samples per channel]. Fs_out[k], D[k]

Methods:

Name Description
step

Samples in; [baseband samples per channel] out (empty arrays until a hop is in). active: the channels to

flush

The end of the stream: the samples still held, zero padded, trimmed to the input's length

Source code in src/rpps/signal/fftbank.py
def __init__(self, Fs, channels, oversample=4.0, guard=1.3, transition=0.2, min_bins=16, max_n=2**21):
    self.Fs = float(Fs)
    self.mid = np.array([float(c[0]) for c in channels])
    self.width = np.array([float(c[1]) for c in channels])
    if len(self.mid) == 0:
        raise ValueError("FFTBank: no channels")
    # Decimation: the largest power of two that keeps oversample x width (and at least 4 output samples a hop)
    self.D = [max(1, 1 << int(np.floor(np.log2(max(self.Fs/(oversample*w), 1.0))))) for w in self.width]
    need = max(min_bins*self.Fs/(transition*w) for w in self.width)
    self.n = int(min(max_n, max(_pow2_at_least(need), 8*max(self.D), 4096)))
    self.D = [min(D, self.n//8) for D in self.D]
    self.overlap = self.n//8
    self.hop = self.n - 2*self.overlap
    self.Fs_out = [self.Fs/D for D in self.D]
    self.bins, self.mask, self.k0, self.res = [], [], [], []
    for mid, width, D in zip(self.mid, self.width, self.D):
        m = self.n//D
        k0 = int(np.round(mid*self.n/self.Fs))
        off = np.fft.fftfreq(m)*m # 0..m/2-1, -m/2..-1: the bins around the centre, in IFFT order
        self.bins.append(((k0 + off).astype(np.int64)) % self.n)
        f = np.fft.fftfreq(m, D/self.Fs) + (k0*self.Fs/self.n - mid) # Each bin's offset from the channel's centre
        p = 0.5*guard*width
        s = min(p + transition*width, 0.5*self.Fs/D)
        a = np.abs(f)
        w = np.where(a <= p, 1.0, np.where(a >= s, 0.0, 0.5*(1 + np.cos(np.pi*(a - p)/max(s - p, 1e-12)))))
        self.mask.append((w*m/self.n).astype(np.complex64)) # (and the scale: n/D bins give n/D samples)
        self.k0.append(k0)
        self.res.append(mid/self.Fs - k0/self.n) # Cycles a sample the bin grid leaves to turn back
    self.buf = np.zeros(self.overlap, np.complex64) # The first hop's left overlap: before the stream, zeros
    self.start = -self.overlap # Absolute index of buf[0]
    self.seen = 0 # Input samples so far
    self.out = [0]*len(self.D) # Output samples given so far, per channel
step
step(x, active=None)

Samples in; [baseband samples per channel] out (empty arrays until a hop is in). active: the channels to compute (others give empty arrays and lose these samples)

Source code in src/rpps/signal/fftbank.py
def step(self, x, active=None):
    """Samples in; [baseband samples per channel] out (empty arrays until a hop is in). active: the channels to
    compute (others give empty arrays and lose these samples)"""
    which = range(len(self.D)) if active is None else list(active)
    x = np.asarray(x, dtype=np.complex64)
    self.buf = np.concatenate((self.buf, x))
    self.seen += len(x)
    parts = {k: [] for k in which}
    while len(self.buf) >= self.n:
        for k, y in self._hop(self.buf[:self.n], which).items():
            parts[k].append(y)
        self.buf = self.buf[self.hop:]
        self.start += self.hop
    return self._gather(parts)
flush
flush(active=None)

The end of the stream: the samples still held, zero padded, trimmed to the input's length

Source code in src/rpps/signal/fftbank.py
def flush(self, active=None):
    """The end of the stream: the samples still held, zero padded, trimmed to the input's length"""
    which = range(len(self.D)) if active is None else list(active)
    end = self.seen
    parts = {k: [] for k in which}
    while self.start + self.overlap < end:
        seg = self.buf[:self.n]
        if len(seg) < self.n:
            seg = np.concatenate((seg, np.zeros(self.n - len(seg), np.complex64)))
        for k, y in self._hop(seg, which).items():
            parts[k].append(y)
        self.buf = self.buf[self.hop:]
        self.start += self.hop
    out = self._gather(parts)
    for k in which: # Only the outputs of samples that came in
        keep = max(0, -(-end//self.D[k]) - (self.out[k] - len(out[k])))
        self.out[k] -= len(out[k]) - min(keep, len(out[k]))
        out[k] = out[k][:keep]
    return out

loops

Conditioning as per-sample loops (second class): the recursions DCBlock and Deemphasis run sample by sample, in the C++ kernels when they are built (rpps._native: dc_block, one_pole) and a Python loop otherwise

The first-class stages, rpps.signal.DCBlock and rpps.signal.Deemphasis, are the same recursions as IIR sections run with no loop over the samples (rpps.signal.filters.iir); these give the same output to rounding. They stay as the references the sections are checked against, and for whoever wants the plain loop.

Classes:

Name Description
DCBlock

Removes the DC offset, a one pole high pass run sample by sample: y[n] = x[n] - x[n-1] + r*y[n-1]

Deemphasis

FM broadcast de-emphasis, a one pole low pass with time constant tau run sample by sample: y += a*(x - y)

DCBlock

DCBlock(r=0.999)

Bases: Stage

Removes the DC offset, a one pole high pass run sample by sample: y[n] = x[n] - x[n-1] + r*y[n-1]

Source code in src/rpps/signal/loops.py
def __init__(self, r=0.999):
    self.r = r

Deemphasis

Deemphasis(tau=7.5e-05)

Bases: Stage

FM broadcast de-emphasis, a one pole low pass with time constant tau run sample by sample: y += a*(x - y)

Source code in src/rpps/signal/loops.py
def __init__(self, tau=75e-6):
    self.tau = tau

rpps.signal.filters

Filters as stages: FIR/IIR design (low_pass, band_pass, remez...), pulse shaping, windows, frequency shifts and a polyphase channelizer: samples + rp.signal.filters.low_pass(401, 3e6, 100e6)

Modules:

Name Description
convert

Bring filter coefficients from elsewhere into the config format

convolve

FFT convolution for long filters

filter
filters
iir

IIR filters, with numpy only

pfb
serial

Filter definitions, config/filter///.json (rp.signal.filters.load("fir/taps/name")), and pulses,

shaping
shift
window

convert

Bring filter coefficients from elsewhere into the config format

A definition in config/ never refers to another file; this is how coefficients that live in a file (or in another tool's output) become one. Read a file, get the definition as a dict, or have it written into a config directory:

d = rp.signal.filters.import_fir("taps.txt")                                  # {"base": "fir", "type": "taps", "taps": [...]}
rp.signal.filters.import_fir("lp.f32", dtype="f32", name="my_lp", dest="mine")  # writes mine/filter/fir/taps/my_lp.json
rp.signal.filters.import_iir("sections.npy", form="sos", name="my_iir")
rp.add_config_path("mine"); rp.signal.filters.load("fir/taps/my_lp")

Formats: text/CSV, NumPy .npy/.npz, headerless raw binary (GNU Radio file sinks, tofile), numbers in a C/Python/Verilog array literal, Xilinx .coe. Arrays already in memory (scipy, firdes...) go through fir_def, sos_def, ba_def and zpk_def.

Functions:

Name Description
read_table

The numbers of a file as a list of 1-D arrays (one per row of text, one for a vector).

fir_def

Definition of an FIR with these taps (real, or complex: the imaginary parts go in taps_imag). fields: comment, gain, fs...

sos_def

Definition of an IIR from second-order sections, rows [b0 b1 b2 a0 a1 a2] (scipy's sos)

ba_def

Definition of an IIR from a transfer function. convention (the sign of the feedback taps a):

zpk_def

Definition of an IIR from zeros, poles and gain (z-plane; complex values are stored as [re, im])

import_fir

The FIR in a file as a config definition (a dict). A text file may wrap the taps over lines. scale multiplies the taps (integer .coe data: 1/32768 for 16 bit).

import_iir

The IIR in a file as a config definition. form says what the numbers are:

read_table

read_table(path, fmt=None, dtype=None, key=None)

The numbers of a file as a list of 1-D arrays (one per row of text, one for a vector).

fmt: text, npy, npz, raw, source, coe (default from the extension). dtype: for raw files, f16 f32 f64 cf32 cf64 i8t ui8 i16t i32t (pysdrlib's names) or a numpy dtype string. key: the array to take from an .npz

Source code in src/rpps/signal/filters/convert.py
def read_table(path, fmt=None, dtype=None, key=None):
    """The numbers of a file as a list of 1-D arrays (one per row of text, one for a vector).

    fmt: text, npy, npz, raw, source, coe (default from the extension). dtype: for raw files, f16 f32 f64 cf32 cf64 i8t ui8 i16t i32t (pysdrlib's names)
    or a numpy dtype string. key: the array to take from an .npz"""
    path = Path(path)
    if path.stat().st_size > MAX_BYTES:
        raise ValueError(f"{path.name} is {path.stat().st_size} bytes: that is not a coefficient file")
    ext = path.suffix.lower()
    fmt = fmt or EXTENSIONS.get(ext)
    if fmt is None:
        raise ValueError(f"{path.name}: unknown file type, say fmt= one of text, npy, npz, raw, source, coe")
    if fmt == "text":
        return _read_text(path.read_text(), path.name)
    if fmt == "source":
        return _read_source(path.read_text(), path.name)
    if fmt == "coe":
        return _read_coe(path.read_text(), path.name)
    if fmt == "raw":
        dtype = dtype or IMPLIED_DTYPE.get(ext)
        if dtype is None:
            raise ValueError(f"{path.name}: a raw file has no header, say dtype= (f32, f64, cf32, i16t... or a numpy dtype)")
        if isinstance(dtype, str) and dtype not in DTYPES and dtype[:1] not in "<>=|":
            # A bare numpy code reads wrong silently ("i8" is int64 to numpy, int8 to an SDR tool): names or explicit dtypes only
            raise ValueError(f"dtype {dtype!r}: one of {sorted(DTYPES)}, or a numpy dtype with its byte order (\"<i2\")")
        dt = np.dtype(DTYPES.get(dtype, dtype))
        if path.stat().st_size % dt.itemsize:
            raise ValueError(f"{path.name}: {path.stat().st_size} bytes is not a whole number of {dtype} values")
        return [np.fromfile(path, dtype=dt)]
    if fmt in ("npy", "npz"):
        loaded = np.load(path, allow_pickle=False)
        if fmt == "npz":
            names = list(loaded.files)
            if key is None and len(names) != 1:
                raise ValueError(f"{path.name} holds {names}: say key=")
            if key is not None and key not in names:
                raise ValueError(f"{path.name} has no array {key!r}, only {names}")
            loaded = loaded[key or names[0]]
        a = np.asarray(loaded)
        return [a] if a.ndim <= 1 else [row for row in a]
    raise ValueError(f"unknown format {fmt!r}")

fir_def

fir_def(taps, **fields)

Definition of an FIR with these taps (real, or complex: the imaginary parts go in taps_imag). fields: comment, gain, fs...

Source code in src/rpps/signal/filters/convert.py
def fir_def(taps, **fields):
    """Definition of an FIR with these taps (real, or complex: the imaginary parts go in `taps_imag`). fields: comment, gain, fs..."""
    t = np.asarray(taps)
    if t.ndim != 1 or t.size == 0:
        raise ValueError(f"taps must be a non-empty 1-D list, got shape {t.shape}")
    if not np.all(np.isfinite(t)):
        raise ValueError("taps contain inf or nan")
    obj = {"base": "fir", "type": "taps", **_fields(f"{t.size}-tap FIR", dict(fields))}
    if t.dtype.kind == "c" and np.any(t.imag):
        obj["taps"], obj["taps_imag"] = _nums(t.real), _nums(t.imag)
    else:
        obj["taps"] = _nums(t.real if t.dtype.kind == "c" else t)
    return obj

sos_def

sos_def(sos, **fields)

Definition of an IIR from second-order sections, rows [b0 b1 b2 a0 a1 a2] (scipy's sos)

Source code in src/rpps/signal/filters/convert.py
def sos_def(sos, **fields):
    """Definition of an IIR from second-order sections, rows [b0 b1 b2 a0 a1 a2] (scipy's `sos`)"""
    s = _iir.as_sos(sos)
    _check_stable(s)
    return {"base": "iir", "type": "sos", **_fields(f"{len(s)}-section IIR", dict(fields)), "sos": _nums(_real(sos).reshape(-1, 6))}

ba_def

ba_def(b, a, convention='scipy', **fields)

Definition of an IIR from a transfer function. convention (the sign of the feedback taps a): scipy, matlab, gnuradio-new y[n] = sum b[k] x[n-k] - sum a[k] y[n-k] (k >= 1), a[0] = 1 gnuradio (gnuradio-old) y[n] = sum b[k] x[n-k] + sum a[k] y[n-k] (k >= 1); a[0] is ignored (iir_filter_ffd oldstyle=True) The definition holds the scipy form.

Source code in src/rpps/signal/filters/convert.py
def ba_def(b, a, convention="scipy", **fields):
    """Definition of an IIR from a transfer function. convention (the sign of the feedback taps `a`):
        scipy, matlab, gnuradio-new   y[n] = sum b[k] x[n-k] - sum a[k] y[n-k] (k >= 1), a[0] = 1
        gnuradio (gnuradio-old)       y[n] = sum b[k] x[n-k] + sum a[k] y[n-k] (k >= 1); a[0] is ignored (iir_filter_ffd oldstyle=True)
    The definition holds the scipy form."""
    if convention not in CONVENTIONS:
        raise ValueError(f"convention must be one of {sorted(CONVENTIONS)}, not {convention!r}")
    b, a = _real(b), _real(a)
    if CONVENTIONS[convention]:
        a = np.concatenate(([1.0], -a[1:]))
    _check_stable(_iir.tf2sos(b, a))
    return {"base": "iir", "type": "ba", **_fields(f"order {max(len(a), len(b)) - 1} IIR", dict(fields)), "b": _nums(b), "a": _nums(a)}

zpk_def

zpk_def(z, p, k, **fields)

Definition of an IIR from zeros, poles and gain (z-plane; complex values are stored as [re, im])

Source code in src/rpps/signal/filters/convert.py
def zpk_def(z, p, k, **fields):
    """Definition of an IIR from zeros, poles and gain (z-plane; complex values are stored as [re, im])"""
    z, p = np.atleast_1d(np.asarray(z, dtype=complex)), np.atleast_1d(np.asarray(p, dtype=complex))
    _check_stable(_iir.zpk2sos(z, p, k))
    pair = lambda v: [[float(x.real), float(x.imag)] if x.imag else float(x.real) for x in v]
    return {"base": "iir", "type": "zpk", **_fields(f"{len(p)}-pole IIR", dict(fields)), "z": pair(z), "p": pair(p), "k": float(k)}

import_fir

import_fir(path, fmt=None, dtype=None, key=None, scale=1.0, name=None, dest=None, overwrite=False, **fields)

The FIR in a file as a config definition (a dict). A text file may wrap the taps over lines. scale multiplies the taps (integer .coe data: 1/32768 for 16 bit).

name: also write it as config/filter/fir/taps/.json under dest (default: the first added config path, else the shipped config; an existing file is kept unless overwrite) and return the file. fields: comment, gain...

Source code in src/rpps/signal/filters/convert.py
def import_fir(path, fmt=None, dtype=None, key=None, scale=1.0, name=None, dest=None, overwrite=False, **fields):
    """The FIR in a file as a config definition (a dict). A text file may wrap the taps over lines. scale multiplies the taps (integer .coe data: 1/32768 for 16 bit).

    name: also write it as config/filter/fir/taps/<name>.json under dest (default: the first added config path, else the shipped
    config; an existing file is kept unless overwrite) and return the file. fields: comment, gain..."""
    rows = read_table(path, fmt, dtype, key)
    if (fmt or EXTENSIONS.get(Path(path).suffix.lower())) == "text": # Taps wrapped over several lines, or one per line
        rows = [np.concatenate(rows)] if rows else rows
    if len(rows) != 1:
        raise ValueError(f"{Path(path).name} has {len(rows)} rows: taps are one list (an sos or ba table is for import_iir)")
    obj = fir_def(np.asarray(rows[0]) * scale, **{"comment": f"FIR from {Path(path).name}", **fields})
    return obj if name is None else _config.save("filter", "fir", f"taps/{name}", obj, dest, overwrite)

import_iir

import_iir(path, form='sos', fmt=None, dtype=None, key=None, convention='scipy', name=None, dest=None, overwrite=False, **fields)

The IIR in a file as a config definition. form says what the numbers are: sos rows of 6 (b0 b1 b2 a0 a1 a2), one per section ba two rows or arrays, b then a (see ba_def for convention) zpk three rows, zeros, poles, then the gain; from an .npz, the arrays z, p, k A .npz may hold the arrays by name (sos | b, a | z, p, k). name/dest/overwrite as for import_fir (written under filter/iir/

/).

Source code in src/rpps/signal/filters/convert.py
def import_iir(path, form="sos", fmt=None, dtype=None, key=None, convention="scipy", name=None, dest=None, overwrite=False, **fields):
    """The IIR in a file as a config definition. form says what the numbers are:
        sos   rows of 6 (b0 b1 b2 a0 a1 a2), one per section
        ba    two rows or arrays, b then a (see `ba_def` for convention)
        zpk   three rows, zeros, poles, then the gain; from an .npz, the arrays z, p, k
    A .npz may hold the arrays by name (sos | b, a | z, p, k). name/dest/overwrite as for `import_fir` (written under filter/iir/<form>/)."""
    fields = {"comment": f"IIR from {Path(path).name}", **fields}
    fmt = fmt or EXTENSIONS.get(Path(path).suffix.lower())
    if fmt == "npz":
        arrays = dict(np.load(path, allow_pickle=False))
        names = {"sos": ("sos",), "ba": ("b", "a"), "zpk": ("z", "p", "k")}.get(form)
        if names is None or not all(n in arrays for n in names):
            raise ValueError(f"{Path(path).name} holds {sorted(arrays)}: form={form!r} needs {names}")
        rows = [np.atleast_1d(arrays[n]) for n in names] if form != "sos" else [r for r in np.atleast_2d(arrays["sos"])]
    else:
        rows = read_table(path, fmt, dtype, key)
    if form == "sos":
        obj = sos_def(np.vstack(rows) if len({len(r) for r in rows}) == 1 else rows, **fields)
    elif form == "ba":
        if len(rows) != 2:
            raise ValueError(f"form='ba' needs two rows (b then a), {Path(path).name} has {len(rows)}")
        obj = ba_def(rows[0], rows[1], convention, **fields)
    elif form == "zpk":
        if len(rows) != 3 or len(rows[2]) != 1:
            raise ValueError(f"form='zpk' needs three rows (zeros, poles, then one gain), {Path(path).name} has {[len(r) for r in rows]}")
        obj = zpk_def(rows[0], rows[1], rows[2][0].real, **fields)
    else:
        raise ValueError(f"form must be sos, ba or zpk, not {form!r}")
    return obj if name is None else _config.save("filter", "iir", f"{form}/{name}", obj, dest, overwrite)

convolve

FFT convolution for long filters

Functions:

Name Description
fft_pays

Is convolving nx samples with nh taps cheaper by FFT blocks than directly

convolve

Convolution of the signal x with the filter h by overlap-add FFT blocks when that is cheaper than np.convolve

correlate

sum_i x[n + i] conj(t[i]) at every n where the template t fits in x (len(x) - len(t) + 1 values, as

fft_pays

fft_pays(nx, nh)

Is convolving nx samples with nh taps cheaper by FFT blocks than directly

Source code in src/rpps/signal/filters/convolve.py
def fft_pays(nx, nh):
    """Is convolving nx samples with nh taps cheaper by FFT blocks than directly"""
    return not (nh < _DIRECT or nx < _MIN_SIGNAL or nh*8 > nx)

convolve

convolve(x, h, mode='full')

Convolution of the signal x with the filter h by overlap-add FFT blocks when that is cheaper than np.convolve

mode: "full" (len(x) + len(h) - 1 samples), "same" (len(x), centred on the full output) or "valid" (len(x) - len(h) + 1, no edges) Real and complex inputs; the result is float32 / complex64 when both inputs are single precision, else double.

Source code in src/rpps/signal/filters/convolve.py
def convolve(x, h, mode="full"):
    """Convolution of the signal `x` with the filter `h` by overlap-add FFT blocks when that is cheaper than `np.convolve`

    mode: "full" (len(x) + len(h) - 1 samples), "same" (len(x), centred on the full output) or "valid" (len(x) - len(h) + 1, no edges)
    Real and complex inputs; the result is float32 / complex64 when both inputs are single precision, else double.
    """
    if mode not in ("full", "same", "valid"):
        raise ValueError(f"mode must be full, same or valid, not {mode!r}")
    x = np.asarray(x); h = np.asarray(h)
    if x.ndim != 1 or h.ndim != 1:
        raise ValueError("convolve takes 1-D signals")
    if len(x) < len(h) and mode == "valid": # Same as np.convolve: the shorter one is the filter
        x, h = h, x
    nx, nh = len(x), len(h)
    single = x.dtype in (np.float32, np.complex64) and h.dtype in (np.float32, np.complex64, np.float16)
    if not fft_pays(nx, nh):
        out = np.convolve(x, h, "full")
    else:
        cplx = np.iscomplexobj(x) or np.iscomplexobj(h)
        n = 1 << int(np.ceil(np.log2(8*nh)))        # FFT size: each block gives n - nh + 1 new samples
        step = n - nh + 1
        fwd, inv = (np.fft.fft, np.fft.ifft) if cplx else (np.fft.rfft, np.fft.irfft)
        kw = {} if cplx else {"n": n}
        dt = (np.complex64 if single else np.complex128) if cplx else (np.float32 if single else np.float64) # (numpy 2 keeps single precision through the FFT)
        H = fwd(h.astype(dt), n)
        nout = nx + nh - 1
        nb = -(-nout//step)
        # Overlap-save: the blocks are overlapping windows of the zero-padded signal (rows of a strided view, no copy), each
        # row's valid part (its last `step` samples) is the output of one stretch, so the output is the rows end to end
        xp = np.zeros((nb - 1)*step + n, dtype=dt)
        xp[nh - 1:nh - 1 + nx] = x
        win = np.lib.stride_tricks.sliding_window_view(xp, n)[::step][:nb]
        out = np.empty(nb*step, dtype=dt)
        group = max(1, _GROUP//n) # rows per FFT call: bounded memory
        for g in range(0, nb, group):
            y = inv(fwd(win[g:g + group], n, axis=1)*H, axis=1, **kw)
            out[g*step:(g + len(y))*step] = y[:, nh - 1:].reshape(-1)
        out = out[:nout]
    if mode == "same":
        s = (nh - 1)//2
        out = out[s:s + nx]
    elif mode == "valid":
        out = out[nh - 1:nx]
    dtype = (np.complex64 if np.iscomplexobj(out) else np.float32) if single else None
    return out.astype(dtype, copy=False) if dtype else out

correlate

correlate(x, t)

sum_i x[n + i] conj(t[i]) at every n where the template t fits in x (len(x) - len(t) + 1 values, as np.correlate(x, t, "valid")), by FFT blocks when that is cheaper

Source code in src/rpps/signal/filters/convolve.py
def correlate(x, t):
    """sum_i x[n + i] conj(t[i]) at every n where the template t fits in x (len(x) - len(t) + 1 values, as
    np.correlate(x, t, "valid")), by FFT blocks when that is cheaper"""
    return convolve(x, np.conj(np.asarray(t)[::-1]), "valid")

filter

Classes:

Name Description
FIR

Causal FIR that carries its history across blocks: len(out) == len(in)

FIR

Bases: Filter

Causal FIR that carries its history across blocks: len(out) == len(in)

Methods:

Name Description
stream

Filter a block. Returns (output, new history)

stream staticmethod
stream(samples, taps, hist)

Filter a block. Returns (output, new history)

Source code in src/rpps/signal/filters/filter.py
@staticmethod
def stream(samples, taps, hist):
    """Filter a block. Returns (output, new history)"""
    keep = len(taps) - 1
    if hist is None:
        hist = np.zeros(keep, dtype=samples.dtype)
    if len(samples) == 0:
        return samples, hist
    buf = np.concatenate((hist, samples))
    taps = np.asarray(taps)
    if (_accel.native is not None and buf.dtype == np.complex64 and taps.dtype.kind == "f"
            and (len(taps) <= NATIVE_TAPS or not fft_pays(len(buf), len(taps)))):
        # The C++ dot products (vectorised, on several threads) beat FFT blocks up to a few hundred taps, and
        # np.convolve (neither) wherever that would run
        out = _accel.native.fir_decimate(buf, np.ascontiguousarray(taps, dtype=np.float64), keep, 1, len(samples))
    else:
        out = convolve(buf, taps, "valid") # FFT blocks for a long filter on a long block, else np.convolve
    return out, buf[len(buf)-keep:]

filters

Classes:

Name Description
ConvFilter

Functions:

Name Description
low_pass

Windowed-sinc low pass: taps coefficients, cut off at cutoff Hz of sample rate fs (None: normalised, Nyquist is 1)

kaiser_window

A Kaiser window of shape beta, as a function of the length

kaiser_params

Taps and beta for a Kaiser-window FIR with atten_db stopband attenuation and a transition width wide

low_pass_kaiser

Low pass that meets a specification: stopband atten_db down, the transition (Hz) centred on cutoff

remez

Equiripple (Parks-McClellan) FIR: the smallest possible maximum weighted error for taps coefficients

ConvFilter

ConvFilter(filt)

Bases: FIR

Methods:

Name Description
run

One-shot (stateless) filtering, drops the edges

Source code in src/rpps/signal/filters/filters.py
def __init__(self, filt):
    self.filt = filt
run
run(samples)

One-shot (stateless) filtering, drops the edges

Source code in src/rpps/signal/filters/filters.py
def run(self, samples):
    """One-shot (stateless) filtering, drops the edges"""
    return np.convolve(samples, self.filt, mode="valid")

low_pass

low_pass(taps, cutoff, fs=None, window=np.hamming)

Windowed-sinc low pass: taps coefficients, cut off at cutoff Hz of sample rate fs (None: normalised, Nyquist is 1) window: a function of the length, e.g. np.hamming (default), np.blackman, or kaiser_window(beta)

Source code in src/rpps/signal/filters/filters.py
def low_pass(taps, cutoff, fs=None, window=np.hamming):
    """Windowed-sinc low pass: `taps` coefficients, cut off at `cutoff` Hz of sample rate `fs` (None: normalised, Nyquist is 1)
    window: a function of the length, e.g. np.hamming (default), np.blackman, or `kaiser_window(beta)`"""
    return ConvFilter(designer(taps, cutoff, fs=fs, pass_zero=True, window=window))

kaiser_window

kaiser_window(beta)

A Kaiser window of shape beta, as a function of the length

Source code in src/rpps/signal/filters/filters.py
def kaiser_window(beta):
    """A Kaiser window of shape `beta`, as a function of the length"""
    return lambda n: np.kaiser(n, beta)

kaiser_params

kaiser_params(atten_db, width)

Taps and beta for a Kaiser-window FIR with atten_db stopband attenuation and a transition width wide (a fraction of the sample rate, e.g. 0.05)

Source code in src/rpps/signal/filters/filters.py
def kaiser_params(atten_db, width):
    """Taps and beta for a Kaiser-window FIR with `atten_db` stopband attenuation and a transition `width` wide
    (a fraction of the sample rate, e.g. 0.05)"""
    if atten_db > 50:
        beta = 0.1102*(atten_db - 8.7)
    elif atten_db >= 21:
        beta = 0.5842*(atten_db - 21)**0.4 + 0.07886*(atten_db - 21)
    else:
        beta = 0.0
    taps = int(np.ceil((atten_db - 7.95)/(2.285*2*np.pi*width))) + 1
    return taps | 1, beta

low_pass_kaiser

low_pass_kaiser(cutoff, transition, atten_db=60, fs=1.0)

Low pass that meets a specification: stopband atten_db down, the transition (Hz) centred on cutoff

Source code in src/rpps/signal/filters/filters.py
def low_pass_kaiser(cutoff, transition, atten_db=60, fs=1.0):
    """Low pass that meets a specification: stopband `atten_db` down, the transition (Hz) centred on `cutoff`"""
    taps, beta = kaiser_params(atten_db, transition/fs)
    return low_pass(taps, cutoff, fs, kaiser_window(beta))

remez

remez(taps, bands, desired, weight=None, fs=1.0, type='bandpass')

Equiripple (Parks-McClellan) FIR: the smallest possible maximum weighted error for taps coefficients

remez(101, [0, 1000, 1500, 5000], [1, 0], fs=10e3)   # low pass: pass 0-1 kHz, stop 1.5 kHz up

bands: band edges in Hz of fs, two per band; desired: one gain per band; weight: one per band (a heavier band gets less ripple); type: "bandpass", "hilbert" or "differentiator". Needs no scipy

Source code in src/rpps/signal/filters/filters.py
def remez(taps, bands, desired, weight=None, fs=1.0, type="bandpass"):
    """Equiripple (Parks-McClellan) FIR: the smallest possible maximum weighted error for `taps` coefficients

        remez(101, [0, 1000, 1500, 5000], [1, 0], fs=10e3)   # low pass: pass 0-1 kHz, stop 1.5 kHz up

    bands: band edges in Hz of `fs`, two per band; desired: one gain per band; weight: one per band (a heavier band gets less ripple);
    type: "bandpass", "hilbert" or "differentiator". Needs no scipy
    """
    return ConvFilter(np.asarray(_remez(taps, bands, desired, weight=weight, fs=fs, type=type), dtype=np.float32))

iir

IIR filters, with numpy only

An IIR is a cascade of second-order sections, one row [b0 b1 b2 a0 a1 a2] each: H(z) = (b0 + b1 z^-1 + b2 z^-2) / (a0 + a1 z^-1 + a2 z^-2) IIR(sos) filters a stream with them. The design helpers here make the sections from a specification: butter, cheby1, cheby2, the RBJ biquads, single_pole, and zpk2sos / tf2sos for coefficients from elsewhere. Frequencies are fractions of the sample rate (0.5 is Nyquist).

Filtering is exact and has no loop over samples (_Cascade): the sections are one state space system, its input cut into chunks of L samples. Every chunk's zero-state output is one matrix product (the L x L impulse-response matrix), and so is every chunk's contribution to the state at its end. The states at the chunk starts are an inclusive scan over the chunks (s_k = A^L s_(k-1) + u_k) in log2(chunks) array passes. The start states' outputs are one more product. Any block length works, it agrees with the sample-by-sample recursion to rounding (float64 inside), and it needs only array operations: the form a GPU runs. On the CPU, the C++ kernel (sos_filter, sample by sample, about 5 operations a sample and section) is 1.3-1.7x faster single-threaded, so it runs when loaded. An IIR has no constant group delay, so a stream's delay is not changed by it.

Classes:

Name Description
IIR

Cascade of second-order sections sos (rows [b0 b1 b2 a0 a1 a2]); gain scales the output

RunningMean

An exponential average that starts at the first sample: m[0] = x[0], m[n] = m[n-1] + alpha (x[n] - m[n-1]), a

Functions:

Name Description
as_sos

Sections as a float (n, 6) array normalised to a0 = 1

poles

Every pole of the cascade (a first-order section has one: its unused second pole at the origin is not listed)

sos2zpk

(zeros, poles, gain) of a cascade. Zeros at infinity (a section whose b0 is 0) are left out

zpk2sos

Sections for a filter of zeros z, poles p and gain k (z-plane, conjugates in pairs). Fewer zeros than poles means delays

tf2sos

Sections for the transfer function b(z^-1) / a(z^-1) (coefficients of rising powers of z^-1, as scipy.signal)

design

Sections of a Butterworth ("butter") or Chebyshev ("cheby1": ripple_db in the pass band, "cheby2": atten_db in the stop band) filter

single_pole

y[n] = alpha x[n] + (1 - alpha) y[n-1]: a leaky integrator / exponential average (0 < alpha <= 1)

biquad

One RBJ audio-EQ cookbook biquad. f0: centre/corner as a fraction of the sample rate; q: quality factor;

IIR

IIR(sos, gain=1.0)

Bases: Filter

Cascade of second-order sections sos (rows [b0 b1 b2 a0 a1 a2]); gain scales the output

The state carries across blocks, so any block length (including 0) works. Real or complex samples: the coefficients are real and act on both parts. Poles must be inside or on the unit circle (an integrator is allowed).

Methods:

Name Description
run

One-shot (stateless) filtering from zero state

response

(f, H): frequency response at n points from 0 to Nyquist (f in cycles per sample)

Source code in src/rpps/signal/filters/iir.py
def __init__(self, sos, gain=1.0):
    self.sos = as_sos(sos)
    self.sos[0, :3] *= gain
    if len(poles(self.sos)) and np.max(np.abs(poles(self.sos))) > 1 + 1e-9:
        raise ValueError(f"unstable IIR: a pole has radius {np.max(np.abs(poles(self.sos))):.6g}")
    self._cascade = _Cascade(self.sos)
run
run(samples)

One-shot (stateless) filtering from zero state

Source code in src/rpps/signal/filters/iir.py
def run(self, samples):
    """One-shot (stateless) filtering from zero state"""
    return self._run(samples, self.new_state(None).z)
response
response(n=512)

(f, H): frequency response at n points from 0 to Nyquist (f in cycles per sample)

Source code in src/rpps/signal/filters/iir.py
def response(self, n=512):
    """(f, H): frequency response at n points from 0 to Nyquist (f in cycles per sample)"""
    f = np.linspace(0, 0.5, n)
    zi = np.exp(-2j*np.pi*f)
    H = np.ones(n, dtype=complex)
    for b0, b1, b2, _, a1, a2 in self.sos:
        H *= (b0 + b1*zi + b2*zi**2) / (1 + a1*zi + a2*zi**2)
    return f, H

RunningMean

RunningMean(alpha)

An exponential average that starts at the first sample: m[0] = x[0], m[n] = m[n-1] + alpha (x[n] - m[n-1]), a single_pole IIR whose state is set from the first sample. run(x, z) -> (m, z); z None until a sample is seen

Source code in src/rpps/signal/filters/iir.py
def __init__(self, alpha):
    self.alpha = float(alpha)
    self.iir = IIR(single_pole(alpha))

as_sos

as_sos(sos)

Sections as a float (n, 6) array normalised to a0 = 1

Source code in src/rpps/signal/filters/iir.py
def as_sos(sos):
    """Sections as a float (n, 6) array normalised to a0 = 1"""
    sos = np.atleast_2d(np.asarray(sos, dtype=float))
    if sos.ndim != 2 or sos.shape[1] != 6 or len(sos) == 0:
        raise ValueError(f"sos is a list of rows [b0 b1 b2 a0 a1 a2], got shape {sos.shape}")
    if np.any(sos[:, 3] == 0):
        raise ValueError("a section has a0 = 0")
    return sos / sos[:, 3:4]

poles

poles(sos)

Every pole of the cascade (a first-order section has one: its unused second pole at the origin is not listed)

Source code in src/rpps/signal/filters/iir.py
def poles(sos):
    """Every pole of the cascade (a first-order section has one: its unused second pole at the origin is not listed)"""
    sos = as_sos(sos)
    return np.concatenate([np.roots(np.trim_zeros([1.0, r[4], r[5]], "b")) for r in sos])

sos2zpk

sos2zpk(sos)

(zeros, poles, gain) of a cascade. Zeros at infinity (a section whose b0 is 0) are left out

Source code in src/rpps/signal/filters/iir.py
def sos2zpk(sos):
    """(zeros, poles, gain) of a cascade. Zeros at infinity (a section whose b0 is 0) are left out"""
    sos = as_sos(sos)
    z, p, k = [], [], 1.0
    for r in sos:
        b = np.trim_zeros(r[:3], "f")
        k *= b[0] if len(b) else 0.0
        z.append(np.roots(b) if len(b) > 1 else np.zeros(0))
        p.append(np.roots([1.0, r[4], r[5]]))
    return np.concatenate(z), np.concatenate(p), k

zpk2sos

zpk2sos(z, p, k=1.0)

Sections for a filter of zeros z, poles p and gain k (z-plane, conjugates in pairs). Fewer zeros than poles means delays

Source code in src/rpps/signal/filters/iir.py
def zpk2sos(z, p, k=1.0):
    """Sections for a filter of zeros z, poles p and gain k (z-plane, conjugates in pairs). Fewer zeros than poles means delays"""
    z, p = np.asarray(z, dtype=complex), np.asarray(p, dtype=complex)
    if len(z) > len(p):
        raise ValueError(f"{len(z)} zeros and {len(p)} poles: the filter would not be causal")
    delay = len(p) - len(z)
    if len(p) == 0:
        return as_sos([[k, 0, 0, 1, 0, 0]])
    zp = _pairs(np.concatenate((z, np.zeros(delay))))
    pp = sorted(_pairs(p), key=lambda q: abs(q[0]))
    rows = []
    for pair in reversed(pp): # The poles nearest the unit circle pick their zeros first
        j = min(range(len(zp)), key=lambda i: min(abs(a - b) for a in pair if a is not None for b in zp[i] if b is not None))
        rows.append((pair, zp.pop(j)))
    rows.reverse()
    n = len(rows)
    g = abs(k)**(1.0/n) if k != 0 else 0.0
    sos = [np.concatenate((_poly(zero)*g*(np.sign(k) if i == 0 and k != 0 else 1.0), _poly(pole))) for i, (pole, zero) in enumerate(rows)]
    return as_sos(sos + _delay_rows(delay))

tf2sos

tf2sos(b, a=(1.0,))

Sections for the transfer function b(z^-1) / a(z^-1) (coefficients of rising powers of z^-1, as scipy.signal)

Source code in src/rpps/signal/filters/iir.py
def tf2sos(b, a=(1.0,)):
    """Sections for the transfer function b(z^-1) / a(z^-1) (coefficients of rising powers of z^-1, as scipy.signal)"""
    b, a = np.atleast_1d(np.asarray(b, dtype=float)), np.atleast_1d(np.asarray(a, dtype=float))
    if len(a) == 0 or a[0] == 0:
        raise ValueError("a[0] must not be 0")
    if not np.any(b):
        raise ValueError("all numerator coefficients are 0")
    delay = len(b) - len(np.trim_zeros(b, "f")) # Leading zeros of b are a pure delay
    b = np.trim_zeros(b, "f")
    n = max(len(a), len(b)) - 1
    if n > MAX_ORDER_TF:
        warnings.warn(f"order {n} transfer function: converting to sections loses accuracy, give sos or zpk instead")
    b, a = np.pad(b, (0, n + 1 - len(b))), np.pad(a, (0, n + 1 - len(a)))
    if n == 0:
        sos = as_sos([[b[0]/a[0], 0, 0, 1, 0, 0]])
    else:
        sos = zpk2sos(np.roots(b), np.roots(a), b[0]/a[0])
    return as_sos(np.vstack((sos, _delay_rows(delay)))) if delay else sos

design

design(kind, order, pass_, cutoff, ripple_db=None, atten_db=None)

Sections of a Butterworth ("butter") or Chebyshev ("cheby1": ripple_db in the pass band, "cheby2": atten_db in the stop band) filter

cutoff: the edge as a fraction of the sample rate (the -3 dB point of a butter; the ripple edge of cheby1; the stop edge of cheby2), or [low, high] for bandpass and bandstop.

Source code in src/rpps/signal/filters/iir.py
def design(kind, order, pass_, cutoff, ripple_db=None, atten_db=None):
    """Sections of a Butterworth ("butter") or Chebyshev ("cheby1": ripple_db in the pass band, "cheby2": atten_db in the stop band) filter

    cutoff: the edge as a fraction of the sample rate (the -3 dB point of a butter; the ripple edge of cheby1; the stop edge of cheby2),
    or [low, high] for bandpass and bandstop."""
    if kind not in ("butter", "cheby1", "cheby2"):
        raise ValueError(f"unknown design {kind!r}")
    if pass_ not in PASSES:
        raise ValueError(f"pass must be one of {PASSES}, not {pass_!r}")
    if int(order) != order or not 1 <= order <= 40:
        raise ValueError(f"order must be a whole number from 1 to 40, not {order}")
    if kind == "cheby1" and not (ripple_db and ripple_db > 0):
        raise ValueError("cheby1 needs ripple_db > 0")
    if kind == "cheby2" and not (atten_db and atten_db > 0):
        raise ValueError("cheby2 needs atten_db > 0")
    band = pass_ in ("bandpass", "bandstop")
    edges = np.atleast_1d(np.asarray(cutoff, dtype=float))
    if len(edges) != (2 if band else 1):
        raise ValueError(f"a {pass_} needs {'[low, high]' if band else 'one cutoff'}")
    if np.any(edges <= 0) or np.any(edges >= 0.5) or (band and edges[0] >= edges[1]):
        raise ValueError(f"cutoff must lie in (0, 0.5) of the sample rate, and low < high: {cutoff}")
    z, p, k = _proto(kind, int(order), ripple_db, atten_db)
    w = 2*np.tan(np.pi*edges)
    if pass_ == "lowpass":
        z, p, k = _lp2lp(z, p, k, w[0])
    elif pass_ == "highpass":
        z, p, k = _lp2hp(z, p, k, w[0])
    else:
        wo, bw = np.sqrt(w[0]*w[1]), w[1] - w[0]
        z, p, k = (_lp2bp if pass_ == "bandpass" else _lp2bs)(z, p, k, wo, bw)
    return zpk2sos(*_bilinear(z, p, k))

single_pole

single_pole(alpha)

y[n] = alpha x[n] + (1 - alpha) y[n-1]: a leaky integrator / exponential average (0 < alpha <= 1)

Source code in src/rpps/signal/filters/iir.py
def single_pole(alpha):
    """y[n] = alpha x[n] + (1 - alpha) y[n-1]: a leaky integrator / exponential average (0 < alpha <= 1)"""
    if not 0 < alpha <= 1:
        raise ValueError(f"alpha must be in (0, 1], not {alpha}")
    return as_sos([[alpha, 0, 0, 1, -(1 - alpha), 0]])

biquad

biquad(shape, f0, q=0.7071067811865476, gain_db=0.0)

One RBJ audio-EQ cookbook biquad. f0: centre/corner as a fraction of the sample rate; q: quality factor; gain_db: for peaking and the shelves

Source code in src/rpps/signal/filters/iir.py
def biquad(shape, f0, q=0.7071067811865476, gain_db=0.0):
    """One RBJ audio-EQ cookbook biquad. f0: centre/corner as a fraction of the sample rate; q: quality factor;
    gain_db: for peaking and the shelves"""
    if shape not in BIQUADS:
        raise ValueError(f"biquad shape must be one of {BIQUADS}, not {shape!r}")
    if not 0 < f0 < 0.5:
        raise ValueError(f"f0 must lie in (0, 0.5) of the sample rate, not {f0}")
    if q <= 0:
        raise ValueError("q must be positive")
    w0 = 2*np.pi*f0
    c, alpha, A = np.cos(w0), np.sin(w0)/(2*q), 10**(gain_db/40)
    sa = 2*np.sqrt(A)*alpha
    if shape == "lowpass":
        row = [(1 - c)/2, 1 - c, (1 - c)/2, 1 + alpha, -2*c, 1 - alpha]
    elif shape == "highpass":
        row = [(1 + c)/2, -(1 + c), (1 + c)/2, 1 + alpha, -2*c, 1 - alpha]
    elif shape == "bandpass":
        row = [alpha, 0, -alpha, 1 + alpha, -2*c, 1 - alpha]
    elif shape == "notch":
        row = [1, -2*c, 1, 1 + alpha, -2*c, 1 - alpha]
    elif shape == "allpass":
        row = [1 - alpha, -2*c, 1 + alpha, 1 + alpha, -2*c, 1 - alpha]
    elif shape == "peaking":
        row = [1 + alpha*A, -2*c, 1 - alpha*A, 1 + alpha/A, -2*c, 1 - alpha/A]
    elif shape == "lowshelf":
        row = [A*((A + 1) - (A - 1)*c + sa), 2*A*((A - 1) - (A + 1)*c), A*((A + 1) - (A - 1)*c - sa),
               (A + 1) + (A - 1)*c + sa, -2*((A - 1) + (A + 1)*c), (A + 1) + (A - 1)*c - sa]
    else:
        row = [A*((A + 1) + (A - 1)*c + sa), -2*A*((A - 1) + (A + 1)*c), A*((A + 1) + (A - 1)*c - sa),
               (A + 1) - (A - 1)*c + sa, 2*((A - 1) - (A + 1)*c), (A + 1) - (A - 1)*c - sa]
    return as_sos([row])

pfb

Classes:

Name Description
Channelizer

Polyphase filter bank: splits a wideband signal into channels equal bands, each at Fs/channels

Channelizer

Channelizer(channels, taps_per=12, window=np.hamming)

Bases: Stage

Polyphase filter bank: splits a wideband signal into channels equal bands, each at Fs/channels

bands = wide + rp.signal.filters.Channelizer(8)      # bands.data is (time, 8); column k is centred on k*Fs/8
one = bands.data[:, 2]

Channel k is centred on k*Fs/channels (channels above half the rate are the negative frequencies). taps_per: prototype filter taps per channel (longer: sharper channels, more delay)

Source code in src/rpps/signal/filters/pfb.py
def __init__(self, channels, taps_per=12, window=np.hamming):
    self.M = int(channels)
    L = self.M*taps_per
    self.h = designer(L, 1.0/self.M, fs=2, window=window).astype(np.float32) # Cut off at half a channel (fs=2: Nyquist is 1)

serial

Filter definitions, config/filter///.json (rp.signal.filters.load("fir/taps/name")), and pulses, config/pulse//.json (rp.signal.filters.load("pulse/rrc/0p35")): two resources

All frequencies are fractions of the sample rate (0.5 is Nyquist), or Hz with "units": "hz". FIR and shaping filters build their taps when a stream starts, from its Fs and sps (stage.taps(Fs=..., sps=...) shows them). "gain" scales any of them; "fs" (optional) is the rate the definition was made for, and warns if the stream differs.

fir      "type": "taps"      "taps": [...], "taps_imag": [...] (complex), "normalize": "dc" (unity gain at DC)
         "type": "windowed"  "pass": lowpass | highpass | bandpass | bandstop, "cutoff": f or [low, high], then
                             "taps": n, "window": name (default np.hamming, as rp.signal.filters.low_pass; "hamming" is the built-in one)
                             or "transition": width, "atten_db": dB (Kaiser window sized to meet it)
         "type": "remez"    "taps": n, "bands": [...], "desired": [...], "weight": [...]   "response": bandpass (default) | hilbert | differentiator; no scipy
iir      numpy only, as second-order sections. No constant group delay, so a stream's `delay` is unchanged. Unstable: rejected.
         "type": "sos"       "sos": [[b0, b1, b2, a0, a1, a2], ...]
         "type": "ba"        "b": [...], "a": [...]       scipy sign: y[n] = sum(b x) - sum(a[1:] y)
         "type": "zpk"       "z": [...], "p": [...], "k": gain       complex values as [re, im]; fewer zeros than poles = delay
         "type": "butter" | "cheby1" | "cheby2"
                             "order", "pass": as fir, "cutoff": f or [low, high], "ripple_db" (cheby1), "atten_db" (cheby2)
         "type": "biquad"    "shape": lowpass | highpass | bandpass | notch | allpass | peaking | lowshelf | highshelf,
                             "f0", "q", "gain_db"                                                  (RBJ audio-EQ cookbook)
         "type": "single_pole"  "alpha": y[n] = alpha x[n] + (1 - alpha) y[n-1]
pulse    "type": "rrc" | "rc"    "beta": 0.35, "span": 25 (symbols) or "taps": n, "sps": override the stream's
         "type": "sinc" | "rect" "taps", "sps"           "type": "biphase"   Manchester matched filter
window   "type": a built-in window name (`Window.s()`), "params": {its arguments}: kaiser/a8 is kaiser(N, a=8).
         Plain windows (hann, blackman...) are code, not files; `Window.get` and a design's "window" accept either.

Coefficients that are in a file or another tool go in through rpps.signal.filters.convert, never as a path in a definition.

Classes:

Name Description
Designed

A FIR defined by a config entry: the taps are made when the stream starts, from its sample rate and symbol rate

DesignedIIR

An IIR defined by a config entry: the sections are made when the stream starts (designs in Hz need its sample rate)

Functions:

Name Description
builtin

A window function of the code, by name (see Window.s())

window

A window function f(N): a preset ("kaiser/a8"), a built-in ("hann"), inline {"type": "kaiser", "params": {"a": 8}}, or a function

ls

List the filter and pulse definitions: {"fir/windowed": [names], "pulse/rrc": [...], "window/kaiser": [...]}

load

Load a filter, config/filter///.json, or a pulse, config/pulse//.json:

Designed

Designed(name, build, fs=None)

Bases: FIR

A FIR defined by a config entry: the taps are made when the stream starts, from its sample rate and symbol rate

Methods:

Name Description
taps

The coefficients for a sample rate and samples per symbol (needed by designs in Hz and by shaping pulses)

run

One-shot (stateless) filtering, drops the edges

Source code in src/rpps/signal/filters/serial.py
def __init__(self, name, build, fs=None):
    self.name, self.build, self.fs = name, build, fs
taps
taps(Fs=None, sps=None)

The coefficients for a sample rate and samples per symbol (needed by designs in Hz and by shaping pulses)

Source code in src/rpps/signal/filters/serial.py
def taps(self, Fs=None, sps=None):
    """The coefficients for a sample rate and samples per symbol (needed by designs in Hz and by shaping pulses)"""
    return np.asarray(self.build(Meta(Fs=Fs if Fs else float("nan"), sps=sps or 0.0)))
run
run(samples, Fs=None, sps=None)

One-shot (stateless) filtering, drops the edges

Source code in src/rpps/signal/filters/serial.py
def run(self, samples, Fs=None, sps=None):
    """One-shot (stateless) filtering, drops the edges"""
    return np.convolve(samples, self.taps(Fs, sps), mode="valid")

DesignedIIR

DesignedIIR(name, build, gain=1.0, fs=None)

Bases: Filter

An IIR defined by a config entry: the sections are made when the stream starts (designs in Hz need its sample rate)

Methods:

Name Description
sos

The sections for a sample rate (needed only by designs in Hz)

response

(f, H) from 0 to Nyquist, f in cycles per sample

run

One-shot (stateless) filtering from zero state

Source code in src/rpps/signal/filters/serial.py
def __init__(self, name, build, gain=1.0, fs=None):
    self.name, self.build, self.gain, self.fs = name, build, gain, fs
    self._made = (None, None)
sos
sos(Fs=None)

The sections for a sample rate (needed only by designs in Hz)

Source code in src/rpps/signal/filters/serial.py
def sos(self, Fs=None):
    """The sections for a sample rate (needed only by designs in Hz)"""
    return self._stage(Fs if Fs else float("nan")).sos.copy()
response
response(Fs=None, n=512)

(f, H) from 0 to Nyquist, f in cycles per sample

Source code in src/rpps/signal/filters/serial.py
def response(self, Fs=None, n=512):
    """(f, H) from 0 to Nyquist, f in cycles per sample"""
    return self._stage(Fs if Fs else float("nan")).response(n)
run
run(samples, Fs=None)

One-shot (stateless) filtering from zero state

Source code in src/rpps/signal/filters/serial.py
def run(self, samples, Fs=None):
    """One-shot (stateless) filtering from zero state"""
    return self._stage(Fs if Fs else float("nan")).run(samples)

builtin

builtin(name)

A window function of the code, by name (see Window.s())

Source code in src/rpps/signal/filters/serial.py
def builtin(name):
    """A window function of the code, by name (see `Window.s()`)"""
    if name not in _windows.s:
        raise ConfigError(f"No window {name!r}: not a preset ({sorted(_config.ls('filter').get('window', []))}) and not built in ({_windows.s})")
    return _windows.get(name)

window

window(spec='hamming')

A window function f(N): a preset ("kaiser/a8"), a built-in ("hann"), inline {"type": "kaiser", "params": {"a": 8}}, or a function

Source code in src/rpps/signal/filters/serial.py
def window(spec="hamming"):
    """A window function f(N): a preset ("kaiser/a8"), a built-in ("hann"), inline {"type": "kaiser", "params": {"a": 8}}, or a function"""
    if callable(spec):
        return spec
    if isinstance(spec, dict):
        return _window_def("inline", spec)
    file = _config.find("filter", spec, "window")
    if file is not None:
        return _config.load_obj("filter", spec, _config.read(file))
    return builtin(spec)

ls

ls(path=None)

List the filter and pulse definitions: {"fir/windowed": [names], "pulse/rrc": [...], "window/kaiser": [...]}

Source code in src/rpps/signal/filters/serial.py
def ls(path=None):
    """List the filter and pulse definitions: {"fir/windowed": [names], "pulse/rrc": [...], "window/kaiser": [...]}"""
    return {**_config.ls("filter", path), **{f"pulse/{k}": v for k, v in _config.ls("pulse", path).items()}}

load

load(ref: str, path=None, **params)

Load a filter, config/filter///.json, or a pulse, config/pulse//.json: load("fir/taps/moving_average_4"), load("pulse/rrc/0p35"). kind: fir | iir | window | pulse. params: values of the definition's "params" (see rp._config.resolve)

Source code in src/rpps/signal/filters/serial.py
def load(ref: str, path=None, **params):
    """Load a filter, config/filter/<kind>/<family>/<name>.json, or a pulse, config/pulse/<family>/<name>.json:
    `load("fir/taps/moving_average_4")`, `load("pulse/rrc/0p35")`. kind: fir | iir | window | pulse.
    params: values of the definition's "params" (see rp._config.resolve)"""
    kind, _, rest = str(ref).strip("/").partition("/")
    if kind not in KINDS or not rest:
        raise ConfigError(f"{ref}: give <kind>/<family>/<name>, kind one of {KINDS}")
    if kind == "pulse":
        return _config.load("pulse", rest, None, path, params=params)
    return _config.load("filter", rest, kind, path, params=params)

shaping

Classes:

Name Description
ShapingFilter
ShapingRRC
ShapingRC
ShapingHalfSine
ShapingGaussian
ShapingMatRRC
ShapingBiphase

Matched filter for biphase (Manchester) symbols: first half +1, second half -1

Functions:

Name Description
rrc_pulse

Root-raised-cosine pulse, t in symbols. Handles the t=0 and |t|=1/(4*beta) limits

rc_pulse

Raised-cosine pulse, t in symbols. Handles the |t| = 1/(2*beta) limit

ShapingFilter

Bases: FIR

Methods:

Name Description
run

One-shot (stateless) filtering

run
run(samples)

One-shot (stateless) filtering

Source code in src/rpps/signal/filters/shaping.py
def run(self, samples):
    """One-shot (stateless) filtering"""
    return np.convolve(samples, self.pulse, mode="same")

ShapingRRC

ShapingRRC(taps, sps, beta=0.35, gain=1.0)

Bases: ShapingFilter

Root-Raised Cosine shaping taps: number of taps for FIR (None: 25 symbols) sps: samples per symbol (sample width for 0 ISI) beta: roll off factor [0.35, 0 <= beta <= 1] gain: filter gain [1]

Source code in src/rpps/signal/filters/shaping.py
def __init__(self, taps, sps, beta=0.35, gain=1.0):
    """Root-Raised Cosine shaping
    taps: number of taps for FIR (None: 25 symbols)
    sps: samples per symbol (sample width for 0 ISI)
    beta: roll off factor [0.35, 0 <= beta <= 1]
    gain: filter gain [1]
    """
    taps = _default_taps(sps) if taps is None else int(taps)
    self.pulse = gain/sps*rrc_pulse(_centred(taps, sps), beta)

ShapingRC

ShapingRC(taps, sps, beta=0.35, gain=1.0)

Bases: ShapingFilter

Raised Cosine shaping taps: number of taps for FIR (None: 25 symbols) sps: samples per symbol (sample width for 0 ISI) beta: roll off factor [0.35, 0 <= beta <= 1] gain: filter gain [1]

Source code in src/rpps/signal/filters/shaping.py
def __init__(self, taps, sps, beta=0.35, gain=1.0):
    """Raised Cosine shaping
    taps: number of taps for FIR (None: 25 symbols)
    sps: samples per symbol (sample width for 0 ISI)
    beta: roll off factor [0.35, 0 <= beta <= 1]
    gain: filter gain [1]
    """
    taps = _default_taps(sps) if taps is None else int(taps)
    self.pulse = gain*rc_pulse(_centred(taps, sps), beta)

ShapingHalfSine

ShapingHalfSine(sps, gain=1.0)

Bases: ShapingFilter

Half-sine pulse lasting one symbol: sin(pi*n/sps) for n = 0..sps, so the ends are zero and, for an even sps, the centre is a whole sample (sps + 1 taps, peak gain). On both rails of O-QPSK (staggered by half a symbol) it is MSK sps: samples per symbol

Source code in src/rpps/signal/filters/shaping.py
def __init__(self, sps, gain=1.0):
    """Half-sine pulse lasting one symbol: sin(pi*n/sps) for n = 0..sps, so the ends are zero and, for an even sps, the centre
    is a whole sample (sps + 1 taps, peak `gain`). On both rails of O-QPSK (staggered by half a symbol) it is MSK
    sps: samples per symbol"""
    sps = int(round(sps))
    if sps < 2:
        raise ValueError(f"A half-sine pulse needs at least 2 samples per symbol, got {sps}")
    self.pulse = gain*np.sin(np.pi*np.arange(sps + 1)/sps)

ShapingGaussian

ShapingGaussian(sps, bt=0.5, span=4, gain=1.0)

Bases: ShapingFilter

Gaussian-filtered rectangle: the frequency pulse of GMSK and GFSK, from a held level of one symbol sps: samples per symbol. bt: 3 dB bandwidth times the symbol period (BLE 0.5, GSM 0.3). span: symbols the Gaussian covers The taps sum to sps, so a level held for a symbol comes out as that level: zero-stuff each symbol to sps samples, then filter, and the shaped signal integrates (rp.wave.FM) to the phase the modulation index asks for

Source code in src/rpps/signal/filters/shaping.py
def __init__(self, sps, bt=0.5, span=4, gain=1.0):
    """Gaussian-filtered rectangle: the frequency pulse of GMSK and GFSK, from a held level of one symbol
    sps: samples per symbol. bt: 3 dB bandwidth times the symbol period (BLE 0.5, GSM 0.3). span: symbols the Gaussian covers
    The taps sum to `sps`, so a level held for a symbol comes out as that level: zero-stuff each symbol to `sps` samples,
    then filter, and the shaped signal integrates (rp.wave.FM) to the phase the modulation index asks for"""
    sps = int(round(sps))
    sigma = np.sqrt(np.log(2))/(2*np.pi*bt)*sps # Samples: the Gaussian whose 3 dB bandwidth is bt/T
    n = int(round(span*sps)) | 1
    g = np.exp(-0.5*((np.arange(n) - (n - 1)/2)/sigma)**2)
    g /= g.sum()
    self.pulse = gain*np.convolve(np.ones(sps), g)

ShapingMatRRC

ShapingMatRRC(N, sps, poff=0, beta=0.35)

Bases: ShapingFilter

Methods:

Name Description
calc_tmat

N: the sample count at 1 SPS

pulse_rrc

tmat: time matrix to generated pulses

Source code in src/rpps/signal/filters/shaping.py
def __init__(self, N, sps, poff=0, beta=0.35):
    self.N = N
    self.sps = sps
    tmat = self.calc_tmat(N, sps)
    self.pulse = self.pulse_rrc(tmat, poff, beta)
calc_tmat
calc_tmat(N, sps)

N: the sample count at 1 SPS sps: desired SPS

Source code in src/rpps/signal/filters/shaping.py
def calc_tmat(self, N, sps):
    """
    N: the sample count at 1 SPS
    sps: desired SPS
    """
    num_out = N*sps
    vmat = np.ones((num_out, num_out)) * np.arange(num_out)
    tmat = vmat / sps - vmat.T
    tmat = tmat[0:num_out//sps, :]
    return tmat
pulse_rrc
pulse_rrc(tmat, poff=0, beta=0.35)

tmat: time matrix to generated pulses poff: pulse offset beta: beta rolloff

returns (N, N*sps) RRC matrix

Source code in src/rpps/signal/filters/shaping.py
def pulse_rrc(self, tmat, poff=0, beta=0.35):
    """
    tmat: time matrix to generated pulses
    poff: pulse offset
    beta: beta rolloff

    returns (N, N*sps) RRC matrix
    """
    return rrc_pulse(tmat - poff, beta)

ShapingBiphase

ShapingBiphase(gain=1.0)

Bases: ShapingFilter

Matched filter for biphase (Manchester) symbols: first half +1, second half -1

One symbol is meta.isps samples, so this takes sps from Meta when the stream starts.

Source code in src/rpps/signal/filters/shaping.py
def __init__(self, gain=1.0):
    self.gain = gain

rrc_pulse

rrc_pulse(t, beta=0.35)

Root-raised-cosine pulse, t in symbols. Handles the t=0 and |t|=1/(4*beta) limits

Source code in src/rpps/signal/filters/shaping.py
def rrc_pulse(t, beta=0.35):
    """Root-raised-cosine pulse, t in symbols. Handles the t=0 and |t|=1/(4*beta) limits"""
    t = np.asarray(t, dtype=np.float64)
    if beta == 0:
        return np.sinc(t)
    out = np.empty_like(t)
    at0 = np.abs(t) < 1e-9
    atS = np.abs(np.abs(t) - 1/(4*beta)) < 1e-9
    rest = ~(at0 | atS)
    out[at0] = 1.0 + beta*(4/np.pi - 1)
    out[atS] = beta/np.sqrt(2) * (
        (1 + 2/np.pi) * np.sin(np.pi/(4*beta)) + (1 - 2/np.pi) * np.cos(np.pi/(4*beta))
    )
    tr = t[rest]
    out[rest] = (np.sin(np.pi*tr*(1 - beta)) + 4*beta*tr*np.cos(np.pi*tr*(1 + beta))) \
        / (np.pi*tr*(1 - (4*beta*tr)**2))
    return out

rc_pulse

rc_pulse(t, beta=0.35)

Raised-cosine pulse, t in symbols. Handles the |t| = 1/(2*beta) limit

Source code in src/rpps/signal/filters/shaping.py
def rc_pulse(t, beta=0.35):
    """Raised-cosine pulse, t in symbols. Handles the |t| = 1/(2*beta) limit"""
    t = np.asarray(t, dtype=np.float64)
    if beta == 0:
        return np.sinc(t)
    den = 1 - (2*beta*t)**2
    sing = np.abs(den) < 1e-9
    safe = np.where(sing, 1.0, den)
    out = np.sinc(t)*np.cos(np.pi*beta*t)/safe
    out[sing] = np.pi/4*np.sinc(1/(2*beta))
    return out

shift

Classes:

Name Description
ShiftFreq

Shift the spectrum by fo Hz. The oscillator phase carries across blocks

ShiftFreqIdx

Shift by fo cycles per sample (fo is normalised to the sample rate)

ShiftTime

Delay by a fraction of a sample (windowed-sinc fractional delay), carrying its history across blocks

ShiftFreq

ShiftFreq(fo)

Bases: Filter

Shift the spectrum by fo Hz. The oscillator phase carries across blocks

Methods:

Name Description
run

One-shot (stateless) shift; Fs 1: fo is in cycles per sample

Source code in src/rpps/signal/filters/shift.py
def __init__(self, fo):
    self.fo = fo
run
run(samples, Fs=1.0)

One-shot (stateless) shift; Fs 1: fo is in cycles per sample

Source code in src/rpps/signal/filters/shift.py
def run(self, samples, Fs=1.0):
    """One-shot (stateless) shift; Fs 1: fo is in cycles per sample"""
    t = np.arange(len(samples))/Fs
    return (samples * np.exp(2j*np.pi*self.fo*t)).astype(_cdtype(samples), copy=False)

ShiftFreqIdx

ShiftFreqIdx(fo)

Bases: ShiftFreq

Shift by fo cycles per sample (fo is normalised to the sample rate)

Source code in src/rpps/signal/filters/shift.py
def __init__(self, fo):
    self.fo = fo

ShiftTime

ShiftTime(delay, taps=21)

Bases: FIR

Delay by a fraction of a sample (windowed-sinc fractional delay), carrying its history across blocks

delay: samples, normally in [0, 1). The filter's own latency is (taps-1)/2 samples

Methods:

Name Description
run

One-shot (stateless) shift, drops the edges

Source code in src/rpps/signal/filters/shift.py
def __init__(self, delay, taps=21):
    pulse = np.arange(taps) - (taps-1)/2
    pulse = np.sinc(pulse - delay) # calc filter taps
    pulse *= np.hamming(taps)
    pulse /= np.sum(pulse)  # unity gain
    self.pulse = pulse
run
run(samples)

One-shot (stateless) shift, drops the edges

Source code in src/rpps/signal/filters/shift.py
def run(self, samples):
    """One-shot (stateless) shift, drops the edges"""
    return np.convolve(samples, self.pulse, mode="valid")

window

Classes:

Name Description
Window

Window

Window(name, N=None, *args, **kwargs)

Bases: Filter

Methods:

Name Description
step

Weight each block by the window (one window per block: N, or the block's length)

s

Names of the built-in windows (presets are listed by rp.signal.filters.ls())

get

The window function name: a built-in (see s()), or a preset from config/filter/window ("kaiser/a8")

Source code in src/rpps/signal/filters/window.py
def __init__(self, name, N=None, *args, **kwargs):
    self.N = N
    self.window = serial.window(name)
    if self.N is not None:
        self.w = self.window(self.N, *args, **kwargs)
step
step(samples, st, meta: Meta)

Weight each block by the window (one window per block: N, or the block's length)

Source code in src/rpps/signal/filters/window.py
def step(self, samples, st, meta: Meta):
    """Weight each block by the window (one window per block: N, or the block's length)"""
    if self.N is None:
        return samples * self.window(len(samples))
    if len(samples) != self.N:
        raise ValueError(f"Window of {self.N} was given a block of {len(samples)}")
    return samples * self.w
s staticmethod
s()

Names of the built-in windows (presets are listed by rp.signal.filters.ls())

Source code in src/rpps/signal/filters/window.py
@staticmethod
def s():
    """Names of the built-in windows (presets are listed by `rp.signal.filters.ls()`)"""
    return s
get staticmethod
get(name)

The window function name: a built-in (see s()), or a preset from config/filter/window ("kaiser/a8")

Source code in src/rpps/signal/filters/window.py
@staticmethod
def get(name):
    """The window function `name`: a built-in (see `s()`), or a preset from config/filter/window ("kaiser/a8")"""
    return serial.window(name)

rpps.signal.filters.impl

Building blocks behind rpps.signal.filters: designer (simple lowpass/highpass prototypes by name: sinc, delta, exponential...), gaussian (the Gaussian and its FWHM), window (window functions and their properties)

Modules:

Name Description
designer
gaussian
remez

Parks-McClellan equiripple FIR design (the Remez exchange), numpy only

window

Window functions

designer

gaussian

remez

Parks-McClellan equiripple FIR design (the Remez exchange), numpy only

The amplitude response of a linear-phase FIR is A(w) = Q(w) P(w), P a cosine series of r terms and Q fixed by the type:

type  taps  symmetry   Q            h
I     odd   even       1            h[c +- m] =  b[m] / 2
II    even  even       cos(w/2)     h[c +- m] =  b[m] / 2
III   odd   odd        sin(w)       h[c + m]  =  s[m] / 2, h[c - m] = -s[m] / 2   (Hilbert, differentiator)
IV    even  odd        sin(w/2)     as III

with c = (taps - 1) / 2. Dividing the desired response by Q and multiplying the weight by it turns every type into the same weighted approximation of D by P. Each pass of the exchange fits P through r points of the current extremal set with the error alternating in sign, then moves the extremals to the extrema of the weighted error on a dense grid. The error equioscillates at the optimum.

Functions:

Name Description
remez

Equiripple FIR of taps coefficients, optimal in the weighted Chebyshev sense: the maximum error is the smallest possible

remez

remez(taps, bands, desired, weight=None, fs=1.0, type='bandpass', maxiter=100, density=_DENSITY)

Equiripple FIR of taps coefficients, optimal in the weighted Chebyshev sense: the maximum error is the smallest possible

bands edges of the bands that count, in Hz of sample rate fs, rising: [0, 1000, 1500, 5000] is two bands. The gaps are don't-care desired one gain per band (bandpass, hilbert), or one slope per band (differentiator) weight one weight per band, default all 1. A heavier band is held to a smaller error type "bandpass" (a filter; the default), "hilbert" or "differentiator" (odd symmetry)

Returns the float64 coefficients. Raises ValueError for an impossible specification and RuntimeError when the exchange does not converge

Source code in src/rpps/signal/filters/impl/remez.py
def remez(taps, bands, desired, weight=None, fs=1.0, type="bandpass", maxiter=100, density=_DENSITY):
    """Equiripple FIR of `taps` coefficients, optimal in the weighted Chebyshev sense: the maximum error is the smallest possible

    bands    edges of the bands that count, in Hz of sample rate `fs`, rising: [0, 1000, 1500, 5000] is two bands. The gaps are don't-care
    desired  one gain per band (`bandpass`, `hilbert`), or one slope per band (`differentiator`)
    weight   one weight per band, default all 1. A heavier band is held to a smaller error
    type     "bandpass" (a filter; the default), "hilbert" or "differentiator" (odd symmetry)

    Returns the float64 coefficients. Raises ValueError for an impossible specification and RuntimeError when the exchange does not converge
    """
    taps, bands, desired, weight = _check(taps, np.asarray(bands, np.float64)/fs, desired, weight, type)
    sym = type == "bandpass"
    even = taps % 2 == 0
    r = (taps + 1)//2 if sym and not even else taps//2 if even else (taps - 1)//2 # terms of P: (N+1)/2 (I), N/2 (II, IV), (N-1)/2 (III)
    f, D, W, seg = _grid(bands, desired, weight, r, type, sym, even, density)
    if len(f) < r + 1:
        raise ValueError("remez: too many taps for the width of the bands")
    x = np.cos(2*np.pi*f)
    ext = np.round(np.linspace(0, len(f) - 1, r + 1)).astype(int)
    for _ in range(maxiter):
        delta, y = _fit(x[ext], D[ext], W[ext])
        A = _eval(x, x[ext][:-1], y)
        E = W*(D - A)
        new = _extrema(E, seg)
        if len(new) < r + 1:
            raise RuntimeError("remez: failure to converge (lost extremals): the ripple is below what float64 resolves, try a wider transition band or fewer taps")
        new = _reduce(new, E, r + 1)
        e = np.abs(E[new])
        if np.array_equal(new, ext) or (e.max() - e.min()) <= 1e-9*e.max():
            ext = np.array(new)
            delta, y = _fit(x[ext], D[ext], W[ext])
            break
        ext = np.array(new)
    else:
        raise RuntimeError(f"remez: no convergence in {maxiter} iterations")
    # P is a cosine series of r terms: recover it from r samples at the Chebyshev points (exact for that degree)
    wj = np.pi*(np.arange(r) + 0.5)/r
    P = _eval(np.cos(wj), x[ext][:-1], y)
    c = (2.0/r)*np.cos(np.outer(np.arange(r), wj)) @ P
    c[0] /= 2
    h = _taps(c, taps, sym, even)
    return h if sym else -h # antisymmetric: A > 0 is a positive impulse response after the centre (Hilbert), as scipy

window

Window functions

Generalized properties - (NB) Noise bandwidth, / Spectral leakage - (SL) Scalloping loss / Amplitude accuracy - (FR) Frequency resolution Ratings, (Best, Good, Fair, Poor) [5,3,1,0]

Window NB SL FR
Blackman 5 3 1
Flattop 3 5 0
Gaussian 1 3 1
Rectangle 0 0 5
Hanning 3 1 3
Hamming 1 1 3
Kaiser 3 3 1

rpps.signal.sample

Sample-rate changes as stages: down (decimation), up (interpolation) and re (rational resampling), fractional (any ratio, with a shift fused in); resample_poly and fractional_resample resample an array in one call

Modules:

Name Description
down
fractional

Resampling by any ratio with a windowed-sinc polyphase filter, and an optional frequency shift fused in front of it

re
resample

One-shot rational resampling of an array

sample
up

down

Classes:

Name Description
Decimate

Keep every ratioth sample, starting with sample offset. The phase carries across blocks, so any block length works

FractionalSpline

Functions:

Name Description
interpolate_stream

Read samples at positions st.pos, st.pos + step, ... by interpolation, carrying the position and the unread

Decimate

Decimate(ratio: int, offset: int = 0)

Bases: Downsample

Keep every ratioth sample, starting with sample offset. The phase carries across blocks, so any block length works

Methods:

Name Description
run

One-shot (stateless) decimation

Source code in src/rpps/signal/sample/down.py
def __init__(self, ratio: int, offset: int = 0):
    self.ratio = int(ratio)
    self.offset = int(offset)
run
run(samples)

One-shot (stateless) decimation

Source code in src/rpps/signal/sample/down.py
def run(self, samples):
    """One-shot (stateless) decimation"""
    return samples[::self.ratio]

FractionalSpline

FractionalSpline(ratio: float, kind='linear')

Bases: Downsample

kind: "linear", or "cubic" for a smoother result

Methods:

Name Description
run

One-shot (stateless) resampling

Source code in src/rpps/signal/sample/down.py
def __init__(self, ratio: float, kind="linear"):
    """kind: "linear", or "cubic" for a smoother result"""
    if not ratio > 0:
        raise ValueError("Resample ratio must be positive")
    if kind not in ("linear", "cubic"):
        raise ValueError("kind must be linear or cubic")
    self.ratio = ratio
    self.kind = kind
run
run(samples)

One-shot (stateless) resampling

Source code in src/rpps/signal/sample/down.py
def run(self, samples):
    """One-shot (stateless) resampling"""
    return interpolate_stream(samples, self.new_state(None), 1/self.ratio, self.kind)

interpolate_stream

interpolate_stream(samples, st, step, kind='linear')

Read samples at positions st.pos, st.pos + step, ... by interpolation, carrying the position and the unread tail in st (SimpleNamespace(tail=None, pos=0.0); for "cubic", pos starts at 1.0). step: input samples per output sample. kind: "linear", or "cubic" (Catmull-Rom: smoother, needs one sample before and two after)

Source code in src/rpps/signal/sample/down.py
def interpolate_stream(samples, st, step, kind="linear"):
    """Read `samples` at positions st.pos, st.pos + step, ... by interpolation, carrying the position and the unread
    tail in `st` (SimpleNamespace(tail=None, pos=0.0); for "cubic", pos starts at 1.0). step: input samples per output
    sample. kind: "linear", or "cubic" (Catmull-Rom: smoother, needs one sample before and two after)"""
    cubic = kind == "cubic"
    pre = 1 if cubic else 0
    if st.tail is None and pre and len(samples):
        samples = np.concatenate((samples[:1], samples)) # Nothing before the first sample: repeat it
    buf = samples if st.tail is None else np.concatenate((st.tail, samples))
    n = len(buf)
    last = n - 1 - (2 if cubic else 0) # Newest position that has what it needs
    count = int(np.floor((last - st.pos)/step)) + 1 if n and st.pos <= last else 0
    pos = st.pos + step*np.arange(count)
    i0 = pos.astype(np.int64)
    mu = (pos - i0).astype(np.float32)
    if not count:
        out = buf[:0]
    elif cubic:
        a, b, c, d = buf[i0 - 1], buf[i0], buf[i0 + 1], buf[i0 + 2]
        out = b + 0.5*mu*(c - a + mu*(2*a - 5*b + 4*c - d + mu*(3*(b - c) + d - a)))
    else:
        out = buf[i0]*(1 - mu) + buf[np.minimum(i0 + 1, n - 1)]*mu
    nxt = st.pos + step*count
    keep = max(0, min(int(nxt) - pre, n)) # Samples before this can't be reached any more
    st.tail = buf[keep:]
    st.pos = nxt - keep
    return out.astype(buf.dtype, copy=False)

fractional

Resampling by any ratio with a windowed-sinc polyphase filter, and an optional frequency shift fused in front of it

Classes:

Name Description
FractionalPolyphase

Resample by any ratio (output rate over input rate) with a Kaiser-windowed sinc polyphase filter, and optionally move the spectrum first

Functions:

Name Description
design_bank

(phases + 1, taps) table of the interpolation filter: row p is the kernel for a read position p/phases of the way past a sample

read_python

The reference for native.polyphase_read: output k is buf read at pos + k*step, the nearest of the table's phases. A chunk of outputs at a time

fractional_resample

Resample the array x (sample rate Fs, which only matters to cutoff and shift, in Hz) by ratio: a one-call FractionalPolyphase

FractionalPolyphase

FractionalPolyphase(ratio, cutoff=None, taps=32, phases=512, beta=7.0, shift=0.0)

Bases: Sample

Resample by any ratio (output rate over input rate) with a Kaiser-windowed sinc polyphase filter, and optionally move the spectrum first

stage = FractionalPolyphase(10.7622/20)                              # 20 MS/s to 10.7622 MS/s, anti-aliased
stage = FractionalPolyphase(10.7622/20, cutoff=3.7e6, shift=-0.5e6)  # the channel at +0.5 MHz to baseband, then resample

Output m is the input at time m/ratio, with no delay (as resample_poly). The read position and the oscillator phase carry across blocks, so any block length gives the same stream, and ratio may be changed between blocks (a clock error trim): the position carries in input samples and the filter stays as designed. Real input gives real output unless a shift is asked for.

output rate / input rate. cutoff: [Hz, at the input rate] edge of the pass band; None: the lower Nyquist, so decimating

does not alias. taps: filter length (even): it sets the transition width. phases: kernels tabulated over one input sample: the read position is rounded to the nearest, so the interpolation error of the position is about 1/(2phases) of a sample (the image it makes is -20log10(pi*bandwidth/phases) dB below the signal). beta: Kaiser window, sets the stop band depth (7: about 70 dB).

shift: [Hz] translation applied before the filter, equal to ShiftFreq(shift) followed by this stage; the centre frequency moves with it.

Methods:

Name Description
bank

The (phases + 1, taps) table for an input sample rate Fs

Source code in src/rpps/signal/sample/fractional.py
def __init__(self, ratio, cutoff=None, taps=32, phases=512, beta=7.0, shift=0.0):
    if not ratio > 0:
        raise ValueError("ratio must be positive")
    design_bank(taps, 1, 0.25, beta) # Check the settings now
    self.ratio, self.cutoff, self.taps, self.phases, self.beta, self.shift = float(ratio), cutoff, int(taps), int(phases), float(beta), float(shift)
bank
bank(Fs)

The (phases + 1, taps) table for an input sample rate Fs

Source code in src/rpps/signal/sample/fractional.py
def bank(self, Fs):
    """The (phases + 1, taps) table for an input sample rate `Fs`"""
    cut = 0.5*min(1.0, self.ratio) if self.cutoff is None else self.cutoff/Fs
    return design_bank(self.taps, self.phases, cut, self.beta)

design_bank

design_bank(taps, phases, cutoff, beta=7.0)

(phases + 1, taps) table of the interpolation filter: row p is the kernel for a read position p/phases of the way past a sample

taps: even length (the kernel spans taps/2 samples either side of the read position). cutoff: [cycles per input sample] 0..0.5. Kaiser window, every row normalised to unit gain at DC so a constant keeps its level wherever it is read

Source code in src/rpps/signal/sample/fractional.py
def design_bank(taps, phases, cutoff, beta=7.0):
    """(phases + 1, taps) table of the interpolation filter: row p is the kernel for a read position p/phases of the way past a sample

    taps: even length (the kernel spans taps/2 samples either side of the read position). cutoff: [cycles per input sample] 0..0.5.
    Kaiser window, every row normalised to unit gain at DC so a constant keeps its level wherever it is read"""
    if taps < 2 or taps % 2:
        raise ValueError("taps must be even and at least 2")
    if not 0 < cutoff <= 0.5:
        raise ValueError("cutoff must be in (0, 0.5] cycles per input sample")
    half = taps//2
    f = np.arange(phases + 1)/phases
    d = f[:, None] - np.arange(-half + 1, half + 1)[None, :] # distance from the read position to each tap's sample
    win = np.where(np.abs(d) < half, np.i0(beta*np.sqrt(np.clip(1 - (d/half)**2, 0, 1)))/np.i0(beta), 0.0) # zero at the ends: the last row (a whole sample) is then the first row one sample on
    g = 2*cutoff*np.sinc(2*cutoff*d)*win
    return np.ascontiguousarray(g/g.sum(axis=1, keepdims=True))

read_python

read_python(buf, table, pos, step, nout)

The reference for native.polyphase_read: output k is buf read at pos + k*step, the nearest of the table's phases. A chunk of outputs at a time

Source code in src/rpps/signal/sample/fractional.py
def read_python(buf, table, pos, step, nout):
    """The reference for `native.polyphase_read`: output k is `buf` read at pos + k*step, the nearest of the table's phases. A chunk of outputs at a time"""
    half = table.shape[1]//2
    nph = table.shape[0] - 1
    out = np.empty(nout, dtype=np.result_type(buf.dtype, np.float32))
    taps = np.arange(-half + 1, half + 1)
    for a in range(0, nout, _CHUNK):
        p = pos + step*np.arange(a, min(nout, a + _CHUNK))
        i0 = p.astype(np.int64)
        ph = np.floor((p - i0)*nph + 0.5).astype(np.int64)
        out[a:a + len(p)] = np.einsum("nj,nj->n", buf[i0[:, None] + taps[None, :]], table[ph])
    return out

fractional_resample

fractional_resample(x, ratio, Fs=1.0, **kw)

Resample the array x (sample rate Fs, which only matters to cutoff and shift, in Hz) by ratio: a one-call FractionalPolyphase

Source code in src/rpps/signal/sample/fractional.py
def fractional_resample(x, ratio, Fs=1.0, **kw):
    """Resample the array `x` (sample rate `Fs`, which only matters to `cutoff` and `shift`, in Hz) by `ratio`: a one-call `FractionalPolyphase`"""
    from ...base import Data
    return np.asarray((Data(x, Fs=Fs, sps=1, flush=True) + FractionalPolyphase(ratio, **kw)).data)

re

Classes:

Name Description
Resample
Polyphase

Stateful FIR rational resampler. Output length tracks up/down across blocks

Resample

Resample(up, down, taps=None)

Bases: Sample

Rational resampler by up/down taps: anti-image/anti-alias FIR length at the up-sampled rate [20*max(up, down)+1]

Source code in src/rpps/signal/sample/re.py
def __init__(self, up, down, taps=None):
    """Rational resampler by up/down
    taps: anti-image/anti-alias FIR length at the up-sampled rate [20*max(up, down)+1]
    """
    self.up = int(up)
    self.down = int(down)
    n = max(self.up, self.down)
    if taps is None:
        taps = 20*n+1
    # Cutoff is the Nyquist of the lower rate, at the up-sampled rate. Gain `up` makes up for the zero stuffing
    self.taps = self.up * designer(taps, 1/n, window=np.hamming, scale=True).astype(np.float64)

Polyphase

Polyphase(up, down, taps=None)

Bases: Resample

Stateful FIR rational resampler. Output length tracks up/down across blocks

Source code in src/rpps/signal/sample/re.py
def __init__(self, up, down, taps=None):
    """Rational resampler by up/down
    taps: anti-image/anti-alias FIR length at the up-sampled rate [20*max(up, down)+1]
    """
    self.up = int(up)
    self.down = int(down)
    n = max(self.up, self.down)
    if taps is None:
        taps = 20*n+1
    # Cutoff is the Nyquist of the lower rate, at the up-sampled rate. Gain `up` makes up for the zero stuffing
    self.taps = self.up * designer(taps, 1/n, window=np.hamming, scale=True).astype(np.float64)

resample

One-shot rational resampling of an array

Functions:

Name Description
design

The filter resample_poly uses: (taps at the up-sampled rate, gain up included, centre index)

resample_poly

Resample x by the rational factor up/down with a linear-phase FIR low pass and no delay: output m is the input at time m*down/up

design

design(up, down, window=('kaiser', 5.0))

The filter resample_poly uses: (taps at the up-sampled rate, gain up included, centre index)

Source code in src/rpps/signal/sample/resample.py
def design(up, down, window=("kaiser", 5.0)):
    """The filter `resample_poly` uses: (taps at the up-sampled rate, gain `up` included, centre index)"""
    n = max(up, down)
    c = 10*n
    if isinstance(window, tuple) and window and window[0] == "kaiser":
        beta = float(window[1]) if len(window) > 1 else 5.0
        win = lambda m: np.kaiser(m, beta)
    elif callable(window):
        win = window
    elif isinstance(window, tuple):
        raise ValueError(f"unknown window {window!r}: use ('kaiser', beta), a function of the length, or the taps themselves")
    else:
        h = np.asarray(window, np.float64)
        return h, (len(h) - 1)//2
    return up*designer(2*c + 1, 1/n, window=win, scale=True), c

resample_poly

resample_poly(x, up, down, window=('kaiser', 5.0))

Resample x by the rational factor up/down with a linear-phase FIR low pass and no delay: output m is the input at time m*down/up

Only the outputs that are kept are computed (polyphase). Returns ceil(len(x)*up/down) samples; single precision stays single. window: ("kaiser", beta), a function of the length, or the taps themselves (at the up-sampled rate, odd length)

Source code in src/rpps/signal/sample/resample.py
def resample_poly(x, up, down, window=("kaiser", 5.0)):
    """Resample `x` by the rational factor up/down with a linear-phase FIR low pass and no delay: output m is the input at time m*down/up

    Only the outputs that are kept are computed (polyphase). Returns ceil(len(x)*up/down) samples; single precision stays single.
    window: ("kaiser", beta), a function of the length, or the taps themselves (at the up-sampled rate, odd length)
    """
    x = np.asarray(x)
    up, down = int(up), int(down)
    if up < 1 or down < 1:
        raise ValueError("up and down must be positive whole numbers")
    g = gcd(up, down)
    up, down = up//g, down//g
    if x.ndim != 1:
        raise ValueError("resample_poly takes a 1-D array")
    single = x.dtype in (np.float32, np.complex64)
    if up == down == 1:
        return x.copy()
    h, c = design(up, down, window)
    nout = -(-len(x)*up//down)
    cplx = np.iscomplexobj(x)
    work = np.complex64 if (single and cplx) else np.float32 if single else np.complex128 if cplx else np.float64
    h = h.astype(np.float32 if single else np.float64, copy=False)
    out = np.empty(nout, dtype=work)
    if nout == 0:
        return out
    J = (c + up - 1)//up + 1                 # taps on each side of an input sample at the up-sampled phase
    K = 2*J + 1
    # y[m] = sum_j x[i0 - j] h[ph + c + j up], i0 = m down // up, ph = m down % up; every up-th output shares ph
    xp = np.concatenate((np.zeros(J, x.dtype), x, np.zeros(J + down + 1, x.dtype))).astype(work, copy=False)
    win = np.lib.stride_tricks.sliding_window_view(xp, K)
    for u in range(min(up, nout)):
        ph = (u*down) % up
        j = np.arange(J, -J - 1, -1)          # j = J - q for the window element q
        idx = ph + c + j*up
        gr = np.where((idx >= 0) & (idx <= 2*c), h[np.clip(idx, 0, len(h) - 1)], 0).astype(h.dtype)
        i0 = (u*down)//up
        nt = -(-(nout - u)//up)
        rows = win[i0:i0 + nt*down:down][:nt]
        step = max(_CHUNK//K, 1)
        for a in range(0, nt, step):
            blk = rows[a:a + step]
            if cplx:
                y = (np.ascontiguousarray(blk.real) @ gr) + 1j*(np.ascontiguousarray(blk.imag) @ gr)
            else:
                y = blk @ gr
            out[u + up*a:u + up*(a + len(blk)):up] = y
    return out

sample

up

Classes:

Name Description
Interpolate

Zero stuff by ratio and filter with filt (an FIR stage, a pulse shape) in one step: the same output as

Sinc

Zero stuff and interpolate with a windowed sinc. The filter history carries across blocks

Interpolate

Interpolate(ratio, filt)

Bases: Upsample

Zero stuff by ratio and filter with filt (an FIR stage, a pulse shape) in one step: the same output as Zeros(ratio) + filt, in polyphase form, so the zeros are never multiplied (ratio times less work)

tx = symbols + rp.signal.sample.up.Interpolate(8, rp.signal.filters.load("pulse/rrc/0_35"))

Output sample n*ratio + p is phase p of the taps (taps[p::ratio]) run over the input, so each phase is an ordinary FIR on the input samples, with one history shared by all of them. A flush (the end of the stream) also sends the filter's tail, so the last symbols' pulses are complete.

Source code in src/rpps/signal/sample/up.py
def __init__(self, ratio, filt):
    super().__init__(ratio)
    self.filt = filt

Sinc

Sinc(ratio, taps=None)

Bases: Interpolate

Zero stuff and interpolate with a windowed sinc. The filter history carries across blocks

Methods:

Name Description
run

One-shot (stateless) interpolation, same length as ratio*samples

Source code in src/rpps/signal/sample/up.py
def __init__(self, ratio, taps=None):
    ratio = int(ratio)
    taps = max(ratio*12, 31) if taps is None else int(taps)
    super().__init__(ratio, ConvFilter(np.sinc((np.arange(taps | 1) - (taps | 1)//2)/ratio))) # Streaming: symmetric, centre tap
    self.pulse = shaping.ShapingSinc(taps, ratio, 1) # One-shot kernel
run
run(samples)

One-shot (stateless) interpolation, same length as ratio*samples

Source code in src/rpps/signal/sample/up.py
def run(self, samples):
    """One-shot (stateless) interpolation, same length as ratio*samples"""
    up = np.zeros(len(samples)*self.ratio, dtype=samples.dtype)
    up[::self.ratio] = samples
    up = self.pulse.run(up)
    return up