Algorithm Search⌘K

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.

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)
Properties
deterministicnot exact mlexact without noise
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 y=Hx+wy = H x + w with H∈Cmc×ncH \in \mathbb{C}^{m_c \times n_c} known, xx a vector of square QAM or PAM points, and w∼CN(0,N0I)w \sim \mathcal{CN}(0, N_0 I). In the real-valued form, yr=(Re y,Im y)y_r = (\mathrm{Re}\, y, \mathrm{Im}\, y), and for QAM

Hr=(Re H−Im HIm HRe H),xr=(Re x,Im x),H_r = \begin{pmatrix} \mathrm{Re}\, H & -\mathrm{Im}\, H \\ \mathrm{Im}\, H & \mathrm{Re}\, H \end{pmatrix}, \qquad x_r = (\mathrm{Re}\, x, \mathrm{Im}\, x),

so ∥y−Hx∥2=∥yr−Hrxr∥2\|y - H x\|^2 = \|y_r - H_r x_r\|^2 (a closed form). For PAM, HrH_r is Re H\mathrm{Re}\, H above Im H\mathrm{Im}\, H and xr=Re xx_r = \mathrm{Re}\, x. Let HrH_r be m×nm \times n. Each entry of xrx_r takes qq values (2z−(q−1))/s(2 z - (q - 1)) / s with z∈{0,…,q−1}z \in \{0, \ldots, q - 1\}, where q=Mq = \sqrt M and s=2(M−1)/3s = \sqrt{2 (M - 1) / 3} for MM-QAM, and q=Mq = M and s=(M2−1)/3s = \sqrt{(M^2 - 1) / 3} for MM-PAM. With y′=(s yr+(q−1)Hr1)/2y' = (s\, y_r + (q - 1) H_r \mathbf{1}) / 2,

y′=Hrz+w′,z∈{0,…,q−1}n,w′=s2wr.y' = H_r z + w', \qquad z \in \{0, \ldots, q - 1\}^n, \qquad w' = \tfrac{s}{2} w_r.

So detection is a closest vector problem in the lattice {Hrz:z∈Zn}\{H_r z : z \in \mathbb{Z}^n\}, with a box constraint on zz. The detector returns a vector of constellation indices.

