Algorithmresearch
Expectation propagation detection
Also called EP detector.
Approximates the posterior of the symbol vector by a Gaussian that expectation propagation refines one symbol at a time, then decides each symbol. It starts from the MMSE estimate.
- Solves
- MIMO detection
- Time
- O(n^2 m + T (n^3 + n M)) worst
- Space
- O(n^2 + n m) extra
- Where
- M = the constellation size; T = the number of iterations; m = the number of receive antennas; n = the number of transmitted streams
- Model
- Real RAM
- Properties
- deterministicnot exact mlneeds matrix inverseneeds noise level
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Javier Céspedes, Pablo M. Olmos, Matilde Sánchez Fernández, Fernando Pérez Cruz, 2014
Expectation propagation (EP) detection solves the MIMO detection problem by an approximation of the posterior distribution of the transmitted vector. The true posterior is a Gaussian likelihood times a discrete prior, one factor for each symbol. EP replaces each discrete prior factor by a Gaussian factor and then improves the Gaussian factors one at a time. For each symbol it removes that symbol's Gaussian factor, puts in the true discrete factor, computes the mean and variance of the result, and picks the new Gaussian factor that gives the same mean and variance. The first approximation is the linear MMSE estimate, and the next ones use the constellation. The detector of this page is the one of Céspedes, Olmos, Sánchez-Fernández and Pérez-Cruz (2014). The general method, for any model with factors, is on the expectation propagation page. This page gives the MIMO form, with the cavity and moment formulas for a PAM alphabet, the safeguards that the detector needs, and the results that are true for this model. AMP detection has a similar aim and costs less per step, but it needs a large channel with i.i.d. entries.
In plain words
The receiver wants to know which symbol vector was sent. It can compute the best Gaussian guess, which is what the MMSE detector does. But the true symbols are not Gaussian: each one is one of a few points. EP corrects the Gaussian guess one symbol at a time. For symbol , it asks what the rest of the system says about . This is a Gaussian bump, the cavity. It then multiplies the bump by the true rule " is one of the points" and gets a small discrete distribution. It makes the Gaussian factor of symbol agree with the mean and the variance of that distribution. After a few rounds, the means of the Gaussian are usually much closer to the true symbols than the MMSE estimate.
The problem
The model is with known, for a square QAM constellation of equally likely points with energy , and . EP works on the real form with
Now has entries, each in the PAM alphabet of levels with energy , and has i.i.d. entries with . For real symbols (BPSK or PAM), and . The posterior is
The detector returns one decision in for each stream and, for soft output, the mean and variance of each real symbol.
The algorithm
EP replaces each factor by a Gaussian site with . The approximation is then the Gaussian with
For a site , the cavity is the marginal of divided by site . It is with
The tilted distribution puts the weight on each . Let and be its mean and variance.
EP-DETECT(y_r, H_r, A, σ², T, β, ε)- 1
γ ← 0; Λ ← (1/e_s, ..., 1/e_s) - 2
for t ← 1 to T - 3
Σ ← (Hᵀ H / σ² + diag Λ)⁻¹; μ ← Σ (Hᵀ y / σ² + γ) - 4
for each i: h²_i ← Σ_ii / (1 - Σ_ii Λ_i); t_i ← h²_i (μ_i / Σ_ii - γ_i) - 5
(μ_p, σ²_p) ← mean and variance of the tilted distribution on A; σ²_p ← max(σ²_p, ε) - 6
Λ' ← 1/σ²_p - 1/h²_i; γ' ← μ_p/σ²_p - t_i/h²_i - 7
if Λ' > 0: Λ_i ← β Λ' + (1 - β) Λ_i; γ_i ← β γ' + (1 - β) γ_i - 8
for each stream k: decide the level of A nearest to μ_k (and to μ_{n+k} for the imaginary part) - 9
return the decisions
Line L1 sets every site to the prior variance with mean 0, so the first is the linear MMSE estimate. Line L3 is one solve with a symmetric positive definite matrix. Line L4 forms the cavity. Line L5 computes weights per real symbol, with the largest exponent subtracted first so that nothing underflows. Line L6 gives the site that makes the marginal of have the tilted mean and variance. Line L7 keeps the old site when the new precision is not positive, and damps the update with a factor . All sites in one iteration use the same ; this is a parallel schedule. The implementation uses , and by default. Céspedes et al. also use damping, a variance floor and a fixed small number of iterations; their exact values are not repeated here. Line L8 rounds each mean to the nearest level.
Example
A small channel, where EP corrects MMSE. Take BPSK, ,
The four metrics are 2.5 for , 1.3 for , 0.5 for and 7.3 for , so ML decides . The real model has and . With and , line L3 gives
This is the MMSE estimate, and its signs give , which is wrong. Now take one EP iteration with . For BPSK the tilted mean is and the tilted variance is .
| site | action | |||||
|---|---|---|---|---|---|---|
| 1 | 0.4960 | 0.0800 | 0.1600 | 0.9744 | keep , | |
| 2 | 0.4960 | 0.6240 | 0.8505 | 0.2766 | 1.599 | set , |
The new has and the variances . The site of symbol 1 did not change, but the stronger belief that pulls below 0 through the correlation of the columns. The decisions are , the ML vector. More iterations do not change , because site 2 already matches its tilted moments and the update of site 1 is still negative. The test checks the means and the variances of after 0 and 1 iterations within , and the decisions.
Correctness
The proof is in proofs/correctness.md. It shows the following, for every channel unless stated. First, the cavity formulas of line L4 are the marginal of divided by site , and line L6 gives the site that makes the marginal of equal in mean and variance to the tilted distribution. Second, all stay positive, so always exists, and the cavity is a proper Gaussian when column of is not zero. Third, the first has the mean in real form, the linear MMSE estimate. Fourth, at a fixed point where every site was kept, each marginal of has the mean and variance of its tilted distribution. Fifth, if is diagonal and every update is kept, which is true when , the means and variances of converge to the exact posterior marginals. EP is not an exact ML detector in general, and it need not converge. Its good error rate on random channels is a measurement, not a theorem.
Proof: The EP updates match moments, the sites stay proper, the first iterate is the linear MMSE estimate, and the marginals are exact on orthogonal channelsfull
The model is the real form of the page, with real symbols in the alphabet , and the mean of over . Write and . The lines L1 to L9 are those of the pseudocode on the page. A Gaussian factor is written in natural parameters . For it is proportional to . This file claims only the results below. It does not claim that EP converges in general or that it finds the ML vector; the page shows a case where it does not.
Lemma 1 (the sites stay positive and exists)
At every point of the algorithm, for all , and is positive definite. If column of is not zero, the cavity precision is positive.
Proof. Line L1 sets . Line L7 changes only when , and then to with , a convex combination of two positive numbers. So always, by induction. For , , so is positive definite and exists.
For the cavity, let be with replaced by 0. By the Schur complement, , where is without row and column and is column of without its entry . The same formula for has the same and and the entry . So is the Schur complement of in . It is positive if is positive definite. Now , which is 0 only if for and . When column is not zero, this forces .
Theorem 2 (the cavity and the moment-matching site)
Line L4 gives the Gaussian proportional to , where is the marginal of and is site . If site is replaced by the site of line L6, with no damping, the new marginal of for is , the Gaussian with the mean and variance of the tilted distribution on .
Proof. In natural parameters, dividing Gaussian factors subtracts parameters. The marginal has . So the cavity has the precision , which is positive by Lemma 1, and the linear term . Its variance is , and its mean is , as in line L4.
The density is proportional to the likelihood times all sites. Write it as , where collects the likelihood and the other sites. Then the marginal of is , so , the cavity. Replacing by a new site does not change , so the new marginal is proportional to . With of parameters , the product has the parameters , which is . These are the formulas of line L6.
A negative can make the joint improper, because the proof of Lemma 1 then fails, and then the marginal of is not defined. That is why line L7 keeps the old site in that case. Among all Gaussians, minimizes the Kullback-Leibler divergence from the tilted distribution, which is the general EP rule (Minka 2001).
Theorem 3 (the first iterate is the linear MMSE estimate)
On the first pass of line L3, . For the real form of a complex model with square QAM, this is the real form of .
Proof. Line L1 gives and . So . For the complex model, and , since the real and imaginary parts of a square QAM point are independent and share the energy equally. So . The map respects sums and products, sends to and the identity to the identity, and acts on vectors by stacking the real and imaginary parts in the same way. So , is the stacked , and . Hence is the stacked .
The test checks this within on five channels with and . The MMSE detector of the MMSE page rounds this estimate, after a bias correction that does not change the signs. For a constellation with more than two levels per dimension, the bias correction can change the decision, so EP with equals the MMSE detector without that correction.
Theorem 4 (fixed points match moments)
Suppose that in an iteration with , every site was kept () and no site changed. Then for every , the marginal of for has the mean and variance of its tilted distribution.
Proof. No change with means and for every . All sites in the iteration were computed from the same , so by Theorem 2 the marginal of divided by the cavity is the site . So the marginal is the cavity times the site, which by the proof of Theorem 2 is .
The floor of line L5 changes only when it is below . In that case the statement holds with replaced by .
Theorem 5 (exact marginals on orthogonal channels)
Suppose with all , and for every . Then every update of line L7 is kept, and as the mean and variance of each marginal of converge to the mean and variance of under the exact posterior. With they are equal after one iteration (ignoring the floor ).
Proof. With diagonal, is diagonal, so and . Then line L4 gives and , whatever the sites are.
The exact posterior factorizes. Indeed, , so
So the exact marginal of is the tilted distribution of site , and it does not depend on the sites. Let be its moments. The variance is at most , so and every update is kept. The targets are the same at every iteration, so line L7 gives , and the same for . Both go to 0 for , and they are 0 after one step when . With the limit site, the marginal of is the cavity times the site, which is by Theorem 2. The mean and variance of are continuous in , so they converge to .
For the complex model, is diagonal exactly when is diagonal, since and the off-diagonal blocks are , whose diagonal is 0. The test builds with a rotation, , , 16-QAM and , so . It compares the means and variances with a sum over all 256 vectors, within .
What the tests check
- Theorem 2 with BPSK: the tilted mean and variance equal and within .
- Theorem 3: the first iterate against the complex linear MMSE solve, within .
- Theorem 5: exact posterior means and variances on orthogonal channels, within .
- The page example, step by step, within , and that further steps do not change (Theorem 4 in a concrete case).
- Measurements: agreement with brute-force ML on at least 92 of 100 vectors for 4-QAM, , 15 dB (seed 2204; 97 in the run), at most of the MMSE symbol errors for at 10 dB (seed 2206; 19 against 38), and the strongly correlated case where EP settles on a non-ML vector.
Complexity
The Gram matrix and the vector cost once. Each iteration inverts a matrix in and computes tilted moments of terms each. So iterations cost in the real RAM, which the front matter bounds by . The space is . The cost is that of the MMSE detector times , and it grows only with in the constellation size. A sphere search, by contrast, can grow fast with at low SNR. A rank-one update of after each site gives a sequential schedule at per site, the same order per iteration.
Properties
- MMSE start. The first iterate is the linear MMSE estimate (theorem). So EP with is the MMSE detector without the bias correction.
- Moment matching. At a fixed point where all sites were kept, the mean and variance of each marginal of match the tilted distribution (theorem).
- Exact on orthogonal channels. When is diagonal and the cavity variance is above , EP gives the exact posterior marginals. The test checks this against a sum over all 256 vectors of 16-QAM with , within .
- Measured agreement with ML. For 4-QAM, , i.i.d. entries and dB, the test with seed 2204 runs 100 vectors, and EP with 10 iterations agrees with brute-force ML on 97 (measurement; the test asks for at least 92).
- Measured gain over MMSE. For 4-QAM, and dB, EP made 19 symbol errors on 320 symbols and the MMSE start made 38 (seed 2206, measurement).
- No guarantee. On a strongly correlated channel EP can settle on a wrong vector, as Pitfalls shows.
Variants and improvements
- Sequential schedule. Update one site at a time and change by a rank-one formula. The parallel schedule of this page is simpler; the sequential one often needs fewer iterations.
- Soft output for coding. The pairs of the cavity are extrinsic values for each real symbol. They feed a soft demapper and a channel decoder, and the decoder output can come back as a new prior, as in turbo equalization.
- Complex form. EP can also work with complex Gaussian sites on the complex model. For square QAM the real form is equivalent and simpler.
- Lower cost for large systems. For massive MIMO, later work looks for cheaper ways to compute or approximate than the inverse. These change the cost and the accuracy, and this page does not cover them.
- Other site families. EP can use a full covariance per site or a mixture, at more cost.
When to use it
Use EP when is moderate (up to a few tens of streams), the constellation is large (16-QAM to 256-QAM), and the channel may be correlated, so that AMP is not safe and a sphere search is too slow. It costs a small multiple of the MMSE detector and is often much more accurate. For small with a low-order constellation, an exact search such as Schnorr-Euchner enumeration or the K-best detector is affordable and better. For very large i.i.d. systems, AMP detection avoids the inverse.
Pitfalls
- Negative site precision. The update can be negative, for example when the cavity sits between two points and the tilted distribution is wider than the cavity. Then may stop being a proper Gaussian. Keep the old site, as line L7 does.
- Too small a tilted variance. At high SNR the tilted variance can be 0 in floating point. Without the floor the update divides by 0.
- No damping. Without damping the parallel schedule can oscillate. Choose , and check the choice by measurement on the channels of interest.
- Strong correlation. Take BPSK, , and . The columns have the correlation . ML decides with metric 0.61, and the exact posterior means are . EP with goes to and decides , with metric 2.61. The test checks this case.
- Wrong real form. For real symbols (BPSK, PAM), do not add imaginary parts as unknowns: they are 0, and treating them as breaks the model. The implementation uses in that case.
- Wrong noise variance. The real model has per real dimension, and each real level has energy . Mixing the complex and the real values gives the wrong first iterate.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the communications pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Complex baseband tools for the communications pages.
Vectors are lists of complex numbers. Matrices are lists of rows. The
functions here are plain building blocks: small linear algebra, convolution,
the DFT as a direct sum, the Gaussian Q function, dB conversion, complex
Gaussian noise and the Wilson score interval. No page algorithm (equalizer,
estimator, synchronizer, detector, precoder, demapper or power allocation)
lives in this file.
Conventions (prompts of the communications area):
- dft is X[k] = sum_n x[n] e^(-j 2 pi k n / N) with no factor; idft has 1/N.
- udft and uidft are the unitary pair, with 1/sqrt(N) on both sides.
- qfunc(x) = 0.5 erfc(x / sqrt(2)); it never computes 1 - Phi(x).
- cn(rng, var) draws CN(0, var): real and imaginary parts are independent
with variance var / 2 each, so E|w|^2 = var.
"""
import cmath
import math
import random
# ---------------------------------------------------------------- vectors and matrices
def zeros(rows: int, cols: int | None = None) -> list:
"""A zero vector of length rows, or a rows by cols zero matrix."""
if cols is None:
return [0j] * rows
return [[0j] * cols for _ in range(rows)]
def eye(n: int) -> list[list[complex]]:
"""The n by n identity matrix."""
return [[1 + 0j if i == k else 0j for k in range(n)] for i in range(n)]
def add(a: list, b: list) -> list:
"""Elementwise a + b for two vectors or two matrices of the same shape."""
if len(a) != len(b):
raise ValueError("shapes differ")
if a and isinstance(a[0], list):
return [add(r, s) for r, s in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a: list, b: list) -> list:
"""Elementwise a - b for two vectors or two matrices of the same shape."""
if len(a) != len(b):
raise ValueError("shapes differ")
if a and isinstance(a[0], list):
return [sub(r, s) for r, s in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(c: complex, a: list) -> list:
"""The scalar c times a vector or a matrix."""
if a and isinstance(a[0], list):
return [scale(c, r) for r in a]
return [c * x for x in a]
def matmul(a: list[list[complex]], b: list[list[complex]]) -> list[list[complex]]:
"""The matrix product a b."""
if not a or not b or len(a[0]) != len(b):
raise ValueError("inner dimensions differ")
cols = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in cols] for row in a]
def matvec(a: list[list[complex]], x: list[complex]) -> list[complex]:
"""The matrix times vector product a x."""
if a and len(a[0]) != len(x):
raise ValueError("inner dimensions differ")
return [sum(p * q for p, q in zip(row, x)) for row in a]
def herm(a: list) -> list:
"""The conjugate transpose of a matrix. A vector gives its conjugate."""
if a and isinstance(a[0], list):
return [[complex(a[i][k]).conjugate() for i in range(len(a))] for k in range(len(a[0]))]
return [complex(x).conjugate() for x in a]
def dot(x: list[complex], y: list[complex]) -> complex:
"""The inner product x^H y = sum of conj(x_i) y_i."""
if len(x) != len(y):
raise ValueError("lengths differ")
return sum(complex(p).conjugate() * q for p, q in zip(x, y))
def norm2(x: list) -> float:
"""The squared Euclidean norm sum |x_i|^2 (squared Frobenius norm for a matrix)."""
if x and isinstance(x[0], list):
return sum(norm2(r) for r in x)
return sum(abs(v) ** 2 for v in x)
# ---------------------------------------------------------------- linear systems
def _lu(a: list[list[complex]]) -> tuple[list[list[complex]], list[int], int]:
"""LU factorization with partial pivoting. Returns (lu, perm, sign)."""
n = len(a)
if any(len(r) != n for r in a):
raise ValueError("matrix is not square")
m = [[complex(v) for v in r] for r in a]
perm = list(range(n))
sign = 1
for k in range(n):
p = max(range(k, n), key=lambda i: abs(m[i][k]))
if abs(m[p][k]) == 0.0:
raise ValueError("matrix is singular")
if p != k:
m[k], m[p] = m[p], m[k]
perm[k], perm[p] = perm[p], perm[k]
sign = -sign
for i in range(k + 1, n):
f = m[i][k] / m[k][k]
m[i][k] = f
if f != 0:
rk, ri = m[k], m[i]
for c in range(k + 1, n):
ri[c] -= f * rk[c]
return m, perm, sign
def _lu_solve(lu: list[list[complex]], perm: list[int], b: list[complex]) -> list[complex]:
n = len(lu)
y = [complex(b[perm[i]]) for i in range(n)]
for i in range(n):
for c in range(i):
y[i] -= lu[i][c] * y[c]
for i in range(n - 1, -1, -1):
for c in range(i + 1, n):
y[i] -= lu[i][c] * y[c]
y[i] /= lu[i][i]
return y
def solve(a: list[list[complex]], b: list) -> list:
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector, or a matrix whose columns are right-hand sides.
Raises ValueError if a is singular.
"""
lu, perm, _ = _lu(a)
if b and isinstance(b[0], list):
cols = [list(c) for c in zip(*b)]
xs = [_lu_solve(lu, perm, c) for c in cols]
return [list(r) for r in zip(*xs)]
if len(b) != len(a):
raise ValueError("lengths differ")
return _lu_solve(lu, perm, b)
def inv(a: list[list[complex]]) -> list[list[complex]]:
"""The inverse of a square matrix."""
return solve(a, eye(len(a)))
def det(a: list[list[complex]]) -> complex:
"""The determinant of a square matrix (0 for a singular matrix)."""
try:
lu, _, sign = _lu(a)
except ValueError as e:
if "singular" in str(e):
return 0j
raise
d = complex(sign)
for i in range(len(lu)):
d *= lu[i][i]
return d
def cholesky(a: list[list[complex]]) -> list[list[complex]]:
"""The lower triangular L with a = L L^H, for a Hermitian positive definite a.
Raises ValueError if a is not positive definite (to rounding).
"""
n = len(a)
low = zeros(n, n)
for i in range(n):
for k in range(i + 1):
s = complex(a[i][k]) - sum(low[i][c] * low[k][c].conjugate() for c in range(k))
if i == k:
if s.real <= 0.0:
raise ValueError("matrix is not positive definite")
low[i][i] = complex(math.sqrt(s.real))
else:
low[i][k] = s / low[k][k].real
return low
# ---------------------------------------------------------------- convolution and the DFT
def conv(a: list[complex], b: list[complex]) -> list[complex]:
"""Linear convolution, of length len(a) + len(b) - 1."""
if not a or not b:
return []
out = [0j] * (len(a) + len(b) - 1)
for i, x in enumerate(a):
for k, y in enumerate(b):
out[i + k] += x * y
return out
def cconv(a: list[complex], b: list[complex], n: int | None = None) -> list[complex]:
"""Circular convolution of length n (default: the longer length).
Both inputs are padded with zeros to length n, or must not be longer than n.
"""
if n is None:
n = max(len(a), len(b))
if len(a) > n or len(b) > n:
raise ValueError("input longer than n")
out = [0j] * n
for i, x in enumerate(a):
for k, y in enumerate(b):
out[(i + k) % n] += x * y
return out
def _twiddles(n: int, sign: int) -> list[complex]:
return [cmath.exp(sign * 2j * math.pi * t / n) for t in range(n)]
def dft(x: list[complex]) -> list[complex]:
"""X[k] = sum over n of x[n] e^(-j 2 pi k n / N), as a direct O(N^2) sum."""
n = len(x)
w = _twiddles(n, -1)
return [sum(x[t] * w[(k * t) % n] for t in range(n)) for k in range(n)]
def idft(xf: list[complex]) -> list[complex]:
"""x[n] = (1/N) sum over k of X[k] e^(j 2 pi k n / N), the inverse of dft."""
n = len(xf)
w = _twiddles(n, 1)
return [sum(xf[k] * w[(k * t) % n] for k in range(n)) / n for t in range(n)]
def udft(x: list[complex]) -> list[complex]:
"""The unitary DFT: dft(x) / sqrt(N)."""
s = 1.0 / math.sqrt(len(x)) if x else 1.0
return [v * s for v in dft(x)]
def uidft(xf: list[complex]) -> list[complex]:
"""The unitary inverse DFT: sqrt(N) idft(X), the inverse of udft."""
s = math.sqrt(len(xf)) if xf else 1.0
return [v * s for v in idft(xf)]
# ---------------------------------------------------------------- Q function and dB
def qfunc(x: float) -> float:
"""Q(x) = P(Z > x) for a standard normal Z, computed as 0.5 erfc(x / sqrt(2))."""
return 0.5 * math.erfc(x / math.sqrt(2.0))
def qinv(p: float) -> float:
"""The x with Q(x) = p, for 0 < p < 1, by bisection on Q (which decreases)."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
lo, hi = -40.0, 40.0
for _ in range(200):
mid = 0.5 * (lo + hi)
if qfunc(mid) > p:
lo = mid
else:
hi = mid
if hi - lo <= 1e-15 * max(1.0, abs(mid)):
break
return 0.5 * (lo + hi)
def db(x: float) -> float:
"""10 log10(x), for a ratio of powers or energies."""
return 10.0 * math.log10(x)
def undb(d: float) -> float:
"""10^(d / 10), the inverse of db."""
return 10.0 ** (d / 10.0)
# ---------------------------------------------------------------- noise and statistics
def cn(rng: random.Random, var: float) -> complex:
"""One sample of CN(0, var): independent real and imaginary parts of variance var / 2."""
s = math.sqrt(var / 2.0)
return complex(rng.gauss(0.0, s), rng.gauss(0.0, s))
def awgn(rng: random.Random, x: list[complex], n0: float) -> list[complex]:
"""x plus independent CN(0, n0) noise on each sample."""
return [v + cn(rng, n0) for v in x]
def wilson(k: int, n: int, z: float = 3.29) -> tuple[float, float]:
"""The Wilson score interval for k successes in n trials (z = 3.29 is about 0.999 two-sided)."""
if n <= 0 or not 0 <= k <= n:
raise ValueError("need 0 <= k <= n and n > 0")
p = k / n
z2 = z * z
den = 1.0 + z2 / n
mid = (p + z2 / (2 * n)) / den
half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / den
return max(0.0, mid - half), min(1.0, mid + half)
constel.py 117 lines
# SPDX-License-Identifier: MIT
# Shared helper of the communications pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Constellations, Gray labels and brute-force maximum likelihood detection.
Each constellation function returns a list of M complex points with unit
average energy, ordered by label: points[i] is the point whose bit label is
the integer i, and bits(i, log2 M) gives that label, most significant bit
first. The labels follow the communications area rules:
- M-PAM: the point with amplitude index m = 0, ..., M-1 (raw amplitude
M - 1 - 2m, from the most positive) gets the Gray label gray(m).
So 2-PAM maps bit 0 to +1 and bit 1 to -1.
- Square M-QAM, M = 4^k: the label is the in-phase PAM label followed by the
quadrature PAM label, each of log2(sqrt(M)) bits.
- M-PSK: the point e^(j(2 pi m / M + phase0)) gets the label gray(m).
PAM points are returned as complex numbers with zero imaginary part.
This file imports nothing from cbb.py. It holds no demapper: soft and
max-log demapping are algorithm pages of their own.
"""
import cmath
import itertools
import math
def gray(n: int) -> int:
"""The binary reflected Gray code of n: n XOR (n >> 1)."""
return n ^ (n >> 1)
def _gray_inv(g: int) -> int:
n = 0
while g:
n ^= g
g >>= 1
return n
def bits(i: int, m: int) -> list[int]:
"""The m bits of the integer i, most significant bit first."""
if i < 0 or i >= 1 << m:
raise ValueError("i does not fit in m bits")
return [(i >> (m - 1 - t)) & 1 for t in range(m)]
def _log2(m: int) -> int:
if m < 2 or m & (m - 1):
raise ValueError("M must be a power of two, at least 2")
return m.bit_length() - 1
def pam(m: int) -> list[complex]:
"""Unit-energy M-PAM, ordered by Gray label."""
_log2(m)
s = math.sqrt((m * m - 1) / 3.0)
return [complex((m - 1 - 2 * _gray_inv(lab)) / s, 0.0) for lab in range(m)]
def qam(m: int) -> list[complex]:
"""Unit-energy square M-QAM (M = 4, 16, 64, ...), ordered by label (in-phase bits first)."""
k = _log2(m)
if k % 2:
raise ValueError("square QAM needs M = 4^k")
side = 1 << (k // 2)
s = math.sqrt(2.0 * (m - 1) / 3.0)
raw = [side - 1 - 2 * _gray_inv(lab) for lab in range(side)]
return [complex(raw[lab // side], raw[lab % side]) / s for lab in range(m)]
def psk(m: int, phase0: float = 0.0) -> list[complex]:
"""Unit-energy M-PSK with first point at angle phase0, ordered by Gray label."""
_log2(m)
return [cmath.exp(1j * (2.0 * math.pi * _gray_inv(lab) / m + phase0)) for lab in range(m)]
def energy(points: list[complex]) -> float:
"""The average energy (1/M) sum |p|^2 of equally likely points."""
return sum(abs(p) ** 2 for p in points) / len(points)
def ml_detect(y: complex, points: list[complex], h: complex = 1) -> int:
"""The index of the point p that minimizes |y - h p|^2, by brute force (lowest index on a tie)."""
best, arg = math.inf, -1
for i, p in enumerate(points):
d = abs(y - h * p) ** 2
if d < best:
best, arg = d, i
return arg
def ml_vector(y: list[complex], h: list[list[complex]], points: list[complex]) -> list[int]:
"""The index vector that minimizes ||y - H x||^2 over all M^n vectors x, by brute force.
h is the m by n channel matrix as a list of rows; the result has n indices.
The first minimizer in lexicographic order of the indices wins a tie.
"""
n = len(h[0])
best, arg = math.inf, None
for idx in itertools.product(range(len(points)), repeat=n):
x = [points[i] for i in idx]
d = 0.0
for yi, row in zip(y, h):
d += abs(yi - sum(a * b for a, b in zip(row, x))) ** 2
if d < best:
best, arg = d, idx
return list(arg)
def bit_errors(a, b) -> int:
"""The number of differing bits between two integer labels, or summed over two equal-length lists."""
if isinstance(a, int) and isinstance(b, int):
return bin(a ^ b).count("1")
if len(a) != len(b):
raise ValueError("lengths differ")
return sum(bit_errors(x, y) for x, y in zip(a, b))
expectation_propagation_detection.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/expectation-propagation-detection/. The authors are listed in prov/R4B3XS.jsonl.
"""Expectation propagation (EP) MIMO detection, in the real-valued form.
The complex model y = H x + w, with H an m by n matrix, x in S^n for a square
QAM constellation S and w ~ CN(0, N0 I), is first written as a real model
y_r = H_r x_r + w_r of size 2m by 2n. Each real symbol takes values in a PAM
alphabet A, and the noise has variance s2 = N0 / 2 per real dimension.
EP replaces the prior factor 1{x_i in A} of each real symbol by a Gaussian
factor exp(gamma_i x_i - Lambda_i x_i^2 / 2). The product with the Gaussian
likelihood is a Gaussian q(x) = N(mu, Sigma) with
Sigma = (H_r^T H_r / s2 + diag(Lambda))^(-1), mu = Sigma (H_r^T y_r / s2 + gamma).
Each iteration removes factor i from the marginal of q (the cavity),
multiplies the cavity by the true prior factor, matches the mean and the
variance of the result, and updates (gamma_i, Lambda_i) with damping.
This is the detector of Cespedes, Olmos, Sanchez-Fernandez and Perez-Cruz,
IEEE Trans. Comm. 62(8), 2014.
"""
import math
import cbb
def real_model(y: list[complex], h: list[list[complex]], real_symbols: bool = False) -> tuple[list[float], list[list[float]]]:
"""(y_r, H_r) with y_r = (Re y, Im y) and H_r = [[Re H, -Im H], [Im H, Re H]].
If the symbols are real (PAM), x has no imaginary part and H_r = [Re H; Im H].
"""
m, n = len(h), len(h[0])
yr = [complex(v).real for v in y] + [complex(v).imag for v in y]
hr = []
for i in range(m):
row = [complex(h[i][k]).real for k in range(n)]
hr.append(row if real_symbols else row + [-complex(h[i][k]).imag for k in range(n)])
for i in range(m):
row = [complex(h[i][k]).imag for k in range(n)]
hr.append(row if real_symbols else row + [complex(h[i][k]).real for k in range(n)])
return yr, hr
def real_alphabet(points: list[complex]) -> list[float]:
"""The sorted levels of the real part of a square QAM (or real PAM) constellation."""
return sorted({round(complex(p).real, 12) for p in points})
def tilted_moments(t: float, h2: float, alphabet: list[float]) -> tuple[float, float]:
"""Mean and variance of p(a) proportional to exp(-(a - t)^2 / (2 h2)) on the alphabet."""
logs = [-(a - t) ** 2 / (2.0 * h2) for a in alphabet]
top = max(logs)
ws = [math.exp(v - top) for v in logs]
tot = sum(ws)
mean = sum(w * a for w, a in zip(ws, alphabet)) / tot
var = sum(w * (a - mean) ** 2 for w, a in zip(ws, alphabet)) / tot
return mean, var
def gaussian_q(gram: list[list[float]], hty: list[float], s2: float, gamma: list[float], lam: list[float]) -> tuple[list[float], list[list[float]]]:
"""(mu, Sigma) of q: Sigma = (G / s2 + diag(Lambda))^(-1), mu = Sigma (H^T y / s2 + gamma)."""
d = len(gram)
a = [[gram[i][k] / s2 + (lam[i] if i == k else 0.0) for k in range(d)] for i in range(d)]
sig = [[v.real for v in row] for row in cbb.inv(a)]
b = [hty[i] / s2 + gamma[i] for i in range(d)]
mu = [sum(sig[i][k] * b[k] for k in range(d)) for i in range(d)]
return mu, sig
def ep_real(yr: list[float], hr: list[list[float]], alphabet: list[float], s2: float, iters: int = 10, damping: float = 0.7, eps: float = 1e-9) -> tuple[list[float], list[float]]:
"""Run EP on a real model. Returns (mu, diag Sigma) of the final Gaussian approximation q."""
m2, d = len(hr), len(hr[0])
es = sum(a * a for a in alphabet) / len(alphabet)
gram = [[sum(hr[r][i] * hr[r][k] for r in range(m2)) for k in range(d)] for i in range(d)]
hty = [sum(hr[r][i] * yr[r] for r in range(m2)) for i in range(d)]
gamma = [0.0] * d # @line L1
lam = [1.0 / es] * d
for _ in range(iters): # @line L2
mu, sig = gaussian_q(gram, hty, s2, gamma, lam) # @line L3
for i in range(d):
h2 = sig[i][i] / (1.0 - sig[i][i] * lam[i]) # @line L4
t = h2 * (mu[i] / sig[i][i] - gamma[i])
mp, vp = tilted_moments(t, h2, alphabet) # @line L5
vp = max(vp, eps)
lam_new = 1.0 / vp - 1.0 / h2 # @line L6
gam_new = mp / vp - t / h2
if lam_new > 0.0: # @line L7
lam[i] = damping * lam_new + (1.0 - damping) * lam[i]
gamma[i] = damping * gam_new + (1.0 - damping) * gamma[i]
mu, sig = gaussian_q(gram, hty, s2, gamma, lam)
return mu, [sig[i][i] for i in range(d)]
def ep_detect(y: list[complex], h: list[list[complex]], points: list[complex], n0: float, iters: int = 10, damping: float = 0.7) -> list[int]:
"""EP decisions for a complex model with a square QAM (or PAM) constellation, as point indices."""
n = len(h[0])
real_only = all(abs(complex(p).imag) < 1e-12 for p in points)
yr, hr = real_model(y, h, real_only)
alphabet = real_alphabet(points)
mu, _ = ep_real(yr, hr, alphabet, n0 / 2.0, iters, damping)
out = []
for k in range(n): # @line L8
re = min(alphabet, key=lambda a: abs(mu[k] - a))
im = 0.0 if real_only else min(alphabet, key=lambda a: abs(mu[n + k] - a))
out.append(min(range(len(points)), key=lambda i: abs(points[i] - complex(re, im))))
return out # @line L9
test_expectation_propagation_detection.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/expectation-propagation-detection/. The authors are listed in prov/R4B3XS.jsonl.
import itertools
import math
import random
import unittest
import cbb
import constel
from expectation_propagation_detection import ep_detect, ep_real, real_alphabet, real_model, tilted_moments
def iid(rng: random.Random, m: int, n: int) -> list[list[complex]]:
return [[cbb.cn(rng, 1.0 / m) for _ in range(n)] for _ in range(m)]
def posterior_moments(y, h, points, n0):
"""Exact marginal means and variances of Re x_k and Im x_k, by summing over all M^n vectors."""
n = len(h[0])
ws, xs = [], []
for xv in itertools.product(points, repeat=n):
r = cbb.sub(y, cbb.matvec(h, list(xv)))
ws.append(-cbb.norm2(r) / n0)
xs.append(xv)
top = max(ws)
ws = [math.exp(w - top) for w in ws]
tot = sum(ws)
comps = [lambda v: v.real, lambda v: v.imag]
mean, var = [], []
for part in comps:
for k in range(n):
mk = sum(w * part(xv[k]) for w, xv in zip(ws, xs)) / tot
vk = sum(w * (part(xv[k]) - mk) ** 2 for w, xv in zip(ws, xs)) / tot
mean.append(mk)
var.append(vk)
return mean, var
class TestExpectationPropagationDetection(unittest.TestCase):
def test_tilted_moments_bpsk(self):
for t, h2 in [(0.3, 0.5), (-1.2, 0.1), (2.0, 3.0), (40.0, 0.01)]:
mean, var = tilted_moments(t, h2, [-1.0, 1.0])
self.assertAlmostEqual(mean, math.tanh(t / h2), delta=1e-12)
self.assertAlmostEqual(var, 1.0 - math.tanh(t / h2) ** 2, delta=1e-12)
def test_first_q_is_lmmse(self):
rng = random.Random(2201)
pts = constel.qam(4)
n0 = 0.3
for _ in range(5):
h = iid(rng, 6, 4)
y = cbb.awgn(rng, cbb.matvec(h, [pts[rng.randrange(4)] for _ in range(4)]), n0)
yr, hr = real_model(y, h)
mu, _ = ep_real(yr, hr, real_alphabet(pts), n0 / 2.0, iters=0)
a = cbb.add(cbb.matmul(cbb.herm(h), h), cbb.scale(n0, cbb.eye(4)))
want = cbb.solve(a, cbb.matvec(cbb.herm(h), y))
for k in range(4):
self.assertAlmostEqual(mu[k], want[k].real, delta=1e-9)
self.assertAlmostEqual(mu[4 + k], want[k].imag, delta=1e-9)
def test_page_example(self):
h = [[1.0, 0.5], [0.5, 1.0]]
y = [0.2, 0.6]
bpsk = constel.pam(2)
yr, hr = real_model(y, h, True)
mu0, var0 = ep_real(yr, hr, [-1.0, 1.0], 0.3, iters=0)
for got, want in zip(mu0 + var0, [0.0535, 0.4171, 0.3316, 0.3316]):
self.assertAlmostEqual(got, want, delta=1e-4)
mu1, var1 = ep_real(yr, hr, [-1.0, 1.0], 0.3, iters=1, damping=1.0)
for got, want in zip(mu1 + var1, [-0.2261, 0.8505, 0.3087, 0.2766]):
self.assertAlmostEqual(got, want, delta=1e-4)
mu5, _ = ep_real(yr, hr, [-1.0, 1.0], 0.3, iters=5, damping=1.0)
for a, b in zip(mu1, mu5):
self.assertAlmostEqual(a, b, delta=1e-12)
self.assertEqual(constel.ml_vector(y, h, bpsk), [1, 0])
self.assertEqual(ep_detect(y, h, bpsk, 0.6, damping=1.0), [1, 0])
def test_correlated_channel_can_fail(self):
# Columns with correlation 3 / sqrt(10): EP settles on (-1, +1), ML is (+1, -1).
h = [[2.0, 1.0], [1.0, 1.0]]
y = [0.5, 0.6]
bpsk = constel.pam(2)
self.assertEqual(constel.ml_vector(y, h, bpsk), [0, 1])
self.assertEqual(ep_detect(y, h, bpsk, 0.25, damping=1.0), [1, 0])
yr, hr = real_model(y, h, True)
mu, _ = ep_real(yr, hr, [-1.0, 1.0], 0.125, iters=10, damping=1.0)
self.assertAlmostEqual(mu[0], -1.0, delta=1e-3)
self.assertAlmostEqual(mu[1], 1.0, delta=1e-3)
def test_orthogonal_channel_gives_exact_marginals(self):
# H = U diag(d) with U a rotation, so H^H H is diagonal. The gains are small enough
# that the cavity variance s2 / |d|^2 is above 0.9 = max a^2, so every update is kept.
rng = random.Random(2202)
pts = constel.qam(16)
n0 = 1.0
for _ in range(4):
d = [0.6 * complex(math.cos(p), math.sin(p)) for p in (rng.uniform(0, 6.3), rng.uniform(0, 6.3))]
d[1] *= 5.0 / 6.0
phi = rng.uniform(0, 6.3)
c, s = math.cos(phi), math.sin(phi)
h = [[c * d[0], -s * d[1]], [s * d[0], c * d[1]]]
y = cbb.awgn(rng, cbb.matvec(h, [pts[rng.randrange(16)] for _ in range(2)]), n0)
yr, hr = real_model(y, h)
mu, var = ep_real(yr, hr, real_alphabet(pts), n0 / 2.0, iters=40)
mean, vexact = posterior_moments(y, h, pts, n0)
for a, b in zip(mu, mean):
self.assertAlmostEqual(a, b, delta=1e-6)
for a, b in zip(var, vexact):
self.assertAlmostEqual(a, b, delta=1e-6)
def test_agrees_with_ml_at_high_snr(self):
# 4-QAM, n = 4, m = 4, 15 dB, seed 2204: 97 of 100 in the reference run.
rng = random.Random(2204)
pts = constel.qam(4)
n0 = cbb.undb(-15.0)
agree = 0
for _ in range(100):
h = iid(rng, 4, 4)
y = cbb.awgn(rng, cbb.matvec(h, [pts[rng.randrange(4)] for _ in range(4)]), n0)
agree += ep_detect(y, h, pts, n0) == constel.ml_vector(y, h, pts)
self.assertGreaterEqual(agree, 92)
def test_fewer_errors_than_lmmse(self):
# 4-QAM, n = m = 8, 10 dB, seed 2206, 40 vectors (320 symbols): 19 errors against 38.
rng = random.Random(2206)
pts = constel.qam(4)
n0 = cbb.undb(-10.0)
e_ep = e_lin = 0
for _ in range(40):
h = iid(rng, 8, 8)
idx = [rng.randrange(4) for _ in range(8)]
y = cbb.awgn(rng, cbb.matvec(h, [pts[i] for i in idx]), n0)
e_ep += sum(a != b for a, b in zip(ep_detect(y, h, pts, n0), idx))
e_lin += sum(a != b for a, b in zip(ep_detect(y, h, pts, n0, iters=0), idx))
self.assertLessEqual(5 * e_ep, 3 * e_lin)
if __name__ == "__main__":
unittest.main()
History
Minka (2001) introduced expectation propagation as a general method for approximate Bayesian inference, an extension of assumed-density filtering that can revisit each factor. It has been used for many models since. Céspedes, Olmos, Sánchez-Fernández and Pérez-Cruz (2014) applied EP to MIMO detection with high-order constellations, with the real-valued model, the rule for negative precisions and damping. They reported a large gain over MMSE at a complexity of the same cubic order. Later work extended EP detection to massive MIMO with lower-cost inverses and to iterative receivers with channel decoding.
References
- Javier Céspedes, Pablo M. Olmos, Matilde Sánchez-Fernández and Fernando Pérez-Cruz, Expectation propagation detection for high-order high-dimensional MIMO systems, IEEE Transactions on Communications 62(8), 2840-2849, 2014, the EP detector for the real-valued MIMO model: the Gaussian site factors, the cavity and moment-matching updates, the rule that keeps the old site when the new precision is negative, the damping, and the comparison with MMSE and other detectors
- Thomas P. Minka, Expectation propagation for approximate Bayesian inference, Proc. 17th Conference on Uncertainty in Artificial Intelligence (UAI), 2001, the general EP algorithm: exponential-family approximation, removal of one site, moment matching and the site update
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag R4B3XS Edit this page History Report an error Markdown