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 ( |
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 |
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 |
to_base2 |
Every |
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 |
find |
Where |
periodic_scores |
Periodic marker fit. |
unstuff |
Bit destuffing (HDLC's: after |
entropy ¶
Entropy of a bit stream [bits per bit]: H = -p0 log2 p0 - p1 log2 p1 (0 log 0 = 0)
reflect ¶
to_base2 ¶
Every order-bit pattern in counting order: (2^order, order) array of 0/1, most significant bit first
to_base10 ¶
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
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
find ¶
periodic_scores ¶
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
unstuff ¶
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
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 |
correct |
Find the errors of one word from its syndromes. Returns (positions, values) or None if uncorrectable |
berlekamp_massey ¶
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
erasure_locator ¶
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
chien ¶
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
forney ¶
Error values at positions. None where the derivative of sigma vanishes (the word is not correctable)
Source code in src/rpps/math/cyclic.py
correct ¶
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
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. |
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: |
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 ¶
mask_matrix ¶
(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
distances ¶
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
noise_variance ¶
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
llr_rows ¶
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
gf ¶
Finite field GF(2^m) arithmetic
Classes:
| Name | Description |
|---|---|
GF |
GF(2^m) with log tables |
GF ¶
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
pow_alpha ¶
pow ¶
polymul ¶
evaluate ¶
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
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 |
unpack_rows |
|
eliminate_packed |
Reduced row echelon form in place over GF(2) of packed rows A ( |
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 |
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 |
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 ¶
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
gh_to_parity ¶
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
to_checks ¶
pack_rows ¶
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
unpack_rows ¶
eliminate_packed ¶
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
rref ¶
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
rank ¶
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
nullspace ¶
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
systematic ¶
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
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 ¶
pgcd ¶
porder ¶
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
berlekamp_massey ¶
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
fwht ¶
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
lfsr_taps ¶
rank_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
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
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 |
fractional_edge |
|
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, |
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
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
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
(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
fractional_edge ¶
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
fractional ¶
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
interpolate ¶
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
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 ¶
(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
optimize ¶
Nonlinear least squares
Functions:
| Name | Description |
|---|---|
least_squares |
Minimise 0.5 * sum(fun(x)**2) from |
least_squares ¶
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
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 ¶
log(sum(exp(x))) along an axis, without overflow
Source code in src/rpps/math/prob.py
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 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
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 a random n-bit window is within e errors of a word. -inf below 0
Source code in src/rpps/math/prob.py
deviance_z ¶
Signed z-like score of k events in n trials against probability p0 (binomial deviance)
Source code in src/rpps/math/prob.py
mixture_variance ¶
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
rolling ¶
Rolling statistics of a 1-D array
Functions:
| Name | Description |
|---|---|
percentile_filter |
The |
percentile_filter ¶
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)