Algorithm Search⌘K

Algorithmcore

Soft demapping

Also called soft-output demapper, bit LLR computation.

Computes the exact log-likelihood ratio of each bit of a received symbol as a log-sum-exp over all constellation points, with optional prior LLRs from a decoder.

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 priorsdeterministicexactneeds noise level
Origin
Giuseppe Caire, Giorgio Taricco, Ezio Biglieri, 1998

Soft demapping computes, for each bit of a received symbol, the log-likelihood ratio (LLR): the log of the ratio of the probability that the bit is 00 to the probability that it is 11, given the received sample. Its sign is the hard decision and its size is the reliability. A soft-input decoder for an LDPC code, a turbo code or a convolutional code with the BCJR algorithm needs these values, and in bit-interleaved coded modulation the demapper is the link between the channel and the binary decoder. The exact LLR is a log-sum-exp over all MM points of the constellation. Max-log demapping keeps only the largest term of each sum, which is simpler but not exact; this page is the exact form. With prior LLRs from a decoder, the same algorithm is the demapper of iterative receivers and of turbo equalization.

In plain words

The receiver gets a point that noise has moved. Each possible transmitted point gets a score that says how likely it is to have produced what was received: near points get high scores, far points get low ones. For the first bit, the receiver adds the scores of all points whose first bit is 0, and separately the scores of all points whose first bit is 1. The log of the ratio of the two totals says how sure it is about that bit, and in which direction. It does the same for every bit. Adding all the scores, and not only the best one, is what makes the answer exact.

The problem

The receiver sees one complex sample after the matched filter:

y=hx+w,x∈{a0,…,aM−1},w∼CN(0,N0).y = h x + w, \qquad x \in \{a_0, \ldots, a_{M-1}\}, \qquad w \sim \mathcal{CN}(0, N_0).

The gain h≠0h \ne 0 and the noise density N0>0N_0 > 0 are known; hh includes the amplitude Es\sqrt{E_s}, and Es/N0=∣h∣2/N0E_s/N_0 = |h|^2/N_0 is the SNR per complex symbol. The point aia_i carries the bit label ii with m=log⁡2Mm = \log_2 M bits b0(i),…,bm−1(i)b_0(i), \ldots, b_{m-1}(i), most significant bit first. A priori the bits are independent, with prior LLRs Lka=ln⁡P(bk=0)/P(bk=1)L^a_k = \ln P(b_k = 0)/P(b_k = 1), all zero for equally likely points. The output is the a posteriori LLR of each bit,

Lk=ln⁡P(bk=0∣y)P(bk=1∣y)=ln⁡∑i: bk(i)=0p(y∣ai) P(ai)∑i: bk(i)=1p(y∣ai) P(ai),k=0,…,m−1,L_k = \ln\frac{P(b_k = 0 \mid y)}{P(b_k = 1 \mid y)} = \ln\frac{\sum_{i:\, b_k(i) = 0} p(y \mid a_i)\, P(a_i)}{\sum_{i:\, b_k(i) = 1} p(y \mid a_i)\, P(a_i)}, \qquad k = 0, \ldots, m-1,

and the extrinsic LLR Lke=Lk−LkaL^e_k = L_k - L^a_k. A positive value favors the bit 00. This is symbol-by-symbol MAP decoding of the bits of one symbol.

The algorithm

The density is p(y∣ai)=1πN0e−∣y−hai∣2/N0p(y \mid a_i) = \frac{1}{\pi N_0}e^{-|y - h a_i|^2/N_0}, and a bit with prior LLR LaL^a has P(b)∝e(1−2b)La/2P(b) \propto e^{(1 - 2b)L^a/2}. So each point gets the log metric did_i of line L2, and each sum in LkL_k is a log-sum-exp of these metrics. The algorithm folds each sum with the Jacobian logarithm

