Algorithm Search⌘K

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.

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
Properties
cost depends on noisedeterministicexact list
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 MnM^n transmitted vectors, which is too much work for large nn or MM. The list sphere decoder runs a depth-first sphere search, as in Schnorr-Euchner enumeration, but it keeps the LL best vectors that it has found instead of one, and it prunes a subtree only when its partial metric is not below the LL-th best metric in the list. At the end the list holds LL vectors with the smallest metrics of all MnM^n (a theorem). The LLRs then use only the vectors in the list. With L=1L = 1 the search is exact ML detection, and with L=MnL = M^n 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 y=Hx+wy = H x + w with H∈Cm×nH \in \mathbb{C}^{m \times n} known, m≥nm \ge n and full column rank, x∈Snx \in \mathcal{S}^n for a constellation S\mathcal{S} of size M=2bM = 2^b with a bit label for each point, and w∼CN(0,N0I)w \sim \mathcal{CN}(0, N_0 I). For bit jj of stream kk, the LLR with equal priors is

Λk,j=ln⁡∑x:bk,j(x)=0e−∥y−Hx∥2/N0∑x:bk,j(x)=1e−∥y−Hx∥2/N0,\Lambda_{k,j} = \ln \frac{\sum_{x : b_{k,j}(x) = 0} e^{-\|y - H x\|^2 / N_0}}{\sum_{x : b_{k,j}(x) = 1} e^{-\|y - H x\|^2 / N_0}},

so a positive LLR favors bit 0. The max-log approximation keeps the largest term of each sum:

Λk,j≈1N0(min⁡x:bk,j(x)=1∥y−Hx∥2−min⁡x:bk,j(x)=0∥y−Hx∥2).\Lambda_{k,j} \approx \frac{1}{N_0} \Big( \min_{x : b_{k,j}(x) = 1} \|y - H x\|^2 - \min_{x : b_{k,j}(x) = 0} \|y - H x\|^2 \Big).

The list sphere decoder returns a list L\mathcal{L} of LL vectors with the smallest metrics, and the LLRs computed with the sums or minimums restricted to L\mathcal{L}. A bit value that no vector of L\mathcal{L} has gives the LLR ±Λmax⁡\pm \Lambda_{\max}, a fixed clipping level.

The algorithm

As on the K-best page, let HHH=RHRH^H H = R^H R with RR upper triangular and a positive diagonal, let yˉ\bar y solve RHyˉ=HHyR^H \bar y = H^H y, and let c=∥y∥2−∥yˉ∥2c = \|y\|^2 - \|\bar y\|^2. Then ∥y−Hx∥2=∥yˉ−Rx∥2+c\|y - H x\|^2 = \|\bar y - R x\|^2 + c, and ∥yˉ−Rx∥2\|\bar y - R x\|^2 is the sum of the level terms ∣yˉi−∑j>iRijxj−Riixi∣2|\bar y_i - \sum_{j > i} R_{ij} x_j - R_{ii} x_i|^2 for i=ni = n down to 1. The partial metric of (xi,…,xn)(x_i, \ldots, x_n) is the sum of the terms from ii to nn, and it can only grow as the search goes down.

  1. LIST-SPHERE(y, H, S, L)
  2. 1(R, ȳ, c) ← TRIANGULARIZE(y, H)
  3. 2list ← empty; radius ← ∞
  4. 3SEARCH(n, 0)
  5. 4return the list, with c added to each metric, best first
  6. SEARCH(i, D) ▷ x_{i+1}, ..., x_n are fixed
  7. 5u ← ȳ_i - Σ_{j>i} R_ij x_j
  8. 6for each s in S, in increasing order of |u - R_ii s|
  9. 7D' ← D + |u - R_ii s|²
  10. 8if D' ≥ radius then break ▷ the other children are farther
  11. 9x_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
  12. 10else 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 LL 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 kk and bit jj, split the list by the value of bit jj of xkx_k. If both parts are nonempty, the max-log LLR is (D1−D0)/N0(D_1 - D_0) / N_0 with DvD_v the smallest metric in the part with value vv, and the full form is the difference of the two log-sum-exp values of −D/N0-D / N_0. If one part is empty, the LLR is +Λmax⁡+\Lambda_{\max} when all vectors in the list have bit 0 and −Λmax⁡-\Lambda_{\max} when all have bit 1. The constant cc cancels in every difference.

Example

