Algorithmadvanced
Semidefinite relaxation detection
Also called SDR detector.
Relaxes ML detection of BPSK or 4-QAM vectors to a semidefinite program over matrices with unit diagonal, solves it, and rounds the solution to a symbol vector, with a lower bound that can prove ML.
- Solves
- MIMO detection
- Time
- O(N^2 m + T N^2 k + J N^3 + R N^2) worst
- Space
- O(N^2 + N m) extra
- Where
- J = the number of Jacobi sweeps; N = the number of real binary symbols; R = the number of rounding draws; T = the number of mixing sweeps; k = the rank of the low-rank factor; m = the number of real receive dimensions
- Model
- Real RAM
- Properties
- certifies ml when tightnot exact mlexact without noisegives lower boundnot needs noise level
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter H. Tan, Lars K. Rasmussen, 2001
Semidefinite relaxation (SDR) detection is an approximate method for the MIMO detection problem with binary symbols: BPSK, or 4-QAM, which is BPSK in each real dimension. ML detection then minimizes a quadratic form over the corners of a cube, a problem of the same kind as maximum cut and NP-hard in general. SDR writes the quadratic form with the rank-one matrix and replaces that matrix by any positive semidefinite matrix with a unit diagonal. The result is a semidefinite program, a convex relaxation that is solvable in polynomial time. Its value is a lower bound on the ML metric. A rounding step turns its solution into a symbol vector. When the rounded vector has a metric equal to the lower bound, the vector is proved to be ML (a theorem). The implementation is a teaching solver, described below.
In plain words
The receiver must choose a sign, plus or minus, for each of several signals so that the total error is smallest. Trying every choice takes too long. The receiver first solves an easier problem, where each sign may be any arrow of length one in a space with a few dimensions, not only plus or minus. The easier problem has no traps and can be solved well. Its best error is never larger than the best error of the real problem. Then the receiver cuts the space with random flat walls and gives each signal the sign of the side its arrow is on. If the result is as good as the lower limit, the receiver knows it has the best answer.
The problem
The model is with known, a vector of BPSK or 4-QAM points, and . In the real-valued form (as on the LR-aided detection page), every real symbol is with , where for BPSK and for unit-energy 4-QAM. With (an real matrix) and the real received vector , ML detection is
With one more sign and ,
so is recovered from an optimal as (a closed form). The SDR is
whose dual is subject to (by Lagrangian duality).
The algorithm
SDR-DETECT(y, H, S, R)- 1
(G, y_r) ← REAL-VALUED MODEL(y, H) ▷ x = a b with b in {-1, +1}^N - 2
Q ← the homogeneous matrix of (G, y_r) - 3
repeat for T sweeps or until the vectors stop moving - 4
for i ← 0 to N: u_i ← -g / ‖g‖ with g = Σ_{j≠i} Q_ij u_j ▷ mixing method, X = U Uᵀ - 5
λ_i ← (Q U Uᵀ)_ii for each i - 6
lower ← Σ λ_i + (N + 1) λ_min(Q - Diag(λ)) ▷ a valid dual bound - 7
b ← (sign(u_i · u_N))_{i<N} ▷ deterministic rounding - 8
repeat R times: draw r ~ N(0, I); b ← sign(u_N · r) (sign(u_i · r))_{i<N}; keep the b with the smallest metric - 9
return the points a b as constellation indices, and the bound
An interior-point method solves the SDR to any accuracy in polynomial time, but it is long to write. The teaching solver of lines L3 and L4 is the mixing method: it writes with unit rows , so the diagonal constraint holds by construction, and it minimizes over one at a time. With the others fixed, the objective is , which minimizes exactly. The rank is , enough to hold an optimal solution, because some optimal has a rank with (a theorem of Barvinok and Pataki). The solver does not prove that it reached the optimum. Lines L5 and L6 make that unnecessary for the bound: for any unit vectors, is dual feasible, so line L6 is a valid lower bound on the SDR value and so on the ML metric. The smallest eigenvalue comes from the Jacobi eigenvalue algorithm.
Line L8 is the random hyperplane rounding of Goemans and Williamson: each vector gets the sign of its side of a random hyperplane, relative to the side of , the vector of . This is a form of randomized rounding.
Example
Take BPSK over and , the example of the ZF page, sent with . Here and
The four sign vectors have the metrics 0.61 for , 2.61, 8.21 and 19.01, so ML gives with 0.61. The solver of the implementation (seed 0) stops after 25 sweeps with , and line L6 gives the lower bound , so the SDR value is about 0.5972 (a measurement on this example). It is below 0.61, so the relaxation is not tight here, and no rank-one matrix is optimal. The rounding still returns , the ML vector, with metric 0.61. The bound shows that no vector can have a metric below 0.5972, but it cannot prove that 0.61 is optimal; the brute-force list above does.
Correctness
The proof is in proofs/correctness.md. It shows the homogeneous form (a closed form), that the SDR value is at most the ML metric (a theorem), and that line L6 is a lower bound on the SDR value for any unit vectors, by weak duality (a theorem). So if the rounded vector has a metric equal to the bound, it is an ML vector (a theorem). It shows that each update of line L4 does not increase the objective (a theorem). Without noise and with of full column rank, the only optimal is for the transmitted , and the rounding of that matrix returns the transmitted vector (a theorem).
Jaldén and Ottersten (2008) proved that SDR detection has the same diversity order as ML detection for BPSK over real-valued i.i.d. Rayleigh fading (a theorem of the reference, not proved here).
Proof: Correctness of semidefinite relaxation detectionfull
This proof refers to the lines of the pseudocode main on the page. The real-valued model is for and , where has rows and columns. For BPSK, and hold the real and the imaginary parts of and in two blocks of rows, and . For 4-QAM, with , and holds the real signs and then the imaginary signs. In both cases the identity holds because for every entry of . So the ML vectors of the two problems are the same (a closed form). Let be the ML metric.
Theorem 1 (homogeneous form)
Let be the matrix of line L2. For with , .
Proof. Expand: . Since , this equals .
So . An optimal gives the ML vector , and the vector with has metric for , which is the function metric of the implementation.
Theorem 2 (the relaxation is a lower bound)
Let . Then .
Proof. For every , the matrix is positive semidefinite and has , and . So the feasible set of the SDR contains every point of the ML problem in Theorem 1, and the minimum over the larger set is not larger.
The feasible set is compact (all entries satisfy , because every principal minor is nonnegative), so the minimum exists.
Theorem 3 (the bound of line L6 is valid for any unit vectors)
Let be any vectors, let (line L5), and let be the smallest eigenvalue of . Then .
Proof. Put . Then , because its eigenvalues are those of minus their minimum. Let be feasible for the SDR. The trace of the product of two positive semidefinite matrices is nonnegative (write ; then for ). So
This holds for every feasible , so also for the minimum . Theorem 2 gives the second inequality.
This is weak duality for the dual program subject to . The proof uses no property of the vectors , so the bound holds whether the solver of lines L3 and L4 converged or not. In floating point the bound is correct up to the rounding error of the Jacobi method, which the tests allow for with a tolerance of .
Theorem 4 (certificate)
Let be the vector that the algorithm returns, with metric , and let be the bound of line L6. Then . In particular, if , then is an ML vector.
Proof. Theorem 3 gives , so . If , then , and by the definition of , so .
The returned vector is always a feasible point: lines L7 and L8 make a sign vector, and line L8 multiplies it by the sign of , so by Theorem 1 the metric that the algorithm compares is the true metric of that vector. Line L9 maps each (or each pair of real and imaginary parts) to the constellation point that it equals. So the output is a valid symbol vector in all cases, and an ML vector whenever the certificate holds.
Theorem 5 (each step of the mixing method does not increase the objective)
Let with all . Fix all vectors but , and let . If , then minimizes over the unit vectors , and line L4 does not increase .
Proof. Since is symmetric, the terms of that contain are . By the Cauchy-Schwarz inequality, , with equality for . So this choice is a minimizer over the unit sphere, and the value after the update is at most the value before. If , does not depend on , and the implementation leaves unchanged.
So the values after each sweep form a nonincreasing sequence that is bounded below by (every with unit rows gives a feasible ), and so it converges. The proof does not show that the limit is ; Theorem 3 is what makes the bound valid without that.
Theorem 6 (exact without noise)
Let , so for the transmitted , and let have full column rank . Let . Then is the unique optimal solution of the SDR, , and the rounding of lines L7 and L8 applied to any factor with returns .
Proof. By Theorem 1 with , for , and for a general the same expansion gives . So , and for every feasible (as in the proof of Theorem 3). is feasible with , so it is optimal and . Also , attained by .
Uniqueness. The null space of is the set of with , which by the full column rank is , the line spanned by . Let be optimal. Then with gives over the columns of , and each term is nonnegative, so for each . So each column is a multiple of , and for some . The diagonal condition gives .
Rounding. means . In particular for , and since , this gives . Line L7 returns . In line L8, whenever , which has probability one.
The solver of lines L3 and L4 reaches only up to its stopping tolerance, so the implementation gets when its vectors are close enough to that every sign is right. The test with seed 1906 checks this on noiseless instances (a measurement), and Theorem 4 then certifies the result whenever the bound is within rounding of 0.
Theorem 7 (rank of the low-rank factor)
The rank used by the implementation is large enough to hold some optimal solution of the SDR.
Proof. The SDR has linear equality constraints. By the theorem of Barvinok and Pataki, a feasible and bounded SDP in standard form with linear constraints has an optimal solution of rank with . Here , and gives (or in the other case of the minimum). So an optimal factors as with of columns.
The theorem says only that the low-rank set contains an optimum. It does not say that the mixing method finds it; that is why the bound of Theorem 3 does not rely on it.
Summary
Theorem 1 shows that line L2 encodes ML detection exactly. Theorems 2 and 3 show that line L6 gives a lower bound on the ML metric for any output of the solver. Theorem 4 turns that bound into a proof of optimality whenever the rounded metric reaches it. Theorem 5 shows that the solver is monotone. Theorem 6 shows that without noise the relaxation is tight and its unique solution rounds to the transmitted vector. In general the relaxation need not be tight, as the example on the page shows, and the result is then an approximation without a guarantee of optimality.
Complexity
The homogeneous matrix costs . A sweep of the mixing method costs , so sweeps cost with . The Jacobi method costs per sweep, and it needs a few sweeps for full accuracy. Each rounding draw costs for the signs and the metric. The total is in the real RAM (a closed form). The number of sweeps depends on the instance; the solver has no bound on it in terms of . A general interior-point method solves the SDR to a fixed accuracy in polynomial time, which is what makes SDR detection polynomial, against the exponential worst case of ML.
Properties
- Lower bound. Line L6 is a lower bound on the ML metric for any vectors , whether the solver converged or not (theorem).
- Certificate. When the rounded metric equals the bound, the result is ML (theorem). The test with seed 1905 (3x3 4-QAM, i.i.d. Rayleigh, dB, 40 vectors) found this certificate on 21 vectors (a measurement).
- Exact without noise. With and of full column rank, the SDR has the unique solution (theorem).
- Measured agreement with ML. In the same test, SDR agreed with ML on 39 of 40 vectors and ZF on 30 (a measurement).
- Only binary symbols. The constraint models . Larger constellations need more constraints, see below.
- Randomized. The solver starts from random vectors, and the rounding draws random hyperplanes; a fixed seed makes the result reproducible.
Variants and improvements
- Interior-point solvers. Solve the SDR with a general SDP solver, which gives the optimum to a set accuracy and a dual certificate directly. The detection papers above used such solvers.
- Low-rank solvers. The mixing method of this page and the low-rank method of Burer and Monteiro work on with a small number of columns, at a much lower cost per iteration than an interior-point method.
- Higher-order constellations. For 16-QAM, write each real symbol as a sum of two binary variables with weights 2 and 1, or add bound constraints on the diagonal of . Several such relaxations exist, and they are not equally tight.
- Rounding. Use the sign of the leading eigenvector of , or the column of that belongs to , or many random hyperplanes followed by a local search that flips single signs.
- Soft output. Use the candidates of the rounding as a list for bit LLRs, as in the list sphere decoder.
When to use it
Use SDR detection when the symbols are binary or 4-QAM, the number of real dimensions is moderate (tens to a few hundreds), and the receiver needs a quality close to ML with a polynomial cost, or a certificate that a decision is ML. For small a K-best detector or Schnorr-Euchner enumeration is cheaper. For large systems with fast fading, the SDP solve is too slow in practice, and MMSE detection or AMP is preferred.
Pitfalls
- Trusting the solver value. A low-rank or first-order solver can stop before the optimum. Its value is then not a lower bound. Only a dual feasible point, as in line L6, gives a valid bound.
- Forgetting the homogenizing sign. The rounded vector must be multiplied by the sign of ; otherwise half of the rounding draws return the negated vector.
- A singular channel. With , is singular, the noiseless solution is no longer unique, and the relaxation is weaker.
- Scaling of 4-QAM. The binary variables are , but the unit-energy 4-QAM points are , so must include the factor .
- Comparing metrics. The rounding must compare the true metric of each candidate, not the inner products of the vectors.
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))
semidefinite_relaxation_detection.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/semidefinite-relaxation-detection/. The authors are listed in prov/QN7FSW.jsonl.
"""Semidefinite relaxation (SDR) detection of BPSK and 4-QAM vectors.
The model is y = H x + w with x a vector of BPSK (constel.pam(2)) or 4-QAM
(constel.qam(4)) points. In the real-valued model every real symbol is a b_i
with b_i in {-1, +1}, so ML detection is
minimize ||y_r - G b||^2 over b in {-1, +1}^N, G = a H_r.
With the extra variable t in {-1, +1} and v = (b, t), the metric is v^T Q v
for Q = [[G^T G, -G^T y_r], [-y_r^T G, y_r^T y_r]], and the SDR replaces
v v^T by any positive semidefinite X with unit diagonal:
minimize trace(Q X) subject to X_ii = 1 and X positive semidefinite.
This file is a teaching solver. It solves the SDR by the mixing method, a
low-rank coordinate descent over unit vectors u_i with X_ij = u_i . u_j, and
it does not claim the accuracy of an interior-point solver. Its lower bound
is always valid, because it comes from a dual feasible point that is built
from the smallest eigenvalue of Q - Diag(lambda) (Jacobi eigenvalue method).
Candidates come from randomized hyperplane rounding.
"""
import math
import random
import constel
def _dot(a: list[float], b: list[float]) -> float:
return sum(x * y for x, y in zip(a, b))
def _real_model(y, h, points):
"""(G, yr, kind) with ||y - H x||^2 = ||yr - G b||^2 for b in {-1, +1}^N."""
if len(points) == 2 and all(abs(p - q) < 1e-12 for p, q in zip(points, constel.pam(2))):
a, kind = 1.0, "pam"
elif len(points) == 4 and all(abs(p - q) < 1e-12 for p, q in zip(points, constel.qam(4))):
a, kind = 1.0 / math.sqrt(2.0), "qam"
else:
raise ValueError("points must be constel.pam(2) or constel.qam(4)")
yr = [complex(v).real for v in y] + [complex(v).imag for v in y]
if kind == "qam":
top = [[a * complex(c).real for c in row] + [-a * complex(c).imag for c in row] for row in h]
bot = [[a * complex(c).imag for c in row] + [a * complex(c).real for c in row] for row in h]
else:
top = [[complex(c).real for c in row] for row in h]
bot = [[complex(c).imag for c in row] for row in h]
return top + bot, yr, kind
def homogeneous_matrix(g: list[list[float]], yr: list[float]) -> list[list[float]]:
"""Q of size N + 1 with (b, 1)^T Q (b, 1) = ||yr - G b||^2."""
n = len(g[0])
cols = [[row[k] for row in g] for k in range(n)]
q = [[_dot(cols[i], cols[j]) for j in range(n)] + [-_dot(cols[i], yr)] for i in range(n)]
q.append([-_dot(cols[j], yr) for j in range(n)] + [_dot(yr, yr)])
return q
def mixing_method(q: list[list[float]], rank: int, sweeps: int, rng: random.Random, tol: float = 1e-10):
"""Unit vectors u_0, ..., u_N in R^rank that locally minimize sum_ij Q_ij u_i . u_j."""
n = len(q)
u = []
for _ in range(n):
v = [rng.gauss(0.0, 1.0) for _ in range(rank)]
s = math.sqrt(_dot(v, v))
u.append([c / s for c in v])
used = 0
for used in range(1, sweeps + 1): # @line L3
change = 0.0
for i in range(n):
g = [0.0] * rank
for j in range(n):
if j != i and q[i][j] != 0.0:
g = [a + q[i][j] * c for a, c in zip(g, u[j])]
s = math.sqrt(_dot(g, g))
if s == 0.0:
continue
new = [-c / s for c in g] # the exact minimizer over u_i # @line L4
change += sum((a - c) ** 2 for a, c in zip(new, u[i]))
u[i] = new
if change < tol:
break
return u, used
def jacobi_min_eig(a: list[list[float]]) -> float:
"""The smallest eigenvalue of a symmetric matrix, by the cyclic Jacobi method."""
n = len(a)
m = [list(map(float, row)) for row in a]
for _ in range(100):
off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
if off < 1e-22 * max(1.0, sum(m[i][i] ** 2 for i in range(n))):
break
for p in range(n - 1):
for r in range(p + 1, n):
if abs(m[p][r]) < 1e-300:
continue
theta = (m[r][r] - m[p][p]) / (2.0 * m[p][r])
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
s = t * c
for k in range(n):
mkp, mkr = m[k][p], m[k][r]
m[k][p], m[k][r] = c * mkp - s * mkr, s * mkp + c * mkr
for k in range(n):
mpk, mrk = m[p][k], m[r][k]
m[p][k], m[r][k] = c * mpk - s * mrk, s * mpk + c * mrk
return min(m[i][i] for i in range(n))
def dual_bound(q: list[list[float]], u: list[list[float]]) -> tuple[float, float]:
"""(lower bound, relaxed value): a valid lower bound on the SDR value and trace(Q X) for X = U U^T."""
n = len(q)
lam = [sum(q[i][j] * _dot(u[i], u[j]) for j in range(n)) for i in range(n)] # @line L5
s = [[q[i][j] - (lam[i] if i == j else 0.0) for j in range(n)] for i in range(n)]
emin = jacobi_min_eig(s) # @line L6
return sum(lam) + n * emin, sum(lam)
def sdr_detect(
y: list[complex],
h: list[list[complex]],
points: list[complex],
draws: int = 30,
seed: int = 0,
sweeps: int = 300,
info: dict | None = None,
) -> list[int]:
"""Constellation indices from SDR with randomized rounding.
If info is a dict, it receives the lower bound "lower" on the ML metric
of the real model, the metric "metric" of the result, the relaxed value
"relaxed" and the number of sweeps "sweeps".
"""
if draws < 0:
raise ValueError("draws must be at least 0")
g, yr, kind = _real_model(y, h, points) # @line L1
q = homogeneous_matrix(g, yr) # @line L2
n = len(q)
rank = min(n, int(math.ceil(math.sqrt(2.0 * n))) + 1)
rng = random.Random(seed)
u, used = mixing_method(q, rank, sweeps, rng)
lower, relaxed = dual_bound(q, u)
def metric(b):
v = b + [1.0]
return sum(q[i][j] * v[i] * v[j] for i in range(n) for j in range(n))
best = [1.0 if _dot(u[i], u[-1]) >= 0 else -1.0 for i in range(n - 1)] # @line L7
best_m = metric(best)
for _ in range(draws):
r = [rng.gauss(0.0, 1.0) for _ in range(rank)]
st = 1.0 if _dot(u[-1], r) >= 0 else -1.0
b = [st * (1.0 if _dot(u[i], r) >= 0 else -1.0) for i in range(n - 1)] # @line L8
mb = metric(b)
if mb < best_m:
best, best_m = b, mb
if info is not None:
info.update(lower=lower, metric=best_m, relaxed=relaxed, sweeps=used)
nc = len(h[0])
a = 1.0 if kind == "pam" else 1.0 / math.sqrt(2.0)
if kind == "qam":
x = [complex(a * best[k], a * best[nc + k]) for k in range(nc)]
else:
x = [complex(best[k]) for k in range(nc)]
return [constel.ml_detect(v, points) for v in x] # @line L9
test_semidefinite_relaxation_detection.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/semidefinite-relaxation-detection/. The authors are listed in prov/QN7FSW.jsonl.
import math
import random
import pytest
import cbb
import constel
from semidefinite_relaxation_detection import (
_real_model,
dual_bound,
homogeneous_matrix,
jacobi_min_eig,
mixing_method,
sdr_detect,
)
def metric(y, h, pts, idx):
return cbb.norm2(cbb.sub(y, cbb.matvec(h, [pts[i] for i in idx])))
def rand_case(rng, m, n, pts, n0):
h = [[cbb.cn(rng, 1.0) for _ in range(n)] for _ in range(m)]
idx = [rng.randrange(len(pts)) for _ in range(n)]
y = cbb.awgn(rng, cbb.matvec(h, [pts[i] for i in idx]), n0)
return y, h, idx
def objective(q, u):
n = len(q)
return sum(q[i][j] * sum(a * b for a, b in zip(u[i], u[j])) for i in range(n) for j in range(n))
def test_example():
h = [[2, 1], [1, 1]]
y = [0.5, 0.6]
pts = constel.pam(2)
g, yr, _ = _real_model(y, h, pts)
q = homogeneous_matrix(g, yr)
want = [[5, 3, -1.6], [3, 2, -1.1], [-1.6, -1.1, 0.61]]
assert all(abs(q[i][j] - want[i][j]) < 1e-12 for i in range(3) for j in range(3))
info = {}
assert sdr_detect(y, h, pts, info=info) == [0, 1] == constel.ml_vector(y, h, pts)
assert abs(info["metric"] - 0.61) < 1e-12
# the relaxation is not tight here: its value is about 0.5972 < 0.61
assert 0.5971 < info["lower"] <= info["relaxed"] + 1e-12 < 0.5973
def test_homogeneous_metric():
rng = random.Random(1901)
for pts, m, n in ((constel.qam(4), 3, 2), (constel.pam(2), 2, 3)):
for _ in range(10):
y, h, _ = rand_case(rng, m, n, pts, 0.5)
g, yr, kind = _real_model(y, h, pts)
q = homogeneous_matrix(g, yr)
idx = [rng.randrange(len(pts)) for _ in range(n)]
x = [pts[i] for i in idx]
a = 1.0 if kind == "pam" else 1.0 / math.sqrt(2.0)
b = [v.real / a for v in x] + ([v.imag / a for v in x] if kind == "qam" else [])
for t in (1.0, -1.0):
v = [t * c for c in b] + [t]
val = sum(q[i][j] * v[i] * v[j] for i in range(len(v)) for j in range(len(v)))
assert abs(val - metric(y, h, pts, idx)) < 1e-9
def test_jacobi_min_eig():
assert abs(jacobi_min_eig([[2, 1], [1, 2]]) - 1.0) < 1e-12
assert abs(jacobi_min_eig([[4, 1, 0], [1, 3, 1], [0, 1, 2]]) - (3 - math.sqrt(3))) < 1e-12
rng = random.Random(1902)
for n in (2, 4, 7):
for _ in range(5):
a = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(n)]
a = [[a[i][j] + a[j][i] for j in range(n)] for i in range(n)]
e = jacobi_min_eig(a)
# A - e I is positive semidefinite, and A - (e + 1e-6) I is not
shifted = [[a[i][j] - (e - 1e-9 if i == j else 0.0) for j in range(n)] for i in range(n)]
cbb.cholesky(shifted)
with pytest.raises(ValueError):
cbb.cholesky([[a[i][j] - (e + 1e-6 if i == j else 0.0) for j in range(n)] for i in range(n)])
def test_mixing_method_monotone():
rng = random.Random(1903)
y, h, _ = rand_case(rng, 3, 3, constel.qam(4), 0.5)
g, yr, _ = _real_model(y, h, constel.qam(4))
q = homogeneous_matrix(g, yr)
prev = math.inf
for k in range(1, 15):
u, _ = mixing_method(q, 5, k, random.Random(7), tol=0.0)
assert all(abs(sum(c * c for c in v) - 1.0) < 1e-12 for v in u)
val = objective(q, u)
assert val <= prev + 1e-12
prev = val
def test_lower_bound_is_valid():
rng = random.Random(1904)
for pts, m, n in ((constel.qam(4), 2, 2), (constel.pam(2), 4, 4), (constel.qam(4), 3, 3)):
for t in range(6):
y, h, _ = rand_case(rng, m, n, pts, 1.0)
info = {}
got = sdr_detect(y, h, pts, seed=t, info=info)
dml = metric(y, h, pts, constel.ml_vector(y, h, pts))
assert info["lower"] <= dml + 1e-9 <= info["metric"] + 2e-9
assert abs(info["metric"] - metric(y, h, pts, got)) < 1e-9
# an arbitrary point of the sphere also gives a valid bound
g, yr, _ = _real_model(y, h, pts)
q = homogeneous_matrix(g, yr)
u = [[rng.gauss(0, 1) for _ in range(3)] for _ in q]
u = [[c / math.sqrt(sum(d * d for d in v)) for c in v] for v in u]
assert dual_bound(q, u)[0] <= dml + 1e-9
def test_noiseless_exact():
rng = random.Random(1906)
for pts, m, n in ((constel.qam(4), 3, 3), (constel.pam(2), 3, 4)):
for t in range(5):
y, h, idx = rand_case(rng, m, n, pts, 0.0)
info = {}
assert sdr_detect(y, h, pts, seed=t, info=info) == idx
assert abs(info["metric"]) < 1e-9 and info["lower"] < 1e-9 and info["lower"] > -1e-4
def test_bad_arguments():
with pytest.raises(ValueError):
sdr_detect([0j], [[1]], constel.qam(16))
with pytest.raises(ValueError):
sdr_detect([0j], [[1]], constel.psk(4))
with pytest.raises(ValueError):
sdr_detect([0j], [[1]], constel.pam(2), draws=-1)
def test_measured_agreement():
"""Measurement, seed 1905: 3x3 4-QAM, i.i.d. Rayleigh, 5 dB, 40 vectors."""
rng = random.Random(1905)
pts = constel.qam(4)
n0 = cbb.undb(-5)
sdr_ok = zf_ok = certified = 0
for t in range(40):
y, h, _ = rand_case(rng, 3, 3, pts, n0)
ml = constel.ml_vector(y, h, pts)
info = {}
got = sdr_detect(y, h, pts, seed=t, info=info)
sdr_ok += got == ml
hh = cbb.herm(h)
z = cbb.solve(cbb.matmul(hh, h), cbb.matvec(hh, y))
zf_ok += [constel.ml_detect(v, pts) for v in z] == ml
if info["metric"] - info["lower"] < 1e-6:
certified += 1
assert got == ml
# measured on CPython 3: SDR 39 of 40, ZF 30 of 40, 21 certified
assert sdr_ok >= 37 and zf_ok <= 33 and certified >= 15
History
Goemans and Williamson showed in 1995 that a semidefinite relaxation with random hyperplane rounding gives a 0.878-approximation for maximum cut, which started the use of SDR for problems over . Tan and Rasmussen (2001) applied it to multiuser detection in CDMA, and Ma, Davidson, Wong, Luo and Ching (2002) studied it as a quasi-ML detector, with results that applied to MIMO detection. Jaldén and Ottersten proved in 2008 that the SDR detector has the diversity order of ML for BPSK over real-valued Rayleigh fading. Later work extended the relaxation to larger constellations and to soft output.
References
- Peter H. Tan and Lars K. Rasmussen, The application of semidefinite programming for detection in CDMA, IEEE Journal on Selected Areas in Communications 19(8), 1442-1449, 2001, the semidefinite relaxation of binary multiuser detection and its randomized rounding
- Wing-Kin Ma, Timothy N. Davidson, Kon Max Wong, Zhi-Quan Luo and Pak-Chung Ching, Quasi-maximum-likelihood multiuser detection using semi-definite relaxation with application to synchronous CDMA, IEEE Transactions on Signal Processing 50(4), 912-922, 2002, the SDR detector as a quasi-ML detector and its comparison with ML
- Joakim Jaldén and Björn Ottersten, The diversity order of the semidefinite relaxation detector, IEEE Transactions on Information Theory 54(4), 1406-1422, 2008, the proof that SDR has the diversity order of ML for BPSK over real-valued i.i.d. Rayleigh fading
- Michel X. Goemans and David P. Williamson, Improved approximation algorithms for maximum cut and satisfiability problems using semidefinite programming, Journal of the ACM 42(6), 1115-1145, 1995, the random hyperplane rounding of the vectors of a semidefinite solution
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 QN7FSW Edit this page History Report an error Markdown