max⁡∗(u,v)=ln⁡(eu+ev)=max⁡(u,v)+ln⁡(1+e−∣u−v∣),\max{}^*(u, v) = \ln(e^u + e^v) = \max(u, v) + \ln\big(1 + e^{-|u - v|}\big),

which never overflows (see the log-sum-exp trick).

  1. SOFT-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. 4A_0 ← -∞ ; A_1 ← -∞
  6. 5for i ← 0 to M - 1
  7. 6A_{b_k(i)} ← max*(A_{b_k(i)}, d_i)
  8. 7L_k ← A_0 - A_1
  9. 8return L_0..L_{m-1} and the extrinsic values E_k ← L_k - La_k

The constant −ln⁡(πN0)-\ln(\pi N_0) and the normalizers of the priors are the same for every point, so line L2 leaves them out; they cancel in line L7.

Example

16-QAM at a high SNR. Take the Gray-labeled 16-QAM of the area, h=1h = 1, N0=0.1N_0 = 0.1 (an SNR of 1010 dB), no priors, and y=0.5−0.2jy = 0.5 - 0.2j. The nearest point is a7=(1−j)/10a_7 = (1 - j)/\sqrt{10}, label 0111, with d7=−0.4728d_7 = -0.4728. The folds of lines L4 to L7 give:

bit kk A0A_0 A1A_1 LkL_k best point with bk=0b_k = 0 best point with bk=1b_k = 1
0 −0.2206-0.2206 −6.7168-6.7168 6.49626.4962 a7a_7, d=−0.4728d = -0.4728 a15a_{15}, d=−6.7974d = -6.7974
1 −2.0677-2.0677 −0.3905-0.3905 −1.6772-1.6772 a3a_3, d=−2.1483d = -2.1483 a7a_7
2 −2.8295-2.8295 −0.2955-0.2955 −2.5340-2.5340 a5a_5, d=−3.0026d = -3.0026 a7a_7
3 −5.7694-5.7694 −0.2230-0.2230 −5.5463-5.5463 a6a_6, d=−5.9430d = -5.9430 a7a_7

The signs give the bits 0111, the decision of the minimum distance detector. Bit 0, the sign of the in-phase component, is the most reliable; bit 1, which separates the inner from the outer in-phase levels, is the least reliable, because 10 Re y=1.58\sqrt{10}\,\mathrm{Re}\,y = 1.58 is close to the boundary at 22. Max-log demapping gives 6.3246,−1.6754,−2.5298,−5.47026.3246, -1.6754, -2.5298, -5.4702, close to these values.

16-QAM at a low SNR. With N0=1N_0 = 1 and the same yy, the exact LLRs are 1.0313,−0.4539,−0.4103,−0.73761.0313, -0.4539, -0.4103, -0.7376 and the max-log values 0.6325,−0.1675,−0.2530,−0.54700.6325, -0.1675, -0.2530, -0.5470. At low SNR many points contribute to each sum, and the maximum alone is far from the total.

A prior. With N0=0.1N_0 = 0.1 and a prior L2a=−3L^a_2 = -3 on bit 2 only, the output is 6.4962,−1.6772,−5.5340,−5.47416.4962, -1.6772, -5.5340, -5.4741. The prior moves L2L_2 by −3-3, and it also changes L3L_3 a little, because it reweights the points that both sums share. The extrinsic value of bit 2 is −5.5340+3=−2.5340-5.5340 + 3 = -2.5340, the value without the prior.

Correctness

