Algorithmadvanced
Lattice reduction aided detection
Also called LR-aided detection.
Reduces the real channel basis with LLL, detects the integer coordinates in the reduced basis by ZF or SIC, and maps back. It gets much closer to ML than plain ZF or SIC at a similar cost.
- Solves
- MIMO detection
- Time
- O((S + 1) n^2 m + n^3 + n M) worst
- Space
- O(n m) extra
- Where
- M = the constellation size; S = the number of LLL swaps; m = the number of real receive dimensions; n = the number of real symbol dimensions (2 times the streams for QAM)
- Model
- Real RAM
- Properties
- deterministicnot exact mlexact without noise
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Huan Yao, Gregory W. Wornell, 2002
Lattice reduction aided detection is an approximate method for the MIMO detection problem. For QAM and PAM, the transmitted vector is a shifted and scaled vector of integers, so the noiseless received vectors are points of a lattice generated by the columns of the channel matrix. ZF and SIC detection work badly when these columns are long and nearly parallel, because the noise is then amplified in some directions. The detector first changes the basis of the same lattice to short, nearly orthogonal vectors with the LLL algorithm. Then it runs ZF (Babai rounding) or SIC (Babai nearest plane) in the new basis, where the noise is much less amplified. A unimodular integer matrix maps the decision back to the original coordinates, and a last step clips it to the constellation. The cost is close to that of ZF or SIC, and the error rate is much closer to ML.
In plain words
The receiver sees a point on a regular grid of possible signals, moved a little by noise, and it must find the nearest grid point. A simple receiver describes the grid with the directions given by the antennas. When two of these directions are almost the same, a small move by the noise looks like a large change of the signal, and the simple receiver makes many errors. The same grid can be described with other, better directions that are short and close to perpendicular. The receiver first finds such directions, then does the simple detection in them, and at the end translates the answer back. The translation is exact because the new directions describe the same grid.
The problem
The model is with known, a vector of square QAM or PAM points, and . In the real-valued form, , and for QAM
so (a closed form). For PAM, is above and . Let be . Each entry of takes values with , where and for -QAM, and and for -PAM. With ,
So detection is a closest vector problem in the lattice , with a box constraint on . The detector returns a vector of constellation indices.
The algorithm
LR-DETECT(y, H, S, method)- 1
(y_r, H_r) ← REAL-VALUED MODEL(y, H) - 2
y' ← (s y_r + (q - 1) H_r 1) / 2 ▷ y' = H_r z + w' with integer z - 3
(B, T) ← LLL(columns of H_r, δ = 3/4) ▷ B = H_r T, T integer with |det T| = 1 - 4
if method = ZF: u ← round(B⁺ y') - 5
else (SIC): for i ← n down to 1: u_i ← round(⟨r, b*_i⟩ / ‖b*_i‖²), r ← r - u_i b_i, starting from r = y' - 6
z ← T u - 7
clip each z_i to {0, ..., q - 1} - 8
return the constellation points (2 z - (q - 1)) / s, as indices
The LLL algorithm of line L3 keeps the basis size-reduced ( for the Gram-Schmidt coefficients) and makes a swap of and whenever the Lovász condition fails. Every operation on the basis is applied to the columns of as well, so holds at all times. Line L5 is SIC in the reduced basis: it detects the coordinate along the last Gram-Schmidt vector first and cancels it. With (no reduction), lines L4 and L5 are plain ZF and plain ZF-SIC in a fixed order.
The MMSE form replaces by and by , with the ratio of the noise variance to the symbol variance in one real dimension ( for unit-energy QAM). The metric is then (a closed form), as for the MMSE detector.
Example
Take BPSK (, ) over and , the example of the ZF page, sent with , so . Then , and .
Plain ZF computes , which rounds to , so : both symbols are wrong. The reason is the noise after the inverse, , which is larger than in both entries.
LLL on the columns and : the size reduction subtracts the first column from the second and gives . Now is far below , so the two vectors are swapped. A second size reduction gives , and the basis is reduced, with
In the reduced basis, rounds to , and , so , the transmitted vector and the ML decision. The noise in the reduced basis is , inside in both entries. Here SIC gives the same decisions as ZF, in both bases. The tests check every number of this example.
Correctness
The proof is in proofs/correctness.md. It shows that the shift of line L2 gives with an integer vector (a closed form), that LLL terminates and returns with unimodular, size-reduced and satisfying the Lovász condition (a theorem), and that the detector is exact without noise (a theorem). It shows that LR-SIC returns the transmitted vector whenever , and that after LLL with this holds whenever , with the length of the shortest nonzero lattice vector (a theorem). The unbounded lattice ML decision is guaranteed only for , so LR-SIC loses at most a factor in this noise radius, a factor that does not depend on the channel. Without reduction, can be arbitrarily small compared with , so plain ZF-SIC has no such bound.
Taherzadeh, Mobasher and Khandani (2007) proved that LLL-aided ZF and SIC reach the receive diversity of ML for lattice decoding, that is, when the box constraint of line L7 is ignored (a theorem of the reference, not proved here). With receive antennas and streams, plain ZF over i.i.d. Rayleigh fading has diversity , by the ZF page, against for ML.
Proof: LR-aided detection is exact without noise, and LR-SIC is correct inside a noise radius within 2^((n-1)/2) of the lattice ML radiusfull
Notation. is the real channel with linearly independent columns , and is the lattice they generate. For a basis , the Gram-Schmidt vectors are and with . The vectors are orthogonal, and .
Lemma 1 (the real model and the shift). , and with and , the model becomes with .
Proof. For complex , and , which is for QAM; for PAM, and the second block column drops out. A complex vector and its stacked real and imaginary parts have the same squared norm. For the shift, . Multiply by and add .
Lemma 2 (unimodular change of basis). If with , then , the columns of generate , and is a bijection of .
Proof. , and the adjugate of an integer matrix is an integer matrix. So and both map into , and .
Theorem 3 (LLL). For , the LLL loop terminates. At the end, with an integer matrix with , for , and for .
Proof. Invariant. The loop changes the basis only by with an integer and , or by a swap of and , and it applies the same operation to the columns of . Both operations multiply on the right by an integer matrix of determinant , so , is an integer matrix and at all times, starting from .
Size reduction. with does not change any , because lies in the span of . It changes to for (with ) and leaves for unchanged. The loop runs down to 1 and chooses , so after step , , and later steps (with smaller ) do not change it.
Termination. Let , the squared volume of the sublattice spanned by , and let . Size reduction does not change . A swap at position changes only , which is multiplied by , where is the new Gram-Schmidt vector. So when the Lovász condition fails, and is multiplied by less than . Each is the squared determinant of an -dimensional sublattice of . By the definition of the Hermite constant , the sublattice has a nonzero vector of squared length at most , and that vector is in , so , with the length of a shortest nonzero vector of . So has a positive lower bound that does not depend on the basis, and the number of swaps is at most , with the initial value. Between two swaps, grows by one at each step, so the loop ends.
Reduced prefix. At the start of each iteration with current position (1-based), the vectors are size-reduced and satisfy the Lovász condition among themselves. This holds for . An iteration size-reduces , which changes no other vector and no . If the test passes, are reduced and grows by one. If it fails, the swap changes only positions and , and becomes , so the prefix up to the new is unchanged. The loop ends with , so the whole basis is reduced.
Theorem 4 (exact without noise). If , the detector returns , with or without reduction, for both ZF and SIC.
Proof. By Lemma 1, with . Let , an integer vector by Lemma 2, so . ZF: , which rounding does not change. SIC: Lemma 5 below with . Then , which lies in the box, so clipping does not change it, and line L8 maps to the points of .
Lemma 5 (SIC, the nearest plane step). Let with and . Then line L5 returns .
Proof. By downward induction on . Assume for all . Then the residual before step is . For , lies in the span of , which is orthogonal to , and . So
by the Cauchy-Schwarz inequality. So rounding gives .
Theorem 6 (the noise radius of LR-SIC). After LLL with , . So if , LR-SIC returns the transmitted .
Proof. Size reduction gives , so the Lovász condition gives . By induction, , since is a nonzero vector of . Under the assumption on , Lemma 5 gives , so line L6 gives , which is in the box, and the argument of Theorem 4 ends the proof.
For comparison, the nearest point of to is whenever , because any other lattice point has . So the guarantee of Theorem 6 is smaller by the factor , which depends only on . Without reduction, has no lower bound in terms of . For example, the basis , with an integer generates , so , but , which goes to zero as grows. So plain SIC in this basis can fail at noise levels that LR-SIC always handles.
Lemma 7 (ZF in the reduced basis). If every entry of lies in , LR-ZF returns the transmitted .
Proof. , and exactly when . So , , clipping does not change , and line L8 returns .
Lemma 8 (the MMSE form). With and , , the metric equals , and has linearly independent columns for every .
Proof. The squared norm of a stacked vector is the sum of the squared norms of its blocks. If , the lower block gives .
With , the noise variance of in one dimension, , divided by the variance of a uniform , this is the regularized metric of the MMSE detector in the integer coordinates. For unit-energy -QAM, gives , and for -PAM, gives (closed forms). Theorems 3 to 6 apply to and unchanged, with the lattice generated by .
Complexity
The real-valued model and the shift cost . Each LLL iteration costs for the size reduction, and the implementation recomputes the Gram-Schmidt vectors after a swap in , so LLL with swaps costs . ZF solves an system in , SIC costs , and the mapping to points costs . The total is in the real RAM (a closed form). For real bases, has no bound in terms of alone, because it depends on how badly the channel is conditioned. The proof shows that is finite. For 2x2 4-QAM over i.i.d. Rayleigh fading (4 real dimensions), the test with seed 1805 measured 2.34 swaps per channel on average over 1000 channels, and at most 10 (a measurement). The reduction depends only on , so on a channel that stays the same for many vectors its cost is spread over all of them.
Properties
- Exact without noise. is recovered exactly from (theorem).
- Same lattice. and generate the same lattice, because and are integer matrices (theorem).
- Noise radius. LR-SIC is correct whenever (theorem).
- Measured error rates. For 2x2 4-QAM over i.i.d. Rayleigh fading at dB, the test with seed 1805 runs 1000 vectors. Plain ZF made 11 vector errors and LR-SIC made 1 (a measurement).
- Not ML. The box constraint is applied only at the end, by clipping, so a lattice point outside the box is moved to the nearest box point, which need not be the ML vector.
- Only for lattice constellations. The method needs a constellation that is a shifted and scaled part of , such as square QAM and PAM. PSK has no such form.
Variants and improvements
- MMSE-based reduction. Reduce the extended matrix of the MMSE form instead of . Wübben, Böhnke, Kühn and Kammeyer described this form in 2004. The implementation uses it when is given.
- Complex LLL. Run the reduction on the complex matrix with Gaussian integers instead of the real matrix , which halves the dimension.
- Other reductions. Seysen reduction reduces the primal and the dual basis together. Stronger reductions such as HKZ reduction give better bases at a higher cost. Deep LLL is between the two.
- Sorted QR. Compute a sorted QR decomposition first, as in V-BLAST, so that LLL starts from a basis that is already partly ordered and needs fewer swaps.
- Precoding. The same reduction, applied at the transmitter, gives lattice-reduction-aided precoding, a relative of Tomlinson-Harashima precoding.
- List and soft output. Search a small neighbourhood of the LR decision for a list of candidates, from which LLRs can be computed as in the list sphere decoder.
When to use it
Use LR-aided detection for square QAM or PAM when ZF or MMSE detection loses too much against ML, the number of streams is too large for a sphere search, and the channel stays the same for many symbol vectors, so the reduction is paid once per channel. When the channel changes for each vector and is small, a K-best detector can be cheaper. For the exact ML vector, use Schnorr-Euchner enumeration, which also gains from a reduced basis.
Pitfalls
- Rounding in the wrong domain. Rounding needs the shifted and scaled integer vector , not the constellation values. For QAM, the shift by per real dimension and the scale must match the constellation exactly.
- Forgetting to clip. can lie outside , because the reduced basis does not see the box. Without line L7, the result is not a constellation vector.
- Mismatched . Every swap and size reduction of LLL must be applied to as well. If is updated in a different order from , the mapping back is wrong.
- Round half to even. Python's built-in round sends 0.5 to 0 and 1.5 to 2. A detector should use one fixed rule; the implementation uses .
- A singular channel. With in the real model, the columns of are linearly dependent and LLL as written fails. The MMSE extension makes the basis full rank.
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))
lattice_reduction_aided_detection.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lattice-reduction-aided-detection/. The authors are listed in prov/YKT7T0.jsonl.
"""Lattice reduction aided MIMO detection with LLL, in the real-valued model.
The model is y = H x + w with H an m by n complex matrix and x a vector of
points of square M-QAM (constel.qam) or M-PAM (constel.pam). The real-valued
model has the real channel Hr and the real symbol vector xr. Each real
symbol takes q equally spaced values (2 z - (q - 1)) / s with z in
{0, ..., q - 1}, so the shifted and scaled vector y' = (s yr + (q - 1) Hr 1) / 2
satisfies y' = Hr z + w' with an integer vector z. The detector reduces the
basis Hr to B = Hr T with LLL (T unimodular), estimates the integer vector
u = T^-1 z by rounding (ZF) or by Babai nearest plane (SIC) in the basis B,
maps back with z = T u, clips each entry of z to {0, ..., q - 1}, and returns
constellation indices.
"""
import math
import cbb
import constel
def _round(v: float) -> int:
return math.floor(v + 0.5)
def _grid(points: list[complex]) -> tuple[str, int, float]:
"""(kind, q, s) for constel.qam(M) or constel.pam(M)."""
m = len(points)
if all(abs(p.imag) < 1e-12 for p in points):
ref, kind, q, s = constel.pam(m), "pam", m, math.sqrt((m * m - 1) / 3.0)
else:
q = math.isqrt(m)
if q * q != m:
raise ValueError("points must be square QAM or PAM from constel")
ref, kind, s = constel.qam(m), "qam", math.sqrt(2.0 * (m - 1) / 3.0)
if any(abs(a - b) > 1e-9 for a, b in zip(points, ref)):
raise ValueError("points must be square QAM or PAM from constel")
return kind, q, s
def real_model(y: list[complex], h: list[list[complex]], kind: str) -> tuple[list[float], list[list[float]]]:
"""(yr, Hr): yr = (Re y, Im y); Hr = [[Re H, -Im H], [Im H, Re H]] for QAM, [[Re H], [Im H]] for PAM."""
yr = [complex(v).real for v in y] + [complex(v).imag for v in y]
if kind == "qam":
top = [[complex(a).real for a in row] + [-complex(a).imag for a in row] for row in h]
bot = [[complex(a).imag for a in row] + [complex(a).real for a in row] for row in h]
else:
top = [[complex(a).real for a in row] for row in h]
bot = [[complex(a).imag for a in row] for row in h]
return yr, top + bot
def _dot(a: list[float], b: list[float]) -> float:
return sum(x * y for x, y in zip(a, b))
def gram_schmidt(b: list[list[float]]) -> tuple[list[list[float]], list[list[float]], list[float]]:
"""(bstar, mu, norms) of the basis vectors b[0], ..., b[n-1] (no normalization)."""
n = len(b)
bstar: list[list[float]] = []
mu = [[0.0] * n for _ in range(n)]
norms = [0.0] * n
for i in range(n):
v = list(b[i])
for j in range(i):
mu[i][j] = _dot(b[i], bstar[j]) / norms[j]
v = [a - mu[i][j] * c for a, c in zip(v, bstar[j])]
mu[i][i] = 1.0
bstar.append(v)
norms[i] = _dot(v, v)
if norms[i] <= 1e-24 * max(1.0, _dot(b[i], b[i])):
raise ValueError("the basis vectors are linearly dependent")
return bstar, mu, norms
def lll(cols: list[list[float]], delta: float = 0.75) -> tuple[list[list[float]], list[list[int]], int]:
"""LLL reduction of the basis vectors cols[0], ..., cols[n-1].
Returns (b, t, swaps): the reduced vectors, the integer matrix t with
b[k] = sum_j t[k][j] cols[j] (so the matrix T with columns t[k] is
unimodular and B = Hr T), and the number of swaps.
"""
if not 0.25 < delta < 1.0:
raise ValueError("delta must be in (1/4, 1)")
n = len(cols)
b = [list(c) for c in cols]
t = [[1 if i == k else 0 for i in range(n)] for k in range(n)]
_, mu, norms = gram_schmidt(b)
swaps = 0
k = 1
while k < n:
for j in range(k - 1, -1, -1): # size reduction
qq = _round(mu[k][j])
if qq:
b[k] = [a - qq * c for a, c in zip(b[k], b[j])]
t[k] = [a - qq * c for a, c in zip(t[k], t[j])]
for l in range(j + 1):
mu[k][l] -= qq * mu[j][l]
if norms[k] >= (delta - mu[k][k - 1] ** 2) * norms[k - 1]: # Lovasz condition
k += 1
else:
b[k], b[k - 1] = b[k - 1], b[k] # swap
t[k], t[k - 1] = t[k - 1], t[k]
swaps += 1
_, mu, norms = gram_schmidt(b)
k = max(k - 1, 1)
return b, t, swaps
def lr_detect(
y: list[complex],
h: list[list[complex]],
points: list[complex],
method: str = "sic",
n0: float = 0.0,
reduce: bool = True,
delta: float = 0.75,
stats: dict | None = None,
) -> list[int]:
"""Constellation indices from LR-aided ZF (method="zf") or SIC (method="sic").
n0 > 0 uses the MMSE form: the extended channel [Hr; sigma I] and
y' extended by sigma times the mean of z, with sigma^2 the ratio of the
noise variance to the symbol variance per real dimension.
reduce=False skips LLL (T = I), which gives plain ZF or SIC in a fixed order.
"""
if method not in ("zf", "sic"):
raise ValueError("method must be zf or sic")
kind, q, s = _grid(points)
yr, hr = real_model(y, h, kind) # @line L1
nr = len(hr[0])
yp = [(s * v + (q - 1) * sum(row)) / 2.0 for v, row in zip(yr, hr)] # @line L2
hp = [list(row) for row in hr]
if n0 > 0: # MMSE extension
sig = math.sqrt(3.0 * s * s * n0 / (2.0 * (q * q - 1)))
hp += [[sig if i == k else 0.0 for k in range(nr)] for i in range(nr)]
yp += [sig * (q - 1) / 2.0] * nr
cols = [[row[k] for row in hp] for k in range(nr)]
if reduce:
b, t, swaps = lll(cols, delta) # @line L3
else:
b, t, swaps = cols, [[1 if i == k else 0 for i in range(nr)] for k in range(nr)], 0
if stats is not None:
stats["swaps"] = swaps
if method == "zf": # @line L4
g = [[_dot(bi, bk) for bk in b] for bi in b]
rhs = [_dot(bi, yp) for bi in b]
u = [_round(v.real) for v in cbb.solve(g, rhs)]
else: # Babai nearest plane: SIC in the reduced basis
bstar, _, norms = gram_schmidt(b)
r = list(yp)
u = [0] * nr
for i in range(nr - 1, -1, -1): # @line L5
u[i] = _round(_dot(r, bstar[i]) / norms[i])
r = [a - u[i] * c for a, c in zip(r, b[i])]
z = [sum(t[k][i] * u[k] for k in range(nr)) for i in range(nr)] # z = T u # @line L6
z = [min(max(v, 0), q - 1) for v in z] # @line L7
xr = [(2 * v - (q - 1)) / s for v in z]
n = len(h[0])
x = [complex(xr[k], xr[n + k]) for k in range(n)] if kind == "qam" else [complex(v) for v in xr]
return [constel.ml_detect(v, points) for v in x] # @line L8
test_lattice_reduction_aided_detection.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lattice-reduction-aided-detection/. The authors are listed in prov/YKT7T0.jsonl.
import math
import random
import pytest
import cbb
import constel
from lattice_reduction_aided_detection import gram_schmidt, lll, lr_detect, real_model
def rand_channel(rng, m, n):
return [[cbb.cn(rng, 1.0) for _ in range(n)] for _ in range(m)]
def det_int(a):
"""The determinant of a small integer matrix by cofactor expansion."""
if len(a) == 1:
return a[0][0]
return sum((-1) ** j * a[0][j] * det_int([row[:j] + row[j + 1 :] for row in a[1:]]) for j in range(len(a)))
def test_example():
h = [[2, 1], [1, 1]]
y = [0.5, 0.6]
pts = constel.pam(2)
b, t, swaps = lll([[2.0, 1.0], [1.0, 1.0]])
assert b == [[-1.0, 0.0], [0.0, 1.0]] and t == [[-1, 1], [-1, 2]] and swaps == 1
# without reduction, ZF and SIC both decide x = (-1, +1); with LLL both decide (+1, -1), the ML vector
assert lr_detect(y, h, pts, "zf", reduce=False) == [1, 0]
assert lr_detect(y, h, pts, "sic", reduce=False) == [1, 0]
assert lr_detect(y, h, pts, "zf") == [0, 1]
assert lr_detect(y, h, pts, "sic") == [0, 1]
assert constel.ml_vector(y, h, pts) == [0, 1]
def test_real_model_preserves_metric():
rng = random.Random(1801)
for kind, pts in (("qam", constel.qam(16)), ("pam", constel.pam(4))):
for _ in range(10):
h = rand_channel(rng, 3, 2)
y = [cbb.cn(rng, 1.0) for _ in range(3)]
x = [rng.choice(pts) for _ in range(2)]
yr, hr = real_model(y, h, kind)
xr = [v.real for v in x] + ([v.imag for v in x] if kind == "qam" else [])
lhs = cbb.norm2(cbb.sub(y, cbb.matvec(h, x)))
rhs = sum((a - sum(c * d for c, d in zip(row, xr))) ** 2 for a, row in zip(yr, hr))
assert abs(lhs - rhs) < 1e-9
def test_lll_output_is_reduced_and_unimodular():
rng = random.Random(1802)
for n in (2, 3, 4, 6):
for _ in range(10):
cols = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(n)]
if rng.random() < 0.5: # a badly conditioned basis
cols[1] = [a + 0.01 * rng.gauss(0, 1) for a in cols[0]]
b, t, _ = lll(cols, 0.75)
for k in range(n):
want = [sum(t[k][j] * cols[j][i] for j in range(n)) for i in range(n)]
assert all(abs(u - v) < 1e-9 for u, v in zip(b[k], want))
assert all(isinstance(v, int) for row in t for v in row)
assert abs(det_int(t)) == 1
_, mu, norms = gram_schmidt(b)
for k in range(n):
for j in range(k):
assert abs(mu[k][j]) <= 0.5 + 1e-9
for k in range(1, n):
assert norms[k] >= (0.75 - mu[k][k - 1] ** 2) * norms[k - 1] - 1e-9
def test_noiseless_exact():
rng = random.Random(1803)
for pts, m, n in ((constel.qam(16), 3, 3), (constel.qam(4), 4, 4), (constel.pam(8), 2, 3)):
for _ in range(10):
h = rand_channel(rng, m, n)
x = [rng.randrange(len(pts)) for _ in range(n)]
y = cbb.matvec(h, [pts[i] for i in x])
for method in ("zf", "sic"):
for red in (False, True):
assert lr_detect(y, h, pts, method, reduce=red) == x
def test_babai_radius_guarantee():
"""LR-SIC is correct whenever the scaled noise is shorter than half the smallest Gram-Schmidt length."""
rng = random.Random(1804)
pts = constel.qam(4)
s = math.sqrt(2.0)
for _ in range(40):
h = rand_channel(rng, 3, 3)
x = [rng.randrange(4) for _ in range(3)]
_, hr = real_model([0j] * 3, h, "qam")
b, _, _ = lll([[row[k] for row in hr] for k in range(6)])
_, _, norms = gram_schmidt(b)
rad = 0.5 * math.sqrt(min(norms))
# noise w with ||s w_r / 2|| just below rad
w = [cbb.cn(rng, 1.0) for _ in range(3)]
wn = math.sqrt(cbb.norm2(w)) * s / 2
w = [v * 0.99 * rad / wn for v in w]
y = cbb.add(cbb.matvec(h, [pts[i] for i in x]), w)
assert lr_detect(y, h, pts, "sic") == x
def test_bad_arguments():
with pytest.raises(ValueError):
lr_detect([0j], [[1]], constel.psk(8))
with pytest.raises(ValueError):
lr_detect([0j], [[1]], constel.pam(2), "ml")
with pytest.raises(ValueError):
lll([[1.0, 0.0], [0.0, 1.0]], 0.2)
with pytest.raises(ValueError):
lll([[1.0, 2.0], [2.0, 4.0]])
def test_measured_errors():
"""Measurement, seed 1805: 2x2 4-QAM, i.i.d. Rayleigh, 20 dB, 1000 vectors."""
rng = random.Random(1805)
pts = constel.qam(4)
n0 = cbb.undb(-20)
err_zf = err_lr = swaps = most = 0
for _ in range(1000):
h = rand_channel(rng, 2, 2)
x = [rng.randrange(4) for _ in range(2)]
y = cbb.awgn(rng, cbb.matvec(h, [pts[i] for i in x]), n0)
err_zf += lr_detect(y, h, pts, "zf", reduce=False) != x
st = {}
err_lr += lr_detect(y, h, pts, "sic", stats=st) != x
swaps += st["swaps"]
most = max(most, st["swaps"])
# measured on CPython 3: ZF 11 vector errors, LR-SIC 1; 2.34 swaps on average, at most 10
assert err_zf >= 8
assert err_lr <= 3
assert swaps / 1000 < 3 and most <= 12
History
The idea of using a reduced lattice basis for decoding comes from Babai, who in 1986 analysed rounding and the nearest plane method on an LLL-reduced basis. Lenstra, Lenstra and Lovász had published the LLL algorithm in 1982. Yao and Wornell proposed LR-aided linear and SIC detection for MIMO in 2002, and Windpassinger and Fischer applied LLL to it in 2003. Taherzadeh, Mobasher and Khandani proved in 2007 that LLL reduction gives the receive diversity of lattice decoding. Later work studied complex LLL, MMSE-based reduction and hardware designs.
References
- Huan Yao and Gregory W. Wornell, Lattice-reduction-aided detectors for MIMO communication systems, Proc. IEEE Global Telecommunications Conference (Globecom) 2002, vol. 1, pages 424-428, the idea of linear and SIC detection in a reduced basis of the channel lattice
- Christoph Windpassinger and Robert F. H. Fischer, Low-complexity near-maximum-likelihood detection and precoding for MIMO systems using lattice reduction, Proc. IEEE Information Theory Workshop (ITW) 2003, pages 345-348, LLL-aided detection with the shift and scaling of QAM to an integer lattice
- Mahmoud Taherzadeh, Amin Mobasher and Amir K. Khandani, LLL reduction achieves the receive diversity in MIMO decoding, IEEE Transactions on Information Theory 53(12), 4801-4805, 2007, the proof that LLL-aided lattice decoding reaches the receive diversity
- Arjen K. Lenstra, Hendrik W. Lenstra Jr. and Laszlo Lovasz, Factoring polynomials with rational coefficients, Mathematische Annalen 261, 515-534, 1982, the LLL reduction algorithm and its reduction conditions
- Laszlo Babai, On Lovasz' lattice reduction and the nearest lattice point problem, Combinatorica 6(1), 1-13, 1986, the nearest plane algorithm on an LLL-reduced basis
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 YKT7T0 Edit this page History Report an error Markdown