Algorithmintro
Minimum distance detector
Also called minimum Euclidean distance detector.
Choose the constellation point closest to the received sample. For PAM, square QAM and PSK a slicer finds it in O(1) time, and it is the ML decision for equal priors in white Gaussian noise.
- Solves
- Symbol detection
- Time
- Θ(1) worst
- Space
- Θ(1) extra
- Counts
- time general constellation Θ(M n) worst
- Where
- M = the number of constellation points; n = the number of real dimensions of a point
- Model
- Real RAM
- Properties
- deterministicexact ml in awgnseparable for square qam
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John M. Wozencraft, Irwin M. Jacobs, 1965
The minimum distance detector takes a received sample and chooses the point of a known signal constellation that is nearest to it in Euclidean distance. For equally likely symbols in additive white Gaussian noise, this is the maximum likelihood decision, so it solves the symbol detection problem exactly in that case. For pulse amplitude modulation, square QAM and phase-shift keying, a slicer finds the nearest point in a constant number of operations, without computing all distances. The problem page states the general MAP and ML rules; this page is the algorithm for the Gaussian case with equal priors. It differs from the binary threshold tests of signal detection and the Neyman-Pearson lemma, which decide between two hypotheses with a chosen false alarm rate, not among symbols.
In plain words
A transmitter sends one of a few agreed points, for example one of sixteen dots on a grid. Noise moves the point a little, so the receiver gets a dot that is near the sent one but usually not on it. The receiver picks the agreed dot that is nearest to what it got. When the noise is the usual random hiss and each dot is equally likely, no other rule makes fewer mistakes.
The receiver does not need to measure the distance to every dot. On a grid, it rounds the horizontal position and the vertical position to the nearest grid line, one at a time. On a circle of dots, it rounds the angle to the nearest dot angle. Each rounding is a few operations, however many dots there are.
The problem
The receiver sees one complex sample after the matched filter:
The gain is known; it includes the amplitude and any channel phase. The points have unit average energy, and carries the bit label (the Gray labels of the Gray labeling page). The symbols are equally likely. The output is the index
The SNR is per complex symbol. The real and imaginary parts of are independent, each with variance .
The algorithm
Let be the number of levels on one axis: for -PAM and for square -QAM. The raw amplitudes on an axis are for , and level has the Gray label . The unit-energy points are the raw points divided by for PAM and by for QAM. The -PSK point with level is and has the label .
SLICE-AXIS(u, L) ▷ u is in raw units: the levels are L-1, L-3, ..., -(L-1)- 1
m ← ⌊(L - 1 - u)/2 + 1/2⌋ ▷ the nearest level index - 2
m ← min(max(m, 0), L - 1) ▷ clamp to the outer levels - 3
return g(m) DETECT-PAM(y, h, M)- 4
u ← Re(y / h) · sqrt((M² - 1)/3) - 5
return SLICE-AXIS(u, M) DETECT-QAM(y, h, M) ▷ M = L², the label is the in-phase bits, then the quadrature bits- 6
z ← (y / h) · sqrt(2(M - 1)/3) - 7
return SLICE-AXIS(Re z, L) · L + SLICE-AXIS(Im z, L) DETECT-PSK(y, h, M, φ0)- 8
θ ← arg(y / h) - φ0 - 9
k ← ⌊M θ / (2π) + 1/2⌋ mod M ▷ the nearest point on the circle - 10
return g(k)
Line L4 and line L6 remove the gain and undo the unit-energy scaling, so the levels of each axis are the odd integers. For PAM, the imaginary part of does not change the decision, because all points are real. For a constellation with no such structure, the detector computes all distances; the reference code of the area does this by brute force.
Example
16-QAM. Take and . Line L6 gives , with .
| step | in-phase | quadrature |
|---|---|---|
| after L1 and L2 | ||
| raw level | ||
| label | = 01 | = 11 |
Line L7 returns , the bits 0111, and the point . Its squared distance to is . The next two points are index 3, , at , and index 5, , at . A search over all 16 points gives the same index 7.
8-PSK with a channel. Take , and . Then , and line L8 gives rad (108.4 degrees). Line L9 gives , so : the point at 90 degrees. Line L10 returns , the bits 011.
Correctness
The detector is exact: for every it returns an index that minimizes , and this index is a maximum likelihood decision. Three facts give this. First, the Gaussian density makes the likelihood a decreasing function of . Second, , so the problem is the nearest point to in the unit-energy constellation. Third, for PAM and square QAM the squared distance is a sum of one term for each axis, and each term is smallest at the rounded level, clamped to the outer levels; for PSK the distance to a point on the unit circle depends only on the angle between them. Ties occur only on the boundaries of the decision regions, a set of probability zero, and there any of the tied points is a maximum likelihood decision. The full proof is below.
Proof: The slicers return a nearest point, which is a maximum likelihood decisionfull
The model is with known, uniform on the unit-energy constellation , and . We write .
Lemma 1 (ML is minimum distance). For each , the density of given is . With equal priors, the MAP rule maximizes , which is the ML rule. The function is strictly decreasing, so the maximizers of are exactly the minimizers of .
Proof. The density is that of a circularly symmetric complex Gaussian with mean and variance : the real and imaginary parts of are independent , and the product of their two densities is the given formula. The rest is the monotonicity of the exponential.
Lemma 2 (removing the gain). for every . So the minimizers of are the minimizers of .
Proof. and . Since , the factor does not change the order.
Lemma 3 (one axis). Let , let for , and let be real. Put and . Then for every .
Proof. , so , and we must minimize over the integers . Let , so and . There are three cases.
- If , then , so . Every has .
- If , then , so . Every has .
- If , then , so and . Every integer has , so .
In each case for all in .
Lemma 4 (labels). In the reference constellations, the PAM point with label is with , the QAM point with label is with and , and the PSK point with label is with . Since is a bijection on for a power of two, each level has exactly one label.
Proof. This is the definition of the labels in the area conventions. The map has the inverse , so it is a bijection on the integers of bits for each .
Theorem. For every with , DETECT-PAM, DETECT-QAM and DETECT-PSK return the label of a point that minimizes . So each returns a maximum likelihood decision.
Proof. By Lemmas 1 and 2 it suffices to show that the returned point minimizes .
PAM. All points are real, so . The second term is the same for every point. With the scale , for , which is line L4. Lemma 3 with shows that line L1 and line L2 give a nearest level , and line L3 returns its label by Lemma 4.
Square QAM. With and (line L6), the squared distance to the point with levels is . The constellation is the full product of the levels on each axis, so the two levels can be chosen independently, and the sum is smallest when each term is smallest. Lemma 3 gives a minimizing level on each axis, and line L7 combines the two labels in the order of Lemma 4.
PSK. Each point has . If , every point has the distance 1, and any output is a minimizer. Otherwise write . For the point at angle ,
So the nearest point maximizes , that is, it minimizes the distance on the circle between and . Put (line L8) and . The circular distance from to is times the distance from to the set . The integer is nearest to among all integers, as in Lemma 3, so minimizes the distance from to over when we take (line L9). Line L10 returns its label by Lemma 4.
In each case a tie between two points happens only when lies on the boundary between their decision regions. These boundaries are lines (PAM and QAM) or rays (PSK), which have probability zero under the Gaussian density, and on them every tied point is a maximum likelihood decision.
Cost. Each procedure runs a fixed sequence of lines with no loop, so its number of operations is a constant that does not depend on .
Complexity
In the real RAM with a floor operation, each of DETECT-PAM, DETECT-QAM and DETECT-PSK does a constant number of operations: one complex division, one or two scalings, at most two floors and clamps, and one or two Gray conversions on a small integer. The cost does not depend on . The extra space is , and no table of points is needed.
A general constellation of points in real dimensions costs per symbol by exhaustive search. For a vector channel with , maximum likelihood detection is a closest vector problem over a finite part of a lattice, and exhaustive search costs distance evaluations of each for receive dimensions. The per-axis slicer does not solve that problem; see MIMO detection.
Properties
- Exact for equal priors in white Gaussian noise. It minimizes the symbol error probability among all detectors in that model.
- Decision regions. The region of each point is its Voronoi cell, the set of samples nearer to it than to any other point (see Voronoi diagram). For square QAM the cells are rectangles, and the outer cells are unbounded. For PSK they are wedges of angle .
- Invariant to the scale of for PSK. DETECT-PSK uses only the angle of , so an error in does not change its decisions. PAM and QAM need the exact , because their decision boundaries scale with it.
- Hard output. The detector gives one point and its bits, not a reliability. A decoder that needs soft inputs uses soft demapping or max-log demapping instead; the max-log form reuses the same slicer for each bit.
Variants and improvements
- MAP with unequal priors. Minimize , where is the prior of point . This needs , which the minimum distance rule does not.
- Colored noise. With noise covariance , whiten first: minimize .
- Lattice decoding. For a large constellation cut from a lattice, round in the lattice coordinates and then check the boundary. Sphere decoders such as Fincke-Pohst enumeration solve the vector case exactly with less work than exhaustive search at high SNR.
- APSK. For points on several rings, deciding the ring by the radius and then the phase on that ring is fast but is not always the nearest point; an exact slicer must also check the neighbors on the adjacent rings. See amplitude and phase-shift keying.
When to use it
Use the slicer whenever the constellation is PAM, square QAM or PSK, the noise is white and Gaussian, and the symbols are equally likely; it is the standard hard decision device after an equalizer or a single-tap OFDM channel correction. Use the exhaustive form for an irregular constellation of a few dozen points. When the decision feeds a soft-input decoder, compute LLRs instead of hard decisions.
Pitfalls
- The wrong scale. If the transmit points are times the unit points, must include . A slicer for raw amplitudes applied to unit-energy samples decides wrongly for every outer point.
- Rounding at a half. Python's
roundrounds a half to the even integer; this is a tie, and either choice is correct, but code must not rely on one fixed answer at a boundary. The pseudocode uses . - Forgetting the clamp. A sample beyond the outer level gives an index outside without line L2.
- Cross and other non-square QAM. 32-QAM and 128-QAM have no corner points, so independent slicing of the two axes can return a point that does not exist.
- Not ML outside the model. With unequal priors, impulsive noise, phase noise or an imperfect estimate of , the nearest point is not the most likely one.
- Dividing by a small . The division in lines L4, L6 and L8 is safe for the decision, because a scale does not change the order of distances, but has the noise variance . Use the scaled form when you also need the noise level, for example for LLRs.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the communications pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Complex baseband tools for the communications pages.
Vectors are lists of complex numbers. Matrices are lists of rows. The
functions here are plain building blocks: small linear algebra, convolution,
the DFT as a direct sum, the Gaussian Q function, dB conversion, complex
Gaussian noise and the Wilson score interval. No page algorithm (equalizer,
estimator, synchronizer, detector, precoder, demapper or power allocation)
lives in this file.
Conventions (prompts of the communications area):
- dft is X[k] = sum_n x[n] e^(-j 2 pi k n / N) with no factor; idft has 1/N.
- udft and uidft are the unitary pair, with 1/sqrt(N) on both sides.
- qfunc(x) = 0.5 erfc(x / sqrt(2)); it never computes 1 - Phi(x).
- cn(rng, var) draws CN(0, var): real and imaginary parts are independent
with variance var / 2 each, so E|w|^2 = var.
"""
import cmath
import math
import random
# ---------------------------------------------------------------- vectors and matrices
def zeros(rows: int, cols: int | None = None) -> list:
"""A zero vector of length rows, or a rows by cols zero matrix."""
if cols is None:
return [0j] * rows
return [[0j] * cols for _ in range(rows)]
def eye(n: int) -> list[list[complex]]:
"""The n by n identity matrix."""
return [[1 + 0j if i == k else 0j for k in range(n)] for i in range(n)]
def add(a: list, b: list) -> list:
"""Elementwise a + b for two vectors or two matrices of the same shape."""
if len(a) != len(b):
raise ValueError("shapes differ")
if a and isinstance(a[0], list):
return [add(r, s) for r, s in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a: list, b: list) -> list:
"""Elementwise a - b for two vectors or two matrices of the same shape."""
if len(a) != len(b):
raise ValueError("shapes differ")
if a and isinstance(a[0], list):
return [sub(r, s) for r, s in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(c: complex, a: list) -> list:
"""The scalar c times a vector or a matrix."""
if a and isinstance(a[0], list):
return [scale(c, r) for r in a]
return [c * x for x in a]
def matmul(a: list[list[complex]], b: list[list[complex]]) -> list[list[complex]]:
"""The matrix product a b."""
if not a or not b or len(a[0]) != len(b):
raise ValueError("inner dimensions differ")
cols = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in cols] for row in a]
def matvec(a: list[list[complex]], x: list[complex]) -> list[complex]:
"""The matrix times vector product a x."""
if a and len(a[0]) != len(x):
raise ValueError("inner dimensions differ")
return [sum(p * q for p, q in zip(row, x)) for row in a]
def herm(a: list) -> list:
"""The conjugate transpose of a matrix. A vector gives its conjugate."""
if a and isinstance(a[0], list):
return [[complex(a[i][k]).conjugate() for i in range(len(a))] for k in range(len(a[0]))]
return [complex(x).conjugate() for x in a]
def dot(x: list[complex], y: list[complex]) -> complex:
"""The inner product x^H y = sum of conj(x_i) y_i."""
if len(x) != len(y):
raise ValueError("lengths differ")
return sum(complex(p).conjugate() * q for p, q in zip(x, y))
def norm2(x: list) -> float:
"""The squared Euclidean norm sum |x_i|^2 (squared Frobenius norm for a matrix)."""
if x and isinstance(x[0], list):
return sum(norm2(r) for r in x)
return sum(abs(v) ** 2 for v in x)
# ---------------------------------------------------------------- linear systems
def _lu(a: list[list[complex]]) -> tuple[list[list[complex]], list[int], int]:
"""LU factorization with partial pivoting. Returns (lu, perm, sign)."""
n = len(a)
if any(len(r) != n for r in a):
raise ValueError("matrix is not square")
m = [[complex(v) for v in r] for r in a]
perm = list(range(n))
sign = 1
for k in range(n):
p = max(range(k, n), key=lambda i: abs(m[i][k]))
if abs(m[p][k]) == 0.0:
raise ValueError("matrix is singular")
if p != k:
m[k], m[p] = m[p], m[k]
perm[k], perm[p] = perm[p], perm[k]
sign = -sign
for i in range(k + 1, n):
f = m[i][k] / m[k][k]
m[i][k] = f
if f != 0:
rk, ri = m[k], m[i]
for c in range(k + 1, n):
ri[c] -= f * rk[c]
return m, perm, sign
def _lu_solve(lu: list[list[complex]], perm: list[int], b: list[complex]) -> list[complex]:
n = len(lu)
y = [complex(b[perm[i]]) for i in range(n)]
for i in range(n):
for c in range(i):
y[i] -= lu[i][c] * y[c]
for i in range(n - 1, -1, -1):
for c in range(i + 1, n):
y[i] -= lu[i][c] * y[c]
y[i] /= lu[i][i]
return y
def solve(a: list[list[complex]], b: list) -> list:
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector, or a matrix whose columns are right-hand sides.
Raises ValueError if a is singular.
"""
lu, perm, _ = _lu(a)
if b and isinstance(b[0], list):
cols = [list(c) for c in zip(*b)]
xs = [_lu_solve(lu, perm, c) for c in cols]
return [list(r) for r in zip(*xs)]
if len(b) != len(a):
raise ValueError("lengths differ")
return _lu_solve(lu, perm, b)
def inv(a: list[list[complex]]) -> list[list[complex]]:
"""The inverse of a square matrix."""
return solve(a, eye(len(a)))
def det(a: list[list[complex]]) -> complex:
"""The determinant of a square matrix (0 for a singular matrix)."""
try:
lu, _, sign = _lu(a)
except ValueError as e:
if "singular" in str(e):
return 0j
raise
d = complex(sign)
for i in range(len(lu)):
d *= lu[i][i]
return d
def cholesky(a: list[list[complex]]) -> list[list[complex]]:
"""The lower triangular L with a = L L^H, for a Hermitian positive definite a.
Raises ValueError if a is not positive definite (to rounding).
"""
n = len(a)
low = zeros(n, n)
for i in range(n):
for k in range(i + 1):
s = complex(a[i][k]) - sum(low[i][c] * low[k][c].conjugate() for c in range(k))
if i == k:
if s.real <= 0.0:
raise ValueError("matrix is not positive definite")
low[i][i] = complex(math.sqrt(s.real))
else:
low[i][k] = s / low[k][k].real
return low
# ---------------------------------------------------------------- convolution and the DFT
def conv(a: list[complex], b: list[complex]) -> list[complex]:
"""Linear convolution, of length len(a) + len(b) - 1."""
if not a or not b:
return []
out = [0j] * (len(a) + len(b) - 1)
for i, x in enumerate(a):
for k, y in enumerate(b):
out[i + k] += x * y
return out
def cconv(a: list[complex], b: list[complex], n: int | None = None) -> list[complex]:
"""Circular convolution of length n (default: the longer length).
Both inputs are padded with zeros to length n, or must not be longer than n.
"""
if n is None:
n = max(len(a), len(b))
if len(a) > n or len(b) > n:
raise ValueError("input longer than n")
out = [0j] * n
for i, x in enumerate(a):
for k, y in enumerate(b):
out[(i + k) % n] += x * y
return out
def _twiddles(n: int, sign: int) -> list[complex]:
return [cmath.exp(sign * 2j * math.pi * t / n) for t in range(n)]
def dft(x: list[complex]) -> list[complex]:
"""X[k] = sum over n of x[n] e^(-j 2 pi k n / N), as a direct O(N^2) sum."""
n = len(x)
w = _twiddles(n, -1)
return [sum(x[t] * w[(k * t) % n] for t in range(n)) for k in range(n)]
def idft(xf: list[complex]) -> list[complex]:
"""x[n] = (1/N) sum over k of X[k] e^(j 2 pi k n / N), the inverse of dft."""
n = len(xf)
w = _twiddles(n, 1)
return [sum(xf[k] * w[(k * t) % n] for k in range(n)) / n for t in range(n)]
def udft(x: list[complex]) -> list[complex]:
"""The unitary DFT: dft(x) / sqrt(N)."""
s = 1.0 / math.sqrt(len(x)) if x else 1.0
return [v * s for v in dft(x)]
def uidft(xf: list[complex]) -> list[complex]:
"""The unitary inverse DFT: sqrt(N) idft(X), the inverse of udft."""
s = math.sqrt(len(xf)) if xf else 1.0
return [v * s for v in idft(xf)]
# ---------------------------------------------------------------- Q function and dB
def qfunc(x: float) -> float:
"""Q(x) = P(Z > x) for a standard normal Z, computed as 0.5 erfc(x / sqrt(2))."""
return 0.5 * math.erfc(x / math.sqrt(2.0))
def qinv(p: float) -> float:
"""The x with Q(x) = p, for 0 < p < 1, by bisection on Q (which decreases)."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
lo, hi = -40.0, 40.0
for _ in range(200):
mid = 0.5 * (lo + hi)
if qfunc(mid) > p:
lo = mid
else:
hi = mid
if hi - lo <= 1e-15 * max(1.0, abs(mid)):
break
return 0.5 * (lo + hi)
def db(x: float) -> float:
"""10 log10(x), for a ratio of powers or energies."""
return 10.0 * math.log10(x)
def undb(d: float) -> float:
"""10^(d / 10), the inverse of db."""
return 10.0 ** (d / 10.0)
# ---------------------------------------------------------------- noise and statistics
def cn(rng: random.Random, var: float) -> complex:
"""One sample of CN(0, var): independent real and imaginary parts of variance var / 2."""
s = math.sqrt(var / 2.0)
return complex(rng.gauss(0.0, s), rng.gauss(0.0, s))
def awgn(rng: random.Random, x: list[complex], n0: float) -> list[complex]:
"""x plus independent CN(0, n0) noise on each sample."""
return [v + cn(rng, n0) for v in x]
def wilson(k: int, n: int, z: float = 3.29) -> tuple[float, float]:
"""The Wilson score interval for k successes in n trials (z = 3.29 is about 0.999 two-sided)."""
if n <= 0 or not 0 <= k <= n:
raise ValueError("need 0 <= k <= n and n > 0")
p = k / n
z2 = z * z
den = 1.0 + z2 / n
mid = (p + z2 / (2 * n)) / den
half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / den
return max(0.0, mid - half), min(1.0, mid + half)
constel.py 117 lines
# SPDX-License-Identifier: MIT
# Shared helper of the communications pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Constellations, Gray labels and brute-force maximum likelihood detection.
Each constellation function returns a list of M complex points with unit
average energy, ordered by label: points[i] is the point whose bit label is
the integer i, and bits(i, log2 M) gives that label, most significant bit
first. The labels follow the communications area rules:
- M-PAM: the point with amplitude index m = 0, ..., M-1 (raw amplitude
M - 1 - 2m, from the most positive) gets the Gray label gray(m).
So 2-PAM maps bit 0 to +1 and bit 1 to -1.
- Square M-QAM, M = 4^k: the label is the in-phase PAM label followed by the
quadrature PAM label, each of log2(sqrt(M)) bits.
- M-PSK: the point e^(j(2 pi m / M + phase0)) gets the label gray(m).
PAM points are returned as complex numbers with zero imaginary part.
This file imports nothing from cbb.py. It holds no demapper: soft and
max-log demapping are algorithm pages of their own.
"""
import cmath
import itertools
import math
def gray(n: int) -> int:
"""The binary reflected Gray code of n: n XOR (n >> 1)."""
return n ^ (n >> 1)
def _gray_inv(g: int) -> int:
n = 0
while g:
n ^= g
g >>= 1
return n
def bits(i: int, m: int) -> list[int]:
"""The m bits of the integer i, most significant bit first."""
if i < 0 or i >= 1 << m:
raise ValueError("i does not fit in m bits")
return [(i >> (m - 1 - t)) & 1 for t in range(m)]
def _log2(m: int) -> int:
if m < 2 or m & (m - 1):
raise ValueError("M must be a power of two, at least 2")
return m.bit_length() - 1
def pam(m: int) -> list[complex]:
"""Unit-energy M-PAM, ordered by Gray label."""
_log2(m)
s = math.sqrt((m * m - 1) / 3.0)
return [complex((m - 1 - 2 * _gray_inv(lab)) / s, 0.0) for lab in range(m)]
def qam(m: int) -> list[complex]:
"""Unit-energy square M-QAM (M = 4, 16, 64, ...), ordered by label (in-phase bits first)."""
k = _log2(m)
if k % 2:
raise ValueError("square QAM needs M = 4^k")
side = 1 << (k // 2)
s = math.sqrt(2.0 * (m - 1) / 3.0)
raw = [side - 1 - 2 * _gray_inv(lab) for lab in range(side)]
return [complex(raw[lab // side], raw[lab % side]) / s for lab in range(m)]
def psk(m: int, phase0: float = 0.0) -> list[complex]:
"""Unit-energy M-PSK with first point at angle phase0, ordered by Gray label."""
_log2(m)
return [cmath.exp(1j * (2.0 * math.pi * _gray_inv(lab) / m + phase0)) for lab in range(m)]
def energy(points: list[complex]) -> float:
"""The average energy (1/M) sum |p|^2 of equally likely points."""
return sum(abs(p) ** 2 for p in points) / len(points)
def ml_detect(y: complex, points: list[complex], h: complex = 1) -> int:
"""The index of the point p that minimizes |y - h p|^2, by brute force (lowest index on a tie)."""
best, arg = math.inf, -1
for i, p in enumerate(points):
d = abs(y - h * p) ** 2
if d < best:
best, arg = d, i
return arg
def ml_vector(y: list[complex], h: list[list[complex]], points: list[complex]) -> list[int]:
"""The index vector that minimizes ||y - H x||^2 over all M^n vectors x, by brute force.
h is the m by n channel matrix as a list of rows; the result has n indices.
The first minimizer in lexicographic order of the indices wins a tie.
"""
n = len(h[0])
best, arg = math.inf, None
for idx in itertools.product(range(len(points)), repeat=n):
x = [points[i] for i in idx]
d = 0.0
for yi, row in zip(y, h):
d += abs(yi - sum(a * b for a, b in zip(row, x))) ** 2
if d < best:
best, arg = d, idx
return list(arg)
def bit_errors(a, b) -> int:
"""The number of differing bits between two integer labels, or summed over two equal-length lists."""
if isinstance(a, int) and isinstance(b, int):
return bin(a ^ b).count("1")
if len(a) != len(b):
raise ValueError("lengths differ")
return sum(bit_errors(x, y) for x, y in zip(a, b))
minimum_distance_detector.py 72 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-distance-detector/. The authors are listed in prov/NW9AYJ.jsonl.
"""Minimum distance detection by slicing, in O(1) time per symbol.
The detectors return the label index i of the chosen point, so that
constel.pam(M)[i], constel.qam(M)[i] or constel.psk(M, phase0)[i] is the
decision and constel.bits(i, log2 M) are its bits. The received sample is
y = h x + w with a known complex gain h != 0. Since
|y - h p|^2 = |h|^2 |y/h - p|^2, the closest point to y in the scaled
constellation is the closest point to y/h in the unit-energy constellation.
"""
import cmath
import math
def gray(n: int) -> int:
"""n XOR (n >> 1), the same Gray code as constel.gray."""
return n ^ (n >> 1)
def slice_axis(u: float, side: int) -> int:
"""Gray label of the nearest raw amplitude side - 1 - 2m (m = 0, ..., side - 1) to u."""
m = math.floor((side - 1 - u) / 2.0 + 0.5) # @line L1
m = min(max(m, 0), side - 1) # @line L2
return gray(m) # @line L3
def detect_pam(y: complex, m: int, h: complex = 1) -> int:
"""The label of the closest unit-energy M-PAM point to y/h."""
u = (complex(y) / h).real * math.sqrt((m * m - 1) / 3.0) # @line L4
return slice_axis(u, m) # @line L5
def detect_qam(y: complex, m: int, h: complex = 1) -> int:
"""The label of the closest unit-energy square M-QAM point to y/h."""
side = math.isqrt(m)
if side * side != m or side & (side - 1):
raise ValueError("square QAM needs M = 4^k")
z = complex(y) / h * math.sqrt(2.0 * (m - 1) / 3.0) # @line L6
return slice_axis(z.real, side) * side + slice_axis(z.imag, side) # @line L7
def detect_psk(y: complex, m: int, h: complex = 1, phase0: float = 0.0) -> int:
"""The label of the closest unit-energy M-PSK point to y/h."""
theta = cmath.phase(complex(y) / h) - phase0 # @line L8
k = math.floor(m * theta / (2.0 * math.pi) + 0.5) % m # @line L9
return gray(k) # @line L10
def detect(y: complex, scheme: str, m: int, h: complex = 1, phase0: float = 0.0) -> int:
"""Dispatch on scheme ('pam', 'qam' or 'psk')."""
if h == 0:
raise ValueError("h must not be zero")
if scheme == "pam":
return detect_pam(y, m, h)
if scheme == "qam":
return detect_qam(y, m, h)
if scheme == "psk":
return detect_psk(y, m, h, phase0)
raise ValueError("unknown scheme")
def detect_general(y: complex, points: list[complex], h: complex = 1) -> int:
"""Minimum distance over an arbitrary point list: M distances, O(M) time."""
best, arg = math.inf, -1
for i, p in enumerate(points):
d = abs(y - h * p) ** 2
if d < best:
best, arg = d, i
return arg
test_minimum_distance_detector.py 220 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-distance-detector/. The authors are listed in prov/NW9AYJ.jsonl.
import math
import random
import cbb
import constel
from minimum_distance_detector import detect, detect_general, detect_pam, detect_psk, detect_qam
# ---------------------------------------------------------------- the shared helper cbb.py
def test_cbb_q_function() -> None:
assert abs(cbb.qfunc(1.0) - 0.158655) < 5e-7
assert abs(cbb.qfunc(2.0) - 0.022750) < 5e-7
assert abs(cbb.qfunc(3.0) - 0.0013499) < 5e-8
assert abs(cbb.qinv(1e-5) - 4.26489) < 5e-6
assert abs(cbb.qfunc(cbb.qinv(0.3)) - 0.3) < 1e-12
# No cancellation in the far tail: Q(10) is about 7.6199e-24.
assert abs(cbb.qfunc(10.0) / 7.619853024160527e-24 - 1) < 1e-9
assert abs(cbb.db(2.0) - 3.0103) < 5e-5
assert abs(cbb.undb(cbb.db(7.5)) - 7.5) < 1e-12
def test_cbb_dft_round_trip_and_parseval() -> None:
rng = random.Random(1)
x = [complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(8)]
xf = cbb.dft(x)
assert max(abs(a - b) for a, b in zip(cbb.idft(xf), x)) < 1e-12
assert abs(cbb.norm2(xf) - 8 * cbb.norm2(x)) < 1e-12
u = cbb.udft(x)
assert max(abs(a - b) for a, b in zip(cbb.uidft(u), x)) < 1e-12
assert abs(cbb.norm2(u) - cbb.norm2(x)) < 1e-12
# The DFT turns circular convolution into a product.
h = [0.5 + 0.1j, -0.2j, 0.3]
lhs = cbb.dft(cbb.cconv(x, h, 8))
hf = cbb.dft(h + [0j] * 5)
assert max(abs(a - b * c) for a, b, c in zip(lhs, xf, hf)) < 1e-12
assert cbb.conv([1, 2], [1, -1, 3]) == [1, 1, 1, 6]
def test_cbb_linear_algebra() -> None:
a = [[2 + 1j, 1, -1j], [0.5, 3 - 1j, 1 + 1j], [1j, -1, 4]]
x = [1 - 2j, 0.5j, -1 + 1j]
b = cbb.matvec(a, x)
got = cbb.solve(a, b)
assert max(abs(p - q) for p, q in zip(got, x)) < 1e-12
ai = cbb.inv(a)
i3 = cbb.matmul(a, ai)
assert cbb.norm2(cbb.sub(i3, cbb.eye(3))) < 1e-24
# det by cofactor expansion
d = (a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
- a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
+ a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]))
assert abs(cbb.det(a) - d) < 1e-12
assert cbb.det([[1, 2], [2, 4]]) == 0
# Cholesky of A^H A + I
g = cbb.add(cbb.matmul(cbb.herm(a), a), cbb.eye(3))
low = cbb.cholesky(g)
assert cbb.norm2(cbb.sub(cbb.matmul(low, cbb.herm(low)), g)) < 1e-22
assert all(low[i][k] == 0 for i in range(3) for k in range(i + 1, 3))
assert abs(cbb.dot([1j, 2], [1j, 1]) - 3) < 1e-15
assert cbb.scale(2, [[1, 1j]]) == [[2, 2j]]
assert cbb.zeros(2) == [0j, 0j] and cbb.zeros(1, 2) == [[0j, 0j]]
def test_cbb_noise_and_wilson() -> None:
rng = random.Random(2)
n = 20000
mean = sum(abs(cbb.cn(rng, 0.5)) ** 2 for _ in range(n)) / n
assert abs(mean - 0.5) < 0.03 * 0.5
y = cbb.awgn(rng, [1 + 0j] * 4, 0.0)
assert y == [1 + 0j] * 4
lo, hi = cbb.wilson(50, 1000)
assert lo < 0.05 < hi
# The two ends are the roots of (p - 0.05)^2 = z^2 p (1 - p) / n.
for p in (lo, hi):
assert abs((p - 0.05) ** 2 - 3.29 ** 2 * p * (1 - p) / 1000) < 1e-15
# ---------------------------------------------------------------- the shared helper constel.py
def test_constel_energy_and_labels() -> None:
raw16 = [p * math.sqrt(10) for p in constel.qam(16)]
assert abs(constel.energy(raw16) - 10) < 1e-12
for m in (2, 4, 8, 16):
assert abs(constel.energy(constel.pam(m)) - 1) < 1e-12
assert abs(constel.energy(constel.psk(m)) - 1) < 1e-12
for m in (4, 16, 64):
assert abs(constel.energy(constel.qam(m)) - 1) < 1e-12
assert constel.pam(2) == [1 + 0j, -1 + 0j]
q4 = constel.qam(4)
s = 1 / math.sqrt(2)
assert all(abs(a - b) < 1e-15 for a, b in zip(q4, [s + s * 1j, s - s * 1j, -s + s * 1j, -s - s * 1j]))
assert [constel.gray(i) for i in range(8)] == [0, 1, 3, 2, 6, 7, 5, 4]
assert constel.bits(6, 4) == [0, 1, 1, 0]
assert constel.bit_errors(0b1011, 0b0010) == 2
assert constel.bit_errors([1, 2, 3], [1, 1, 0]) == 4
def _dmin(points):
return min(abs(a - b) for i, a in enumerate(points) for b in points[i + 1:])
def test_constel_gray_neighbors_differ_in_one_bit() -> None:
cases = [constel.pam(m) for m in (2, 4, 8, 16)]
cases += [constel.qam(m) for m in (4, 16, 64)]
cases += [constel.psk(m) for m in (4, 8, 16)] + [constel.psk(8, math.pi / 8)]
for pts in cases:
d = _dmin(pts)
pairs = 0
for i, a in enumerate(pts):
for k in range(i + 1, len(pts)):
if abs(abs(a - pts[k]) - d) < 1e-9:
pairs += 1
assert constel.bit_errors(i, k) == 1
assert pairs >= len(pts) - 1
def test_constel_check_values() -> None:
assert abs(_dmin(constel.qam(16)) ** 2 - 0.4) < 1e-12
assert abs(_dmin(constel.psk(8)) - 0.76537) < 5e-6
def test_constel_ml_vector_matches_ml_detect() -> None:
rng = random.Random(3)
pts = constel.qam(16)
for _ in range(200):
y = complex(rng.uniform(-1.5, 1.5), rng.uniform(-1.5, 1.5))
h = complex(rng.uniform(-1, 1), rng.uniform(-1, 1))
assert constel.ml_vector([y], [[h]], pts) == [constel.ml_detect(y, pts, h)]
# ---------------------------------------------------------------- the detector
def _grid(k, r):
"""A k by k grid on [-r, r]^2, shifted by an irrational step so few points sit on a boundary."""
step = 2 * r / k
return [complex(-r + (i + 0.5 * math.sqrt(2) - 0.5) * step, -r + (q + 0.5 * math.sqrt(3) - 0.5) * step)
for i in range(k) for q in range(k)]
def _check(fast, pts, ys, h):
ties = 0
for y in ys:
got = fast(y)
ref = constel.ml_detect(y, pts, h)
if got != ref:
# Allowed only on a tie: the slicer's point is as close as the brute-force choice.
assert abs(abs(y - h * pts[got]) - abs(y - h * pts[ref])) < 1e-12
ties += 1
assert ties <= len(ys) // 100
def test_slicer_matches_brute_force_on_a_grid() -> None:
ys = _grid(36, 1.8)
for h in (1, 0.6 + 0.8j, -0.3 + 0.2j):
hy = [h * y for y in ys]
for m in (2, 4, 8):
_check(lambda y: detect_pam(y, m, h), constel.pam(m), hy, h)
for m in (4, 16, 64):
_check(lambda y: detect_qam(y, m, h), constel.qam(m), hy, h)
for m in (2, 4, 8, 16):
for ph in (0.0, math.pi / 4):
_check(lambda y: detect_psk(y, m, h, ph), constel.psk(m, ph), hy, h)
def test_slicer_exact_on_points_and_far_away() -> None:
for m in (4, 16, 64):
pts = constel.qam(m)
for i, p in enumerate(pts):
assert detect(p, "qam", m) == i
assert detect(10 * p, "qam", m) == constel.ml_detect(10 * p, pts)
for m in (2, 8, 16):
pts = constel.pam(m)
for i, p in enumerate(pts):
assert detect(p + 0.3j, "pam", m) == i
pts = constel.psk(m, 0.1)
for i, p in enumerate(pts):
assert detect(0.01 * p, "psk", m, phase0=0.1) == i
assert detect_general(p, pts) == i
def test_16qam_symbol_error_rate() -> None:
# 16-QAM at Es/N0 = 15 dB: SER = 0.017782 (check value). n = 20000 symbols gives about
# 356 expected errors. Seed 5, Wilson interval with z = 3.29.
rng = random.Random(5)
m, n = 16, 20000
pts = constel.qam(m)
n0 = 1 / cbb.undb(15.0)
errors = 0
for _ in range(n):
i = rng.randrange(m)
y = pts[i] + cbb.cn(rng, n0)
errors += detect_qam(y, m) != i
p = 2 * (1 - 1 / math.sqrt(m)) * cbb.qfunc(math.sqrt(3 * cbb.undb(15.0) / (m - 1)))
ser = 1 - (1 - p) ** 2
assert abs(ser - 0.017782) < 5e-7
lo, hi = cbb.wilson(errors, n)
assert lo <= ser <= hi
def test_8psk_symbol_error_rate_with_a_channel_gain() -> None:
# 8-PSK at Es/N0 = 12 dB through h = 0.6 + 0.8j (|h| = 1). The approximation
# 2Q(sqrt(2 Es/N0) sin(pi/8)) is about 0.0236 here. n = 10000, seed 6.
rng = random.Random(6)
m, n, h = 8, 10000, 0.6 + 0.8j
pts = constel.psk(m)
n0 = 1 / cbb.undb(12.0)
errors = 0
for _ in range(n):
i = rng.randrange(m)
y = h * pts[i] + cbb.cn(rng, n0)
errors += detect_psk(y, m, h) != i
approx = 2 * cbb.qfunc(math.sqrt(2 * cbb.undb(12.0)) * math.sin(math.pi / m))
lo, hi = cbb.wilson(errors, n)
assert lo <= approx <= hi
History
The rule that the best receiver for equally likely signals in white Gaussian noise picks the nearest signal follows from the likelihood ratio tests of statistical decision theory. Kotelnikov treated optimum reception of known signals in Gaussian noise in his 1947 doctoral thesis, published in English in 1959 as The Theory of Optimum Noise Immunity. Wozencraft and Jacobs, in Principles of Communication Engineering (1965), presented the receiver as a geometric decision in signal space, with a decision region around each signal point, and this became the textbook form.
References
- John G. Proakis and Masoud Salehi, Digital Communications, fifth edition, McGraw-Hill, 2008, Section 4.2-1 (optimal detection for the vector AWGN channel, the minimum distance rule) and Sections 4.3-1 to 4.3-3 (the detectors and error probabilities for PAM, PSK and QAM)
- John R. Barry, Edward A. Lee and David G. Messerschmitt, Digital Communication, third edition, Kluwer Academic Publishers, 2004, Chapter 5, Pulse-Amplitude Modulation (the section on the one-shot minimum-distance receiver), and Chapter 7, Probabilistic Detection
- David Tse and Pramod Viswanath, Fundamentals of Wireless Communication, Cambridge University Press, 2005, Appendix A, Detection and estimation in additive Gaussian noise (detection in the scalar and vector Gaussian channel)
- John M. Wozencraft and Irwin M. Jacobs, Principles of Communication Engineering, Wiley, 1965 (reissued by Waveland Press, 1990), Chapter 4, Optimum receiver principles (vector channels, decision regions and the probability of error)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag NW9AYJ Edit this page History Report an error Markdown