Line L2 gives each point di=ln⁡(p(y∣ai)P(ai))+Cd_i = \ln\big(p(y \mid a_i)P(a_i)\big) + C, where CC does not depend on ii. Lines L4 to L6 keep the invariant that after the points a0,…,ai−1a_0, \ldots, a_{i-1}, AbA_b is the log of the sum of edi′e^{d_{i'}} over the points seen so far with bk(i′)=bb_k(i') = b, because max⁡∗(u,v)=ln⁡(eu+ev)\max^*(u, v) = \ln(e^u + e^v) and max⁡∗(−∞,v)=v\max^*(-\infty, v) = v. At the end the two sums are complete, the constant CC cancels in line L7, and LkL_k is the a posteriori LLR. For the extrinsic value, the prior term of bit kk is the same for all points in each sum, so it moves A0A_0 by +Lka/2+L^a_k/2 and A1A_1 by −Lka/2-L^a_k/2; the difference Lk−LkaL_k - L^a_k is the LLR without the prior of bit kk. The full proof is below.

Proof: SOFT-DEMAP returns the a posteriori LLR of each bit and its extrinsic partfull

The model is 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), and xx one of the points a0,…,aM−1a_0, \ldots, a_{M-1}, M=2mM = 2^m. The point aia_i carries the label ii with bits b0(i),…,bm−1(i)b_0(i), \ldots, b_{m-1}(i). The label bits are independent a priori, with P(bk=0)=pk∈(0,1)P(b_k = 0) = p_k \in (0, 1) and Lka=ln⁡(pk/(1−pk))L^a_k = \ln\big(p_k/(1 - p_k)\big); equal priors are the case Lka=0L^a_k = 0 for all kk.

Lemma 1 (the metric). For each ii, did_i of line L2 satisfies di=ln⁡(p(y∣ai) P(x=ai))+Cd_i = \ln\big(p(y \mid a_i)\, P(x = a_i)\big) + C, where CC does not depend on ii.

Proof. The density of yy given x=aix = a_i is 1πN0exp⁡(−∣y−hai∣2/N0)\frac{1}{\pi N_0}\exp(-|y - h a_i|^2/N_0), a circularly symmetric complex Gaussian with mean haih a_i. Since the label map i↦(b0(i),…,bm−1(i))i \mapsto (b_0(i), \ldots, b_{m-1}(i)) is a bijection onto {0,1}m\{0, 1\}^m and the bits are independent, P(x=ai)=∏kP(bk=bk(i))P(x = a_i) = \prod_k P(b_k = b_k(i)). For one bit, pk=eLka/2/(eLka/2+e−Lka/2)p_k = e^{L^a_k/2}/(e^{L^a_k/2} + e^{-L^a_k/2}) and 1−pk=e−Lka/2/(eLka/2+e−Lka/2)1 - p_k = e^{-L^a_k/2}/(e^{L^a_k/2} + e^{-L^a_k/2}), so P(bk=b)=e(1−2b)Lka/2/ZkP(b_k = b) = e^{(1 - 2b)L^a_k/2}/Z_k with Zk=eLka/2+e−Lka/2Z_k = e^{L^a_k/2} + e^{-L^a_k/2} for both values of bb. Taking logs,

ln⁡(p(y∣ai) P(x=ai))=−∣y−hai∣2N0+∑k(1−2bk(i))Lka2−ln⁡(πN0)−∑kln⁡Zk,\ln\big(p(y \mid a_i)\,P(x = a_i)\big) = -\frac{|y - h a_i|^2}{N_0} + \sum_k \frac{(1 - 2b_k(i))L^a_k}{2} - \ln(\pi N_0) - \sum_k \ln Z_k,

and the last two terms form the constant −C-C. □\square

Lemma 2 (max⁡∗\max^*). For real u,vu, v, max⁡∗(u,v)=max⁡(u,v)+ln⁡(1+e−∣u−v∣)=ln⁡(eu+ev)\max^*(u, v) = \max(u, v) + \ln(1 + e^{-|u - v|}) = \ln(e^u + e^v). With the convention e−∞=0e^{-\infty} = 0, max⁡∗(−∞,v)=v=ln⁡(0+ev)\max^*(-\infty, v) = v = \ln(0 + e^v).