Take m=n=2m = n = 2, BPSK with bit 0 on +1+1 and bit 1 on −1-1, H=(2111)H = \begin{pmatrix} 2 & 1 \\ 1 & 1 \end{pmatrix}, y=(0.5,0.6)y = (0.5, 0.6), the received vector of the ZF example for x=(+1,−1)x = (+1, -1), and N0=1N_0 = 1. As on the K-best page,

R=15(5301),yˉ=15(1.6,0.7),c=0.R = \frac{1}{\sqrt 5} \begin{pmatrix} 5 & 3 \\ 0 & 1 \end{pmatrix}, \qquad \bar y = \frac{1}{\sqrt 5} (1.6, 0.7), \qquad c = 0.

Run the search with L=2L = 2. Level 2: the term (0.7−x2)2/5(0.7 - x_2)^2 / 5 is 0.018 for x2=+1x_2 = +1 and 0.578 for x2=−1x_2 = -1, so x2=+1x_2 = +1 comes first. Under x2=+1x_2 = +1, the term (−1.4−5x1)2/5(-1.4 - 5 x_1)^2 / 5 is 2.592 for x1=−1x_1 = -1 and 8.192 for x1=+1x_1 = +1. 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, x2=−1x_2 = -1 has partial metric 0.578<8.210.578 < 8.21. Under it, x1=+1x_1 = +1 adds (4.6−5)2/5=0.032(4.6 - 5)^2 / 5 = 0.032 for a metric of 0.61, which enters the list and pushes out 8.21. The radius becomes 2.61. The next child, x1=−1x_1 = -1, adds 18.432, which fails the test. The search computed 6 partial metrics, and the list is {(+1,−1):0.61, (−1,+1):2.61}\{(+1, -1) : 0.61, \ (-1, +1) : 2.61\}.

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 2.61−0.61=22.61 - 0.61 = 2. For bit 2 the roles swap and the LLR is −2-2. Both LLRs point to the transmitted (+1,−1)(+1, -1). With all four vectors, the exact LLR of bit 1 is ln⁡(e−0.61+e−8.21)−ln⁡(e−2.61+e−19.01)≈2.0005\ln(e^{-0.61} + e^{-8.21}) - \ln(e^{-2.61} + e^{-19.01}) \approx 2.0005, 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 ∥y−Hx∥2\|y - H x\|^2 (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 LL vectors with the smallest metrics of all MnM^n (a theorem). Two corollaries follow: L=1L = 1 gives an ML vector, and L=MnL = M^n 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 y=Hx+wy = H x + w with H∈Cm×nH \in \mathbb{C}^{m \times n} of full column rank and x∈Snx \in \mathcal{S}^n, ∣S∣=M|\mathcal{S}| = M. Let HHH=RHRH^H H = R^H R with RR upper triangular with a positive diagonal (line L1), let yˉ\bar y solve RHyˉ=HHyR^H \bar y = H^H y, and let c=∥y∥2−∥yˉ∥2c = \|y\|^2 - \|\bar y\|^2. Write f(x)=∥y−Hx∥2f(x) = \|y - H x\|^2 for the metric of x∈Snx \in \mathcal{S}^n.

Theorem 1 (the triangular metric). For every x∈Cnx \in \mathbb{C}^n, f(x)=∥yˉ−Rx∥2+cf(x) = \|\bar y - R x\|^2 + c.

Proof. f(x)=∥y∥2−2 Re(xHHHy)+xHHHHxf(x) = \|y\|^2 - 2 \,\mathrm{Re}(x^H H^H y) + x^H H^H H x and ∥yˉ−Rx∥2=∥yˉ∥2−2 Re(xHRHyˉ)+xHRHRx\|\bar y - R x\|^2 = \|\bar y\|^2 - 2 \,\mathrm{Re}(x^H R^H \bar y) + x^H R^H R x. Since RHyˉ=HHyR^H \bar y = H^H y and RHR=HHHR^H R = H^H H, the two differ by ∥y∥2−∥yˉ∥2=c\|y\|^2 - \|\bar y\|^2 = c. □\square

For 1≤i≤n1 \le i \le n let ti(xi,…,xn)=∣yˉi−∑j>iRijxj−Riixi∣2≥0t_i(x_i, \ldots, x_n) = |\bar y_i - \sum_{j > i} R_{ij} x_j - R_{ii} x_i|^2 \ge 0 and let Di=∑l=intlD_i = \sum_{l = i}^{n} t_l, with Dn+1=0D_{n+1} = 0. Row ii of yˉ−Rx\bar y - R x is the expression inside tit_i, so ∥yˉ−Rx∥2=D1\|\bar y - R x\|^2 = D_1.

Lemma 2 (monotone partial metrics). DiD_i depends only on (xi,…,xn)(x_i, \ldots, x_n), and Di=Di+1+ti≥Di+1D_i = D_{i+1} + t_i \ge D_{i+1}. So for every completion xx of a partial vector (xi,…,xn)(x_i, \ldots, x_n), D1(x)≥Di(xi,…,xn)D_1(x) \ge D_i(x_i, \ldots, x_n).

Proof. Immediate from the definition and tl≥0t_l \ge 0. □\square

Lemma 3 (the call invariant). When SEARCH(i,D)(i, D) is called, xi+1,…,xnx_{i+1}, \ldots, x_n hold the symbols of the current path and D=Di+1(xi+1,…,xn)D = D_{i+1}(x_{i+1}, \ldots, x_n). Each D′D' of line L7 is DiD_i of the child (s,xi+1,…,xn)(s, x_{i+1}, \ldots, x_n), and each list entry inserted by line L9 is a pair (D1(x),x)(D_1(x), x).

Proof. By induction on the depth of the call. The first call is SEARCH(n,0)(n, 0), and Dn+1=0D_{n+1} = 0. In a call, line L5 computes u=yˉi−∑j>iRijxju = \bar y_i - \sum_{j > i} R_{ij} x_j, so ∣u−Riis∣2=ti(s,xi+1,…,xn)|u - R_{ii} s|^2 = t_i(s, x_{i+1}, \ldots, x_n) and D′=Di+1+ti=DiD' = D_{i+1} + t_i = D_i. Line L9 sets xi=sx_i = s before line L10 calls SEARCH(i−1,D′)(i - 1, D'), so the invariant holds for the child call. At i=1i = 1 the inserted value is D1(x)D_1(x). □\square