The algorithm

  1. LR-DETECT(y, H, S, method)
  2. 1(y_r, H_r) ← REAL-VALUED MODEL(y, H)
  3. 2y' ← (s y_r + (q - 1) H_r 1) / 2 ▷ y' = H_r z + w' with integer z
  4. 3(B, T) ← LLL(columns of H_r, δ = 3/4) ▷ B = H_r T, T integer with |det T| = 1
  5. 4if method = ZF: u ← round(B⁺ y')
  6. 5else (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'
  7. 6z ← T u
  8. 7clip each z_i to {0, ..., q - 1}
  9. 8return the constellation points (2 z - (q - 1)) / s, as indices

The LLL algorithm of line L3 keeps the basis size-reduced (∣μkj∣≤1/2|\mu_{kj}| \le 1/2 for the Gram-Schmidt coefficients) and makes a swap of bk−1b_{k-1} and bkb_k whenever the Lovász condition ∥bk∗∥2≥(δ−μk,k−12)∥bk−1∗∥2\|b^*_k\|^2 \ge (\delta - \mu_{k,k-1}^2) \|b^*_{k-1}\|^2 fails. Every operation on the basis is applied to the columns of TT as well, so B=HrTB = H_r T 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 T=IT = I (no reduction), lines L4 and L5 are plain ZF and plain ZF-SIC in a fixed order.

The MMSE form replaces HrH_r by (HrσI)\begin{pmatrix} H_r \\ \sigma I \end{pmatrix} and y′y' by (y′σq−121)\begin{pmatrix} y' \\ \sigma \frac{q - 1}{2} \mathbf{1} \end{pmatrix}, with σ2\sigma^2 the ratio of the noise variance to the symbol variance in one real dimension (σ2=N0\sigma^2 = N_0 for unit-energy QAM). The metric is then ∥y′−Hrz∥2+σ2∥z−q−121∥2\|y' - H_r z\|^2 + \sigma^2 \|z - \frac{q - 1}{2} \mathbf{1}\|^2 (a closed form), as for the MMSE detector.

Example

Take BPSK (q=2q = 2, s=1s = 1) over H=(2111)H = \begin{pmatrix} 2 & 1 \\ 1 & 1 \end{pmatrix} and y=(0.5,0.6)y = (0.5, 0.6), the example of the ZF page, sent with x=(+1,−1)x = (+1, -1), so z=(1,0)z = (1, 0). Then y′=(y+H1)/2=(1.75,1.3)y' = (y + H \mathbf 1) / 2 = (1.75, 1.3), and w′=y′−Hz=(−0.25,0.3)w' = y' - H z = (-0.25, 0.3).

Plain ZF computes H−1y′=(0.45,0.85)H^{-1} y' = (0.45, 0.85), which rounds to z=(0,1)z = (0, 1), so x=(−1,+1)x = (-1, +1): both symbols are wrong. The reason is the noise after the inverse, H−1w′=(−0.55,0.85)H^{-1} w' = (-0.55, 0.85), which is larger than 1/21/2 in both entries.

LLL on the columns (2,1)(2, 1) and (1,1)(1, 1): the size reduction subtracts the first column from the second and gives (−1,0)(-1, 0). Now ∥b2∗∥2=0.2\|b^*_2\|^2 = 0.2 is far below (0.75−0.16)⋅5(0.75 - 0.16) \cdot 5, so the two vectors are swapped. A second size reduction gives (0,1)(0, 1), and the basis B=(−1001)B = \begin{pmatrix} -1 & 0 \\ 0 & 1 \end{pmatrix} is reduced, with

T=(−1−112),HT=B,det⁡T=−1.T = \begin{pmatrix} -1 & -1 \\ 1 & 2 \end{pmatrix}, \qquad H T = B, \qquad \det T = -1.

In the reduced basis, B−1y′=(−1.75,1.3)B^{-1} y' = (-1.75, 1.3) rounds to u=(−2,1)u = (-2, 1), and z=Tu=(1,0)z = T u = (1, 0), so x=(+1,−1)x = (+1, -1), the transmitted vector and the ML decision. The noise in the reduced basis is B−1w′=(0.25,0.3)B^{-1} w' = (0.25, 0.3), inside (−1/2,1/2)(-1/2, 1/2) 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 y′=Hrz+w′y' = H_r z + w' with zz an integer vector (a closed form), that LLL terminates and returns B=HrTB = H_r T with TT 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 ∥w′∥<12min⁡i∥bi∗∥\|w'\| < \frac12 \min_i \|b^*_i\|, and that after LLL with δ=3/4\delta = 3/4 this holds whenever ∥w′∥<2−(n−1)/2λ1/2\|w'\| < 2^{-(n-1)/2} \lambda_1 / 2, with λ1\lambda_1 the length of the shortest nonzero lattice vector (a theorem). The unbounded lattice ML decision is guaranteed only for ∥w′∥<λ1/2\|w'\| < \lambda_1 / 2, so LR-SIC loses at most a factor 2(n−1)/22^{(n-1)/2} in this noise radius, a factor that does not depend on the channel. Without reduction, min⁡i∥bi∗∥\min_i \|b^*_i\| can be arbitrarily small compared with λ1\lambda_1, 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 mcm_c receive antennas and ncn_c streams, plain ZF over i.i.d. Rayleigh fading has diversity mc−nc+1m_c - n_c + 1, by the ZF page, against mcm_c 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. Hr∈Rm×nH_r \in \mathbb{R}^{m \times n} is the real channel with linearly independent columns h1,…,hnh_1, \ldots, h_n, and Λ={Hrz:z∈Zn}\Lambda = \{H_r z : z \in \mathbb{Z}^n\} is the lattice they generate. For a basis b1,…,bnb_1, \ldots, b_n, the Gram-Schmidt vectors are b1∗=b1b^*_1 = b_1 and bk∗=bk−∑j<kμkjbj∗b^*_k = b_k - \sum_{j < k} \mu_{kj} b^*_j with μkj=⟨bk,bj∗⟩/∥bj∗∥2\mu_{kj} = \langle b_k, b^*_j \rangle / \|b^*_j\|^2. The vectors bk∗b^*_k are orthogonal, and bk=bk∗+∑j<kμkjbj∗b_k = b^*_k + \sum_{j < k} \mu_{kj} b^*_j.

Lemma 1 (the real model and the shift). ∥y−Hx∥2=∥yr−Hrxr∥2\|y - H x\|^2 = \|y_r - H_r x_r\|^2, and with xr=(2z−(q−1)1)/sx_r = (2 z - (q - 1) \mathbf 1) / s and y′=(s yr+(q−1)Hr1)/2y' = (s\, y_r + (q - 1) H_r \mathbf 1) / 2, the model y=Hx+wy = H x + w becomes y′=Hrz+w′y' = H_r z + w' with w′=s2wrw' = \frac{s}{2} w_r.

Proof. For complex a=Hxa = H x, Re(Hx)=ReH Rex−ImH Imx\mathrm{Re}(H x) = \mathrm{Re} H\, \mathrm{Re} x - \mathrm{Im} H\, \mathrm{Im} x and Im(Hx)=ImH Rex+ReH Imx\mathrm{Im}(H x) = \mathrm{Im} H\, \mathrm{Re} x + \mathrm{Re} H\, \mathrm{Im} x, which is HrxrH_r x_r for QAM; for PAM, Imx=0\mathrm{Im} x = 0 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, yr=Hrxr+wr=Hr(2z−(q−1)1)/s+wry_r = H_r x_r + w_r = H_r (2 z - (q - 1) \mathbf 1) / s + w_r. Multiply by s/2s / 2 and add (q−1)Hr1/2(q - 1) H_r \mathbf 1 / 2. □\square

Lemma 2 (unimodular change of basis). If T∈Zn×nT \in \mathbb{Z}^{n \times n} with ∣det⁡T∣=1|\det T| = 1, then T−1∈Zn×nT^{-1} \in \mathbb{Z}^{n \times n}, the columns of B=HrTB = H_r T generate Λ\Lambda, and u↦Tuu \mapsto T u is a bijection of Zn\mathbb{Z}^n.

Proof. T−1=adj(T)/det⁡TT^{-1} = \mathrm{adj}(T) / \det T, and the adjugate of an integer matrix is an integer matrix. So TT and T−1T^{-1} both map Zn\mathbb{Z}^n into Zn\mathbb{Z}^n, and BZn=HrTZn=HrZnB \mathbb{Z}^n = H_r T \mathbb{Z}^n = H_r \mathbb{Z}^n. □\square

Theorem 3 (LLL). For 1/4<δ<11/4 < \delta < 1, the LLL loop terminates. At the end, B=HrTB = H_r T with TT an integer matrix with ∣det⁡T∣=1|\det T| = 1, ∣μkj∣≤1/2|\mu_{kj}| \le 1/2 for j<kj < k, and ∥bk∗∥2≥(δ−μk,k−12)∥bk−1∗∥2\|b^*_k\|^2 \ge (\delta - \mu_{k,k-1}^2) \|b^*_{k-1}\|^2 for k≥2k \ge 2.

Proof. Invariant. The loop changes the basis only by bk←bk−c bjb_k \leftarrow b_k - c\, b_j with an integer cc and j<kj < k, or by a swap of bk−1b_{k-1} and bkb_k, and it applies the same operation to the columns of TT. Both operations multiply TT on the right by an integer matrix of determinant ±1\pm 1, so B=HrTB = H_r T, TT is an integer matrix and ∣det⁡T∣=1|\det T| = 1 at all times, starting from T=IT = I.

Size reduction. bk←bk−c bjb_k \leftarrow b_k - c\, b_j with j<kj < k does not change any bi∗b^*_i, because bjb_j lies in the span of b1∗,…,bj∗b^*_1, \ldots, b^*_j. It changes μkl\mu_{kl} to μkl−cμjl\mu_{kl} - c \mu_{jl} for l≤jl \le j (with μjj=1\mu_{jj} = 1) and leaves μkl\mu_{kl} for l>jl > j unchanged. The loop runs j=k−1j = k - 1 down to 1 and chooses c=⌊μkj+1/2⌋c = \lfloor \mu_{kj} + 1/2 \rfloor, so after step jj, ∣μkj∣≤1/2|\mu_{kj}| \le 1/2, and later steps (with smaller jj) do not change it.

Termination. Let di=∏l≤i∥bl∗∥2d_i = \prod_{l \le i} \|b^*_l\|^2, the squared volume of the sublattice spanned by b1,…,bib_1, \ldots, b_i, and let P=∏i=1n−1diP = \prod_{i = 1}^{n - 1} d_i. Size reduction does not change PP. A swap at position kk changes only dk−1d_{k-1}, which is multiplied by ∥bk−1′∗∥2/∥bk−1∗∥2\|b'^*_{k-1}\|^2 / \|b^*_{k-1}\|^2, where bk−1′∗=bk∗+μk,k−1bk−1∗b'^*_{k-1} = b^*_k + \mu_{k,k-1} b^*_{k-1} is the new Gram-Schmidt vector. So ∥bk−1′∗∥2=∥bk∗∥2+μk,k−12∥bk−1∗∥2<δ∥bk−1∗∥2\|b'^*_{k-1}\|^2 = \|b^*_k\|^2 + \mu_{k,k-1}^2 \|b^*_{k-1}\|^2 < \delta \|b^*_{k-1}\|^2 when the Lovász condition fails, and PP is multiplied by less than δ\delta. Each did_i is the squared determinant of an ii-dimensional sublattice of Λ\Lambda. By the definition of the Hermite constant γi\gamma_i, the sublattice has a nonzero vector of squared length at most γidi1/i\gamma_i d_i^{1/i}, and that vector is in Λ\Lambda, so di≥(λ12/γi)i>0d_i \ge (\lambda_1^2 / \gamma_i)^i > 0, with λ1\lambda_1 the length of a shortest nonzero vector of Λ\Lambda. So PP has a positive lower bound that does not depend on the basis, and the number of swaps is at most log⁡1/δ(P0/Pmin⁡)\log_{1/\delta}(P_0 / P_{\min}), with P0P_0 the initial value. Between two swaps, kk grows by one at each step, so the loop ends.

Reduced prefix. At the start of each iteration with current position kk (1-based), the vectors b1,…,bk−1b_1, \ldots, b_{k-1} are size-reduced and satisfy the Lovász condition among themselves. This holds for k=2k = 2. An iteration size-reduces bkb_k, which changes no other vector and no bi∗b^*_i. If the test passes, b1,…,bkb_1, \ldots, b_k are reduced and kk grows by one. If it fails, the swap changes only positions k−1k - 1 and kk, and kk becomes max⁡(k−1,2)\max(k - 1, 2), so the prefix up to the new k−1k - 1 is unchanged. The loop ends with k=n+1k = n + 1, so the whole basis is reduced. □\square

Theorem 4 (exact without noise). If w=0w = 0, the detector returns xx, with or without reduction, for both ZF and SIC.

Proof. By Lemma 1, y′=Hrzy' = H_r z with z∈{0,…,q−1}nz \in \{0, \ldots, q - 1\}^n. Let u∗=T−1zu^\ast = T^{-1} z, an integer vector by Lemma 2, so y′=Bu∗y' = B u^\ast. ZF: B+y′=(BTB)−1BTBu∗=u∗B^+ y' = (B^T B)^{-1} B^T B u^\ast = u^\ast, which rounding does not change. SIC: Lemma 5 below with w′=0w' = 0. Then Tu∗=zT u^\ast = z, which lies in the box, so clipping does not change it, and line L8 maps zz to the points of xx. □\square

Lemma 5 (SIC, the nearest plane step). Let y′=Bu∗+w′y' = B u^\ast + w' with u∗∈Znu^\ast \in \mathbb{Z}^n and ∥w′∥<12min⁡i∥bi∗∥\|w'\| < \frac12 \min_i \|b^*_i\|. Then line L5 returns u=u∗u = u^\ast.

Proof. By downward induction on ii. Assume ul=ul∗u_l = u^\ast_l for all l>il > i. Then the residual before step ii is r=∑l≤iul∗bl+w′r = \sum_{l \le i} u^\ast_l b_l + w'. For l<il < i, blb_l lies in the span of b1∗,…,bi−1∗b^*_1, \ldots, b^*_{i-1}, which is orthogonal to bi∗b^*_i, and ⟨bi,bi∗⟩=∥bi∗∥2\langle b_i, b^*_i \rangle = \|b^*_i\|^2. So

⟨r,bi∗⟩∥bi∗∥2=ui∗+⟨w′,bi∗⟩∥bi∗∥2,∣⟨w′,bi∗⟩∥bi∗∥2∣≤∥w′∥∥bi∗∥<12\frac{\langle r, b^*_i \rangle}{\|b^*_i\|^2} = u^\ast_i + \frac{\langle w', b^*_i \rangle}{\|b^*_i\|^2}, \qquad \Big| \frac{\langle w', b^*_i \rangle}{\|b^*_i\|^2} \Big| \le \frac{\|w'\|}{\|b^*_i\|} < \frac12

by the Cauchy-Schwarz inequality. So rounding gives ui=ui∗u_i = u^\ast_i. □\square

Theorem 6 (the noise radius of LR-SIC). After LLL with δ=3/4\delta = 3/4, min⁡i∥bi∗∥2≥2−(n−1)λ12\min_i \|b^*_i\|^2 \ge 2^{-(n-1)} \lambda_1^2. So if ∥w′∥<2−(n−1)/2λ1/2\|w'\| < 2^{-(n-1)/2} \lambda_1 / 2, LR-SIC returns the transmitted xx.

Proof. Size reduction gives μk,k−12≤1/4\mu_{k,k-1}^2 \le 1/4, so the Lovász condition gives ∥bk∗∥2≥(3/4−1/4)∥bk−1∗∥2=12∥bk−1∗∥2\|b^*_k\|^2 \ge (3/4 - 1/4) \|b^*_{k-1}\|^2 = \frac12 \|b^*_{k-1}\|^2. By induction, ∥bi∗∥2≥2−(i−1)∥b1∗∥2=2−(i−1)∥b1∥2≥2−(n−1)λ12\|b^*_i\|^2 \ge 2^{-(i-1)} \|b^*_1\|^2 = 2^{-(i-1)} \|b_1\|^2 \ge 2^{-(n-1)} \lambda_1^2, since b1b_1 is a nonzero vector of Λ\Lambda. Under the assumption on w′w', Lemma 5 gives u=u∗=T−1zu = u^\ast = T^{-1} z, so line L6 gives zz, which is in the box, and the argument of Theorem 4 ends the proof. □\square

For comparison, the nearest point of Λ\Lambda to y′y' is HrzH_r z whenever ∥w′∥<λ1/2\|w'\| < \lambda_1 / 2, because any other lattice point vv has ∥y′−v∥≥∥v−Hrz∥−∥w′∥≥λ1−∥w′∥>∥w′∥\|y' - v\| \ge \|v - H_r z\| - \|w'\| \ge \lambda_1 - \|w'\| > \|w'\|. So the guarantee of Theorem 6 is smaller by the factor 2(n−1)/22^{(n-1)/2}, which depends only on nn. Without reduction, min⁡i∥hi∗∥\min_i \|h^*_i\| has no lower bound in terms of λ1\lambda_1. For example, the basis h1=(N,1)h_1 = (N, 1), h2=(1,0)h_2 = (1, 0) with an integer NN generates Z2\mathbb{Z}^2, so λ1=1\lambda_1 = 1, but ∥h2∗∥=1/N2+1\|h^*_2\| = 1 / \sqrt{N^2 + 1}, which goes to zero as NN 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 B+w′B^+ w' lies in [−1/2,1/2)[-1/2, 1/2), LR-ZF returns the transmitted xx.

Proof. B+y′=(BTB)−1BT(Bu∗+w′)=u∗+B+w′B^+ y' = (B^T B)^{-1} B^T (B u^\ast + w') = u^\ast + B^+ w', and ⌊v+1/2⌋=ui∗\lfloor v + 1/2 \rfloor = u^\ast_i exactly when v−ui∗∈[−1/2,1/2)v - u^\ast_i \in [-1/2, 1/2). So u=u∗u = u^\ast, Tu=zT u = z, clipping does not change zz, and line L8 returns xx. □\square

Lemma 8 (the MMSE form). With H~=(HrσI)\tilde H = \begin{pmatrix} H_r \\ \sigma I \end{pmatrix} and y~=(y′σc1)\tilde y = \begin{pmatrix} y' \\ \sigma c \mathbf 1 \end{pmatrix}, c=(q−1)/2c = (q - 1)/2, the metric ∥y~−H~z∥2\|\tilde y - \tilde H z\|^2 equals ∥y′−Hrz∥2+σ2∥z−c1∥2\|y' - H_r z\|^2 + \sigma^2 \|z - c \mathbf 1\|^2, and H~\tilde H has linearly independent columns for every σ>0\sigma > 0.

Proof. The squared norm of a stacked vector is the sum of the squared norms of its blocks. If H~v=0\tilde H v = 0, the lower block gives σv=0\sigma v = 0. □\square

With σ2=3s2N02(q2−1)\sigma^2 = \frac{3 s^2 N_0}{2 (q^2 - 1)}, the noise variance of w′w' in one dimension, s2N0/8s^2 N_0 / 8, divided by the variance (q2−1)/12(q^2 - 1)/12 of a uniform ziz_i, this is the regularized metric of the MMSE detector in the integer coordinates. For unit-energy MM-QAM, s2=2(q2−1)/3s^2 = 2(q^2 - 1)/3 gives σ2=N0\sigma^2 = N_0, and for MM-PAM, s2=(q2−1)/3s^2 = (q^2 - 1)/3 gives σ2=N0/2\sigma^2 = N_0 / 2 (closed forms). Theorems 3 to 6 apply to H~\tilde H and y~\tilde y unchanged, with the lattice generated by H~\tilde H.

Complexity

The real-valued model and the shift cost O(nm)O(n m). Each LLL iteration costs O(nm)O(n m) for the size reduction, and the implementation recomputes the Gram-Schmidt vectors after a swap in O(n2m)O(n^2 m), so LLL with SS swaps costs O((S+1)n2m)O((S + 1) n^2 m). ZF solves an n×nn \times n system in O(n2m+n3)O(n^2 m + n^3), SIC costs O(n2m)O(n^2 m), and the mapping to points costs O(nM)O(n M). The total is O((S+1)n2m+n3+nM)O((S + 1) n^2 m + n^3 + n M) in the real RAM (a closed form). For real bases, SS has no bound in terms of nn alone, because it depends on how badly the channel is conditioned. The proof shows that SS 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 HH, so on a channel that stays the same for many vectors its cost is spread over all of them.

Properties

  • Exact without noise. zz is recovered exactly from y′=Hrzy' = H_r z (theorem).
  • Same lattice. BB and HrH_r generate the same lattice, because TT and T−1T^{-1} are integer matrices (theorem).
  • Noise radius. LR-SIC is correct whenever ∥w′∥<2−(n−1)/2λ1/2\|w'\| < 2^{-(n-1)/2} \lambda_1 / 2 (theorem).
  • Measured error rates. For 2x2 4-QAM over i.i.d. Rayleigh fading at Es/N0=20E_s / N_0 = 20 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 Zn\mathbb{Z}^n, 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 HrH_r. Wübben, Böhnke, Kühn and Kammeyer described this form in 2004. The implementation uses it when N0>0N_0 > 0 is given.
  • Complex LLL. Run the reduction on the complex matrix HH with Gaussian integers instead of the real matrix HrH_r, 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 nn 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 zz, not the constellation values. For QAM, the shift by (q−1)/2(q - 1)/2 per real dimension and the scale s/2s / 2 must match the constellation exactly.
  • Forgetting to clip. TuT u can lie outside {0,…,q−1}n\{0, \ldots, q - 1\}^n, because the reduced basis does not see the box. Without line L7, the result is not a constellation vector.
  • Mismatched TT. Every swap and size reduction of LLL must be applied to TT as well. If TT is updated in a different order from BB, 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 ⌊v+1/2⌋\lfloor v + 1/2 \rfloor.
  • A singular channel. With n>mn > m in the real model, the columns of HrH_r 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.

cbb.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example