Proof. Let u≥vu \ge v without loss of generality. Then ln⁡(eu+ev)=ln⁡(eu(1+ev−u))=u+ln⁡(1+e−∣u−v∣)\ln(e^u + e^v) = \ln\big(e^u(1 + e^{v - u})\big) = u + \ln(1 + e^{-|u - v|}). The second claim is the definition used in line L6 for the first term of each sum. □\square

Lemma 3 (the fold). Fix kk. After line L6 has run for the points a0,…,at−1a_0, \ldots, a_{t-1}, for b∈{0,1}b \in \{0, 1\},

Ab=ln⁡∑i<t, bk(i)=bedi,A_b = \ln \sum_{i < t,\ b_k(i) = b} e^{d_i},

with the empty sum giving −∞-\infty.

Proof. By induction on tt. For t=0t = 0 both sums are empty and line L4 sets A0=A1=−∞A_0 = A_1 = -\infty. Step t→t+1t \to t + 1: let b=bk(t)b = b_k(t). Line L6 changes only AbA_b, to max⁡∗(Ab,dt)\max^*(A_b, d_t), which by Lemma 2 and the hypothesis is ln⁡(∑i<t, bk(i)=bedi+edt)\ln\big(\sum_{i < t,\ b_k(i) = b} e^{d_i} + e^{d_t}\big), the sum over i<t+1i < t + 1. The other accumulator keeps its value, and its sum gains no term. □\square

Theorem. For every kk, line L7 returns Lk=ln⁡P(bk=0∣y)/P(bk=1∣y)L_k = \ln P(b_k = 0 \mid y)/P(b_k = 1 \mid y), and line L8 returns Ek=Lk−LkaE_k = L_k - L^a_k, which equals

Ek=ln⁡∑i: bk(i)=0p(y∣ai)∏k′≠kP(bk′=bk′(i))∑i: bk(i)=1p(y∣ai)∏k′≠kP(bk′=bk′(i)),E_k = \ln\frac{\sum_{i:\, b_k(i) = 0} p(y \mid a_i) \prod_{k' \ne k} P(b_{k'} = b_{k'}(i))}{\sum_{i:\, b_k(i) = 1} p(y \mid a_i) \prod_{k' \ne k} P(b_{k'} = b_{k'}(i))},

the LLR of bit kk computed with the priors of all bits except kk.

Proof. Each label ii has bk(i)=0b_k(i) = 0 or bk(i)=1b_k(i) = 1, and both values occur, since the labels are all of {0,1}m\{0, 1\}^m. So after the loop of line L5 has seen all MM points, Lemma 3 gives two nonempty sums, and A0,A1A_0, A_1 are finite. By Lemma 1,

A0−A1=ln⁡∑bk(i)=0eCp(y∣ai)P(ai)∑bk(i)=1eCp(y∣ai)P(ai)=ln⁡p(y, bk=0)p(y, bk=1)=ln⁡P(bk=0∣y)P(bk=1∣y),A_0 - A_1 = \ln\frac{\sum_{b_k(i) = 0} e^{C} p(y \mid a_i) P(a_i)}{\sum_{b_k(i) = 1} e^{C} p(y \mid a_i) P(a_i)} = \ln\frac{p(y,\ b_k = 0)}{p(y,\ b_k = 1)} = \ln\frac{P(b_k = 0 \mid y)}{P(b_k = 1 \mid y)},

where the factor eCe^C cancels and the last step divides the numerator and the denominator by p(y)>0p(y) > 0.

For the extrinsic value, the factor P(bk=bk(i))P(b_k = b_k(i)) is pkp_k for every term of the numerator and 1−pk1 - p_k for every term of the denominator. Taking these factors out of the two sums gives

Lk=ln⁡pk1−pk+Ek=Lka+Ek,L_k = \ln\frac{p_k}{1 - p_k} + E_k = L^a_k + E_k,

with EkE_k as in the statement. So Lk−Lka=EkL_k - L^a_k = E_k. ■\blacksquare