By Lemma 3 and Theorem 1, every metric returned by line L4 is D1(x)+c=f(x)D_1(x) + c = f(x).

Let ρ\rho denote the value of radius. It is ∞\infty until the list holds LL entries, and after that it is the largest metric D1D_1 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 ρ\rho never grows.

Lemma 4 (the break is safe). Line L8 never prevents the insertion of a vector xx with D1(x)<ρendD_1(x) < \rho_{\mathrm{end}}, where ρend\rho_{\mathrm{end}} is the final radius.

Proof. Line L6 orders the children by tit_i, and DD is common to all children, so the values D′D' increase along the loop. When line L8 breaks at a child with D′≥ρD' \ge \rho, every later child of the same node has an even larger D′D'. Every completion xx of any of these children has D1(x)≥D′≥ρ≥ρendD_1(x) \ge D' \ge \rho \ge \rho_{\mathrm{end}} by Lemma 2 and the fact that ρ\rho never grows. So no vector with D1(x)<ρendD_1(x) < \rho_{\mathrm{end}} is lost. □\square

Theorem 5 (the list is the L best). Assume L≤MnL \le M^n. At the end, the list holds LL distinct vectors, and no vector of Sn\mathcal{S}^n outside the list has a smaller metric than a vector inside it. That is, the list is a set of LL vectors with the smallest metrics (with an arbitrary choice among equal metrics at the boundary).

Proof. First, the list becomes full. While ρ=∞\rho = \infty, the test of line L8 never succeeds, so the search visits leaves until LL of them have been inserted. There are Mn≥LM^n \ge L 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 xx be a vector outside the final list and zz a vector inside it. Suppose D1(x)<D1(z)D_1(x) < D_1(z). Then D1(x)<ρendD_1(x) < \rho_{\mathrm{end}}, because ρend\rho_{\mathrm{end}} is the largest metric in the final list. By Lemma 4, no break removed xx, so the search reached the leaf xx, and line L9 inserted it. At that time ρ≥ρend>D1(x)\rho \ge \rho_{\mathrm{end}} > D_1(x), so xx 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 ρ>D1(x)\rho > D_1(x). A later insertion drops one entry with the largest metric of L+1L + 1 entries. That metric is at least the new radius, which is at least ρend>D1(x)\rho_{\mathrm{end}} > D_1(x), so it is never xx. So xx is in the final list, a contradiction. □\square

Corollary 6 (the two limits). With L=1L = 1, the only vector in the list minimizes ff over Sn\mathcal{S}^n, so it is an ML decision. With L=MnL = M^n, the list holds all of Sn\mathcal{S}^n with their metrics.

For stream kk and bit jj, let bk,j(x)b_{k,j}(x) be bit jj of the label of xkx_k. With equal priors, the posterior probability of xx is proportional to e−f(x)/N0e^{-f(x) / N_0}, so the exact LLR is

