Algorithmresearch
Approximate message passing MIMO detection
Also called AMP detector, LAMA.
Detects a large MIMO system by approximate message passing with a symbol denoiser. For large i.i.d. channels its error rate is predicted by a scalar recursion, and it can reach the optimal error rate.
- Solves
- MIMO detection
- Time
- O(T (n m + n M)) worst
- Space
- O(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 mlnot needs matrix inverseneeds noise level
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Charles Jeon, Ramina Ghods, Arian Maleki, Christoph Studer, 2015
Approximate message passing (AMP) MIMO detection solves the MIMO detection problem for large systems by an iteration that costs two matrix-vector products per step and needs no matrix inverse. Each step forms one noisy copy of every transmitted symbol, removes the noise from it with the exact posterior mean for the constellation, and corrects the residual with an extra term, the Onsager term. For a channel with many antennas and i.i.d. zero-mean entries, the copies behave like plus Gaussian noise of a variance that a scalar recursion, the state evolution, predicts. So the large MIMO channel splits into scalar AWGN channels. The detector of this page is LAMA (large MIMO AMP) of Jeon, Ghods, Maleki and Studer (2015). The general AMP method for linear inverse problems, with sparse priors and soft thresholding, is on the approximate message passing page. This page uses a discrete constellation prior and adds the MIMO results. Expectation propagation detection has a similar goal, but it works for small and correlated channels and inverts an matrix at each step.
In plain words
The receiver wants to know every symbol, and each antenna hears a mix of all of them. AMP guesses all symbols at once, computes what the antennas would hear for that guess, and looks at the difference. It uses the difference to make a new noisy copy of each symbol. Then it cleans each copy on its own: it knows that a symbol must be one of a few points, so it replaces the copy by the average of those points, weighted by how likely each one is. The clever part is a small correction term in the difference. Without it, the errors of one step feed back into the next one and pile up. With it, the error in each copy looks like fresh Gaussian noise of a known size. This is only true when the channel is large and random enough.
The problem
The model is with known, for a constellation of equally likely points with mean 0 and energy , and . The SNR is per complex symbol. The system ratio is . The theory of AMP assumes that the entries of are i.i.d. , so every column has a squared norm close to 1, and that and are large with fixed. The detector returns decisions and, for soft output, the copies with their noise variance .
The algorithm
For a point and a variance , let the weights be for , normalized to sum 1. These are the posterior probabilities of given . The denoiser is the posterior mean , and is the posterior variance.
AMP-DETECT(y, H, S, N0, T)- 1
x̂ ← (E[X], ..., E[X]) ▷ the prior mean, 0 here - 2
r ← y - H x̂; s² ← N0 + β Var[X] - 3
for t ← 1 to T - 4
z ← x̂ + Hᴴ r ▷ z_k ≈ x_k + CN(0, s²) - 5
for each k: x̂'_k ← F(z_k, s²), g_k ← G(z_k, s²) - 6
r ← y - H x̂' + (β ḡ / s²) r ▷ ḡ = the mean of g_k; Onsager term - 7
s² ← N0 + β ḡ; x̂ ← x̂' - 8
for each k: x̂_k ← the point of S nearest to z_k - 9
return x̂
Line L4 adds the matched filter output of the residual to the current estimate. Line L5 is independent scalar posterior computations of each. The term of line L6 is the Onsager term: is the mean derivative of with respect to , so the term subtracts the part of the residual that comes from the estimate's own dependence on the earlier residual. Line L7 updates the noise variance. In LAMA this variance is written , with ; it is the same quantity. Line L8 is the ML decision for the scalar channel with equal priors. A soft-output receiver instead computes bit LLRs from and as in soft demapping.
Example
A small channel, where AMP fails. Take BPSK, , the channel of the ZF page with unit-norm columns,
and . Then , and line L2 sets and . For BPSK, and . The first step gives
, , and the new . The next steps give these values of (real parts, from the implementation):
| step | after the step | ||
|---|---|---|---|
| 1 | 0.7155 | 0.7778 | 0.5586 |
| 2 | 0.0889 | 0.1956 | 1.0197 |
| 3 | -0.8603 | -0.4116 | 0.5909 |
| 4 | 0.9588 | 1.3240 | 0.2533 |
| 5 | -0.2224 | -0.1569 | 0.4491 |
The signs flip from step to step, and the iteration does not settle. The ML vector is , with metric 0.588 against 0.837 for . Here the two columns have the correlation , and with is far from the large i.i.d. setting that AMP needs.
A large random channel, where AMP works. Take 4-QAM, , (), i.i.d. entries and ( dB). The state evolution (Monte Carlo with 4000 samples, seed 2105) and the mean of measured over 20 channels (seed 7) are:
| step | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| state evolution | 0.750 | 0.429 | 0.344 | 0.316 | 0.307 | 0.304 | 0.303 |
| measured | 0.796 | 0.413 | 0.328 | 0.303 | 0.297 | 0.289 | 0.290 |
| measured symbol error rate | 0.219 | 0.127 | 0.088 | 0.084 | 0.069 | 0.063 | 0.066 |
The fixed point predicts the symbol error rate of 4-QAM on the scalar channel, and the measurement is 0.066 (measurement, 640 symbols). For comparison, the linear MMSE detector in the same large system has the decoupled variance 0.390, the root of , and the error rate 0.106. The prior of the constellation gains 1.1 dB over the linear filter here.
Correctness
The proof is in proofs/correctness.md. It shows four things. First, and are the exact posterior mean and variance of a symbol seen through the scalar channel , and line L8 is the exact ML decision for that channel (a theorem). Second, with the Gaussian prior in place of the constellation, every fixed point of the iteration is the linear MMSE estimate , for every (a theorem; the test checks it within ). Third, for i.i.d. Gaussian in the large system limit, the state evolution gives the variance of at each step (a theorem of Bayati and Montanari for the real case with Lipschitz denoisers, stated for the complex case by Jeon et al.; this page does not prove it). Fourth, if the state evolution has a unique fixed point, the LAMA error rate equals that of the individually optimal detector. That statement rests on the replica method of statistical physics for the optimal detector, so it is a theorem only where the replica prediction has been proved; Jeon et al. give the conditions on , the SNR and the constellation.
Proof: The AMP denoiser is the exact scalar posterior, the Gaussian-prior fixed point is the linear MMSE estimate, and the state evolution describes the large systempartial
The model is with , with equally likely points, and . Let . The lines L1 to L9 are those of the pseudocode on the page. Theorems 1 to 3 below are proved in full. Theorem 4 is quoted with its source and hypotheses, and Statement 5 is quoted with its status. That is why the status of this file is partial.
Theorem 1 (the denoiser and the decision)
Let with uniform on and independent of . Then with , , , and the decision of line L8 maximizes .
Proof. The density of is . By Bayes' rule, , and the factors that do not depend on cancel in the normalization. So the posterior is . Its mean is and its variance is . The largest belongs to the with the smallest , which is the point that line L8 picks.
The mean minimizes among all functions of , which is why AMP uses it as the denoiser.
Lemma 2 (the Onsager coefficient)
With the Wirtinger derivative (treating and as independent), .
Proof. Write with . Then , so
Hence .
So the factor in line L6 is times the average derivative of the denoiser over the streams. This is the Onsager coefficient of AMP (Donoho, Maleki and Montanari 2009), which is .
Theorem 3 (the Gaussian prior gives the linear MMSE estimate)
Replace the constellation prior by , so that and with . Let . If is a fixed point of lines L4 to L7, then
and solves .
Proof. The variance is the same for every stream, so , and line L7 at the fixed point reads , which is the stated equation. It gives , so .
Line L6 at the fixed point reads , so . Lines L4 and L5 at the fixed point read , so . Here . Put in :
The factor on the left is . So , and the matrix is positive definite, which gives the formula.
The proof uses no property of . So whenever the iteration converges, it converges to the output of the linear MMSE filter before the bias correction. This fixes the scale of : AMP with a Gaussian prior is a way to compute the MMSE estimate without an inverse. The test checks the formula within on five channels with and .
Theorem 4 (state evolution, quoted)
Bayati and Montanari (2011, IEEE Trans. IT 57(2)) prove the following for the real model. Let the entries of be i.i.d. , let with , let the entries of be i.i.d. from a distribution with finite moments, and let the denoisers be Lipschitz and fixed in advance (they may depend on but not on the data). Then for each fixed , the empirical distribution of converges to in the sense of pseudo-Lipschitz test functions, where
independent of , and is the noise variance per real dimension.
Jeon, Ghods, Maleki and Studer state the complex form with and the posterior mean denoiser (Theorem 1 and Corollary 2 of arXiv:1811.01917). The posterior mean for a finite constellation at a fixed is Lipschitz, because both of its Wirtinger derivatives, from Lemma 2 and by the same computation, have modulus at most . The implementation uses the empirical in line L7 instead of the deterministic , as LAMA does; the two agree in the limit, but the theorem as quoted is for the deterministic sequence.
Statement 5 (individual optimality, quoted with its status)
Jeon et al. compare the fixed point of the state evolution with the decoupled noise variance of the individually optimal detector, which Guo and Verdú (2005) derived by the replica method. If the state evolution has a unique fixed point, the two coincide, and LAMA reaches the individually optimal error rate in the large system limit. The step that identifies the optimal detector's variance uses the replica method, which is not a proof in general. For some settings it has since been proved, so read this statement as a theorem only under the hypotheses of those proofs.
What the tests check
- Theorem 1: the denoiser against the BPSK closed form , , within , and against a direct posterior for 16-QAM.
- Theorem 3: the Gaussian-prior fixed point against the linear MMSE solve, within , and the equation for within .
- Theorem 4, as a measurement: for , , 4-QAM and , the measured mean of is within 25 percent of the tracked and of the state evolution.
- Suboptimality: agreement with brute-force ML on at least 95 of 100 vectors at 15 dB (seed 2103; 98 in the run), and exact recovery of 30 of 30 noiseless vectors (seed 2102).
Complexity
Each iteration costs two matrix-vector products, and , of complex multiplications each, and denoiser calls of each. So iterations cost in the real RAM, with space for . There is no matrix inverse and no factorization, which is the main gain over the MMSE detector at per channel when is in the hundreds. The number of iterations does not grow with in the large system limit, because the state evolution does not depend on ; 10 to 20 steps are typical.
Properties
- Decoupling. In the large i.i.d. setting each stream sees a scalar AWGN channel of variance (theorem, in the limit). The test checks the tracked against the measured noise within 25 percent for , .
- Linear MMSE as a special case. With a Gaussian prior, the fixed point is the linear MMSE estimate (theorem).
- Possible optimality. For some , SNR and constellations, the error rate reaches that of the individually optimal detector in the limit (see Correctness for the status of this claim).
- Measured agreement with ML. For 4-QAM, , , i.i.d. entries and dB, the test with seed 2103 runs 100 vectors, and AMP with 15 steps agrees with brute-force ML on 98 (measurement).
- Noiseless recovery. With , , and 4-QAM, AMP recovered all 30 test vectors (seed 2102, measurement).
- No guarantee for small or correlated channels. The iteration can oscillate or diverge, as the first example shows.
Variants and improvements
- Damping. Replace by a convex combination of the new and the old estimate. This helps on mildly correlated channels but removes the exact state evolution.
- Orthogonal and vector AMP. OAMP and VAMP replace the matched filter step by a linear MMSE step and keep a state evolution for right-rotationally invariant matrices, a much larger class than i.i.d. They need a matrix inverse or an SVD per channel.
- Mismatched noise. LAMA allows a postulated noise ; Jeon et al. give the state evolution for this case.
- Soft output for coding. The pairs feed a soft demapper and then an LDPC or turbo decoder, as in turbo equalization.
- Real-valued form. Writing the complex model as a real model of size gives the AMP of compressed sensing with a PAM prior.
When to use it
Use AMP in large MIMO uplinks with and in the tens to hundreds and channels close to i.i.d., where the inverse of the MMSE detector is too costly and a gain over linear detection is wanted. For small systems use a sphere search such as Schnorr-Euchner enumeration or the K-best detector. For correlated channels use expectation propagation detection or a damped or vector form of AMP. In massive MIMO with , the linear detectors are already close to optimal, and AMP gains little.
Pitfalls
- Small or correlated channels. The state evolution is a large-system result for i.i.d. entries. On a small or correlated channel AMP can oscillate, as in the example.
- Wrong normalization. The iteration assumes columns of squared norm about 1 (entries of variance ). Scale and before the iteration, and keep consistent with the scaling.
- Dropping the Onsager term. Without it, the iteration is iterative soft thresholding with a constellation denoiser. The noise in is then not Gaussian, and the tracked is wrong.
- Overflow in the denoiser. At small the weights underflow. Subtract the largest exponent first, as the implementation does.
- Reading the limit theorems as finite results. The decoupling and the optimality are statements in the limit . For finite sizes they are good approximations, and the agreement must be measured.
- Nonzero mean constellations. Line L1 starts at the prior mean. With a constellation of nonzero mean, in line L2 is not .
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
# Part of https://algorithm.tamnd.com/amp-mimo-detection/. The authors are listed in prov/V4YK5H.jsonl.
"""Approximate message passing (AMP) for MIMO detection, in the LAMA form.
The model is y = H x + w with H an m by n complex matrix, x a vector of n
equally likely points of a constellation, and w ~ CN(0, N0 I). AMP is built
for large i.i.d. channels with entries CN(0, 1/m), so that each column has
squared norm close to 1. beta = n / m is the system ratio.
Each iteration forms the pseudo-observation z = xhat + H^H r. In the large
system limit z behaves like x + CN(0, s2) for each stream, and the tracked
value s2 is the variance of that effective noise. The denoiser F is the
posterior mean of a symbol seen through that scalar channel, and G is the
posterior variance. The residual r carries the Onsager term
(beta mean(G) / s2) r_old, which keeps z close to Gaussian around x.
This is the LAMA iteration of Jeon, Ghods, Maleki and Studer (ISIT 2015;
Algorithm 2 of arXiv:1811.01917), written with s2 = N0 (1 + tau).
The prior "gaussian" replaces the constellation by CN(0, Es); then the
fixed point of the iteration is the linear MMSE estimate.
"""
import math
import cbb
def denoise(z: complex, s2: float, points: list[complex]) -> tuple[complex, float]:
"""(F, G): the posterior mean and variance of X, uniform on points, given z = X + CN(0, s2)."""
s2 = max(s2, 1e-300)
logs = [-abs(z - a) ** 2 / s2 for a in points]
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, points)) / tot
var = sum(w * abs(a - mean) ** 2 for w, a in zip(ws, points)) / tot
return mean, var
def denoise_gaussian(z: complex, s2: float, es: float) -> tuple[complex, float]:
"""(F, G) for the prior X ~ CN(0, Es): the linear shrinkage Es z / (Es + s2)."""
return es * z / (es + s2), es * s2 / (es + s2)
def amp(y: list[complex], h: list[list[complex]], points: list[complex] | None, n0: float, iters: int = 20, es: float = 1.0) -> tuple[list[complex], list[complex], float]:
"""Run the AMP iteration. Returns (xhat, z, s2) after the last iteration.
points=None selects the Gaussian prior CN(0, es). xhat is the posterior
mean, z the last pseudo-observation and s2 the tracked variance of z - x.
"""
m, n = len(h), len(h[0])
beta = n / m
hh = cbb.herm(h)
if points is None:
mu, var0 = 0j, es
else:
mu = sum(points) / len(points)
var0 = sum(abs(a - mu) ** 2 for a in points) / len(points)
xhat = [mu] * n # @line L1
r = cbb.sub(y, cbb.matvec(h, xhat))
s2 = n0 + beta * var0 # @line L2
z = xhat
for _ in range(iters): # @line L3
z = cbb.add(xhat, cbb.matvec(hh, r)) # @line L4
if points is None:
fg = [denoise_gaussian(v, s2, es) for v in z]
else:
fg = [denoise(v, s2, points) for v in z] # @line L5
xnew = [f for f, _ in fg]
gbar = sum(g for _, g in fg) / n
onsager = beta * gbar / max(s2, 1e-300)
r = [yi - hx + onsager * ri for yi, hx, ri in zip(y, cbb.matvec(h, xnew), r)] # @line L6
s2 = n0 + beta * gbar # @line L7
xhat = xnew
return xhat, z, s2
def amp_detect(y: list[complex], h: list[list[complex]], points: list[complex], n0: float, iters: int = 20) -> list[int]:
"""The AMP decisions: for each stream, the point nearest to the last pseudo-observation z_k."""
_, z, _ = amp(y, h, points, n0, iters)
out = []
for zk in z: # @line L8
out.append(min(range(len(points)), key=lambda i: abs(zk - points[i])))
return out # @line L9
def state_evolution(points: list[complex], n0: float, beta: float, iters: int, samples: int, rng) -> list[float]:
"""The state evolution s2_(t+1) = N0 + beta E|F(X + sqrt(s2_t) Z, s2_t) - X|^2, by Monte Carlo.
Returns the list s2_1, ..., s2_(iters+1), with s2_1 = N0 + beta Var[X].
The same draws of X and Z are reused at every step.
"""
mu = sum(points) / len(points)
var0 = sum(abs(a - mu) ** 2 for a in points) / len(points)
xs = [points[rng.randrange(len(points))] for _ in range(samples)]
zs = [cbb.cn(rng, 1.0) for _ in range(samples)]
out = [n0 + beta * var0]
for _ in range(iters):
s2 = out[-1]
sd = math.sqrt(s2)
mse = sum(abs(denoise(x + sd * g, s2, points)[0] - x) ** 2 for x, g in zip(xs, zs)) / samples
out.append(n0 + beta * mse)
return out
cbb.py 315 lines
# 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))
test_amp_mimo_detection.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/amp-mimo-detection/. The authors are listed in prov/V4YK5H.jsonl.
import math
import random
import cbb
import constel
from amp_mimo_detection import amp, amp_detect, denoise, denoise_gaussian, state_evolution
def iid(rng, m, n):
"""An m by n channel with i.i.d. CN(0, 1/m) entries."""
return [[cbb.cn(rng, 1.0 / m) for _ in range(n)] for _ in range(m)]
def test_denoiser_bpsk_closed_form() -> None:
bpsk = constel.pam(2)
for z in (0.3 - 0.2j, -1.1 + 0.5j, 2.0 + 0j, -0.05 + 1j):
for s2 in (0.1, 0.5, 2.0):
f, g = denoise(z, s2, bpsk)
t = math.tanh(2 * z.real / s2)
assert abs(f - t) < 1e-12
assert abs(g - (1 - t * t)) < 1e-12
def test_denoiser_against_direct_posterior() -> None:
pts = constel.qam(16)
z, s2 = 0.4 - 0.7j, 0.3
ws = [math.exp(-abs(z - a) ** 2 / s2) for a in pts]
mean = sum(w * a for w, a in zip(ws, pts)) / sum(ws)
var = sum(w * abs(a - mean) ** 2 for w, a in zip(ws, pts)) / sum(ws)
f, g = denoise(z, s2, pts)
assert abs(f - mean) < 1e-12 and abs(g - var) < 1e-12
f, g = denoise(5 + 5j, 1e-6, pts) # far away: no overflow, mass on the corner
assert abs(f - pts[0]) < 1e-9 and g < 1e-9
f, g = denoise_gaussian(1 + 1j, 0.5, 1.0)
assert abs(f - (1 + 1j) / 1.5) < 1e-12 and abs(g - 0.5 / 1.5) < 1e-12
def test_example_on_the_page() -> None:
h = [[2 / math.sqrt(5), 1 / math.sqrt(2)], [1 / math.sqrt(5), 1 / math.sqrt(2)]]
y = [0.5, 0.6]
bpsk = constel.pam(2)
xhat, z, s2 = amp(y, h, bpsk, 0.25, iters=1)
assert abs(z[0] - 1.0 / math.sqrt(5) * 1.6) < 1e-12
assert abs(z[1] - 1.1 / math.sqrt(2)) < 1e-12
assert abs(xhat[0] - math.tanh(2 * z[0].real / 1.25)) < 1e-12
def test_gaussian_prior_fixed_point_is_lmmse() -> None:
rng = random.Random(2101)
for _ in range(5):
m, n = 24, 6
h = iid(rng, m, n)
x = [cbb.cn(rng, 1.0) for _ in range(n)]
n0 = 0.2
y = cbb.awgn(rng, cbb.matvec(h, x), n0)
xa, _, s2 = amp(y, h, None, n0, iters=200)
hh = cbb.herm(h)
g = cbb.matmul(hh, h)
for k in range(n):
g[k][k] += n0
xl = cbb.solve(g, cbb.matvec(hh, y))
assert max(abs(a - b) for a, b in zip(xa, xl)) < 1e-8
# the tracked variance solves s2 = N0 + beta Es s2 / (Es + s2)
assert abs(s2 - (n0 + (n / m) * s2 / (1 + s2))) < 1e-9
def test_noiseless_recovery() -> None:
rng = random.Random(2102)
qpsk = constel.qam(4)
ok = 0
for _ in range(30):
m, n = 32, 8
h = iid(rng, m, n)
idx = [rng.randrange(4) for _ in range(n)]
y = cbb.matvec(h, [qpsk[i] for i in idx])
if amp_detect(y, h, qpsk, 0.0, iters=15) == idx:
ok += 1
assert ok == 30
def test_agreement_with_ml_at_high_snr() -> None:
# 4-QAM, n = 4 streams, m = 8 receive antennas, Es/N0 = 15 dB, seed 2103:
# AMP agrees with brute-force ML on at least 95 of 100 vectors.
rng = random.Random(2103)
qpsk = constel.qam(4)
n0 = cbb.undb(-15.0)
agree = 0
for _ in range(100):
h = iid(rng, 8, 4)
idx = [rng.randrange(4) for _ in range(4)]
y = cbb.awgn(rng, cbb.matvec(h, [qpsk[i] for i in idx]), n0)
if amp_detect(y, h, qpsk, n0, iters=15) == constel.ml_vector(y, h, qpsk):
agree += 1
assert agree >= 95
def test_effective_noise_matches_tracked_variance() -> None:
# n = 32, m = 64 (beta = 0.5), 4-QAM, N0 = 0.25: the measured mean of |z_k - x_k|^2
# is within 25 percent of the tracked s2 and of the state evolution value.
rng = random.Random(2104)
qpsk = constel.qam(4)
m, n, n0, iters = 64, 32, 0.25, 6
meas, track = 0.0, 0.0
trials = 8
for _ in range(trials):
h = iid(rng, m, n)
x = [qpsk[rng.randrange(4)] for _ in range(n)]
y = cbb.awgn(rng, cbb.matvec(h, x), n0)
_, z, s2 = amp(y, h, qpsk, n0, iters=iters)
meas += sum(abs(a - b) ** 2 for a, b in zip(z, x)) / n
# s2 returned is the next value; z used the previous one, so recompute by one more run
_, _, s2prev = amp(y, h, qpsk, n0, iters=iters - 1)
track += s2prev
meas /= trials
track /= trials
se = state_evolution(qpsk, n0, n / m, iters - 1, 4000, random.Random(2105))[-1]
assert abs(meas - track) / track < 0.25
assert abs(meas - se) / se < 0.25
assert n0 < se < n0 + (n / m)
History
Message passing on dense graphs was used in CDMA multiuser detection from statistical physics in the early 2000s. Donoho, Maleki and Montanari (2009) wrote the AMP iteration for compressed sensing, with the Onsager term and the state evolution, and Bayati and Montanari (2011) proved the state evolution for i.i.d. Gaussian matrices. Jeon, Ghods, Maleki and Studer (2015) adapted the complex Bayesian form to MIMO detection with discrete constellations, named it LAMA, and gave conditions under which it reaches the individually optimal detector in the large system limit. Later work on orthogonal and vector AMP extended the method to a much larger class of channel matrices.
References
- Charles Jeon, Ramina Ghods, Arian Maleki and Christoph Studer, Optimality of large MIMO detection via approximate message passing, Proc. IEEE International Symposium on Information Theory (ISIT), Hong Kong, 2015, pages 1227-1231, the LAMA iteration for complex constellations, its state evolution and the conditions under which it reaches the individually optimal detector
- Charles Jeon, Ramina Ghods, Arian Maleki and Christoph Studer, Optimal data detection in large MIMO, arXiv:1811.01917, 2018, Section II-A (the model, assumptions A1 and A2, beta = MT / MR), Section III-B (Algorithm 2, LAMA, and the denoisers F and G), Theorem 1 and Corollary 2 (state evolution), and Section IV (optimality, which uses the replica method for the optimal detector)
- David L. Donoho, Arian Maleki and Andrea Montanari, Message-passing algorithms for compressed sensing, Proceedings of the National Academy of Sciences 106(45), 18914-18919, 2009, the AMP iteration with the Onsager term and its state evolution
- Mohsen Bayati and Andrea Montanari, The dynamics of message passing on dense graphs, with applications to compressed sensing, IEEE Transactions on Information Theory 57(2), 764-785, 2011, the proof of state evolution for i.i.d. Gaussian matrices and Lipschitz denoisers in the large system limit
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 V4YK5H Edit this page History Report an error Markdown