Special cases. For BPSK with the label 0 on +1+1 and 1 on −1-1, the theorem gives L=(−∣y−h∣2+∣y+h∣2)/N0=4 Re(h∗y)/N0L = \big(-|y - h|^2 + |y + h|^2\big)/N_0 = 4\,\mathrm{Re}(h^* y)/N_0, and E=L−LaE = L - L^a does not depend on the prior, since there are no other bits. For Gray QPSK with the points a=(sI+jsQ)/2a = (s_I + j s_Q)/\sqrt{2}, sI,sQ∈{±1}s_I, s_Q \in \{\pm 1\}, the metric is −∣y−ha∣2/N0=c+2(sI Re(h∗y)+sQ Im(h∗y))/N0-|y - h a|^2/N_0 = c + \sqrt{2}\big(s_I\,\mathrm{Re}(h^* y) + s_Q\,\mathrm{Im}(h^* y)\big)/N_0, where cc is the same for all four points. Each sum in the theorem then factors into a term in sIs_I times a term in sQs_Q; the bit 0 fixes sIs_I, the sQs_Q factor cancels, and L0=22 Re(h∗y)/N0L_0 = 2\sqrt{2}\,\mathrm{Re}(h^* y)/N_0. In the same way L1=22 Im(h∗y)/N0L_1 = 2\sqrt{2}\,\mathrm{Im}(h^* y)/N_0.

Cost. Line L2 runs MM times, with mm extra terms each when there are priors, and line L6 runs mMmM times. Each is a constant number of arithmetic operations, exp⁡\exp and ln⁡\ln, so the total is Θ(Mlog⁡M)\Theta(M \log M) per symbol, with Θ(M)\Theta(M) extra space for the metrics.

Complexity

In the real RAM with exp⁡\exp and ln⁡\ln as unit-cost operations, lines L1 and L2 cost Θ(M)\Theta(M) without priors and Θ(Mm)\Theta(M m) with them, and lines L3 to L7 do mMm M evaluations of max⁡∗\max^*. The total is Θ(Mlog⁡M)\Theta(M \log M) per symbol and the extra space is Θ(M)\Theta(M) for the metrics. For a general constellation every point can be the dominant term, so an exact demapper must read all MM points. For square QAM with h≠0h \ne 0, the in-phase bits depend only on Re(y/h)\mathrm{Re}(y/h) and the quadrature bits only on Im(y/h)\mathrm{Im}(y/h), so two one-dimensional demappers on M\sqrt{M} levels each give the same LLRs in Θ(Mlog⁡M)\Theta(\sqrt{M}\log M).

Properties

  • Exact. The output is the a posteriori LLR, not an approximation. Its error is only floating-point rounding.
  • Needs N0N_0. The LLR is not a function of the distances alone: at a high SNR it is close to the max-log value, which scales with 1/N01/N_0, and at a low SNR it is not. A wrong N0N_0 gives wrong LLRs.
  • Extrinsic output. With priors, line L8 gives the information that the channel adds about each bit, which is what an iterative receiver passes back.
  • The bits of one symbol are dependent. The mm LLRs come from the same yy. A BICM decoder treats them as independent, and the bit interleaver puts them far apart in the code to make this a good approximation.
  • Sign and size. For BPSK, L=4 Re(h∗y)/N0L = 4\,\mathrm{Re}(h^* y)/N_0. For Gray QPSK with the area labels, L0=22 Re(h∗y)/N0L_0 = 2\sqrt{2}\,\mathrm{Re}(h^* y)/N_0 and L1=22 Im(h∗y)/N0L_1 = 2\sqrt{2}\,\mathrm{Im}(h^* y)/N_0. In these two cases the exact and the max-log values agree.

