Skip to content

Math

rpps.math

Shared maths: finite fields, GF(2) linear algebra, cyclic-code decoding, probability, interpolation, rolling percentiles, runs of a mask, least squares, bit tricks

Numpy only, no knowledge of the rest of rpps: anything two modules both need and that isn't about signals goes here.

Modules:

Name Description
bits

Bit manipulation; on hard bits (one a byte): the Hamming distance to a word at every position (distance, find)

cyclic

Algebraic decoding of cyclic codes (Reed-Solomon, BCH) from their syndromes

demap

Soft demapping of symbols to bit LLRs, for rows of symbols at once (one frame a row), on any array module xp

gf

Finite field GF(2^m) arithmetic

gf2

Linear algebra over GF(2), and bit sequences filtered over it

interp

Interpolation

mask

Boolean masks along one axis

optimize

Nonlinear least squares

prob

Probability and statistics helpers

rolling

Rolling statistics of a 1-D array

bits

Bit manipulation; on hard bits (one a byte): the Hamming distance to a word at every position (distance, find) and bit destuffing over many spans (unstuff), in C++ when rpps._native is built

Functions:

Name Description
entropy

Entropy of a bit stream [bits per bit]: H = -p0 log2 p0 - p1 log2 p1 (0 log 0 = 0)

reflect

Reverse the order of the low width bits of an integer

to_base2

Every order-bit pattern in counting order: (2^order, order) array of 0/1, most significant bit first

to_base10

Rows of bits (most significant first) -> integers

hamming

Hamming distance: the number of positions where bit arrays a and b differ

distance

The Hamming distance to word at every position of bits (len(bits) - len(word) + 1 of them, int): 0 where the

find

Where word starts in bits with at most errors bits wrong

periodic_scores

Periodic marker fit.

unstuff

