Algorithmadvanced
K-best detector
Also called K-best sphere decoder, M-algorithm detection.
A breadth-first search of the detection tree that keeps the K best partial symbol vectors at each level. Its cost is fixed and it is not exact ML unless K is at least M^(n-1).
- Solves
- MIMO detection
- Time
- O(n^2 m + n^3 + n^2 K + n K M log(K M)) worst
- Space
- O(n m + n K M) extra
- Where
- K = the number of survivors per level; M = the constellation size; m = the number of receive antennas; n = the number of transmitted streams
- Model
- Real RAM
- Properties
- deterministicnot exact mlfixed complexitynot needs noise level
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Kwan wai Wong, Chi ying Tsui, Roger S. K. Cheng, Wai ho Mow, 2002
The K-best detector solves the MIMO detection problem approximately by a breadth-first search over the tree of partial symbol vectors. After a triangular factorization of the channel, the ML metric splits into nonnegative terms, one per tree level, and each level adds one symbol. The detector goes down the tree level by level, extends each surviving partial vector by all symbols, and keeps only the extensions with the smallest partial metrics. So it visits exactly nodes per level, whatever the noise. This fixed cost is the difference from the depth-first sphere searches, Schnorr-Euchner enumeration and Fincke-Pohst enumeration, which are exact ML but have a cost that depends on the noise and the channel. The price is that K-best is not exact: the ML vector is lost if one of its partial vectors falls out of the best at some level. With it is the ZF successive cancellation of V-BLAST in a fixed order, and with it is exact ML (both theorems). In tree search terms it is a beam search with beam width .
In plain words
The receiver must guess several symbols at once. It can guess them one at a time, starting with the symbol that the others do not affect after a change of coordinates. For each guess it keeps a score, the part of the total error that the symbols guessed so far already cause. The score only grows as more symbols are added. A greedy receiver keeps only its single best guess at each step, and one bad early guess ruins the rest. The K-best receiver keeps its K best partial guesses at each step instead of one. A larger K costs more work but makes a fatal early mistake less likely. The work is the same for every received signal, which is useful in hardware.
The problem
The model is with known, and full column rank, for a constellation of size , and . The ML decision minimizes over the vectors of . The K-best detector returns a vector of with a small metric, and the list of its final survivors with their metrics, which a soft-output receiver can use.
The algorithm
Let with upper triangular and a real positive diagonal, from a Cholesky decomposition of or a QR decomposition of . Let solve . Then with , which does not depend on . Row of involves only , so
and the partial metric of is the sum of the terms from to .
K-BEST(y, H, S, K)- 1
(R, ȳ, c) ← TRIANGULARIZE(y, H) - 2
survivors ← {(0, empty vector)} - 3
for i ← n down to 1 ▷ one tree level per symbol - 4
for each (d, (x_{i+1}, ..., x_n)) in survivors - 5
for each s in S: add (d + |ȳ_i - Σ_{j>i} R_ij x_j - R_ii s|², (s, x_{i+1}, ..., x_n)) to the candidates - 6
survivors ← the K candidates with the smallest metrics - 7
return the survivors, with c added to each metric, best first
Line L5 computes the interference term once per survivor and then one squared distance per symbol. Line L6 needs only the smallest of values, so a partial sort or a selection by quickselect is enough; the implementation sorts, which is simpler. Hardware versions avoid the full sort: the Schnorr-Euchner variant of Guo and Nilsson (2006) generates the children of each survivor in order of distance, so only the next best child of each survivor competes for a slot.
Example
Take , BPSK, , and , the received vector of the example on the ZF page for . Then , and
Level 2 (the symbol ): the term is , which is 0.018 for and 0.578 for .
With , only survives. Level 1 then has , and the term is 8.192 for and 2.592 for . The detector returns with metric . Both symbols are wrong. This is the ZF successive cancellation decision that starts with .
With , both level 2 nodes survive. For , , and adds , for a total of . The best final survivor is with metric 0.61, the ML vector. The partial metric of the ML path was the larger one at level 2 (0.578 against 0.018), so a search with pruned it.
Correctness
The proof is in proofs/correctness.md. It shows four things. First, the triangular form gives , so the returned metrics are the true ML metrics (a theorem). Second, partial metrics never decrease down the tree (a theorem), which is why pruning by partial metric is reasonable but also why it can fail: a path can start badly and end well, as in the example. Third, with no node is pruned before the last level, so the survivors are the best vectors of and the first one is the ML vector (a theorem). Fourth, with the detector is ZF successive cancellation in the order (a theorem).
Proof: The K-best metrics are the ML metrics, K at least M^(n-1) gives ML, and K = 1 is ZF successive cancellationfull
The model is with of full column rank and , . Let with upper triangular with a positive diagonal (the Cholesky factor of line L1), let solve , and let .
Theorem 1 (the triangular metric). For every , .
Proof. Expand both sides. . Also . Now and , so the two expressions differ by .
For define the level term
and the partial metric , with . Because is upper triangular, row of is the expression inside , so .
Lemma 2 (partial metrics never decrease). , and depends only on .
Proof. Immediate from the definition, since and for involves only .
Invariant. After the loop body for level , every survivor is a pair with , and line L5 computes of each child correctly from of its parent. This follows from Lemma 2, because line L5 adds exactly . So the metrics returned by line L7 are by Theorem 1.
Theorem 3 (large K is exact ML). If , line L7 returns the vectors of with the smallest metrics, in increasing order of metric, and the first one is an ML vector.
Proof. Before level is processed, there are at most partial vectors of length . For , line L5 creates at most candidates, so line L6 keeps all of them. By induction, before the last level () the survivors are all vectors . Line L5 then creates all vectors with their exact metrics, and line L6 keeps the smallest. The first of them minimizes over .
Theorem 4 (K = 1 is ZF successive cancellation). With , the K-best detector returns the decisions of ZF nulling and cancelling in the fixed order , with the nearest-point slicer (with the same tie rule).
Proof. With there is one survivor. At level the candidates differ only in , and with . Since is common, line L6 keeps the nearest to .
Now compare with ZF nulling and cancelling. After the decisions are cancelled, the residual is , and the ZF output for stream uses the first columns . Its value is the last entry of . The leading block of satisfies , because the leading block of involves only the leading block of when is upper triangular. So the ZF output is the last entry of . The first entries of are , and
where is the vector with in the positions and zeros elsewhere. Let . The first entries of are , because is lower triangular. So , and the ZF output is the last entry of . Since is upper triangular, the last entry of is , and . So the ZF output is , the same value, and the two detectors slice the same number.
Why pruning can fail. Lemma 2 says a partial metric is a lower bound on the final metric of every completion. It does not bound the final metric from above. A path with a large partial metric at a high level can have small terms below, and a path with a small partial metric can have large terms below. When the ML path is not among the best at some level , it is pruned and never returns. The example on the page shows this for : the ML path has partial metric 0.578 at level 2, against 0.018 for the other path, but final metric 0.61, against 2.61.
Complexity
The triangularization costs . Each of the levels computes interference terms of each, squared distances, and a selection of out of values, which is with quickselect or with a sort. So the search costs with sorting, and the total is in the real RAM. The memory holds candidates of up to symbols. The cost does not depend on the noise or on , unlike the depth-first sphere searches, whose expected cost is exponential in (Jaldén and Ottersten, 2005, cited on the MIMO detection page).
Properties
- Fixed cost. Exactly levels with candidates each, for every and .
- Exact metrics. The metric of each survivor is (theorem).
- Exact for large K. With the result is the ML vector (theorem). This is the cost of exhaustive search, final candidates.
- Greedy for K = 1. With it is ZF successive cancellation in a fixed order (theorem).
- No guarantee in between. For the result can differ from ML, and a larger is not guaranteed to give a better metric for every .
- Measured agreement with ML. For 4-QAM, , i.i.d. Rayleigh entries and dB, the test with seed 1605 runs 150 vectors. agreed with ML on 145 and on all 150 (measurement). Here , so is far below the exact bound.
- List output. The final survivors give a list for soft output, as in the list sphere decoder, but the list is not guaranteed to hold the best vectors.
Variants and improvements
- Sorted QR. Order the columns of before the factorization so that the first levels, where pruning is most harmful, have the largest . This is the order question of V-BLAST in tree form.
- Schnorr-Euchner expansion. Generate the children of each survivor in order of distance from , as in Schnorr-Euchner enumeration, and merge the sorted child lists. This is the method of Guo and Nilsson (2006).
- Real-valued decomposition. Write the complex model as a real model of size with -PAM symbols. The tree then has levels with children each, which reduces the sorting cost.
- Adaptive K. Use a larger at the first levels and a smaller one later, or a radius test that drops survivors whose metric is far from the best.
- Soft output. Compute bit LLRs from the final list, with clipping for bits that take only one value in the list, as in the list sphere decoder.
When to use it
Use the K-best detector in hardware receivers that need a fixed throughput, with up to about 8 and moderate constellations, where a sphere search would need a worst-case budget. For a software receiver that needs the exact ML decision, use Schnorr-Euchner enumeration. For large and , where candidates per level are too many, use lattice reduction aided detection or MMSE detection.
Pitfalls
- Expecting ML. For the detector can miss the ML vector even at moderate noise, as the example shows with .
- Ignoring the order of the columns. Without sorting, the first levels can have small , where the partial metrics say little and pruning is most often wrong.
- Forgetting the constant. differs from by when . LLRs computed from differences of metrics do not need , but a comparison with a threshold does.
- Ties. The selection of line L6 needs a fixed tie rule if the result must be reproducible; the implementation keeps the earlier candidate.
- Wide channels. With , is singular and the triangular form above does not exist. Use a regularized form such as , which changes the metric.
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))
k_best_detector.py 65 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-best-detector/. The authors are listed in prov/3ZQXDE.jsonl.
"""The K-best detector: a breadth-first tree search with K survivors per level.
The model is y = H x + w with H an m by n complex matrix of full column rank
(m >= n) and x a vector of n points of a constellation S of size M. With the
upper triangular R and the vector yb of triangularize(), the ML metric is
||y - H x||^2 = ||yb - R x||^2 + c, with c independent of x. The last row of
R involves only x_(n-1), the row before it x_(n-2) and x_(n-1), and so on, so
the metric is a sum of nonnegative terms, one per tree level, and a partial
vector (x_i, ..., x_(n-1)) has a partial metric that can only grow. The search
goes from level n - 1 down to level 0, extends each survivor by all M points,
and keeps the K extensions with the smallest partial metrics.
"""
import cbb
def triangularize(y: list[complex], h: list[list[complex]]) -> tuple[list[list[complex]], list[complex], float]:
"""(R, yb, c) with R upper triangular, R^H R = H^H H, and ||y - H x||^2 = ||yb - R x||^2 + c."""
if len(h) < len(h[0]):
raise ValueError("the K-best detector here needs m >= n")
hh = cbb.herm(h)
try:
low = cbb.cholesky(cbb.matmul(hh, h))
except ValueError:
raise ValueError("H must have full column rank") from None
b = cbb.matvec(hh, y)
n = len(b)
yb = [0j] * n
for i in range(n): # forward substitution: L yb = H^H y
yb[i] = (b[i] - sum(low[i][c] * yb[c] for c in range(i))) / low[i][i]
r = cbb.herm(low)
return r, yb, cbb.norm2(y) - cbb.norm2(yb)
def k_best(
y: list[complex], h: list[list[complex]], points: list[complex], k: int
) -> list[tuple[float, list[int]]]:
"""The K survivors at the bottom of the tree, as (metric, indices), best first.
The metric is the full ||y - H x||^2. Ties keep the earlier candidate,
with the candidates of each level ordered by survivor and then by point index.
"""
if k < 1:
raise ValueError("K must be at least 1")
r, yb, c = triangularize(y, h) # @line L1
n = len(yb)
survivors = [(0.0, [])] # @line L2 (partial metric, indices of x_i, ..., x_(n-1))
for i in range(n - 1, -1, -1): # @line L3
cand = []
for metric, tail in survivors: # @line L4
xs = [points[j] for j in tail]
u = yb[i] - sum(r[i][i + 1 + t] * xs[t] for t in range(len(xs)))
for j, p in enumerate(points): # @line L5
cand.append((metric + abs(u - r[i][i] * p) ** 2, [j] + tail))
cand.sort(key=lambda e: e[0]) # stable: ties keep the generation order
survivors = cand[:k] # @line L6
return [(metric + c, idx) for metric, idx in survivors] # @line L7
def k_best_detect(y: list[complex], h: list[list[complex]], points: list[complex], k: int) -> list[int]:
"""The point indices of the best survivor of the K-best search."""
return k_best(y, h, points, k)[0][1]
test_k_best_detector.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-best-detector/. The authors are listed in prov/3ZQXDE.jsonl.
import itertools
import math
import random
import pytest
import cbb
import constel
from k_best_detector import k_best, k_best_detect, triangularize
def rayleigh(rng, m, n):
return [[cbb.cn(rng, 1.0) for _ in range(n)] for _ in range(m)]
def metric(y, h, points, idx):
return cbb.norm2(cbb.sub(y, cbb.matvec(h, [points[i] for i in idx])))
def zf_sic_fixed_order(y, h, points):
"""ZF nulling and cancelling in the order n - 1, n - 2, ..., 0."""
r, out = list(y), [0] * len(h[0])
for k in range(len(h[0]) - 1, -1, -1):
hk = [row[: k + 1] for row in h]
w = cbb.solve(cbb.matmul(cbb.herm(hk), hk), cbb.herm(hk))
z = sum(c * v for c, v in zip(w[k], r))
out[k] = min(range(len(points)), key=lambda j: abs(z - points[j]))
r = [rv - row[k] * points[out[k]] for rv, row in zip(r, h)]
return out
def test_example_on_the_page() -> None:
h = [[2, 1], [1, 1]]
y = [0.5, 0.6]
bpsk = constel.pam(2)
r, yb, c = triangularize(y, h)
s5 = math.sqrt(5)
assert abs(r[0][0] - s5) < 1e-12 and abs(r[0][1] - 3 / s5) < 1e-12 and abs(r[1][1] - 1 / s5) < 1e-12
assert abs(yb[0] - 1.6 / s5) < 1e-12 and abs(yb[1] - 0.7 / s5) < 1e-12 and abs(c) < 1e-12
one = k_best(y, h, bpsk, 1)
assert one[0][1] == [1, 0] and abs(one[0][0] - 2.61) < 1e-12 # (-1, +1): both symbols wrong
two = k_best(y, h, bpsk, 2)
assert [e[1] for e in two] == [[0, 1], [1, 0]] and abs(two[0][0] - 0.61) < 1e-12 # the ML vector
def test_triangular_metric_equals_the_ml_metric() -> None:
rng = random.Random(1601)
pts = constel.qam(16)
for _ in range(20):
n = rng.randint(1, 4)
m = rng.randint(n, 6)
h = rayleigh(rng, m, n)
y = [cbb.cn(rng, 2.0) for _ in range(m)]
r, yb, c = triangularize(y, h)
assert all(abs(r[i][j]) == 0 for i in range(n) for j in range(i))
idx = [rng.randrange(16) for _ in range(n)]
x = [pts[i] for i in idx]
assert abs(cbb.norm2(cbb.sub(yb, cbb.matvec(r, x))) + c - metric(y, h, pts, idx)) < 1e-9
def test_large_k_is_exact_ml_and_returns_the_k_best_vectors() -> None:
# theorem: with K >= M^(n-1) nothing is pruned before the last level
rng = random.Random(1602)
for M, n, m in [(2, 3, 3), (4, 2, 3), (4, 3, 3), (2, 4, 5)]:
pts = constel.qam(M) if M == 4 else constel.pam(M)
for _ in range(6):
h = rayleigh(rng, m, n)
y = cbb.awgn(rng, cbb.matvec(h, [pts[rng.randrange(M)] for _ in range(n)]), 0.5)
k = M ** (n - 1)
got = k_best(y, h, pts, k)
allm = sorted(metric(y, h, pts, idx) for idx in itertools.product(range(M), repeat=n))
assert all(abs(g[0] - b) < 1e-9 for g, b in zip(got, allm[:k]))
assert all(abs(g[0] - metric(y, h, pts, g[1])) < 1e-9 for g in got)
assert k_best_detect(y, h, pts, k) == constel.ml_vector(y, h, pts)
def test_k_equal_to_one_is_zf_successive_cancellation() -> None:
rng = random.Random(1603)
pts = constel.qam(16)
for _ in range(40):
n = rng.randint(1, 4)
m = rng.randint(n, 5)
h = rayleigh(rng, m, n)
y = cbb.awgn(rng, cbb.matvec(h, [pts[rng.randrange(16)] for _ in range(n)]), 0.05)
assert k_best_detect(y, h, pts, 1) == zf_sic_fixed_order(y, h, pts)
def test_bad_arguments() -> None:
with pytest.raises(ValueError):
k_best([0j], [[1, 1]], constel.pam(2), 2)
with pytest.raises(ValueError):
k_best([0j, 0j], [[1, 2], [2, 4]], constel.pam(2), 2)
with pytest.raises(ValueError):
k_best([0j], [[1]], constel.pam(2), 0)
def test_small_k_is_close_to_ml_at_high_snr() -> None:
# measured: 4-QAM, m = n = 4, Es/N0 = 15 dB, seed 1605, 150 vectors
rng = random.Random(1605)
pts = constel.qam(4)
n0 = 1 / cbb.undb(15.0)
agree = {1: 0, 4: 0}
for _ in range(150):
h = rayleigh(rng, 4, 4)
y = cbb.awgn(rng, cbb.matvec(h, [pts[rng.randrange(4)] for _ in range(4)]), n0)
ml = constel.ml_vector(y, h, pts)
for k in agree:
agree[k] += k_best_detect(y, h, pts, k) == ml
print(agree)
assert agree[1] >= 140 and agree[4] >= 148 and agree[1] <= agree[4]
History
The M-algorithm, a breadth-first search that keeps the best paths of a code tree at each depth, comes from the decoding of tree and trellis codes and from source coding. Anderson and Mohan surveyed it and its cost in 1984. Wong, Tsui, Cheng and Mow applied it to the tree of lattice decoding for MIMO in 2002, under the name K-best, together with a VLSI architecture. Guo and Nilsson (2006) combined it with the Schnorr-Euchner order to reduce the sorting cost, and many chip designs followed.
References
- Kwan-wai Wong, Chi-ying Tsui, Roger S.-K. Cheng and Wai-ho Mow, A VLSI architecture of a K-best lattice decoding algorithm for MIMO channels, Proc. IEEE International Symposium on Circuits and Systems (ISCAS) 2002, vol. 3, pages III-273 to III-276, the breadth-first search with K survivors per level and its hardware architecture
- Zhan Guo and Peter Nilsson, Algorithm and implementation of the K-best sphere decoding for MIMO detection, IEEE Journal on Selected Areas in Communications 24(3), 491-503, 2006, the K-best Schnorr-Euchner variant, which expands the children of each survivor in order of distance, and its VLSI implementation
- John B. Anderson and Seshadri Mohan, Sequential coding algorithms - a survey and cost analysis, IEEE Transactions on Communications 32(2), 169-176, 1984, the M-algorithm, a breadth-first tree search that keeps the M best paths at each depth
- Erik G. Larsson, MIMO detection methods - how they work, IEEE Signal Processing Magazine 26(3), 91-95, 2009, the tree view of MIMO detection after a QR decomposition and the K-best search
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 3ZQXDE Edit this page History Report an error Markdown