Variants and improvements

  • Max-log. Replace max⁡∗\max^* by max⁡\max: max-log demapping. Its error per bit is at most ln⁡(M/2)\ln(M/2) and goes to zero at high SNR.
  • Correction tables. Hardware often computes ln⁡(1+e−∣u−v∣)\ln(1 + e^{-|u - v|}) from a small table of eight or so entries, or as a piecewise linear function. The result is between the exact and the max-log values.
  • Per-axis demapping for square QAM. Demap Re(y/h)\mathrm{Re}(y/h) and Im(y/h)\mathrm{Im}(y/h) separately on M\sqrt{M}-PAM with the noise density N0/∣h∣2N_0/|h|^2.
  • MIMO and ISI. With a vector channel y=Hx+wy = Hx + w, the sums run over all MnM^n vectors; a list sphere decoder keeps only the vectors near yy. See MIMO detection.
  • Iterative demapping. In BICM with iterative decoding the demapper uses the decoder's LLRs as priors in line L2 and passes the extrinsic values back. With priors, a labeling other than Gray can give a better result after a few iterations.

When to use it

Use the exact demapper in front of any soft-input decoder when the SNR is moderate or low, when the constellation is small enough that MM evaluations are cheap, and always in iterative receivers, where the extrinsic values must be accurate. Use max-log when cost matters and the decoder is a min-sum decoder that ignores the scale of its inputs.

Pitfalls

  • The sign convention. This page uses ln⁡P(0)/P(1)\ln P(0)/P(1), so a positive LLR favors 00. Some decoders use the opposite sign; a mismatch makes the decoder fail completely.
  • The noise level. N0N_0 is the density of the complex noise; each of the real and imaginary parts has variance N0/2N_0/2. Using σ2=N0/2\sigma^2 = N_0/2 in place of N0N_0 doubles every LLR.
  • Underflow. Summing e−∣y−hai∣2/N0e^{-|y - h a_i|^2/N_0} directly underflows at a high SNR, and the ratio becomes 0/00/0. Fold in the log domain with max⁡∗\max^*.
  • The bit order. The label is most significant bit first here. A decoder that expects the other order gets the in-phase and quadrature bits swapped.
  • Posterior or extrinsic. In a turbo loop, passing LkL_k instead of Lk−LkaL_k - L^a_k counts the prior twice, and the loop becomes overconfident.
  • The scale of hh. If the points have unit energy, hh must include Es\sqrt{E_s}; otherwise all distances, and so all LLRs, are wrong.

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))
soft_demapping.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/soft-demapping/. The authors are listed in prov/N96EQ7.jsonl.

"""Exact soft demapping: the bit log-likelihood ratios of one received symbol.

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 LLR of bit k is

    L_k = ln P(b_k = 0 | y) / P(b_k = 1 | y),

so a positive value favors the bit 0. Optional prior LLRs la[k] of the same
sign convention enter as the factor exp(+-la[k] / 2) of each point.
"""

import math


def max_star(a: float, b: float) -> float:
    """ln(e^a + e^b), computed as max(a, b) + ln(1 + e^-|a - b|) so it never overflows."""
    if a == -math.inf:
        return b
    if b == -math.inf:
        return a
    return max(a, b) + math.log1p(math.exp(-abs(a - b)))


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 metrics(y: complex, points: list[complex], n0: float, h: complex = 1, la: list[float] | None = None) -> list[float]:
    """The log metric d_i = -|y - h a_i|^2 / N0 + sum_k (1 - 2 b_k(i)) la_k / 2 of every point."""
    m = len(points).bit_length() - 1
    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)
    return d


def soft_demap(y: complex, points: list[complex], n0: float, h: complex = 1, la: list[float] | None = None) -> list[float]:
    """The exact a posteriori LLRs L_0, ..., L_{m-1} of the bits of one symbol."""
    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")
    m = big_m.bit_length() - 1
    d = metrics(y, points, n0, h, la)
    out = []
    for k in range(m):  # @line L3
        acc = [-math.inf, -math.inf]  # @line L4
        for i in range(big_m):  # @line L5
            b = label_bit(i, k, m)
            acc[b] = max_star(acc[b], d[i])  # @line L6
        out.append(acc[0] - acc[1])  # @line L7
    return out