Bit destuffing (HDLC's: after stuff ones a 0 is dropped, stuff + 1 ones abort) of the spans [starts[i], ends[i])

entropy

entropy(bits)

Entropy of a bit stream [bits per bit]: H = -p0 log2 p0 - p1 log2 p1 (0 log 0 = 0)

Source code in src/rpps/math/bits.py
def entropy(bits):
    """Entropy of a bit stream [bits per bit]: H = -p0 log2 p0 - p1 log2 p1 (0 log 0 = 0)"""
    bits = np.asarray(bits)
    p = np.array([np.mean(bits == 0), np.mean(bits == 1)])
    p = p[p > 0]
    return float(-np.sum(p*np.log2(p)))

reflect

reflect(v, width)

Reverse the order of the low width bits of an integer

Source code in src/rpps/math/bits.py
def reflect(v, width):
    """Reverse the order of the low `width` bits of an integer"""
    return int(format(v, f"0{width}b")[::-1], 2)

to_base2

to_base2(order)

Every order-bit pattern in counting order: (2^order, order) array of 0/1, most significant bit first

Source code in src/rpps/math/bits.py
def to_base2(order):
    """Every `order`-bit pattern in counting order: (2^order, order) array of 0/1, most significant bit first"""
    return ((np.arange(2**order)[:, None] >> np.arange(order - 1, -1, -1)) & 1)

to_base10

to_base10(arr)

Rows of bits (most significant first) -> integers

Source code in src/rpps/math/bits.py
def to_base10(arr):
    """Rows of bits (most significant first) -> integers"""
    arr = np.asarray(arr)
    return np.dot(arr, 2**np.arange(arr.shape[1] - 1, -1, -1))

hamming

hamming(a, b)

Hamming distance: the number of positions where bit arrays a and b differ

Source code in src/rpps/math/bits.py
def hamming(a, b):
    """Hamming distance: the number of positions where bit arrays a and b differ"""
    return int(np.count_nonzero(np.asarray(a, dtype=bool) != np.asarray(b, dtype=bool)))

distance

distance(bits, word)

The Hamming distance to word at every position of bits (len(bits) - len(word) + 1 of them, int): 0 where the word starts, len(word) where its inverse does. In C++ for words of up to 64 bits (a shift register and a popcount a bit); else, and as the reference, a window by window count

Source code in src/rpps/math/bits.py
def distance(bits, word):
    """The Hamming distance to `word` at every position of `bits` (len(bits) - len(word) + 1 of them, int): 0 where the
    word starts, len(word) where its inverse does. In C++ for words of up to 64 bits (a shift register and a popcount a
    bit); else, and as the reference, a window by window count"""
    from .. import _accel
    b = np.ascontiguousarray(bits, dtype=np.uint8)
    w = np.ascontiguousarray(word, dtype=np.uint8)
    if len(w) < 1 or len(b) < len(w):
        return np.zeros(0, np.int64)
    if _accel.native is not None and len(w) <= 64:
        return _accel.native.bit_distance(b & 1, w & 1).astype(np.int64)
    win = np.lib.stride_tricks.sliding_window_view(b & 1, len(w))
    return np.count_nonzero(win != (w & 1)[None, :], axis=1).astype(np.int64)

find

find(bits, word, errors=0)

Where word starts in bits with at most errors bits wrong

Source code in src/rpps/math/bits.py
def find(bits, word, errors=0):
    """Where `word` starts in `bits` with at most `errors` bits wrong"""
    return np.nonzero(distance(bits, word) <= errors)[0]

periodic_scores

periodic_scores(bits, span, unit, allowed, periods=None, polarity=True)

Periodic marker fit.

The fraction of periods that start with an allowed unit, at every (polarity, bit offset, pattern position). span: bits a period; unit: bits a marker unit; allowed: [pattern position, unit value] booleans. Returns (2 or 1, span, len(allowed)); its first maximum is what rpps.sync.Align locks on

Source code in src/rpps/math/bits.py
def periodic_scores(bits, span, unit, allowed, periods=None, polarity=True):
    """Periodic marker fit.

    The fraction of periods that start with an `allowed` unit, at every (polarity, bit offset, pattern position).
    span: bits a period; unit: bits a marker unit; allowed: [pattern position, unit value] booleans. Returns
    (2 or 1, span, len(allowed)); its first maximum is what rpps.sync.Align locks on"""
    allowed = np.asarray(allowed, dtype=bool)
    L = len(allowed)
    b = np.asarray(bits).astype(bool)
    n = (len(b) - span)//span if periods is None else int(periods)
    out = np.zeros((2 if polarity else 1, span, L))
    if n <= 0:
        return out
    v = _units(b[:n*span + unit - 1] if span >= unit else b, unit)
    heads = np.empty((span, n), np.int64)
    k = np.arange(n)
    heads[:] = v[np.arange(span)[:, None] + k[None, :]*span] # [offset, period]: the unit starting each period
    pos = (np.arange(L)[:, None] + k[None, :]) % L # [first position, period]: the pattern position of each period
    top = (1 << unit) - 1
    for f, h in enumerate((heads, top - heads) if polarity else (heads,)): # (inverted bits: every unit's complement)
        out[f] = allowed[pos[None, :, :], h[:, None, :]].mean(axis=2)
    return out

unstuff

unstuff(bits, starts, ends, stuff=5)

Bit destuffing (HDLC's: after stuff ones a 0 is dropped, stuff + 1 ones abort) of the spans [starts[i], ends[i]) of bits, each span's bits then packed into bytes least significant bit first. Returns (status per span: 0 whole bytes, 1 aborted, 2 not a whole number of bytes; the bytes of each span, b"" where the status is not 0)

Source code in src/rpps/math/bits.py
def unstuff(bits, starts, ends, stuff=5):
    """Bit destuffing (HDLC's: after `stuff` ones a 0 is dropped, `stuff` + 1 ones abort) of the spans [starts[i], ends[i])
    of `bits`, each span's bits then packed into bytes least significant bit first. Returns (status per span: 0 whole
    bytes, 1 aborted, 2 not a whole number of bytes; the bytes of each span, b"" where the status is not 0)"""
    from .. import _accel
    b = np.ascontiguousarray(bits, dtype=np.uint8)
    s = np.ascontiguousarray(starts, dtype=np.int64)
    e = np.ascontiguousarray(ends, dtype=np.int64)
    if _accel.native is not None:
        status, off, raw = _accel.native.bit_unstuff(b, s, e, int(stuff))
        raw = raw.tobytes()
        return status.astype(np.int64), [raw[off[i]:off[i + 1]] for i in range(len(s))]
    status, out = np.zeros(len(s), np.int64), []
    for i, (a, z) in enumerate(zip(s, e)):
        bits_out, ones, bad = [], 0, 0
        for bit in b[max(int(a), 0):min(int(z), len(b))] & 1:
            if ones == stuff:
                ones = 0
                if bit == 0:
                    continue # the stuffed zero
                bad = 1 # more than `stuff` ones inside a span: an abort
                break
            bits_out.append(bit)
            ones = ones + 1 if bit else 0
        if not bad and len(bits_out) % 8:
            bad = 2
        status[i] = bad
        out.append(np.packbits(np.array(bits_out, dtype=np.uint8), bitorder="little").tobytes() if not bad else b"")
    return status, out

cyclic

Algebraic decoding of cyclic codes (Reed-Solomon, BCH) from their syndromes

Berlekamp-Massey finds the error locator polynomial, a Chien search finds its roots (the error positions), and Forney finds the error values. A binary code needs no values: every error flips a bit.

Syndromes are S_i = r(alpha^((fcr + i)*prim)), i = 0..nroots-1, of a received word r of length N. Position 0 is the first symbol of the word (the highest power of x). Polynomials are arrays of field elements, lowest degree first unless noted.

Functions:

Name Description
berlekamp_massey

Error locator sigma (nroots+1 coefficients, lowest degree first) and its degree L from the syndromes

erasure_locator

Gamma(x) = prod (1 + X_j x), X_j = alpha^((N-1-pos)*prim): lowest degree first

chien

Positions of a word of length N whose locator root is sigma(alpha^(-(N-1-pos)*prim)) = 0

forney

Error values at positions. None where the derivative of sigma vanishes (the word is not correctable)

correct

Find the errors of one word from its syndromes. Returns (positions, values) or None if uncorrectable

berlekamp_massey

berlekamp_massey(gf, S, nroots, gamma=None)

Error locator sigma (nroots+1 coefficients, lowest degree first) and its degree L from the syndromes

gamma: the erasure locator (lowest degree first, its degree is the number of erasures e). The result is then the errors-and-erasures locator, of degree L = e + errors, found from the remaining nroots - e syndromes.

Source code in src/rpps/math/cyclic.py
def berlekamp_massey(gf, S, nroots, gamma=None):
    """Error locator sigma (nroots+1 coefficients, lowest degree first) and its degree L from the syndromes

    gamma: the erasure locator (lowest degree first, its degree is the number of erasures e). The result is then
    the errors-and-erasures locator, of degree L = e + errors, found from the remaining nroots - e syndromes.
    """
    sigma = np.zeros(nroots + 1, dtype=np.int64)
    if gamma is None:
        sigma[0], e = 1, 0
    else:
        e = len(gamma) - 1
        sigma[:e + 1] = gamma
    prev = sigma.copy()
    L, m, b = e, 1, 1
    for n in range(e, nroots):
        d = int(S[n])
        for i in range(1, min(L, n) + 1):
            d ^= int(gf.mul(sigma[i], S[n - i]))
        if d == 0:
            m += 1
            continue
        T = sigma.copy()
        shifted = np.zeros(nroots + 1, dtype=np.int64)
        shifted[m:] = gf.mul(int(gf.mul(d, gf.inv(b))), prev[:nroots + 1 - m])
        sigma = sigma ^ shifted
        if 2*L <= n + e:
            L, prev, b, m = n + 1 - L + e, T, d, 1
        else:
            m += 1
    return sigma, L

erasure_locator

erasure_locator(gf, positions, N, prim=1)

Gamma(x) = prod (1 + X_j x), X_j = alpha^((N-1-pos)*prim): lowest degree first

Source code in src/rpps/math/cyclic.py
def erasure_locator(gf, positions, N, prim=1):
    """Gamma(x) = prod (1 + X_j x), X_j = alpha^((N-1-pos)*prim): lowest degree first"""
    g = np.array([1], dtype=np.int64)
    for pos in positions:
        X = int(gf.pow_alpha(((N - 1 - int(pos))*prim) % (gf.size - 1)))
        nxt = np.zeros(len(g) + 1, dtype=np.int64)
        nxt[:-1] = g
        nxt[1:] ^= gf.mul(g, X)
        g = nxt
    return g

chien

chien(gf, sigma, L, N, prim=1)

Positions of a word of length N whose locator root is sigma(alpha^(-(N-1-pos)*prim)) = 0

Source code in src/rpps/math/cyclic.py
def chien(gf, sigma, L, N, prim=1):
    """Positions of a word of length N whose locator root is sigma(alpha^(-(N-1-pos)*prim)) = 0"""
    e = np.arange(N - 1, -1, -1) * prim
    val = np.zeros(N, dtype=np.int64)
    for i in range(L + 1):
        if sigma[i]:
            val ^= gf.exp[(gf.log[sigma[i]] - e*i) % (gf.size - 1)]
    return np.nonzero(val == 0)[0]

forney

forney(gf, S, sigma, L, positions, N, nroots, fcr=0, prim=1)

Error values at positions. None where the derivative of sigma vanishes (the word is not correctable)

Source code in src/rpps/math/cyclic.py
def forney(gf, S, sigma, L, positions, N, nroots, fcr=0, prim=1):
    """Error values at `positions`. None where the derivative of sigma vanishes (the word is not correctable)"""
    omega = np.zeros(nroots, dtype=np.int64) # S(x) sigma(x) mod x^nroots
    for i in range(nroots):
        for j in range(min(i + 1, L + 1)):
            omega[i] ^= int(gf.mul(sigma[j], S[i - j]))
    values = []
    for pos in positions:
        x = int(gf.pow_alpha((N - 1 - pos)*prim))
        xinv = int(gf.inv(x))
        num = 0
        for k, c in enumerate(omega):
            num ^= int(gf.mul(c, gf.pow(xinv, k)))
        den = 0
        for i in range(1, L + 1, 2): # Formal derivative: the odd terms
            den ^= int(gf.mul(sigma[i], gf.pow(xinv, i - 1)))
        if den == 0:
            return None
        values.append(int(gf.mul(gf.mul(num, gf.inv(den)), gf.pow(x, 1 - fcr))))
    return np.array(values, dtype=np.int64)

correct

correct(gf, S, N, nroots, t, fcr=0, prim=1, binary=False, erasures=())

Find the errors of one word from its syndromes. Returns (positions, values) or None if uncorrectable

t: errors the code corrects. binary: values are all 1 and not computed (BCH) erasures: positions known to be unreliable (or not sent): with e of them, up to (nroots - e)//2 further errors are corrected. Their values are found like any error's, and may be 0 (the symbol was right after all)

Source code in src/rpps/math/cyclic.py
def correct(gf, S, N, nroots, t, fcr=0, prim=1, binary=False, erasures=()):
    """Find the errors of one word from its syndromes. Returns (positions, values) or None if uncorrectable

    t: errors the code corrects. binary: values are all 1 and not computed (BCH)
    erasures: positions known to be unreliable (or not sent): with e of them, up to (nroots - e)//2 further errors
    are corrected. Their values are found like any error's, and may be 0 (the symbol was right after all)
    """
    erasures = sorted(set(int(p) for p in erasures))
    if _accel.native is not None and np.ndim(S) == 1 and len(S) >= nroots:
        return _accel.native.cyclic_correct(np.ascontiguousarray(S, dtype=np.int64), gf.exp, gf.log, int(N), int(nroots), int(t),
                                            int(fcr), int(prim), bool(binary), erasures)
    e = len(erasures)
    if e:
        if binary:
            raise ValueError("Erasures need a non-binary code (Reed-Solomon)")
        if e > nroots:
            return None
        sigma, L = berlekamp_massey(gf, S, nroots, erasure_locator(gf, erasures, N, prim))
        if 2*L - e > nroots:
            return None
    else:
        sigma, L = berlekamp_massey(gf, S, nroots)
        if L > t:
            return None
    positions = chien(gf, sigma, L, N, prim)
    if len(positions) != L:
        return None
    if binary:
        return positions, np.ones(L, dtype=np.int64)
    values = forney(gf, S, sigma, L, positions, N, nroots, fcr, prim)
    return None if values is None else (positions, values)

demap

Soft demapping of symbols to bit LLRs, for rows of symbols at once (one frame a row), on any array module xp

rpps.symbol.Constellation.llr is this on one row, and rpps.symbol.kernels.Demap on a batch of them: one implementation, so a frame comes out the same alone or in a batch. Each row has its own noise level, estimated from its own symbols by EM over the points (mixture_variance for the one-row case), and every sum over points keeps the nearest point's distance out of the exponentials, so they stay in range.

Functions:

Name Description
em_stride

Noise stride

mask_matrix

(points, 2*bits) float matrix of the bit values of each point: the zeros first, then the ones. labels: (points, bits) bool

distances

Squared distances (rows, L, points) of the symbols (rows, L) from the points, and each symbol's nearest one

noise_variance

Variance per real dimension of each row (rows,), by EM of one shared variance over equiprobable points: iters

llr_rows

LLRs log(P(bit=0)/P(bit=1)), positive means 0, of symbols (rows, L): (rows, L*bits) float32, symbol after symbol.

em_stride

em_stride(L)

Noise stride

Source code in src/rpps/math/demap.py
def em_stride(L):
    """Noise stride"""
    return max(1, -(-int(L)//EM_SYMBOLS))

mask_matrix

mask_matrix(labels)

(points, 2*bits) float matrix of the bit values of each point: the zeros first, then the ones. labels: (points, bits) bool

Source code in src/rpps/math/demap.py
def mask_matrix(labels):
    """(points, 2*bits) float matrix of the bit values of each point: the zeros first, then the ones. `labels`: (points, bits) bool"""
    labels = np.asarray(labels, dtype=bool)
    return np.concatenate((~labels, labels), axis=1).astype(np.float64)

distances

distances(xp, y, points)

Squared distances (rows, L, points) of the symbols (rows, L) from the points, and each symbol's nearest one

Source code in src/rpps/math/demap.py
def distances(xp, y, points):
    """Squared distances (rows, L, points) of the symbols (rows, L) from the points, and each symbol's nearest one"""
    pts = xp.asarray(points)
    y = y.astype(np.complex128)
    dr, di = y.real[:, :, None] - pts.real[None, None, :], y.imag[:, :, None] - pts.imag[None, None, :]
    d2 = dr*dr + di*di
    return d2, d2.min(axis=2)

noise_variance

noise_variance(xp, d2, dmin, iters=8, floor=1e-12, tol=1e-10)

Variance per real dimension of each row (rows,), by EM of one shared variance over equiprobable points: iters iterations, fewer when every row has stopped moving (a relative change under tol; EM converges geometrically, in about four at the SNR a decoder works at)

Source code in src/rpps/math/demap.py
def noise_variance(xp, d2, dmin, iters=8, floor=1e-12, tol=1e-10):
    """Variance per real dimension of each row (rows,), by EM of one shared variance over equiprobable points: `iters`
    iterations, fewer when every row has stopped moving (a relative change under `tol`; EM converges geometrically, in
    about four at the SNR a decoder works at)"""
    shifted = d2 - dmin[:, :, None]
    L = d2.shape[1]
    var = dmin.mean(axis=1)/2 + floor
    for _ in range(iters):
        r = xp.exp(-shifted/(2*var[:, None, None]))
        new = xp.maximum(((r*d2).sum(axis=2)/r.sum(axis=2)).sum(axis=1)/(2*L), floor)
        done = bool((xp.abs(new - var) <= tol*var).all())
        var = new
        if done:
            break
    return var

llr_rows

llr_rows(xp, y, points, labels, masks, noise_var=None, maxlog=False, iters=8, floor=1e-06)

LLRs log(P(bit=0)/P(bit=1)), positive means 0, of symbols (rows, L): (rows, L*bits) float32, symbol after symbol.

noise_var: complex noise variance E|n|^2, per row or one value; None: estimated from each row (from every em_stride-th symbol, floored at floor, per real dimension). labels: (points, bits) bool; masks: mask_matrix(labels)

Source code in src/rpps/math/demap.py
def llr_rows(xp, y, points, labels, masks, noise_var=None, maxlog=False, iters=8, floor=1e-6):
    """LLRs log(P(bit=0)/P(bit=1)), positive means 0, of symbols (rows, L): (rows, L*bits) float32, symbol after symbol.

    noise_var: complex noise variance E|n|^2, per row or one value; None: estimated from each row (from every `em_stride`-th
    symbol, floored at `floor`, per real dimension). labels: (points, bits) bool; masks: `mask_matrix(labels)`"""
    if xp is np and _accel.native is not None: # C++: a row at a time on several threads, only the exponentials that count
        nv = np.zeros(0) if noise_var is None else np.asarray(noise_var, dtype=np.float64).reshape(-1)
        return _accel.native.demap_llr(np.ascontiguousarray(y, dtype=np.complex128), np.asarray(points, dtype=np.complex128),
                                       np.asarray(labels, dtype=np.uint8), nv, bool(maxlog), int(iters), float(floor), 1e-10,
                                       EM_SYMBOLS)
    return _llr_rows(xp, y, points, labels, masks, noise_var, maxlog, iters, floor)

gf

Finite field GF(2^m) arithmetic

Classes:

Name Description
GF

GF(2^m) with log tables

GF

GF(m=8, poly=285)

GF(2^m) with log tables

poly: the field polynomial, with the x^m term included (0x11D for m=8). Elements are ints below 2^m, and every operation takes scalars or numpy arrays. Polynomials are arrays of elements, highest degree first.

Methods:

Name Description
pow_alpha

alpha^e, for the primitive element alpha

pow

a^e for a single element

polymul

Product of two polynomials

evaluate

Sum over positions of words[:, k] * alpha^powers[k]: the polynomial values at a power of alpha, for every word

Source code in src/rpps/math/gf.py
def __init__(self, m=8, poly=0x11D):
    self.m = m
    self.poly = poly
    self.size = 2**m
    if (m, poly) not in GF._TABLES:
        exp = np.zeros(2*self.size, dtype=np.int64)
        log = np.zeros(self.size, dtype=np.int64)
        x = 1
        for i in range(self.size-1):
            exp[i] = x
            log[x] = i
            x <<= 1
            if x & self.size:
                x ^= poly
        exp[self.size-1:2*self.size-2] = exp[:self.size-1]
        exp.flags.writeable = log.flags.writeable = False
        GF._TABLES[(m, poly)] = (exp, log)
    self.exp, self.log = GF._TABLES[(m, poly)]
pow_alpha
pow_alpha(e)

alpha^e, for the primitive element alpha

Source code in src/rpps/math/gf.py
def pow_alpha(self, e):
    """alpha^e, for the primitive element alpha"""
    return self.exp[e % (self.size-1)]
pow
pow(a, e)

a^e for a single element

Source code in src/rpps/math/gf.py
def pow(self, a, e):
    """a^e for a single element"""
    if e == 0:
        return 1
    if a == 0:
        return 0
    return int(self.exp[(int(self.log[a])*e) % (self.size-1)])
polymul
polymul(a, b)

Product of two polynomials

Source code in src/rpps/math/gf.py
def polymul(self, a, b):
    """Product of two polynomials"""
    a, b = np.asarray(a), np.asarray(b)
    out = np.zeros(len(a) + len(b) - 1, dtype=np.int64)
    for i, x in enumerate(a):
        out[i:i+len(b)] ^= self.mul(x, b)
    return out
evaluate
evaluate(words, powers)

Sum over positions of words[:, k] * alpha^powers[k]: the polynomial values at a power of alpha, for every word

words: (W, N) field elements. powers: (N,) exponents of alpha, one per position

Source code in src/rpps/math/gf.py
def evaluate(self, words, powers):
    """Sum over positions of words[:, k] * alpha^powers[k]: the polynomial values at a power of alpha, for every word

    words: (W, N) field elements. powers: (N,) exponents of alpha, one per position
    """
    words = np.asarray(words)
    terms = self.exp[(self.log[words] + np.asarray(powers)[None, :]) % (self.size - 1)]
    return np.bitwise_xor.reduce(np.where(words == 0, 0, terms), axis=1)

gf2

Linear algebra over GF(2), and bit sequences filtered over it

fir(x, delays): y[n] = x[n] ^ XOR x[n-d]; recur(u, delays): y[n] = u[n] ^ XOR y[n-d], both from zeros before the start, on whole arrays. A recursion has no loop over its bits: over GF(2) g(x)^2 = g(x^2), so y = u/g(x) is u g(x) g(x^2) .. g(x^(2^(k-1))) / g(x^(2^k)): k sparse FIR passes, then a recursion whose shortest delay is 2^k times longer, run a chunk of that many bits at a time. Self-synchronizing scramblers (rpps.code.scram.Feedthrough) and the linear recurrences of rpps.sequence are these.

Functions:

Name Description
parity_to_gh

Generator and parity-check matrices (G, H) of a systematic linear code from its parity block

gh_to_parity

Parity block p (k, n-k) of a systematic code from G = [I | p], or from H = [p^T | I]

to_checks

Dense parity-check matrix -> list of variable index arrays (one per check)

pack_rows

Rows of bits (r, c) -> (r, words) uint64, column i at word i // 64, bit 63 - i % 64: what eliminate_packed takes

unpack_rows

pack_rows undone: (r, c) uint8

eliminate_packed

Reduced row echelon form in place over GF(2) of packed rows A (pack_rows), the first ncols columns as pivots: the

rref

Reduced row echelon form of M over GF(2), bit-packed: (rows (r, n) uint8, pivot columns). r is the rank.

rank

Rank of M over GF(2): the pivots of eliminate_packed (the C++ kernel), else _rank_python

nullspace

Basis of {h : M h = 0} over GF(2). M is (R, n) uint8. Returns (d, n) uint8

systematic

GF(2) elimination of dense H. Returns (G, info) with H @ G.T = 0 and the message in codeword columns info

pmod

a(x) mod b(x) over GF(2), polynomials as Python ints (bit i: the coefficient of x^i)

pdivmod

(quotient, remainder) of a(x)/b(x) over GF(2)

pmul

a(x) b(x) over GF(2)

pgcd

Greatest common divisor over GF(2) of polynomials

porder

Smallest N with x^N = 1 mod g(x) (the period of the recurrence g gives, the length of the cyclic code it

berlekamp_massey

The shortest LFSR that makes a bit sequence: (C, L), C its connection polynomial (bit j the coefficient of D^j,

fwht

Walsh-Hadamard transform (unnormalized) of a length-2^B array, a copy: the correlation of a distribution over B-bit

lfsr_taps

The delays j (largest first) of a connection polynomial: s[n] = XOR of s[n-j]

rank_ints

Rank over GF(2) of vectors given as Python ints

fir

y[n] = x[n] ^ XOR over d of x[n - d] (0 before the start), as uint8 0/1

recur

y[n] = u[n] ^ XOR over d of y[n - d] (0 before the start), as uint8 0/1, with no loop over the bits: u is filtered by

parity_to_gh

parity_to_gh(n: int, k: int, p: ndarray)

Generator and parity-check matrices (G, H) of a systematic linear code from its parity block

p is (k, n-k), the parity part of G = [I | p]; H = [p^T | I]. Returns uint8 arrays (k, n) and (n-k, n).

Source code in src/rpps/math/gf2.py
def parity_to_gh(n: int, k: int, p: np.ndarray):
    """Generator and parity-check matrices (G, H) of a systematic linear code from its parity block

    p is (k, n-k), the parity part of G = [I | p]; H = [p^T | I]. Returns uint8 arrays (k, n) and (n-k, n).
    """
    d = n - k
    p = np.asarray(p)
    if p.shape != (k, d):
        raise IndexError(f"p must be shape ({k},{d})!")
    G = np.concatenate((np.eye(k, dtype=np.uint8), p.astype(np.uint8)), axis=1)
    H = np.concatenate((p.T.astype(np.uint8), np.eye(d, dtype=np.uint8)), axis=1)
    return G, H

gh_to_parity

gh_to_parity(n: int, k: int, G=None, H=None)

Parity block p (k, n-k) of a systematic code from G = [I | p], or from H = [p^T | I]

Source code in src/rpps/math/gf2.py
def gh_to_parity(n: int, k: int, G=None, H=None):
    """Parity block p (k, n-k) of a systematic code from G = [I | p], or from H = [p^T | I]"""
    if G is not None:
        return np.asarray(G)[:k, k:]
    if H is not None:
        return np.asarray(H)[:n-k, :k].T
    raise ValueError("Need G or H")

to_checks

to_checks(h)

Dense parity-check matrix -> list of variable index arrays (one per check)

Source code in src/rpps/math/gf2.py
def to_checks(h):
    """Dense parity-check matrix -> list of variable index arrays (one per check)"""
    return [np.nonzero(row)[0] for row in np.asarray(h, dtype=bool)]

pack_rows

pack_rows(B)

Rows of bits (r, c) -> (r, words) uint64, column i at word i // 64, bit 63 - i % 64: what eliminate_packed takes

Source code in src/rpps/math/gf2.py
def pack_rows(B):
    """Rows of bits (r, c) -> (r, words) uint64, column i at word i // 64, bit 63 - i % 64: what `eliminate_packed` takes"""
    B = np.asarray(B, dtype=np.uint8)
    r, c = B.shape
    pad = (-c) % 64
    if pad or not c:
        B = np.concatenate((B, np.zeros((r, pad or 64), np.uint8)), axis=1)
    words = B.shape[1]//64
    return np.ascontiguousarray(np.packbits(B, axis=1)).view(">u8").astype(np.uint64).reshape(r, words)

unpack_rows

unpack_rows(A, c)

pack_rows undone: (r, c) uint8

Source code in src/rpps/math/gf2.py
def unpack_rows(A, c):
    """`pack_rows` undone: (r, c) uint8"""
    return np.unpackbits(np.ascontiguousarray(A).astype(">u8").view(np.uint8), axis=1)[:, :c]

eliminate_packed

eliminate_packed(A, ncols)

Reduced row echelon form in place over GF(2) of packed rows A (pack_rows), the first ncols columns as pivots: the pivot columns. The C++ kernel (gf2_eliminate, Four Russians) gives the same matrix bit for bit; the loop below is its reference

Source code in src/rpps/math/gf2.py
def eliminate_packed(A, ncols):
    """Reduced row echelon form in place over GF(2) of packed rows A (`pack_rows`), the first ncols columns as pivots: the
    pivot columns. The C++ kernel (gf2_eliminate, Four Russians) gives the same matrix bit for bit; the loop below is its
    reference"""
    from .. import _accel
    nat = _accel.native
    if nat is not None and A.dtype == np.uint64 and A.flags.c_contiguous:
        return list(nat.gf2_eliminate(A, int(ncols)))
    return _eliminate_python(A, ncols)

rref

rref(M, pivot_cols=None)

Reduced row echelon form of M over GF(2), bit-packed: (rows (r, n) uint8, pivot columns). r is the rank. pivot_cols: pivot only within the first that many columns (an augmented system [A | B]: the rows give A^-1 B)

Source code in src/rpps/math/gf2.py
def rref(M, pivot_cols=None):
    """Reduced row echelon form of M over GF(2), bit-packed: (rows (r, n) uint8, pivot columns). r is the rank.
    pivot_cols: pivot only within the first that many columns (an augmented system [A | B]: the rows give A^-1 B)"""
    M = np.asarray(M, dtype=np.uint8)
    R, n = M.shape
    A = pack_rows(M)
    piv = eliminate_packed(A, n if pivot_cols is None else min(pivot_cols, n))
    return unpack_rows(A[:len(piv)], n), piv

rank

rank(M)

Rank of M over GF(2): the pivots of eliminate_packed (the C++ kernel), else _rank_python

Source code in src/rpps/math/gf2.py
def rank(M):
    """Rank of M over GF(2): the pivots of `eliminate_packed` (the C++ kernel), else `_rank_python`"""
    from .. import _accel
    M = np.asarray(M, dtype=np.uint8)
    if _accel.native is not None and M.ndim == 2 and M.size:
        return len(eliminate_packed(pack_rows(M), M.shape[1]))
    return _rank_python(M)

nullspace

nullspace(M)

Basis of {h : M h = 0} over GF(2). M is (R, n) uint8. Returns (d, n) uint8

Source code in src/rpps/math/gf2.py
def nullspace(M):
    """Basis of {h : M h = 0} over GF(2). M is (R, n) uint8. Returns (d, n) uint8"""
    M = np.asarray(M, dtype=np.uint8)
    n = M.shape[1]
    A, piv = rref(M)
    pset = set(piv)
    free = [c for c in range(n) if c not in pset]
    basis = np.zeros((len(free), n), dtype=np.uint8)
    if not free:
        return basis
    basis[np.arange(len(free)), free] = 1
    if piv:
        basis[:, piv] = A[:, free].T # Each pivot variable is the sum of the free ones its row holds
    return basis

systematic

systematic(h)

GF(2) elimination of dense H. Returns (G, info) with H @ G.T = 0 and the message in codeword columns info

Source code in src/rpps/math/gf2.py
def systematic(h):
    """GF(2) elimination of dense H. Returns (G, info) with H @ G.T = 0 and the message in codeword columns `info`"""
    H = np.array(h, dtype=bool)
    M, N = H.shape
    perm = np.arange(N)
    r = 0
    for c in range(N):
        if r == M:
            break
        piv = np.nonzero(H[r:, c])[0]
        if len(piv) == 0:
            continue
        piv = piv[0] + r
        H[[r, piv]] = H[[piv, r]]
        others = np.nonzero(H[:, c])[0]
        others = others[others != r]
        H[others] ^= H[r]
        H[:, [r, c]] = H[:, [c, r]] # Move the pivot column to position r
        perm[[r, c]] = perm[[c, r]]
        r += 1
    rank = r
    A = H[:rank, rank:]
    K = N - rank
    Gp = np.concatenate((A.T, np.eye(K, dtype=bool)), axis=1) # Codeword in permuted order: [parity | message]
    G = np.zeros((K, N), dtype=bool)
    G[:, perm] = Gp
    return G, perm[rank:]

pmod

pmod(a, b)

a(x) mod b(x) over GF(2), polynomials as Python ints (bit i: the coefficient of x^i)

Source code in src/rpps/math/gf2.py
def pmod(a, b):
    """a(x) mod b(x) over GF(2), polynomials as Python ints (bit i: the coefficient of x^i)"""
    db = b.bit_length()
    while a.bit_length() >= db:
        a ^= b << (a.bit_length() - db)
    return a

pdivmod

pdivmod(a, b)

(quotient, remainder) of a(x)/b(x) over GF(2)

Source code in src/rpps/math/gf2.py
def pdivmod(a, b):
    """(quotient, remainder) of a(x)/b(x) over GF(2)"""
    q, db = 0, b.bit_length()
    while a.bit_length() >= db:
        sh = a.bit_length() - db
        q |= 1 << sh
        a ^= b << sh
    return q, a

pmul

pmul(a, b)

a(x) b(x) over GF(2)

Source code in src/rpps/math/gf2.py
def pmul(a, b):
    """a(x) b(x) over GF(2)"""
    out = 0
    while b:
        if b & 1:
            out ^= a
        a <<= 1
        b >>= 1
    return out

pgcd

pgcd(*polys)

Greatest common divisor over GF(2) of polynomials

Source code in src/rpps/math/gf2.py
def pgcd(*polys):
    """Greatest common divisor over GF(2) of polynomials"""
    g = 0
    for p in polys:
        a, b = g, int(p)
        while b:
            a, b = b, pmod(a, b)
        g = a
    return g

porder

porder(g, limit=1 << 17)

Smallest N with x^N = 1 mod g(x) (the period of the recurrence g gives, the length of the cyclic code it generates), or None up to limit (g of degree >= 1 with g(0) = 1)

Source code in src/rpps/math/gf2.py
def porder(g, limit=1 << 17):
    """Smallest N with x^N = 1 mod g(x) (the period of the recurrence g gives, the length of the cyclic code it
    generates), or None up to `limit` (g of degree >= 1 with g(0) = 1)"""
    d = g.bit_length() - 1
    if d < 1 or not g & 1:
        return None
    x = 1
    for i in range(1, limit + 1):
        x <<= 1
        if (x >> d) & 1:
            x ^= g
        if x == 1:
            return i
    return None

berlekamp_massey

berlekamp_massey(bits)

The shortest LFSR that makes a bit sequence: (C, L), C its connection polynomial (bit j the coefficient of D^j, bit 0 set: s[n] = XOR of s[n-j] over the j >= 1 where C has bit j) and L its length (the linear complexity). lfsr_taps(C, L) gives the j's

Source code in src/rpps/math/gf2.py
def berlekamp_massey(bits):
    """The shortest LFSR that makes a bit sequence: (C, L), C its connection polynomial (bit j the coefficient of D^j,
    bit 0 set: s[n] = XOR of s[n-j] over the j >= 1 where C has bit j) and L its length (the linear complexity).
    `lfsr_taps(C, L)` gives the j's"""
    C, B = 1, 1
    L, m = 0, 1
    window = 0 # bit j: s[n - j]
    for n, b in enumerate(bits):
        window = (window << 1) | (int(b) & 1)
        d = (C & window).bit_count() & 1 # s[n] + sum C_j s[n-j]
        if d == 0:
            m += 1
        elif 2*L <= n:
            T = C
            C ^= B << m
            L, B, m = n + 1 - L, T, 1
        else:
            C ^= B << m
            m += 1
    return C, L

fwht

fwht(a)

Walsh-Hadamard transform (unnormalized) of a length-2^B array, a copy: the correlation of a distribution over B-bit words with every parity check (what the blind TCM, recurrence and RSC searches rank checks by)

Source code in src/rpps/math/gf2.py
def fwht(a):
    """Walsh-Hadamard transform (unnormalized) of a length-2^B array, a copy: the correlation of a distribution over B-bit
    words with every parity check (what the blind TCM, recurrence and RSC searches rank checks by)"""
    a = np.array(a, dtype=np.float64)
    n = len(a)
    h = 1
    while h < n:
        a = a.reshape(-1, 2, h)
        a = np.stack((a[:, 0] + a[:, 1], a[:, 0] - a[:, 1]), axis=1).reshape(n)
        h *= 2
    return a

lfsr_taps

lfsr_taps(C, L)

The delays j (largest first) of a connection polynomial: s[n] = XOR of s[n-j]

Source code in src/rpps/math/gf2.py
def lfsr_taps(C, L):
    """The delays j (largest first) of a connection polynomial: s[n] = XOR of s[n-j]"""
    return tuple(j for j in range(L, 0, -1) if C >> j & 1)

rank_ints

rank_ints(vectors)

Rank over GF(2) of vectors given as Python ints

Source code in src/rpps/math/gf2.py
def rank_ints(vectors):
    """Rank over GF(2) of vectors given as Python ints"""
    basis = []
    for v in vectors:
        for b in basis:
            v = min(v, v ^ b)
        if v:
            basis.append(v)
    return len(basis)

fir

fir(x, delays)

y[n] = x[n] ^ XOR over d of x[n - d] (0 before the start), as uint8 0/1

Source code in src/rpps/math/gf2.py
def fir(x, delays):
    """y[n] = x[n] ^ XOR over d of x[n - d] (0 before the start), as uint8 0/1"""
    x = np.asarray(x).astype(np.uint8) & 1
    y = x.copy()
    for d in _odd(delays):
        if d < len(x):
            y[d:] ^= x[:-d]
    return y

recur

recur(u, delays, chunk=None)

y[n] = u[n] ^ XOR over d of y[n - d] (0 before the start), as uint8 0/1, with no loop over the bits: u is filtered by g(x^(2^i)) for i < k (g = 1 + sum x^d), which leaves the recursion over delays d 2^k, run chunk (at least the shortest of them) bits at a time. chunk: the bits a step aims for (default about 4 sqrt(n), at least 256)

Source code in src/rpps/math/gf2.py
def recur(u, delays, chunk=None):
    """y[n] = u[n] ^ XOR over d of y[n - d] (0 before the start), as uint8 0/1, with no loop over the bits: u is filtered by
    g(x^(2^i)) for i < k (g = 1 + sum x^d), which leaves the recursion over delays d 2^k, run `chunk` (at least the
    shortest of them) bits at a time. `chunk`: the bits a step aims for (default about 4 sqrt(n), at least 256)"""
    y = np.asarray(u).astype(np.uint8) & 1
    n, D = len(y), _odd(delays)
    if not D or n == 0:
        return y.copy()
    aim = max(256, 4*int(np.sqrt(n))) if chunk is None else int(chunk)
    k = 0
    while (D[0] << k) < min(aim, n):
        k += 1
    for i in range(k): # times g(x^(2^i))
        y = fir(y, [d << i for d in D])
    D = [d << k for d in D]
    C = D[0]
    for a in range(C, n, C): # bits [a, a + C) need only bits before a
        b = min(n, a + C)
        for d in D:
            if d < b:
                lo = max(a, d)
                y[lo:b] ^= y[lo - d:b - d]
    return y

interp

Interpolation

Functions:

Name Description
parabolic_offset

Vertex offset (-0.5..0.5) of the parabola through three equally spaced samples a, b, c (b in the middle)

peak

Index of the largest value of a spectrum, and the sub-bin offset from a parabola through its neighbours

upsampled

x at a, a + 1/u, a + 2/u, ... up to b - REACH (its positions are absolute: x[0] is position base), band limited

fractional_edge

fractional where t may be near either end of x: the samples beyond them are zeros (a stream's start or its

fractional

x (complex or real) at the fractional positions t. taps 4: cubic Lagrange through x[i-1 .. i+2], i = floor(t);

interpolate

x at fractional sample positions pos (Kaiser-windowed sinc, taps long; x band-limited below Fs/2; outside x

parabolic_offset

parabolic_offset(a, b, c)

Vertex offset (-0.5..0.5) of the parabola through three equally spaced samples a, b, c (b in the middle)

Source code in src/rpps/math/interp.py
4
5
6
7
def parabolic_offset(a, b, c):
    """Vertex offset (-0.5..0.5) of the parabola through three equally spaced samples a, b, c (b in the middle)"""
    den = a - 2*b + c
    return 0.0 if den == 0 else 0.5*(a - c)/den

peak

peak(spec, circular=False, log=True)

Index of the largest value of a spectrum, and the sub-bin offset from a parabola through its neighbours

log: fit the parabola to log(spec), the right model for a spectral line circular: the spectrum wraps around (an FFT), so the neighbours of the end bins are the other end Returns (k, offset), the peak is at k + offset. A peak on the end bin of a non-circular spectrum gets offset 0.

Source code in src/rpps/math/interp.py
def peak(spec, circular=False, log=True):
    """Index of the largest value of a spectrum, and the sub-bin offset from a parabola through its neighbours

    log: fit the parabola to log(spec), the right model for a spectral line
    circular: the spectrum wraps around (an FFT), so the neighbours of the end bins are the other end
    Returns (k, offset), the peak is at k + offset. A peak on the end bin of a non-circular spectrum gets offset 0.
    """
    spec = np.asarray(spec)
    k = int(np.argmax(spec))
    n = len(spec)
    if not circular and not 0 < k < n - 1:
        return k, 0.0
    a, b, c = spec[(k - 1) % n], spec[k], spec[(k + 1) % n]
    if log:
        a, b, c = np.log(a + 1e-30), np.log(b + 1e-30), np.log(c + 1e-30)
    return k, parabolic_offset(a, b, c)

upsampled

upsampled(x, a, b, base=0, u=2)

x at a, a + 1/u, a + 2/u, ... up to b - REACH (its positions are absolute: x[0] is position base), band limited (the 12-tap windowed sinc at each k/u of a sample: fixed FIRs, one a phase). u divides _PHASES (2, 4, 8...). Before x's start it reads zeros

Source code in src/rpps/math/interp.py
def upsampled(x, a, b, base=0, u=2):
    """x at a, a + 1/u, a + 2/u, ... up to b - REACH (its positions are absolute: x[0] is position `base`), band limited
    (the 12-tap windowed sinc at each k/u of a sample: fixed FIRs, one a phase). u divides _PHASES (2, 4, 8...). Before
    x's start it reads zeros"""
    if u < 1 or _PHASES % u:
        raise ValueError(f"upsampled: u {u} must divide {_PHASES}")
    tab, n = _sinc_table(2*REACH)
    lo = a + n[0]
    x = np.asarray(x)
    pre = max(0, base - lo)
    ext = x[max(lo - base, 0):b - base]
    if pre:
        ext = np.concatenate((np.zeros(pre, x.dtype), ext))
    K = max(len(ext) - (len(n) - 1), 0) # len b - a - REACH
    out = np.empty(u*K, np.result_type(x.dtype, np.complex128) if x.dtype.kind == "c" else np.float64)
    out[0::u] = ext[-n[0]:-n[0] + K]
    for k in range(1, u): # x(i + k/u) = sum_n h[n] x[i + n], n = 1-REACH .. REACH
        out[k::u] = np.convolve(ext, tab[_PHASES*k//u][::-1], "valid")[:K]
    return out

fractional_edge

fractional_edge(x, t, taps=4)

fractional where t may be near either end of x: the samples beyond them are zeros (a stream's start or its flushed end, as a filter's history is)

Source code in src/rpps/math/interp.py
def fractional_edge(x, t, taps=4):
    """`fractional` where t may be near either end of x: the samples beyond them are zeros (a stream's start or its
    flushed end, as a filter's history is)"""
    t = np.asarray(t, dtype=np.float64)
    if not len(t) or (np.floor(t.min()) - REACH + 1 >= 0 and np.floor(t.max()) + REACH < len(x)):
        return fractional(x, t, taps) # (within x: nothing to pad)
    return fractional(np.pad(np.asarray(x), REACH), t + REACH, taps)

fractional

fractional(x, t, taps=4)

x (complex or real) at the fractional positions t. taps 4: cubic Lagrange through x[i-1 .. i+2], i = floor(t); taps 8, 12...: a windowed sinc over x[i+1-taps/2 .. i+taps/2] (a band-limited interpolator: the error of the matched filter's output at 2 samples per symbol is -44 dB with 8 taps and -56 dB with 12, against -26 dB cubic)

Source code in src/rpps/math/interp.py
def fractional(x, t, taps=4):
    """x (complex or real) at the fractional positions t. taps 4: cubic Lagrange through x[i-1 .. i+2], i = floor(t);
    taps 8, 12...: a windowed sinc over x[i+1-taps/2 .. i+taps/2] (a band-limited interpolator: the error of the matched
    filter's output at 2 samples per symbol is -44 dB with 8 taps and -56 dB with 12, against -26 dB cubic)"""
    t = np.asarray(t, dtype=np.float64)
    if taps == 4 and len(t) and np.asarray(x).dtype in (np.complex64, np.complex128):
        from .. import _accel
        if _accel.native is not None: # The four products a position in C++, in double (the lines below are its reference)
            return _accel.native.cubic_read(np.ascontiguousarray(x), np.ascontiguousarray(t))
    i = np.floor(t).astype(np.int64)
    u = t - i
    if taps == 4:
        c = (-u*(u - 1)*(u - 2)/6, (u + 1)*(u - 1)*(u - 2)/2, -(u + 1)*u*(u - 2)/2, (u + 1)*u*(u - 1)/6)
        return c[0]*x[i - 1] + c[1]*x[i] + c[2]*x[i + 1] + c[3]*x[i + 2]
    if taps//2 > REACH or taps % 2:
        raise ValueError(f"taps is 4 or an even number up to {2*REACH}, not {taps}")
    tab, n = _sinc_table(taps)
    from .. import _accel
    if _accel.native is not None and np.asarray(x).dtype == np.complex64: # Two short dot products a position, in C++
        return _accel.native.fractional_read(x, t, tab, int(n[0]))
    p = u*_PHASES
    k = np.minimum(np.floor(p).astype(np.int64), _PHASES - 1)
    a = (p - k)[:, None]
    h = (1 - a)*tab[k] + a*tab[k + 1]
    return np.sum(h*np.asarray(x)[i[:, None] + n[None, :]], axis=1)

interpolate

interpolate(x, pos, taps=16, chunk=1 << 16)

x at fractional sample positions pos (Kaiser-windowed sinc, taps long; x band-limited below Fs/2; outside x is 0), chunk positions at a time

Source code in src/rpps/math/interp.py
def interpolate(x, pos, taps=16, chunk=1 << 16):
    """x at fractional sample positions pos (Kaiser-windowed sinc, `taps` long; x band-limited below Fs/2; outside x
    is 0), `chunk` positions at a time"""
    x = np.asarray(x, dtype=np.complex128)
    pos = np.asarray(pos, dtype=np.float64)
    k = np.arange(-taps//2 + 1, taps//2 + 1)
    half = taps/2
    out = np.empty(len(pos), np.complex128)
    for a in range(0, len(pos), chunk):
        p = pos[a:a + chunk]
        i0 = np.floor(p).astype(np.int64)
        d = k[None, :] - (p - i0)[:, None]
        w = np.sinc(d)*np.i0(6.0*np.sqrt(np.clip(1 - (d/half)**2, 0, None)))/np.i0(6.0)
        idx = i0[:, None] + k[None, :]
        valid = (idx >= 0) & (idx < len(x))
        out[a:a + chunk] = np.sum(np.where(valid, x[np.clip(idx, 0, max(len(x) - 1, 0))], 0)*w, axis=1)
    return out

mask

Boolean masks along one axis

Functions:

Name Description
runs

(starts, stops) of the True runs of a 1-D mask, stops exclusive: two int arrays of the same length

runs

runs(mask)

(starts, stops) of the True runs of a 1-D mask, stops exclusive: two int arrays of the same length

Source code in src/rpps/math/mask.py
4
5
6
7
8
def runs(mask):
    """(starts, stops) of the True runs of a 1-D mask, stops exclusive: two int arrays of the same length"""
    m = np.asarray(mask)
    d = np.diff(np.concatenate(([0], m.view(np.int8) if m.dtype == bool else (m != 0).astype(np.int8), [0])))
    return np.flatnonzero(d == 1), np.flatnonzero(d == -1)

optimize

Nonlinear least squares

Functions:

Name Description
least_squares

Minimise 0.5 * sum(fun(x)**2) from x0 (Levenberg-Marquardt with Marquardt scaling)

least_squares

least_squares(fun, x0, jac=None, max_nfev=None, xtol=1e-10, ftol=1e-10)

Minimise 0.5 * sum(fun(x)**2) from x0 (Levenberg-Marquardt with Marquardt scaling)

fun(x) -> residual vector; jac(x) -> its Jacobian (rows: residuals, columns: parameters), or None for forward differences. Returns a namespace like scipy's: x, fun (residuals at x), jac (Jacobian at x), cost, nfev, success

Source code in src/rpps/math/optimize.py
def least_squares(fun, x0, jac=None, max_nfev=None, xtol=1e-10, ftol=1e-10):
    """Minimise 0.5 * sum(fun(x)**2) from `x0` (Levenberg-Marquardt with Marquardt scaling)

    fun(x) -> residual vector; jac(x) -> its Jacobian (rows: residuals, columns: parameters), or None for forward differences.
    Returns a namespace like scipy's: x, fun (residuals at x), jac (Jacobian at x), cost, nfev, success
    """
    x = np.atleast_1d(np.asarray(x0, float)).copy()
    max_nfev = max_nfev or 100*len(x)
    f = np.atleast_1d(np.asarray(fun(x), float)); nfev = 1
    J = np.atleast_2d(jac(x)) if jac else _jacobian(fun, x, f)
    cost = 0.5*f@f
    lam, success = 1e-3, False
    while nfev < max_nfev:
        A, g = J.T@J, J.T@f
        if np.linalg.norm(g, np.inf) < 1e-12*max(cost, 1e-300):
            success = True
            break
        improved = False
        while nfev < max_nfev:
            try:
                step = np.linalg.solve(A + lam*np.diag(np.maximum(np.diag(A), 1e-12)), -g)
            except np.linalg.LinAlgError:
                lam *= 10
                continue
            fn = np.atleast_1d(np.asarray(fun(x + step), float)); nfev += 1
            cn = 0.5*fn@fn
            if np.isfinite(cn) and cn < cost:
                small = np.linalg.norm(step) <= xtol*(np.linalg.norm(x) + xtol) or cost - cn <= ftol*cost
                x, f, cost = x + step, fn, cn
                lam = max(lam/3, 1e-12)
                improved = True
                break
            lam *= 4
            if lam > 1e16:
                break
        if not improved:
            success = True # No step lowers the cost: a minimum to this precision
            break
        J = np.atleast_2d(jac(x)) if jac else _jacobian(fun, x, f)
        if small:
            success = True
            break
    return SimpleNamespace(x=x, fun=f, jac=J, cost=cost, nfev=nfev, success=success)

prob

Probability and statistics helpers

Functions:

Name Description
logsumexp

log(sum(exp(x))) along an axis, without overflow

z_critical

z a null hypothesis exceeds with probability alpha/trials (Gaussian tail estimate)

igamc

Q(a, x) = Gamma(a, x)/Gamma(a), the regularized upper incomplete gamma function (the chi-square tail: a chi-square

log_binom_half_cdf

log P(Binomial(n, 1/2) <= e) for every e in an array (or one), exactly, in logs (no overflow at any n): the chance

deviance_z

Signed z-like score of k events in n trials against probability p0 (binomial deviance)

mixture_variance

Noise variance per real dimension of observations scattered around equiprobable points, by EM

logsumexp

logsumexp(x, axis=-1)

log(sum(exp(x))) along an axis, without overflow

Source code in src/rpps/math/prob.py
def logsumexp(x, axis=-1):
    """log(sum(exp(x))) along an axis, without overflow"""
    x = np.asarray(x)
    m = x.max(axis=axis, keepdims=True)
    m = np.where(np.isfinite(m), m, 0.0) # All -inf: the sum is 0 and the log -inf, not nan
    with np.errstate(divide="ignore"):
        return (m + np.log(np.exp(x - m).sum(axis=axis, keepdims=True))).squeeze(axis)

z_critical

z_critical(trials, alpha=0.01)

z a null hypothesis exceeds with probability alpha/trials (Gaussian tail estimate)

Source code in src/rpps/math/prob.py
def z_critical(trials, alpha=0.01):
    """z a null hypothesis exceeds with probability alpha/trials (Gaussian tail estimate)"""
    return float(np.sqrt(2*np.log(max(trials, 2)/alpha)))

igamc

igamc(a, x)

Q(a, x) = Gamma(a, x)/Gamma(a), the regularized upper incomplete gamma function (the chi-square tail: a chi-square statistic X with k degrees of freedom has P-value igamc(k/2, X/2)). By the series for x < a + 1, else the continued fraction (Numerical Recipes 6.2), to double precision

Source code in src/rpps/math/prob.py
def igamc(a, x):
    """Q(a, x) = Gamma(a, x)/Gamma(a), the regularized upper incomplete gamma function (the chi-square tail: a chi-square
    statistic X with k degrees of freedom has P-value igamc(k/2, X/2)). By the series for x < a + 1, else the continued
    fraction (Numerical Recipes 6.2), to double precision"""
    from math import exp, lgamma, log
    a, x = float(a), float(x)
    if x <= 0.0:
        return 1.0
    lead = a*log(x) - x - lgamma(a)
    if x < a + 1.0: # P(a, x) by its series, Q = 1 - P
        term = total = 1.0/a
        ap = a
        for _ in range(10000):
            ap += 1.0
            term *= x/ap
            total += term
            if abs(term) < abs(total)*1e-16:
                break
        return max(0.0, 1.0 - total*exp(lead))
    # Q(a, x) by the continued fraction, modified Lentz
    tiny = 1e-300
    b = x + 1.0 - a
    c, d = 1.0/tiny, 1.0/b
    h = d
    for i in range(1, 10000):
        an = -i*(i - a)
        b += 2.0
        d = an*d + b
        d = tiny if abs(d) < tiny else d
        c = b + an/c
        c = tiny if abs(c) < tiny else c
        d = 1.0/d
        delta = d*c
        h *= delta
        if abs(delta - 1.0) < 1e-16:
            break
    return min(1.0, exp(lead)*h)

log_binom_half_cdf

log_binom_half_cdf(n, e)

log P(Binomial(n, 1/2) <= e) for every e in an array (or one), exactly, in logs (no overflow at any n): the chance a random n-bit window is within e errors of a word. -inf below 0

Source code in src/rpps/math/prob.py
def log_binom_half_cdf(n, e):
    """log P(Binomial(n, 1/2) <= e) for every e in an array (or one), exactly, in logs (no overflow at any n): the chance
    a random n-bit window is within e errors of a word. -inf below 0"""
    from math import lgamma, log
    e = np.atleast_1d(np.asarray(e, dtype=np.int64))
    top = int(min(max(e.max(initial=-1), -1), n))
    if top < 0:
        out = np.full(e.shape, -np.inf)
    else:
        k = np.arange(top + 1)
        lt = np.array([lgamma(n + 1) - lgamma(j + 1) - lgamma(n - j + 1) for j in k]) - n*log(2) # log P(exactly k)
        cum = np.logaddexp.accumulate(lt)
        out = np.where(e < 0, -np.inf, cum[np.clip(e, 0, top)])
    return out if out.size > 1 else float(out[0])

deviance_z

deviance_z(k, n, p0=0.5)

Signed z-like score of k events in n trials against probability p0 (binomial deviance)

Source code in src/rpps/math/prob.py
def deviance_z(k, n, p0=0.5):
    """Signed z-like score of k events in n trials against probability p0 (binomial deviance)"""
    k = np.asarray(k, dtype=np.float64)
    mu = n*p0
    with np.errstate(divide="ignore", invalid="ignore"):
        d = np.where(k > 0, k*np.log(k/mu), 0.0) + np.where(k < n, (n-k)*np.log((n-k)/(n-mu)), 0.0)
    return np.sign(k - mu) * np.sqrt(2*np.maximum(d, 0))

mixture_variance

mixture_variance(d2, iters=8, floor=1e-12)

Noise variance per real dimension of observations scattered around equiprobable points, by EM

d2: (N, P) squared distances of N observations from P points. Each observation is a Gaussian mixture draw over the points with one shared variance, which is what the iterations estimate.

Source code in src/rpps/math/prob.py
def mixture_variance(d2, iters=8, floor=1e-12):
    """Noise variance per real dimension of observations scattered around equiprobable points, by EM

    d2: (N, P) squared distances of N observations from P points. Each observation is a Gaussian mixture draw
    over the points with one shared variance, which is what the iterations estimate.
    """
    var = np.mean(np.min(d2, axis=1))/2 + floor
    for _ in range(iters):
        logp = -d2/(2*var)
        r = np.exp(logp - logp.max(axis=1, keepdims=True))
        r /= r.sum(axis=1, keepdims=True)
        var = max(np.sum(r*d2)/(2*len(d2)), floor)
    return var

rolling

Rolling statistics of a 1-D array

Functions:

Name Description
percentile_filter

The percentile (0-100) of every window of size samples centred on each sample of x (a rolling median at 50)

percentile_filter

percentile_filter(x, percentile, size, mode='nearest')

The percentile (0-100) of every window of size samples centred on each sample of x (a rolling median at 50)

The rank is int(size*percentile/100), the lowest sample being rank 0 (as scipy.ndimage.percentile_filter). The window reaches size//2 samples back and (size - 1)//2 ahead. mode: how it is filled past the ends: "nearest" (repeat the edge sample), "reflect", "mirror", "wrap", or "constant" (zeros)

Source code in src/rpps/math/rolling.py
def percentile_filter(x, percentile, size, mode="nearest"):
    """The `percentile` (0-100) of every window of `size` samples centred on each sample of `x` (a rolling median at 50)

    The rank is int(size*percentile/100), the lowest sample being rank 0 (as scipy.ndimage.percentile_filter). The window reaches
    size//2 samples back and (size - 1)//2 ahead. mode: how it is filled past the ends: "nearest" (repeat the edge sample),
    "reflect", "mirror", "wrap", or "constant" (zeros)
    """
    x = np.asarray(x)
    size = int(size)
    if x.ndim != 1:
        raise ValueError("percentile_filter takes a 1-D array")
    if size < 1:
        raise ValueError("size must be at least 1")
    if not 0 <= percentile <= 100:
        raise ValueError("percentile must be within 0..100")
    if len(x) == 0:
        return x.copy()
    rank = min(int(size*percentile/100), size - 1)
    lo, hi = size//2, (size - 1)//2
    pad_mode = {"nearest": "edge", "reflect": "symmetric", "mirror": "reflect", "wrap": "wrap", "constant": "constant"}.get(mode)
    if pad_mode is None:
        raise ValueError(f"mode must be nearest, reflect, mirror, wrap or constant, not {mode!r}")
    xp = np.pad(x, (lo, hi), mode=pad_mode)
    win = np.lib.stride_tricks.sliding_window_view(xp, size)
    out = np.empty(len(x), dtype=x.dtype)
    step = max(_CHUNK//size, 1)
    for a in range(0, len(x), step):
        out[a:a + step] = np.partition(win[a:a + step], rank, axis=1)[:, rank]
    return out