Algorithm Search⌘K

Algorithmcore

Max-log demapping

Also called max-log LLR approximation.

Approximates each bit LLR by the squared distance to the nearest point with the bit 1, minus that to the nearest point with the bit 0, over N0. It needs no exponentials.

Time
Θ(M log M) worst
Space
Θ(M) extra
Where
M = the number of constellation points; m = the number of bits per point (log2 M)
Properties
accepts priorsdeterministicnot exactnot needs noise level
Origin
Ephraim Zehavi, 1992

Max-log demapping computes an approximate log-likelihood ratio (LLR) for each bit of a received symbol. The exact LLR of soft demapping is the log of a ratio of two sums of exponentials, one over the points whose bit is 00 and one over the points whose bit is 11. Max-log keeps only the largest term of each sum. Without priors, the result is the squared distance from the received sample to the nearest point with the bit 11, minus the squared distance to the nearest point with the bit 00, divided by N0N_0. It needs no exp⁡\exp and no ln⁡\ln, its signs are the bits of the minimum distance detector, and its error is at most ln⁡(M/2)\ln(M/2) per bit. For Gray square QAM it falls apart into simple piecewise linear functions of the in-phase and quadrature components. Most hardware receivers for bit-interleaved coded modulation use it.

In plain words

For each bit, the receiver asks two questions. Of all the points whose bit is 0, which one is nearest to what I received, and how far is it? And the same for the points whose bit is 1. If the nearest "0" point is much nearer than the nearest "1" point, the bit is very likely 0. The difference of the two squared distances is the answer: its sign gives the bit, and its size gives the confidence. The method ignores all points except the two nearest ones in each comparison. That makes it cheap, and at a good signal level it loses almost nothing.

The problem

The receiver sees y=hx+wy = h x + w, where xx is one of the points a0,…,aM−1a_0, \ldots, a_{M-1}, aia_i carries the bit label ii with bits b0(i),…,bm−1(i)b_0(i), \ldots, b_{m-1}(i) (most significant first), h≠0h \ne 0 is a known gain, jj is the imaginary unit and w∼CN(0,N0)w \sim \mathcal{CN}(0, N_0). The optional prior LLRs are Lka=ln⁡P(bk=0)/P(bk=1)L^a_k = \ln P(b_k = 0)/P(b_k = 1). With the point metric

di=−∣y−hai∣2N0+∑k(1−2bk(i)) Lka2,d_i = -\frac{|y - h a_i|^2}{N_0} + \sum_{k} \frac{(1 - 2b_k(i))\, L^a_k}{2},

the exact LLR is Lk=ln⁡∑bk(i)=0edi−ln⁡∑bk(i)=1ediL_k = \ln\sum_{b_k(i) = 0} e^{d_i} - \ln\sum_{b_k(i) = 1} e^{d_i}, and the max-log LLR is

L~k=max⁡i: bk(i)=0di−max⁡i: bk(i)=1di,k=0,…,m−1.\tilde L_k = \max_{i:\, b_k(i) = 0} d_i - \max_{i:\, b_k(i) = 1} d_i, \qquad k = 0, \ldots, m-1.

Without priors, L~k=(min⁡bk(i)=1∣y−hai∣2−min⁡bk(i)=0∣y−hai∣2)/N0\tilde L_k = \big(\min_{b_k(i) = 1}|y - h a_i|^2 - \min_{b_k(i) = 0}|y - h a_i|^2\big)/N_0. A positive value favors the bit 00.

The algorithm

  1. MAX-LOG-DEMAP(y, h, N0, a_0..a_{M-1}, La_0..La_{m-1}) ▷ a_i has the label i; La = 0 without priors
  2. 1for i ← 0 to M - 1
  3. 2d_i ← -|y - h·a_i|² / N0 + Σ_k (1 - 2·b_k(i)) · La_k / 2
  4. 3for k ← 0 to m - 1
  5. 4B_0 ← -∞ ; B_1 ← -∞
  6. 5for i ← 0 to M - 1
  7. 6B_{b_k(i)} ← max(B_{b_k(i)}, d_i)
  8. 7L_k ← B_0 - B_1
  9. 8return L_0..L_{m-1} and the extrinsic values E_k ← L_k - La_k

The only difference from the exact demapper is line L6, which uses max⁡\max where the exact demapper uses max⁡∗(u,v)=max⁡(u,v)+ln⁡(1+e−∣u−v∣)\max^*(u, v) = \max(u, v) + \ln(1 + e^{-|u - v|}).