def extrinsic(y: complex, points: list[complex], n0: float, h: complex = 1, la: list[float] | None = None) -> list[float]:
    """The extrinsic LLRs L_k - la_k, which a turbo loop passes back to the decoder."""
    post = soft_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 soft_demap_block(ys: list[complex], points: list[complex], n0: float, h: complex = 1) -> list[float]:
    """The LLRs of a block of symbols, concatenated in symbol order."""
    out = []
    for y in ys:
        out.extend(soft_demap(y, points, n0, h))
    return out
test_soft_demapping.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/soft-demapping/. The authors are listed in prov/N96EQ7.jsonl.

import math
import random
import unittest

import constel
from soft_demapping import extrinsic, max_star, soft_demap, soft_demap_block


def lse(values):
    """ln sum exp(v), shifted by the maximum."""
    top = max(values)
    return top + math.log(sum(math.exp(v - top) for v in values))


def brute_llr(y, points, n0, h=1, la=None):
    """The LLRs as a log-sum-exp over all points, with the priors as bit probabilities."""
    m = len(points).bit_length() - 1
    logp = []
    for i, a in enumerate(points):
        v = -abs(y - h * a) ** 2 / n0
        if la is not None:
            for k, b in enumerate(constel.bits(i, m)):
                p0 = 1.0 / (1.0 + math.exp(-la[k]))
                v += math.log(p0 if b == 0 else 1.0 - p0)
        logp.append(v)
    out = []
    for k in range(m):
        s0 = [logp[i] for i in range(len(points)) if constel.bits(i, m)[k] == 0]
        s1 = [logp[i] for i in range(len(points)) if constel.bits(i, m)[k] == 1]
        out.append(lse(s0) - lse(s1))
    return out


