Algorithmadvanced
List sphere decoder
Also called soft-output sphere decoder.
A depth-first sphere search that keeps the L best symbol vectors instead of one and computes the bit log-likelihood ratios for the channel decoder from that list.
- Solves
- MIMO detection
- Time
- O(n^2 m + n^3 + M^n (n + log M + L)) worst
- Space
- O(n m + n M + L n) extra
- Counts
- time llrs O(L n b) worst
- Where
- L = the list size; M = the constellation size; b = the number of bits per symbol; m = the number of receive antennas; n = the number of transmitted streams
- Model
- Real RAM
- Properties
- cost depends on noisedeterministicexact list
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Bertrand M. Hochwald, Stephan ten Brink, 2003
The list sphere decoder solves the soft-output form of the MIMO detection problem. A channel decoder, for example of an LDPC code or a turbo code, needs a log-likelihood ratio (LLR) for each coded bit, not a hard decision. The exact LLR is a sum over all transmitted vectors, which is too much work for large or . The list sphere decoder runs a depth-first sphere search, as in Schnorr-Euchner enumeration, but it keeps the best vectors that it has found instead of one, and it prunes a subtree only when its partial metric is not below the -th best metric in the list. At the end the list holds vectors with the smallest metrics of all (a theorem). The LLRs then use only the vectors in the list. With the search is exact ML detection, and with the LLRs are exact (both theorems).
In plain words
The receiver must tell the decoder, for every bit, how sure it is that the bit is 0 or 1. The best answer compares all possible transmitted signals, but there are too many. Most of them fit the received signal very badly and add almost nothing to the answer. So the receiver searches for a short list of the signals that fit best, and it skips every group of signals that cannot get into the list. Then it computes how sure it is about each bit from the list alone. If a bit has the same value in every signal of the list, the receiver says it is very sure, up to a fixed limit.
The problem
The model is with known, and full column rank, for a constellation of size with a bit label for each point, and . For bit of stream , the LLR with equal priors is
so a positive LLR favors bit 0. The max-log approximation keeps the largest term of each sum:
The list sphere decoder returns a list of vectors with the smallest metrics, and the LLRs computed with the sums or minimums restricted to . A bit value that no vector of has gives the LLR , a fixed clipping level.
The algorithm
As on the K-best page, let with upper triangular and a positive diagonal, let solve , and let . Then , and is the sum of the level terms for down to 1. The partial metric of is the sum of the terms from to , and it can only grow as the search goes down.
LIST-SPHERE(y, H, S, L)- 1
(R, ȳ, c) ← TRIANGULARIZE(y, H) - 2
list ← empty; radius ← ∞ - 3
SEARCH(n, 0) - 4
return the list, with c added to each metric, best first SEARCH(i, D) ▷ x_{i+1}, ..., x_n are fixed- 5
u ← ȳ_i - Σ_{j>i} R_ij x_j - 6
for each s in S, in increasing order of |u - R_ii s| - 7
D' ← D + |u - R_ii s|² - 8
if D' ≥ radius then break ▷ the other children are farther - 9
x_i ← s; if i = 1 then insert (D', x) into the list, keep the L best, and if the list is full, radius ← its largest metric - 10
else SEARCH(i - 1, D')
Line L6 is the Schnorr-Euchner order: the nearest child first. Because the children come in increasing order of their level term, the break of line L8 is safe: when one child fails the test, all later children fail too. The radius stays infinite until the list holds vectors, and from then on it is the largest metric in the list, so it can only shrink.
The LLRs come from the list in a second step. For each stream and bit , split the list by the value of bit of . If both parts are nonempty, the max-log LLR is with the smallest metric in the part with value , and the full form is the difference of the two log-sum-exp values of . If one part is empty, the LLR is when all vectors in the list have bit 0 and when all have bit 1. The constant cancels in every difference.
Example
Take , BPSK with bit 0 on and bit 1 on , , , the received vector of the ZF example for , and . As on the K-best page,
Run the search with . Level 2: the term is 0.018 for and 0.578 for , so comes first. Under , the term is 2.592 for and 8.192 for . Both leaves go into the list, with metrics 2.61 and 8.21, and the list is full, so the radius becomes 8.21. Back at level 2, has partial metric . Under it, adds for a metric of 0.61, which enters the list and pushes out 8.21. The radius becomes 2.61. The next child, , adds 18.432, which fails the test. The search computed 6 partial metrics, and the list is .
The four vectors have the metrics 0.61, 2.61, 8.21 and 19.01, so the list holds the two best. For bit 1 (stream 1), the vector with bit 0 has metric 0.61 and the vector with bit 1 has metric 2.61, so the max-log LLR is . For bit 2 the roles swap and the LLR is . Both LLRs point to the transmitted . With all four vectors, the exact LLR of bit 1 is , so the list of two loses almost nothing here (a measurement on this example).
Correctness
The proof is in proofs/correctness.md. It shows that the metrics in the list are the true metrics (a theorem, from the triangular form), that the break of line L8 never removes a vector that belongs in the final list (a theorem, from the monotone partial metrics and the shrinking radius), and so that the final list holds vectors with the smallest metrics of all (a theorem). Two corollaries follow: gives an ML vector, and gives the exact LLRs. The proof also shows that the max-log LLR from the list equals the max-log LLR over all vectors for every bit whose two values both occur in the list (a theorem), because the smallest metric of each value is then in the list.
Proof: The list sphere decoder returns the L best vectors, and its LLRs are exact for the full listfull
The model is with of full column rank and , . Let with upper triangular with a positive diagonal (line L1), let solve , and let . Write for the metric of .
Theorem 1 (the triangular metric). For every , .
Proof. and . Since and , the two differ by .
For let and let , with . Row of is the expression inside , so .
Lemma 2 (monotone partial metrics). depends only on , and . So for every completion of a partial vector , .
Proof. Immediate from the definition and .
Lemma 3 (the call invariant). When SEARCH is called, hold the symbols of the current path and . Each of line L7 is of the child , and each list entry inserted by line L9 is a pair .
Proof. By induction on the depth of the call. The first call is SEARCH, and . In a call, line L5 computes , so and . Line L9 sets before line L10 calls SEARCH, so the invariant holds for the child call. At the inserted value is .
By Lemma 3 and Theorem 1, every metric returned by line L4 is .
Let denote the value of radius. It is until the list holds entries, and after that it is the largest metric in the list. An insertion into a full list either does not change the list (the new metric is the largest and is dropped) or replaces the largest entry by a smaller one, so never grows.
Lemma 4 (the break is safe). Line L8 never prevents the insertion of a vector with , where is the final radius.
Proof. Line L6 orders the children by , and is common to all children, so the values increase along the loop. When line L8 breaks at a child with , every later child of the same node has an even larger . Every completion of any of these children has by Lemma 2 and the fact that never grows. So no vector with is lost.
Theorem 5 (the list is the L best). Assume . At the end, the list holds distinct vectors, and no vector of outside the list has a smaller metric than a vector inside it. That is, the list is a set of vectors with the smallest metrics (with an arbitrary choice among equal metrics at the boundary).
Proof. First, the list becomes full. While , the test of line L8 never succeeds, so the search visits leaves until of them have been inserted. There are distinct leaves, and each leaf is visited at most once, because each path of symbols is visited at most once by the depth-first loop.
Now let be a vector outside the final list and a vector inside it. Suppose . Then , because is the largest metric in the final list. By Lemma 4, no break removed , so the search reached the leaf , and line L9 inserted it. At that time , so stayed in the list: if the list was not full, nothing was dropped, and if it was full, the dropped entry had the largest metric, at least . A later insertion drops one entry with the largest metric of entries. That metric is at least the new radius, which is at least , so it is never . So is in the final list, a contradiction.
Corollary 6 (the two limits). With , the only vector in the list minimizes over , so it is an ML decision. With , the list holds all of with their metrics.
For stream and bit , let be bit of the label of . With equal priors, the posterior probability of is proportional to , so the exact LLR is
Theorem 7 (exact LLRs for the full list). With , the log-sum-exp LLRs computed from the list equal , and the max-log LLRs from the list equal over all of .
Proof. By Corollary 6 the list is with the true metrics . Both bit values occur in , so no clipping applies, and the two sums of the list are the two sums of . For max-log, in each part.
Theorem 8 (max-log from a shorter list). For any , if both values of bit occur in the list, the max-log LLR from the list equals the max-log LLR over all of .
Proof. Let be the first vector of the list, an ML vector by Theorem 5, and let . Then , and it is in the list. Let minimize over the vectors with . Some vector of the list has , so . If were not in the list, then by Theorem 5, for every in the list, and so . Then and is also a minimizer with bit value . In both cases the list holds a vector with bit value and metric . So both minimums of the max-log formula are attained in the list.
When only one value of a bit occurs in the list, the true minimum metric of the other value is at least the largest metric in the list, by Theorem 5. So the true max-log LLR has the sign of the clipped value and a magnitude of at least . The clipping level replaces this unknown magnitude.
Complexity
The triangular form costs . Each visit of SEARCH computes in and sorts level terms in , and each accepted leaf updates the list in . In the worst case no subtree is pruned, so there are fewer than visits and leaves, and the total is in the real RAM (a closed form). The LLR step costs . The memory holds , the list and the recursion stack.
The worst case is exponential, and so is the expected cost over random channels for fixed SNR (Jaldén and Ottersten, cited on the MIMO detection page). The cost in practice depends on the noise: at high SNR the first leaf is near the right answer and the radius shrinks fast. A larger list keeps the radius large longer, so the search visits more nodes. The test with seed 1704 runs 100 vectors of 4-QAM over a Rayleigh channel at dB, where the full tree has 340 nodes. The search computed 8.2 partial metrics per vector on average for and 102.4 for (a measurement).
Properties
- Exact list. The list holds vectors with the smallest metrics of all (theorem). This differs from the K-best detector, whose final survivors need not be the best.
- Two limits. is exact ML detection, and gives the exact LLRs (theorem).
- Max-log from a list. For each bit whose two values both occur in the list, the max-log LLR from the list equals the max-log LLR from all vectors (theorem). Only the bits with one value in the list need clipping.
- Variable cost. The number of visited nodes depends on , and , not only on and .
- Noise level. The search does not need ; the LLR step does.
Variants and improvements
- Fixed initial radius. Start with a finite radius from the noise level, for example a radius that holds the transmitted vector with high probability, and collect every vector inside the sphere up to the list size. This can prune more at the start, but the sphere can be empty, and then the search must restart with a larger radius.
- Single tree search. Instead of one list for all bits, keep for each bit the smallest metric found with the bit value opposite to the ML vector, and prune with a radius per bit. This gives the max-log LLRs over all vectors without a list. Studer, Burg and Bölcskei described this form in 2008, with LLR clipping built into the pruning.
- K-best list. Use the final survivors of the K-best detector as the list. The cost is fixed, but the list is not guaranteed to hold the best vectors.
- Prior information. In iterative detection and decoding, as in turbo equalization, the decoder returns prior LLRs for the bits. They add a term per bit to each metric, and the search can include it in the partial metrics.
- Real-valued decomposition. Write the complex model as a real model of size with -PAM symbols, so each level has children.
When to use it
Use the list sphere decoder when a coded MIMO system needs soft bit values close to the exact ones, and are moderate, and the receiver can accept a cost that varies with the channel. With a fixed hardware budget, use the K-best detector with a list output instead. For a hard decision only, use , which is Schnorr-Euchner enumeration. For large , where the tree search is too slow, use MMSE detection with per-stream soft demapping, or expectation propagation.
Pitfalls
- A list that is too short. If the list has only one value of a bit, the LLR is clipped to , which can be confidently wrong. A large clipping level makes such errors costly for the decoder.
- No clipping. Without a clipping level, a bit with one value in the list gets an infinite LLR, which breaks the arithmetic of most decoders.
- The break with an unsorted child order. The break of line L8 is correct only when the children come in increasing order of their level term. With another order, use continue instead of break.
- A wrong sign convention. On this site a positive LLR favors bit 0. A decoder that expects the other sign gets every bit inverted.
- Bit labels. The LLRs depend on the labeling of the constellation. The detector and the decoder must use the same labels, here those of the shared constellation helper, most significant bit first.
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))
list_sphere_decoder.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/list-sphere-decoder/. The authors are listed in prov/C5A1BF.jsonl.
"""The list sphere decoder and the bit LLRs computed from its list.
The model is y = H x + w with H an m by n complex matrix of full column rank
(m >= n), x a vector of n points of a constellation S of size M, and
w ~ CN(0, N0 I). After the triangular form ||y - H x||^2 = ||yb - R x||^2 + c,
a depth-first search visits the tree of partial vectors (x_i, ..., x_(n-1)),
level n - 1 first, children in order of their level term (the
Schnorr-Euchner order). It keeps the L best full vectors found so far and
prunes every node whose partial metric is not below the L-th best metric.
At the end the list holds L vectors with the smallest metrics of all M^n.
The bit LLRs use L(b) = ln P(b = 0 | y) / P(b = 1 | y) with equal priors.
The bits of stream k are constel.bits(index, log2 M), most significant first.
"""
import math
import cbb
import constel
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 sphere decoder 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):
yb[i] = (b[i] - sum(low[i][c] * yb[c] for c in range(i))) / low[i][i]
return cbb.herm(low), yb, cbb.norm2(y) - cbb.norm2(yb)
def list_sphere(
y: list[complex], h: list[list[complex]], points: list[complex], size: int, stats: dict | None = None
) -> list[tuple[float, list[int]]]:
"""The size best vectors as (metric, indices), smallest metric first.
The metric is the full ||y - H x||^2. If stats is a dict, stats["nodes"]
receives the number of tree nodes whose partial metric was computed.
"""
if size < 1:
raise ValueError("the list size must be at least 1")
r, yb, c = triangularize(y, h) # @line L1
n = len(yb)
best: list[tuple[float, list[int]]] = [] # sorted list of at most size entries # @line L2
radius = [math.inf]
nodes = [0]
x = [0j] * n
idx = [0] * n
def search(i: int, d: float) -> None:
u = yb[i] - sum(r[i][j] * x[j] for j in range(i + 1, n)) # @line L5
terms = sorted((abs(u - r[i][i] * p) ** 2, j) for j, p in enumerate(points)) # @line L6
for t, j in terms:
nodes[0] += 1
dd = d + t # @line L7
if dd >= radius[0]: # @line L8
break
x[i], idx[i] = points[j], j
if i == 0: # @line L9
best.append((dd, list(idx)))
best.sort(key=lambda e: e[0])
if len(best) > size:
best.pop()
if len(best) == size:
radius[0] = best[-1][0]
else:
search(i - 1, dd) # @line L10
search(n - 1, 0.0) # @line L3
if stats is not None:
stats["nodes"] = nodes[0]
return [(d + c, v) for d, v in best] # @line L4
def _logsumexp(vals: list[float]) -> float:
top = max(vals)
return top + math.log(sum(math.exp(v - top) for v in vals))
def list_llrs(
cands: list[tuple[float, list[int]]], m_bits: int, n0: float, maxlog: bool = True, clip: float = 20.0
) -> list[float]:
"""The bit LLRs from a candidate list, stream by stream, most significant bit first.
maxlog=True gives (min metric with b = 1 - min metric with b = 0) / N0.
maxlog=False gives the log-sum-exp form over the list. A bit value that no
candidate has gives the LLR +clip (all candidates have 0) or -clip.
"""
if n0 <= 0:
raise ValueError("N0 must be positive")
n = len(cands[0][1])
labels = [[constel.bits(i, m_bits) for i in v] for _, v in cands]
out = []
for k in range(n):
for b in range(m_bits):
zero = [-d / n0 for (d, _), lab in zip(cands, labels) if lab[k][b] == 0]
one = [-d / n0 for (d, _), lab in zip(cands, labels) if lab[k][b] == 1]
if not one:
out.append(clip)
elif not zero:
out.append(-clip)
elif maxlog:
out.append(max(zero) - max(one))
else:
out.append(_logsumexp(zero) - _logsumexp(one))
return out
test_list_sphere_decoder.py 183 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/list-sphere-decoder/. The authors are listed in prov/C5A1BF.jsonl.
import itertools
import math
import random
import pytest
import cbb
import constel
from list_sphere_decoder import list_llrs, list_sphere, triangularize
def all_metrics(y, h, points):
"""Every (metric, indices) pair, sorted by metric, by brute force."""
out = []
for idx in itertools.product(range(len(points)), repeat=len(h[0])):
x = [points[i] for i in idx]
out.append((cbb.norm2(cbb.sub(y, cbb.matvec(h, x))), list(idx)))
out.sort(key=lambda e: e[0])
return out
def exact_llrs(y, h, points, m_bits, n0):
"""The exact bit LLRs by log-sum-exp over all M^n vectors."""
cands = all_metrics(y, h, points)
out = []
for k in range(len(h[0])):
for b in range(m_bits):
zero, one = [], []
for d, idx in cands:
(one if constel.bits(idx[k], m_bits)[b] else zero).append(-d / n0)
lz = max(zero) + math.log(sum(math.exp(v - max(zero)) for v in zero))
lo = max(one) + math.log(sum(math.exp(v - max(one)) for v in one))
out.append(lz - lo)
return out
def rand_case(rng, m, n, points, n0):
h = [[cbb.cn(rng, 1.0) for _ in range(n)] for _ in range(m)]
idx = [rng.randrange(len(points)) for _ in range(n)]
y = cbb.awgn(rng, cbb.matvec(h, [points[i] for i in idx]), n0)
return y, h, idx
def test_example():
h = [[2, 1], [1, 1]]
y = [0.5, 0.6]
pts = 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
full = list_sphere(y, h, pts, 4)
assert [v for _, v in full] == [[0, 1], [1, 0], [0, 0], [1, 1]]
for (d, _), want in zip(full, [0.61, 2.61, 8.21, 19.01]):
assert abs(d - want) < 1e-12
st = {}
two = list_sphere(y, h, pts, 2, st)
assert [v for _, v in two] == [[0, 1], [1, 0]] and st["nodes"] == 6
ml = list_llrs(two, 1, 1.0)
assert abs(ml[0] - 2.0) < 1e-12 and abs(ml[1] + 2.0) < 1e-12
ex = list_llrs(full, 1, 1.0, maxlog=False)
want0 = math.log(math.exp(-0.61) + math.exp(-8.21)) - math.log(math.exp(-2.61) + math.exp(-19.01))
assert abs(ex[0] - want0) < 1e-12 and abs(ex[0] - 2.0005) < 1e-4
def test_triangular_metric():
rng = random.Random(1701)
pts = constel.qam(4)
for _ in range(20):
y, h, _ = rand_case(rng, 4, 3, pts, 0.3)
r, yb, c = triangularize(y, h)
for _ in range(5):
x = [rng.choice(pts) for _ in range(3)]
lhs = cbb.norm2(cbb.sub(y, cbb.matvec(h, x)))
rhs = cbb.norm2(cbb.sub(yb, cbb.matvec(r, x))) + c
assert abs(lhs - rhs) < 1e-9
def test_list_is_the_best_vectors():
rng = random.Random(1702)
for pts, m, n in ((constel.qam(4), 3, 3), (constel.pam(4), 4, 3), (constel.qam(16), 2, 2), (constel.psk(8), 3, 2)):
for _ in range(8):
y, h, _ = rand_case(rng, m, n, pts, 0.5)
ref = all_metrics(y, h, pts)
for size in (1, 2, 5, 11):
got = list_sphere(y, h, pts, size)
assert len(got) == size
for (d, v), (dr, _) in zip(got, ref):
assert abs(d - dr) < 1e-9
xv = [pts[i] for i in v]
assert abs(d - cbb.norm2(cbb.sub(y, cbb.matvec(h, xv)))) < 1e-9
one = list_sphere(y, h, pts, 1)[0]
mlv = constel.ml_vector(y, h, pts)
dml = cbb.norm2(cbb.sub(y, cbb.matvec(h, [pts[i] for i in mlv])))
assert abs(one[0] - dml) < 1e-9
def test_full_list_gives_exact_llrs():
rng = random.Random(1703)
for pts, mb in ((constel.qam(4), 2), (constel.pam(4), 2), (constel.qam(16), 4)):
n = 3 if len(pts) == 4 else 2
for _ in range(6):
n0 = 0.4
y, h, _ = rand_case(rng, n + 1, n, pts, n0)
full = list_sphere(y, h, pts, len(pts) ** n)
got = list_llrs(full, mb, n0, maxlog=False)
want = exact_llrs(y, h, pts, mb, n0)
for a, b in zip(got, want):
assert abs(a - b) < 1e-9
ref = all_metrics(y, h, pts)
got_ml = list_llrs(full, mb, n0)
k = 0
for s in range(n):
for b in range(mb):
d0 = min(d for d, v in ref if constel.bits(v[s], mb)[b] == 0)
d1 = min(d for d, v in ref if constel.bits(v[s], mb)[b] == 1)
assert abs(got_ml[k] - (d1 - d0) / n0) < 1e-9
k += 1
def test_max_log_exact_when_both_values_in_list():
"""Max-log LLRs from a short list equal the full max-log value for each bit whose two values both occur."""
rng = random.Random(1706)
pts = constel.qam(4)
for _ in range(10):
y, h, _ = rand_case(rng, 3, 3, pts, 0.5)
ref = all_metrics(y, h, pts)
short = list_sphere(y, h, pts, 8)
got = list_llrs(short, 2, 0.5, clip=99.0)
k = 0
for s in range(3):
for b in range(2):
vals = {constel.bits(v[s], 2)[b] for _, v in short}
if len(vals) == 2:
d0 = min(d for d, v in ref if constel.bits(v[s], 2)[b] == 0)
d1 = min(d for d, v in ref if constel.bits(v[s], 2)[b] == 1)
assert abs(got[k] - (d1 - d0) / 0.5) < 1e-9
else:
assert got[k] == (99.0 if vals == {0} else -99.0)
k += 1
def test_clipping():
cands = [(1.0, [0, 3]), (2.0, [0, 2])]
llr = list_llrs(cands, 2, 1.0, clip=7.5)
# stream 0 has label 00 in both: both bits clip to +7.5
assert llr[0] == 7.5 and llr[1] == 7.5
# stream 1: labels 11 and 10; bit 0 is always 1, bit 1 differs
# bit 1 is 0 at metric 2.0 and 1 at metric 1.0: LLR = (1.0 - 2.0) / N0 = -1
assert llr[2] == -7.5 and abs(llr[3] + 1.0) < 1e-12
def test_bad_arguments():
pts = constel.pam(2)
with pytest.raises(ValueError):
list_sphere([1, 1], [[1, 2], [2, 4]], pts, 2)
with pytest.raises(ValueError):
list_sphere([1], [[1, 1]], pts, 2)
with pytest.raises(ValueError):
list_sphere([1, 1], [[1, 0], [0, 1]], pts, 0)
with pytest.raises(ValueError):
list_llrs([(0.0, [0])], 1, 0.0)
def test_measured_node_count():
"""Measurement, seed 1704: 4x4 4-QAM at 15 dB SNR, 100 vectors. The full tree has 340 nodes."""
rng = random.Random(1704)
pts = constel.qam(4)
n0 = cbb.undb(-15)
nodes1 = nodes16 = 0
for _ in range(100):
y, h, _ = rand_case(rng, 4, 4, pts, n0)
st = {}
list_sphere(y, h, pts, 1, st)
nodes1 += st["nodes"]
st = {}
list_sphere(y, h, pts, 16, st)
nodes16 += st["nodes"]
assert nodes1 / 100 < 12
assert nodes16 / 100 < 130
History
Hochwald and ten Brink introduced the list sphere decoder in 2003, in a paper that combined it with an iterative receiver and turbo codes to work close to the capacity of a multiple-antenna channel. The search itself comes from the sphere decoders of lattice theory: the enumeration of Fincke and Pohst and the nearest-child order of Schnorr and Euchner. Later work, such as the single tree search of Studer, Burg and Bölcskei in 2008, reduced the cost of soft output and brought it to chips.
References
- Bertrand M. Hochwald and Stephan ten Brink, Achieving near-capacity on a multiple-antenna channel, IEEE Transactions on Communications 51(3), 389-399, 2003, the list sphere decoder and the computation of bit LLRs from its candidate list
- 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 soft output from a list
- David Tse and Pramod Viswanath, Fundamentals of Wireless Communication, Cambridge University Press, 2005, chapter 8, the MIMO receivers that the list sphere decoder improves on
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 C5A1BF Edit this page History Report an error Markdown