Gray square QAM, one axis at a time. Write z=y/hz = y/h, scale each axis to the raw amplitudes ±1,±3,…\pm 1, \pm 3, \ldots with s=2(M−1)/3s = \sqrt{2(M - 1)/3}, and put u=s Re zu = s\,\mathrm{Re}\,z and v=s Im zv = s\,\mathrm{Im}\,z. Since ∣y−ha∣2=(∣h∣2/s2)((u−cI)2+(v−cQ)2)|y - h a|^2 = (|h|^2/s^2)\big((u - c_I)^2 + (v - c_Q)^2\big) for the point with raw levels (cI,cQ)(c_I, c_Q), the in-phase bits depend only on uu and the quadrature bits only on vv. For 16-QAM with the labels of the area (in-phase level +3,+1,−1,−3+3, +1, -1, -3 with the labels 00,01,11,1000, 01, 11, 10),

Λ0(u)={4u,∣u∣≤2,8(u−sign⁡u),∣u∣>2,Λ1(u)=4(∣u∣−2),\Lambda_0(u) = \begin{cases} 4u, & |u| \le 2, \\ 8(u - \operatorname{sign} u), & |u| > 2, \end{cases} \qquad \Lambda_1(u) = 4(|u| - 2),

and L~0=∣h∣2Λ0(u)/(10N0)\tilde L_0 = |h|^2\Lambda_0(u)/(10 N_0), L~1=∣h∣2Λ1(u)/(10N0)\tilde L_1 = |h|^2\Lambda_1(u)/(10 N_0), L~2=∣h∣2Λ0(v)/(10N0)\tilde L_2 = |h|^2\Lambda_0(v)/(10 N_0), L~3=∣h∣2Λ1(v)/(10N0)\tilde L_3 = |h|^2\Lambda_1(v)/(10 N_0). For example, for 0≤u≤20 \le u \le 2 the nearest in-phase levels with the first bit 00 and 11 are +1+1 and −1-1, and (u+1)2−(u−1)2=4u(u + 1)^2 - (u - 1)^2 = 4u.

Example

Take Gray 16-QAM, h=1h = 1, N0=0.1N_0 = 0.1 and y=0.5−0.2jy = 0.5 - 0.2j, the example of the soft demapping page. Then u=10⋅0.5=1.5811u = \sqrt{10} \cdot 0.5 = 1.5811 and v=10⋅(−0.2)=−0.6325v = \sqrt{10} \cdot (-0.2) = -0.6325, both inside [−2,2][-2, 2]:

bit kk formula max-log L~k\tilde L_k exact LkL_k
0 4u/(10N0)4u/(10 N_0) 6.32466.3246 6.49626.4962
1 4(∣u∣−2)/(10N0)4(\lvert u\rvert - 2)/(10 N_0) −1.6754-1.6754 −1.6772-1.6772
2 4v/(10N0)4v/(10 N_0) −2.5298-2.5298 −2.5340-2.5340
3 4(∣v∣−2)/(10N0)4(\lvert v\rvert - 2)/(10 N_0) −5.4702-5.4702 −5.5463-5.5463

The signs give the label 0111 of the nearest point (1−j)/10(1 - j)/\sqrt{10}, and the values are within 0.180.18 of the exact ones. The brute-force form gives the same: for bit 1, the nearest point with b1=0b_1 = 0 is a3=(3−j)/10a_3 = (3 - j)/\sqrt{10} and the nearest with b1=1b_1 = 1 is a7a_7, and (∣y−a7∣2−∣y−a3∣2)/N0=(0.04728−0.21483)/0.1=−1.6754(|y - a_7|^2 - |y - a_3|^2)/N_0 = (0.04728 - 0.21483)/0.1 = -1.6754.

At N0=1N_0 = 1, the max-log values are ten times smaller, 0.6325,−0.1675,−0.2530,−0.54700.6325, -0.1675, -0.2530, -0.5470, while the exact values are 1.0313,−0.4539,−0.4103,−0.73761.0313, -0.4539, -0.4103, -0.7376. At a low SNR many points contribute to each sum, and the largest term is no longer a good stand-in for the whole sum.

Correctness

Max-log demapping does not compute the exact LLR; what is proved is that it computes the max form and how far that is from the exact value. Lines L4 to L6 keep the invariant that BbB_b is the largest did_i seen so far among the points with bk(i)=bb_k(i) = b, so line L7 returns L~k\tilde L_k. Without priors, max⁡i(−∣y−hai∣2/N0)=−min⁡i∣y−hai∣2/N0\max_i(-|y - h a_i|^2/N_0) = -\min_i|y - h a_i|^2/N_0, which gives the distance form. Each sum in the exact LLR has M/2M/2 terms, each at most its largest, so max⁡≤ln⁡∑edi≤max⁡+ln⁡(M/2)\max \le \ln\sum e^{d_i} \le \max + \ln(M/2) for each bit value, and ∣Lk−L~k∣≤ln⁡(M/2)|L_k - \tilde L_k| \le \ln(M/2). The point ai∗a_{i^*} with the largest did_i lies in one of the two sets of each bit, so the sign of L~k\tilde L_k is the bit bk(i∗)b_k(i^*) of the MAP decision (of the ML decision without priors). The per-axis form for square QAM follows from the separation of ∣y−ha∣2|y - h a|^2 into an in-phase and a quadrature term; the term of the other axis is the same in both minima and cancels. The full proof is below.

Proof: MAX-LOG-DEMAP returns the max form, its signs are the MAP bits, and its error is at most ln(M/2)full

The model and the notation are those of the page: y=hx+wy = h x + w with h≠0h \ne 0 and N0>0N_0 > 0 known, w∼CN(0,N0)w \sim \mathcal{CN}(0, N_0), the points a0,…,aM−1a_0, \ldots, a_{M-1} with M=2mM = 2^m, the label bits bk(i)b_k(i), and the metric did_i of line L2. For a bit kk and a value bb, write Skb={i:bk(i)=b}S_k^b = \{i : b_k(i) = b\}. Since the labels are all of {0,1}m\{0, 1\}^m, each SkbS_k^b has exactly M/2M/2 elements.

Lemma 1 (the fold). Fix kk. After line L6 has run for the points a0,…,at−1a_0, \ldots, a_{t-1}, Bb=max⁡{di:i<t, i∈Skb}B_b = \max\{d_i : i < t,\ i \in S_k^b\} for b∈{0,1}b \in \{0, 1\}, with max⁡∅=−∞\max \emptyset = -\infty. So line L7 returns L~k=max⁡Sk0di−max⁡Sk1di\tilde L_k = \max_{S_k^0} d_i - \max_{S_k^1} d_i, and both terms are finite.

Proof. By induction on tt. For t=0t = 0 line L4 sets both to −∞-\infty. Step t→t+1t \to t + 1: with b=bk(t)b = b_k(t), line L6 sets BbB_b to max⁡(Bb,dt)\max(B_b, d_t), the maximum over the enlarged set, and leaves the other value unchanged. After t=Mt = M both sets are full, and they are nonempty. □\square

Lemma 2 (the distance form). Without priors, L~k=(min⁡Sk1∣y−hai∣2−min⁡Sk0∣y−hai∣2)/N0\tilde L_k = \big(\min_{S_k^1}|y - h a_i|^2 - \min_{S_k^0}|y - h a_i|^2\big)/N_0. In particular N0L~kN_0 \tilde L_k does not depend on N0N_0.

Proof. Here di=−∣y−hai∣2/N0d_i = -|y - h a_i|^2/N_0 with N0>0N_0 > 0, and max⁡S(−f/N0)=−min⁡Sf/N0\max_S(-f/N_0) = -\min_S f/N_0 for any finite set SS. □\square

Lemma 3 (the sandwich). For a finite set SS of n≥1n \ge 1 indices, max⁡Sdi≤ln⁡∑Sedi≤max⁡Sdi+ln⁡n\max_S d_i \le \ln\sum_S e^{d_i} \le \max_S d_i + \ln n.

Proof. Let D=max⁡SdiD = \max_S d_i. The sum contains the term eDe^D and every term is positive, so it is at least eDe^D. Every term is at most eDe^D, so the sum is at most neDn e^D. Take logs. □\square

Theorem. Let Lk=ln⁡∑Sk0edi−ln⁡∑Sk1ediL_k = \ln\sum_{S_k^0} e^{d_i} - \ln\sum_{S_k^1} e^{d_i} be the exact LLR of soft demapping.

  1. ∣Lk−L~k∣≤ln⁡(M/2)|L_k - \tilde L_k| \le \ln(M/2) for every kk.
  2. If i∗i^* is a point with the largest did_i (the MAP decision; without priors, the nearest point to yy after the gain), then L~k≥0\tilde L_k \ge 0 when bk(i∗)=0b_k(i^*) = 0 and L~k≤0\tilde L_k \le 0 when bk(i∗)=1b_k(i^*) = 1. If i∗i^* is the only maximizer, the inequalities are strict, and the hard decisions [L~k<0][\tilde L_k < 0] are the bits of i∗i^*.
  3. For M=2M = 2 and for Gray QPSK, L~k=Lk\tilde L_k = L_k.

Proof. (1) Write Eb=ln⁡∑Skbedi−max⁡SkbdiE_b = \ln\sum_{S_k^b} e^{d_i} - \max_{S_k^b} d_i. By Lemma 3 with n=M/2n = M/2, 0≤Eb≤ln⁡(M/2)0 \le E_b \le \ln(M/2). Then Lk−L~k=E0−E1L_k - \tilde L_k = E_0 - E_1, which lies in [−ln⁡(M/2),ln⁡(M/2)][-\ln(M/2), \ln(M/2)].

(2) Let b=bk(i∗)b = b_k(i^*). Then i∗∈Skbi^* \in S_k^b, so max⁡Skbdi=di∗\max_{S_k^b} d_i = d_{i^*}, and max⁡Sk1−bdi≤di∗\max_{S_k^{1-b}} d_i \le d_{i^*} because di∗d_{i^*} is the largest of all metrics. So the term for bb is at least the term for 1−b1 - b, which gives the signs. If i∗i^* is the only maximizer, every i∈Sk1−bi \in S_k^{1-b} has di<di∗d_i < d_{i^*}, and since the set is finite the maximum over it is also smaller. Without priors, did_i is largest exactly where ∣y−hai∣2|y - h a_i|^2 is smallest.

(3) For M=2M = 2, M/2=1M/2 = 1 and the bound of part 1 is 00. For Gray QPSK, the points are a=(sI+jsQ)/2a = (s_I + j s_Q)/\sqrt{2} with sI,sQ∈{±1}s_I, s_Q \in \{\pm 1\}, the bit 0 fixes sIs_I and the bit 1 fixes sQs_Q. Expanding the square, −∣y−ha∣2/N0=c+αsI+βsQ-|y - h a|^2/N_0 = c + \alpha s_I + \beta s_Q with cc the same for all points, α=2 Re(h∗y)/N0\alpha = \sqrt{2}\,\mathrm{Re}(h^* y)/N_0 and β=2 Im(h∗y)/N0\beta = \sqrt{2}\,\mathrm{Im}(h^* y)/N_0; with priors, each bit adds ±Lka/2\pm L^a_k/2, which keeps this form. For the bit 0, both ln⁡∑\ln\sum and max⁡\max over S0bS_0^b equal the term in sIs_I plus the same function of β\beta (a log-sum-exp in one case and a max in the other), and that function cancels in the difference. So L0=L~0=2αL_0 = \tilde L_0 = 2\alpha plus the prior, and in the same way L1=L~1L_1 = \tilde L_1. ■\blacksquare

Proposition (per-axis form for Gray square QAM). Let the points be a=(cI+jcQ)/sa = (c_I + j c_Q)/s with s=2(M−1)/3s = \sqrt{2(M - 1)/3}, where (cI,cQ)(c_I, c_Q) runs over all pairs of raw levels {±1,±3,…,±(M−1)}\{\pm 1, \pm 3, \ldots, \pm(\sqrt{M} - 1)\} and the label is the Gray label of cIc_I followed by that of cQc_Q. Put z=y/hz = y/h, u=s Re zu = s\,\mathrm{Re}\,z, v=s Im zv = s\,\mathrm{Im}\,z. Without priors, for an in-phase bit kk,

L~k=∣h∣2s2N0(min⁡cI: bk=1(u−cI)2−min⁡cI: bk=0(u−cI)2),\tilde L_k = \frac{|h|^2}{s^2 N_0}\Big(\min_{c_I:\, b_k = 1}(u - c_I)^2 - \min_{c_I:\, b_k = 0}(u - c_I)^2\Big),

and the same holds for a quadrature bit with vv and cQc_Q.

Proof. y−ha=h(z−a)y - h a = h(z - a), so ∣y−ha∣2=∣h∣2∣z−a∣2=(∣h∣2/s2)((u−cI)2+(v−cQ)2)|y - h a|^2 = |h|^2|z - a|^2 = (|h|^2/s^2)\big((u - c_I)^2 + (v - c_Q)^2\big). An in-phase bit depends only on cIc_I, and the set of points is the full product of the levels, so

min⁡Skb∣y−ha∣2=∣h∣2s2(min⁡cI: bk=b(u−cI)2+min⁡cQ(v−cQ)2).\min_{S_k^b}|y - h a|^2 = \frac{|h|^2}{s^2}\Big(\min_{c_I:\, b_k = b}(u - c_I)^2 + \min_{c_Q}(v - c_Q)^2\Big).

The second term is the same for b=0b = 0 and b=1b = 1 and cancels in Lemma 2. □\square

Corollary (16-QAM). With the in-phase levels +3,+1,−1,−3+3, +1, -1, -3 labeled 00,01,11,1000, 01, 11, 10, the first bit is 00 on {+3,+1}\{+3, +1\} and the second bit is 00 on {+3,−3}\{+3, -3\}. For u≥0u \ge 0, the nearest level with the first bit 11 is −1-1, and the nearest with the first bit 00 is +1+1 if u≤2u \le 2 and +3+3 if u>2u > 2. So the bracket is (u+1)2−(u−1)2=4u(u + 1)^2 - (u - 1)^2 = 4u or (u+1)2−(u−3)2=8(u−1)(u + 1)^2 - (u - 3)^2 = 8(u - 1). For the second bit and u≥0u \ge 0, the nearest levels are +1+1 (bit 11) and +3+3 (bit 00), and the bracket is (u−1)2−(u−3)2=4(u−2)(u - 1)^2 - (u - 3)^2 = 4(u - 2). For u<0u < 0 the same follows by the symmetry u↦−uu \mapsto -u, which swaps +c+c and −c-c; it changes the sign of the first bracket and keeps the second. With s2=10s^2 = 10 this is the closed form on the page. □\square

Cost. Line L2 runs MM times, with mm extra terms each when there are priors, and line L6 runs mMmM times, each a constant number of operations. The total is Θ(Mlog⁡M)\Theta(M \log M) per symbol with Θ(M)\Theta(M) extra space. The per-axis form scans M\sqrt{M} levels for each of the mm bits, Θ(Mlog⁡M)\Theta(\sqrt{M}\log M).

Complexity

In the real RAM, lines L1 and L2 cost Θ(M)\Theta(M) without priors and Θ(Mm)\Theta(M m) with them, and lines L3 to L7 do mMmM comparisons. The total is Θ(Mlog⁡M)\Theta(M \log M) per symbol with Θ(M)\Theta(M) extra space; the work is the same as for the exact demapper, but each step is a comparison, not an exp⁡\exp and a ln⁡\ln. For Gray square QAM the per-axis form costs Θ(Mlog⁡M)\Theta(\sqrt{M}\log M) in general and O(log⁡M)O(\log M) with closed forms such as the one for 16-QAM. With a decision region search, the nearest point with each bit value can be found without visiting all points.

Properties

  • No noise level needed for the decoder. Without priors, every L~k\tilde L_k is the same function of yy times 1/N01/N_0. A min-sum decoder, a Viterbi decoder or a max-log BCJR decoder gives the same output for any positive scale of its inputs, so the receiver can skip N0N_0 and pass the distance differences.
  • Hard decisions are ML decisions. The signs of L~0,…,L~m−1\tilde L_0, \ldots, \tilde L_{m-1} are the label of the nearest point.
  • Error bound. ∣Lk−L~k∣≤ln⁡(M/2)|L_k - \tilde L_k| \le \ln(M/2), which is ln⁡8=2.079\ln 8 = 2.079 for 16-QAM. The bound is approached only when the terms of one sum are nearly equal and those of the other are not, as at low SNR. At high SNR the second largest term of each sum is usually much smaller than the largest, and the error is small, except near the boundary between two points with the same bit value.
  • Exact for BPSK and QPSK. For BPSK each sum has one term. For Gray QPSK, each sum has two terms that differ by the same factor in the numerator and the denominator, and the factor cancels. In both cases L~k=Lk\tilde L_k = L_k.
  • Piecewise linear. Each L~k\tilde L_k is piecewise linear in the real and imaginary parts of yy, with breaks where the nearest point with a bit value changes.
  • Biased at low SNR. In the example at N0=1N_0 = 1, L~1=−0.17\tilde L_1 = -0.17 while L1=−0.45L_1 = -0.45. The magnitudes can be too small or too large, so a fixed scaling does not remove the error.

Variants and improvements

  • Exact demapping. Replace max⁡\max by max⁡∗\max^*: soft demapping.
  • Max-log with a correction. Add a table value of ln⁡(1+e−∣u−v∣)\ln(1 + e^{-|u - v|}) in line L6 only when the two terms are close. This recovers most of the loss at a small cost.
  • Scaled max-log. Multiply the LLRs by a constant factor, tuned by simulation for the decoder and the SNR range. It reduces the average error but cannot remove it.
  • Per-axis closed forms for QAM. For Gray MM-QAM each bit is a piecewise linear function of one axis, with closed forms like the 16-QAM one above. OFDM receivers use them per subcarrier.
  • MIMO. For a vector channel, max-log needs the nearest vector with each bit value; a list sphere decoder or a tree search finds it without visiting all MnM^n vectors.

When to use it

Use max-log when the decoder is a min-sum decoder or a max-log BCJR decoder, when N0N_0 is unknown or hard to estimate, and when cost or latency matters, as in hardware for Wi-Fi, LTE and DVB. Use the exact demapper at low SNR with large constellations, and in iterative receivers, where the extrinsic values must be accurate.

Pitfalls

  • A sum-product decoder expects exact LLRs. A sum-product LDPC decoder assumes exact LLRs. With max-log inputs it still works but loses a fraction of a dB, more at low rates and with large constellations.
  • Scale. If the receiver drops 1/N01/N_0, the decoder must also be scale invariant. A sum-product decoder fed with unscaled distances is wrong.
  • Ties. On a decision boundary L~k=0\tilde L_k = 0, and the hard decision is arbitrary. It has probability zero but occurs with quantized inputs; break ties in a fixed way.
  • Closed forms depend on the labeling. The 16-QAM formulas above hold for the area labels (in-phase bits first, Gray per axis). A different labeling or bit order needs different formulas.
  • The gain. The per-axis forms need z=y/hz = y/h and the factor ∣h∣2|h|^2. Dropping ∣h∣2|h|^2 on a fading channel gives the same weight to faded and strong symbols, which hurts the decoder.

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.

constel.pyI0RawGitHub
# 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))
max_log_demapping.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/max-log-demapping/. The authors are listed in prov/BTM11T.jsonl.

"""Max-log demapping: approximate bit log-likelihood ratios without exponentials.

The model is y = h x + w with w ~ CN(0, N0), a known gain h and x one of the
M points of a constellation. points[i] is the point with the bit label i, and
bit k of the label (k = 0 is the most significant bit) is (i >> (m - 1 - k)) & 1
with m = log2 M, as in constel.py. The max-log LLR of bit k is

    L_k = max_{b_k(i) = 0} d_i - max_{b_k(i) = 1} d_i,
    d_i = -|y - h a_i|^2 / N0 + sum_k (1 - 2 b_k(i)) la_k / 2,

which without priors is (min over bit 1 of |y - h a|^2 - min over bit 0) / N0.
A positive value favors the bit 0.
"""

import math


def label_bit(i: int, k: int, m: int) -> int:
    """Bit k (most significant first) of the m-bit label i."""
    return (i >> (m - 1 - k)) & 1


def _check(points: list[complex], n0: float) -> int:
    big_m = len(points)
    if big_m < 2 or big_m & (big_m - 1):
        raise ValueError("the number of points must be a power of two")
    if n0 <= 0:
        raise ValueError("N0 must be positive")
    return big_m.bit_length() - 1


def max_log_demap(y: complex, points: list[complex], n0: float, h: complex = 1, la: list[float] | None = None) -> list[float]:
    """The max-log LLRs L_0, ..., L_{m-1} of the bits of one symbol."""
    m = _check(points, n0)
    d = []
    for i, a in enumerate(points):  # @line L1
        di = -abs(y - h * a) ** 2 / n0  # @line L2
        if la is not None:
            di += sum((1 - 2 * label_bit(i, k, m)) * la[k] / 2.0 for k in range(m))
        d.append(di)
    out = []
    for k in range(m):  # @line L3
        best = [-math.inf, -math.inf]  # @line L4
        for i in range(len(points)):  # @line L5
            b = label_bit(i, k, m)
            if d[i] > best[b]:
                best[b] = d[i]  # @line L6
        out.append(best[0] - best[1])  # @line L7
    return out


def max_log_extrinsic(y: complex, points: list[complex], n0: float, h: complex = 1, la: list[float] | None = None) -> list[float]:
    """The extrinsic values L_k - la_k of the max-log demapper."""
    post = max_log_demap(y, points, n0, h, la)
    if la is None:
        return post
    return [p - a for p, a in zip(post, la)]  # @line L8


def _gray_inv(g: int) -> int:
    n = 0
    while g:
        n ^= g
        g >>= 1
    return n


def _axis(u: float, side: int) -> list[float]:
    """Per-axis max-log values (min over bit 1 of (u - c)^2 minus min over bit 0) on Gray side-PAM.

    The level with label lab has the raw amplitude side - 1 - 2 gray^-1(lab).
    """
    q = side.bit_length() - 1
    best = [[math.inf, math.inf] for _ in range(q)]
    for lab in range(side):
        c = side - 1 - 2 * _gray_inv(lab)
        dist = (u - c) ** 2
        for k in range(q):
            b = label_bit(lab, k, q)
            if dist < best[k][b]:
                best[k][b] = dist
    return [b1 - b0 for b0, b1 in best]


def max_log_square_qam(y: complex, big_m: int, n0: float, h: complex = 1) -> list[float]:
    """Max-log LLRs for Gray square M-QAM (as constel.qam), one axis at a time in O(sqrt(M) log M)."""
    q2 = big_m.bit_length() - 1
    if big_m < 4 or big_m & (big_m - 1) or q2 % 2:
        raise ValueError("square QAM needs M = 4^k")
    if n0 <= 0:
        raise ValueError("N0 must be positive")
    if h == 0:
        raise ValueError("the gain must be nonzero")
    side = 1 << (q2 // 2)
    s2 = 2.0 * (big_m - 1) / 3.0
    z = y / h
    s = math.sqrt(s2)
    scale = abs(h) ** 2 / (s2 * n0)
    return [scale * v for v in _axis(s * z.real, side) + _axis(s * z.imag, side)]


def max_log_16qam_closed_form(y: complex, n0: float, h: complex = 1) -> list[float]:
    """The closed form for Gray 16-QAM: per axis with u = sqrt(10) Re(y / h) (and the same for Im),
    Lambda_0 = 4u if |u| <= 2 else 8(u - sign u), Lambda_1 = 4(|u| - 2), and L = |h|^2 Lambda / (10 N0)."""
    if n0 <= 0:
        raise ValueError("N0 must be positive")
    z = y / h
    scale = abs(h) ** 2 / (10.0 * n0)
    out0, out1 = [], []
    for u in (math.sqrt(10.0) * z.real, math.sqrt(10.0) * z.imag):
        if abs(u) <= 2.0:
            lam0 = 4.0 * u
        else:
            lam0 = 8.0 * (u - math.copysign(1.0, u))
        out0.append(lam0)
        out1.append(4.0 * (abs(u) - 2.0))
    return [scale * out0[0], scale * out1[0], scale * out0[1], scale * out1[1]]
test_max_log_demapping.py 181 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/max-log-demapping/. The authors are listed in prov/BTM11T.jsonl.

import math
import random
import unittest

import constel
from max_log_demapping import max_log_16qam_closed_form, max_log_demap, max_log_extrinsic, max_log_square_qam


def brute_max(y, points, n0, h=1, la=None):
    """The max form by brute force: the best metric with bit 0 minus the best with bit 1."""
    m = len(points).bit_length() - 1
    d = []
    for i, a in enumerate(points):
        v = -abs(y - h * a) ** 2 / n0
        if la is not None:
            v += sum((1 - 2 * constel.bits(i, m)[k]) * la[k] / 2.0 for k in range(m))
        d.append(v)
    out = []
    for k in range(m):
        b0 = max(d[i] for i in range(len(points)) if constel.bits(i, m)[k] == 0)
        b1 = max(d[i] for i in range(len(points)) if constel.bits(i, m)[k] == 1)
        out.append(b0 - b1)
    return out


def min_distance_form(y, points, n0, h=1):
    """(min over bit 1 of |y - h a|^2 - min over bit 0 of |y - h a|^2) / N0."""
    m = len(points).bit_length() - 1
    out = []
    for k in range(m):
        d0 = min(abs(y - h * a) ** 2 for i, a in enumerate(points) if constel.bits(i, m)[k] == 0)
        d1 = min(abs(y - h * a) ** 2 for i, a in enumerate(points) if constel.bits(i, m)[k] == 1)
        out.append((d1 - d0) / n0)
    return out


def exact_llr(y, points, n0, h=1):
    """The exact LLRs as a log-sum-exp over all points."""
    m = len(points).bit_length() - 1
    d = [-abs(y - h * a) ** 2 / n0 for a in points]
    out = []
    for k in range(m):
        acc = []
        for b in (0, 1):
            vals = [d[i] for i in range(len(points)) if constel.bits(i, m)[k] == b]
            top = max(vals)
            acc.append(top + math.log(sum(math.exp(v - top) for v in vals)))
        out.append(acc[0] - acc[1])
    return out


CONSTELLATIONS = {
    "bpsk": constel.pam(2),
    "4pam": constel.pam(4),
    "8pam": constel.pam(8),
    "qpsk": constel.qam(4),
    "8psk": constel.psk(8),
    "16psk": constel.psk(16, math.pi / 16),
    "16qam": constel.qam(16),
    "64qam": constel.qam(64),
}


def sample(rng, pts):
    h = complex(rng.gauss(0, 1), rng.gauss(0, 1))
    n0 = 10 ** rng.uniform(-2.5, 0.5)
    x = pts[rng.randrange(len(pts))]
    y = h * x + complex(rng.gauss(0, 1), rng.gauss(0, 1)) * math.sqrt(n0 / 2)
    return y, n0, h


class TestMaxLogDemapping(unittest.TestCase):
    def test_equals_max_form_exactly(self):
        rng = random.Random(20261120)
        for name, pts in CONSTELLATIONS.items():
            for _ in range(60):
                y, n0, h = sample(rng, pts)
                self.assertEqual(max_log_demap(y, pts, n0, h), brute_max(y, pts, n0, h), name)

    def test_min_distance_form(self):
        rng = random.Random(3)
        for name, pts in CONSTELLATIONS.items():
            for _ in range(40):
                y, n0, h = sample(rng, pts)
                for g, r in zip(max_log_demap(y, pts, n0, h), min_distance_form(y, pts, n0, h)):
                    self.assertLess(abs(g - r), 1e-9 * max(1.0, abs(r)), name)

    def test_bound_against_exact(self):
        rng = random.Random(5)
        for name, pts in CONSTELLATIONS.items():
            bound = math.log(len(pts) / 2)
            for _ in range(60):
                y, n0, h = sample(rng, pts)
                for g, r in zip(max_log_demap(y, pts, n0, h), exact_llr(y, pts, n0, h)):
                    self.assertLessEqual(abs(g - r), bound + 1e-9, name)

    def test_equal_to_exact_for_bpsk_and_qpsk(self):
        rng = random.Random(6)
        for name in ("bpsk", "qpsk"):
            pts = CONSTELLATIONS[name]
            for _ in range(100):
                y, n0, h = sample(rng, pts)
                for g, r in zip(max_log_demap(y, pts, n0, h), exact_llr(y, pts, n0, h)):
                    self.assertLess(abs(g - r), 1e-9 * max(1.0, abs(r)), name)

    def test_scales_with_one_over_n0(self):
        rng = random.Random(8)
        pts = CONSTELLATIONS["16qam"]
        for _ in range(50):
            y = complex(rng.gauss(0, 1), rng.gauss(0, 1))
            a = max_log_demap(y, pts, 1.0)
            b = max_log_demap(y, pts, 0.01)
            for u, v in zip(a, b):
                self.assertLess(abs(100.0 * u - v), 1e-9 * max(1.0, abs(v)))

    def test_signs_give_ml_bits(self):
        rng = random.Random(9)
        for name, pts in CONSTELLATIONS.items():
            m = len(pts).bit_length() - 1
            for _ in range(60):
                y, n0, h = sample(rng, pts)
                ml = constel.bits(constel.ml_detect(y, pts, h), m)
                llr = max_log_demap(y, pts, n0, h)
                self.assertEqual([1 if v < 0 else 0 for v in llr], ml, name)

    def test_square_qam_per_axis(self):
        rng = random.Random(10)
        for big_m in (4, 16, 64, 256):
            pts = constel.qam(big_m)
            for _ in range(40):
                y, n0, h = sample(rng, pts)
                for g, r in zip(max_log_square_qam(y, big_m, n0, h), max_log_demap(y, pts, n0, h)):
                    self.assertLess(abs(g - r), 1e-9 * max(1.0, abs(r)), big_m)

    def test_16qam_closed_form(self):
        rng = random.Random(11)
        pts = constel.qam(16)
        for _ in range(300):
            y, n0, h = sample(rng, pts)
            for g, r in zip(max_log_16qam_closed_form(y, n0, h), max_log_demap(y, pts, n0, h)):
                self.assertLess(abs(g - r), 1e-9 * max(1.0, abs(r)))

    def test_page_example(self):
        pts = constel.qam(16)
        y = 0.5 - 0.2j
        for g, r in zip(max_log_demap(y, pts, 0.1), [6.3246, -1.6754, -2.5298, -5.4702]):
            self.assertAlmostEqual(g, r, delta=1e-4)
        for g, r in zip(exact_llr(y, pts, 0.1), [6.4962, -1.6772, -2.5340, -5.5463]):
            self.assertAlmostEqual(g, r, delta=1e-4)
        for g, r in zip(max_log_demap(y, pts, 1.0), [0.6325, -0.1675, -0.2530, -0.5470]):
            self.assertAlmostEqual(g, r, delta=1e-4)

    def test_priors_and_extrinsic(self):
        rng = random.Random(12)
        for name in ("8psk", "16qam", "64qam"):
            pts = CONSTELLATIONS[name]
            m = len(pts).bit_length() - 1
            for _ in range(40):
                la = [rng.uniform(-6, 6) for _ in range(m)]
                y, n0, h = sample(rng, pts)
                got = max_log_demap(y, pts, n0, h, la)
                self.assertEqual(got, brute_max(y, pts, n0, h, la), name)
                ext = max_log_extrinsic(y, pts, n0, h, la)
                for e, g, a in zip(ext, got, la):
                    self.assertAlmostEqual(e, g - a, delta=1e-12)

    def test_errors(self):
        pts = constel.qam(16)
        with self.assertRaises(ValueError):
            max_log_demap(0.1, pts[:3], 0.3)
        with self.assertRaises(ValueError):
            max_log_demap(0.1, pts, 0.0)
        with self.assertRaises(ValueError):
            max_log_square_qam(0.1, 8, 0.3)


if __name__ == "__main__":
    unittest.main()

History

The max approximation of a sum of exponentials is old; in decoding it appears as the Viterbi metric and as the max-log form of the BCJR algorithm. For bit metrics of a multilevel constellation, Zehavi in 1992 decoded bit-interleaved 8-PSK trellis codes on the Rayleigh channel with a metric per bit of this form, and Caire, Taricco and Biglieri in 1998 gave the theory of bit-interleaved coded modulation with both the exact and the simplified metrics. With LDPC and turbo codes in Wi-Fi, LTE and DVB, the max-log demapper with per-axis closed forms became the common choice in hardware.

References

  1. Ephraim Zehavi, 8-PSK trellis codes for a Rayleigh channel, IEEE Transactions on Communications 40(5), 873-884, 1992, the bit interleaver and the bit metrics of the decoder
  2. Giuseppe Caire, Giorgio Taricco and Ezio Biglieri, Bit-interleaved coded modulation, IEEE Transactions on Information Theory 44(3), 927-946, 1998, the bit metrics of BICM and their simplified form

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
  • at least three sources
  • a scene preset for the example