def prob_llr(y, points, n0, h=1):
    """The LLRs from plain probabilities, for N0 large enough that nothing underflows."""
    m = len(points).bit_length() - 1
    out = []
    for k in range(m):
        p = [0.0, 0.0]
        for i, a in enumerate(points):
            p[constel.bits(i, m)[k]] += math.exp(-abs(y - h * a) ** 2 / n0) / (math.pi * n0)
        out.append(math.log(p[0] / p[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),
}


class TestSoftDemapping(unittest.TestCase):
    def test_max_star(self):
        for a, b in [(0.0, 0.0), (3.0, -2.0), (-700.0, -701.5), (800.0, 799.0)]:
            ref = max(a, b) + math.log(math.exp(a - max(a, b)) + math.exp(b - max(a, b)))
            self.assertAlmostEqual(max_star(a, b), ref, delta=1e-12)
        self.assertEqual(max_star(-math.inf, 2.5), 2.5)
        self.assertEqual(max_star(2.5, -math.inf), 2.5)

    def test_matches_log_sum_exp(self):
        rng = random.Random(20261120)
        for name, pts in CONSTELLATIONS.items():
            for _ in range(60):
                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)
                got = soft_demap(y, pts, n0, h)
                ref = brute_llr(y, pts, n0, h)
                for g, r in zip(got, ref):
                    self.assertLess(abs(g - r), 1e-9, name)

    def test_matches_probabilities(self):
        rng = random.Random(7)
        for name, pts in CONSTELLATIONS.items():
            for _ in range(30):
                n0 = rng.uniform(0.2, 2.0)
                y = complex(rng.uniform(-1.5, 1.5), rng.uniform(-1.5, 1.5))
                for g, r in zip(soft_demap(y, pts, n0), prob_llr(y, pts, n0)):
                    self.assertLess(abs(g - r), 1e-9, name)

    def test_bpsk_closed_form(self):
        rng = random.Random(11)
        pts = constel.pam(2)
        for _ in range(200):
            h = complex(rng.gauss(0, 1), rng.gauss(0, 1))
            y = complex(rng.gauss(0, 2), rng.gauss(0, 2))
            n0 = rng.uniform(0.05, 3.0)
            (llr,) = soft_demap(y, pts, n0, h)
            self.assertAlmostEqual(llr, 4.0 * (y * h.conjugate()).real / n0, delta=1e-9)

    def test_qpsk_closed_form(self):
        rng = random.Random(12)
        pts = constel.qam(4)
        for _ in range(200):
            y = complex(rng.gauss(0, 1), rng.gauss(0, 1))
            n0 = rng.uniform(0.05, 3.0)
            l0, l1 = soft_demap(y, pts, n0)
            self.assertAlmostEqual(l0, 2.0 * math.sqrt(2.0) * y.real / n0, delta=1e-9)
            self.assertAlmostEqual(l1, 2.0 * math.sqrt(2.0) * y.imag / n0, delta=1e-9)

    def test_page_example(self):
        got = soft_demap(0.5 - 0.2j, constel.qam(16), 0.1)
        for g, r in zip(got, [6.4962, -1.6772, -2.5340, -5.5463]):
            self.assertAlmostEqual(g, r, delta=1e-4)

    def test_priors(self):
        rng = random.Random(13)
        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)]
                n0 = 10 ** rng.uniform(-1.5, 0.3)
                y = complex(rng.gauss(0, 1), rng.gauss(0, 1))
                got = soft_demap(y, pts, n0, 1, la)
                for g, r in zip(got, brute_llr(y, pts, n0, 1, la)):
                    self.assertLess(abs(g - r), 1e-9, name)
                ext = extrinsic(y, pts, n0, 1, la)
                for e, g, a in zip(ext, got, la):
                    self.assertAlmostEqual(e, g - a, delta=1e-12)

    def test_extrinsic_of_bpsk_ignores_prior(self):
        pts = constel.pam(2)
        for la in (-3.0, 0.0, 2.5):
            (e,) = extrinsic(0.3 - 0.1j, pts, 0.5, 1, [la])
            self.assertAlmostEqual(e, 4.0 * 0.3 / 0.5, delta=1e-12)

    def test_extreme_noise_levels(self):
        pts = constel.qam(64)
        y = 0.71 - 0.33j
        tiny = soft_demap(y, pts, 1e-7)
        for g, r in zip(tiny, brute_llr(y, pts, 1e-7)):
            self.assertTrue(math.isfinite(g))
            self.assertLess(abs(g - r), 1e-9 * max(1.0, abs(r)))
        huge = soft_demap(y, pts, 1e6)
        for g in huge:
            self.assertLess(abs(g), 1e-5)

    def test_block_and_errors(self):
        pts = constel.qam(16)
        got = soft_demap_block([0.5 - 0.2j, -0.1 + 0.9j], pts, 0.3)
        self.assertEqual(len(got), 8)
        self.assertEqual(got[:4], soft_demap(0.5 - 0.2j, pts, 0.3))
        with self.assertRaises(ValueError):
            soft_demap(0.1, pts[:3], 0.3)
        with self.assertRaises(ValueError):
            soft_demap(0.1, pts, 0.0)


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

History

Soft decisions are as old as the Viterbi decoder, but the bit LLR of a multilevel constellation became central with bit-interleaved coded modulation. Zehavi in 1992 put a bit interleaver between a convolutional code and an 8-PSK mapper for the Rayleigh channel and decoded with one metric per bit. Caire, Taricco and Biglieri in 1998 gave the general theory of BICM, with the exact bit metric as the log of a sum over the points with a given bit value, and its capacity. The Jacobian logarithm max⁡∗\max^* came into use in the log-domain BCJR algorithm in the mid 1990s. Turbo codes and LDPC codes then made the exact demapper a standard block of receivers.

References

  1. 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 as sums over the subsets of points with a given bit value, and the BICM capacity
  2. 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

Where this leads

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