Λk,j=ln⁡∑x:bk,j(x)=0e−f(x)/N0−ln⁡∑x:bk,j(x)=1e−f(x)/N0.\Lambda_{k,j} = \ln \sum_{x : b_{k,j}(x) = 0} e^{-f(x) / N_0} - \ln \sum_{x : b_{k,j}(x) = 1} e^{-f(x) / N_0}.

Theorem 7 (exact LLRs for the full list). With L=MnL = M^n, the log-sum-exp LLRs computed from the list equal Λk,j\Lambda_{k,j}, and the max-log LLRs from the list equal (min⁡b=1f−min⁡b=0f)/N0(\min_{b = 1} f - \min_{b = 0} f) / N_0 over all of Sn\mathcal{S}^n.

Proof. By Corollary 6 the list is Sn\mathcal{S}^n with the true metrics f(x)f(x). Both bit values occur in Sn\mathcal{S}^n, so no clipping applies, and the two sums of the list are the two sums of Λk,j\Lambda_{k,j}. For max-log, max⁡(−f/N0)=−min⁡f/N0\max(-f / N_0) = -\min f / N_0 in each part. □\square

Theorem 8 (max-log from a shorter list). For any LL, if both values of bit bk,jb_{k,j} occur in the list, the max-log LLR from the list equals the max-log LLR over all of Sn\mathcal{S}^n.

Proof. Let x^\hat x be the first vector of the list, an ML vector by Theorem 5, and let v=bk,j(x^)v = b_{k,j}(\hat x). Then min⁡b=vf=f(x^)\min_{b = v} f = f(\hat x), and it is in the list. Let x∗x^\ast minimize ff over the vectors with bk,j=1−vb_{k,j} = 1 - v. Some vector zz of the list has bk,j(z)=1−vb_{k,j}(z) = 1 - v, so f(z)≥f(x∗)f(z) \ge f(x^\ast). If x∗x^\ast were not in the list, then by Theorem 5, f(x∗)≥f(z′)f(x^\ast) \ge f(z') for every z′z' in the list, and so f(x∗)≥f(z)f(x^\ast) \ge f(z). Then f(z)=f(x∗)f(z) = f(x^\ast) and zz is also a minimizer with bit value 1−v1 - v. In both cases the list holds a vector with bit value 1−v1 - v and metric min⁡b=1−vf\min_{b = 1 - v} f. So both minimums of the max-log formula are attained in the list. □\square

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 (ρend−f(x^))/N0(\rho_{\mathrm{end}} - f(\hat x)) / N_0. The clipping level Λmax⁡\Lambda_{\max} replaces this unknown magnitude.

Complexity

The triangular form costs O(n2m+n3)O(n^2 m + n^3). Each visit of SEARCH computes uu in O(n)O(n) and sorts MM level terms in O(Mlog⁡M)O(M \log M), and each accepted leaf updates the list in O(L)O(L). In the worst case no subtree is pruned, so there are fewer than 2Mn−12 M^{n-1} visits and MnM^n leaves, and the total is O(n2m+n3+Mn(n+log⁡M+L))O(n^2 m + n^3 + M^n (n + \log M + L)) in the real RAM (a closed form). The LLR step costs O(Lnb)O(L n b). The memory holds RR, 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 4×44 \times 4 Rayleigh channel at Es/N0=15E_s / N_0 = 15 dB, where the full tree has 340 nodes. The search computed 8.2 partial metrics per vector on average for L=1L = 1 and 102.4 for L=16L = 16 (a measurement).

Properties

  • Exact list. The list holds LL vectors with the smallest metrics of all MnM^n (theorem). This differs from the K-best detector, whose final KK survivors need not be the KK best.
  • Two limits. L=1L = 1 is exact ML detection, and L=MnL = M^n 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 MnM^n vectors (theorem). Only the bits with one value in the list need clipping.
  • Variable cost. The number of visited nodes depends on HH, yy and LL, not only on nn and MM.
  • Noise level. The search does not need N0N_0; 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 MnM^n 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 2n2n with M\sqrt M-PAM symbols, so each level has M\sqrt M children.

When to use it

Use the list sphere decoder when a coded MIMO system needs soft bit values close to the exact ones, nn and MM 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 L=1L = 1, which is Schnorr-Euchner enumeration. For large nn, 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 ±Λmax⁡\pm \Lambda_{\max}, 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.

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))
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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of time_llrs.worst
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