Algorithm Search⌘K

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.

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
Properties
certifies ml when tightnot exact mlexact without noisegives lower boundnot needs noise level
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 {−1,+1}N\{-1, +1\}^N 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 vvTv v^T 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 y=Hx+wy = H x + w with H∈Cmc×ncH \in \mathbb{C}^{m_c \times n_c} known, xx a vector of BPSK or 4-QAM points, and w∼CN(0,N0I)w \sim \mathcal{CN}(0, N_0 I). In the real-valued form (as on the LR-aided detection page), every real symbol is a bia\, b_i with bi∈{−1,+1}b_i \in \{-1, +1\}, where a=1a = 1 for BPSK and a=1/2a = 1/\sqrt 2 for unit-energy 4-QAM. With G=aHrG = a H_r (an m×Nm \times N real matrix) and the real received vector yry_r, ML detection is

min⁡b∈{−1,+1}N∥yr−Gb∥2.\min_{b \in \{-1, +1\}^N} \|y_r - G b\|^2.

With one more sign tt and v=(b,t)∈{−1,+1}N+1v = (b, t) \in \{-1, +1\}^{N+1},

∥yr−G(tb)∥2=vTQv,Q=(GTG−GTyr−yrTGyrTyr),\|y_r - G (t b)\|^2 = v^T Q v, \qquad Q = \begin{pmatrix} G^T G & -G^T y_r \\ -y_r^T G & y_r^T y_r \end{pmatrix},

so bb is recovered from an optimal vv as t bt\, b (a closed form). The SDR is

min⁡ tr(QX)subject toXii=1, X⪰0,\min\ \mathrm{tr}(Q X) \quad \text{subject to} \quad X_{ii} = 1, \ X \succeq 0,

whose dual is max⁡∑iλi\max \sum_i \lambda_i subject to Q−Diag(λ)⪰0Q - \mathrm{Diag}(\lambda) \succeq 0 (by Lagrangian duality).

The algorithm

  1. SDR-DETECT(y, H, S, R)
  2. 1(G, y_r) ← REAL-VALUED MODEL(y, H) ▷ x = a b with b in {-1, +1}^N
  3. 2Q ← the homogeneous matrix of (G, y_r)
  4. 3repeat for T sweeps or until the vectors stop moving
  5. 4for i ← 0 to N: u_i ← -g / ‖g‖ with g = Σ_{j≠i} Q_ij u_j ▷ mixing method, X = U Uᵀ
  6. 5λ_i ← (Q U Uᵀ)_ii for each i
  7. 6lower ← Σ λ_i + (N + 1) λ_min(Q - Diag(λ)) ▷ a valid dual bound
  8. 7b ← (sign(u_i · u_N))_{i<N} ▷ deterministic rounding
  9. 8repeat 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
  10. 9return 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 X=UUTX = U U^T with unit rows ui∈Rku_i \in \mathbb{R}^k, so the diagonal constraint holds by construction, and it minimizes tr(QUUT)\mathrm{tr}(Q U U^T) over one uiu_i at a time. With the others fixed, the objective is 2ui⋅g+const2 u_i \cdot g + \text{const}, which ui=−g/∥g∥u_i = -g / \|g\| minimizes exactly. The rank is k=⌈2(N+1)⌉+1k = \lceil \sqrt{2 (N + 1)} \rceil + 1, enough to hold an optimal solution, because some optimal XX has a rank rr with r(r+1)/2≤N+1r (r + 1) / 2 \le N + 1 (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, λ+λmin⁡1\lambda + \lambda_{\min} \mathbf 1 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 uNu_N, the vector of tt. This is a form of randomized rounding.

Example

Take BPSK over H=(2111)H = \begin{pmatrix} 2 & 1 \\ 1 & 1 \end{pmatrix} and y=(0.5,0.6)y = (0.5, 0.6), the example of the ZF page, sent with x=(+1,−1)x = (+1, -1). Here N=2N = 2 and

Q=(53−1.632−1.1−1.6−1.10.61).Q = \begin{pmatrix} 5 & 3 & -1.6 \\ 3 & 2 & -1.1 \\ -1.6 & -1.1 & 0.61 \end{pmatrix}.

The four sign vectors have the metrics 0.61 for (+1,−1)(+1, -1), 2.61, 8.21 and 19.01, so ML gives (+1,−1)(+1, -1) with 0.61. The solver of the implementation (seed 0) stops after 25 sweeps with tr(QX)≈0.59720\mathrm{tr}(Q X) \approx 0.59720, and line L6 gives the lower bound ≈0.59720\approx 0.59720, 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 (+1,−1)(+1, -1), 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 vTQv=∥yr−G(tb)∥2v^T Q v = \|y_r - G (t b)\|^2 (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 GG of full column rank, the only optimal XX is vvTv v^T for the transmitted vv, 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 ∥y−Hx∥2=∥yr−Gb∥2\|y - H x\|^2 = \|y_r - G b\|^2 for x=abx = a b and b∈{−1,+1}Nb \in \{-1, +1\}^N, where GG has mm rows and NN columns. For BPSK, yry_r and GG hold the real and the imaginary parts of yy and HH in two blocks of rows, and a=1a = 1. For 4-QAM, G=a(ℜH−ℑHℑHℜH)G = a \begin{pmatrix} \Re H & -\Im H \\ \Im H & \Re H \end{pmatrix} with a=1/2a = 1/\sqrt 2, and bb holds the real signs and then the imaginary signs. In both cases the identity holds because ∣z∣2=(ℜz)2+(ℑz)2|z|^2 = (\Re z)^2 + (\Im z)^2 for every entry of y−Hxy - H x. So the ML vectors of the two problems are the same (a closed form). Let M⋆=min⁡b∥yr−Gb∥2M^\star = \min_b \|y_r - G b\|^2 be the ML metric.

Theorem 1 (homogeneous form)

Let QQ be the matrix of line L2. For v=(b,t)v = (b, t) with t∈{−1,+1}t \in \{-1, +1\}, vTQv=∥yr−G(tb)∥2v^T Q v = \|y_r - G (t b)\|^2.

Proof. Expand: vTQv=bTGTGb−2t bTGTyr+t2yrTyrv^T Q v = b^T G^T G b - 2 t\, b^T G^T y_r + t^2 y_r^T y_r. Since t2=1t^2 = 1, this equals (tb)TGTG(tb)−2(tb)TGTyr+yrTyr=∥yr−G(tb)∥2(t b)^T G^T G (t b) - 2 (t b)^T G^T y_r + y_r^T y_r = \|y_r - G (t b)\|^2. □\square

So min⁡v∈{−1,+1}N+1vTQv=M⋆\min_{v \in \{-1, +1\}^{N+1}} v^T Q v = M^\star. An optimal vv gives the ML vector tbt b, and the vector with t=1t = 1 has metric vTQvv^T Q v for v=(b,1)v = (b, 1), which is the function metric of the implementation.

Theorem 2 (the relaxation is a lower bound)

Let P⋆=min⁡{tr(QX):X⪰0,Xii=1}P^\star = \min \{ \mathrm{tr}(Q X) : X \succeq 0, X_{ii} = 1 \}. Then P⋆≤M⋆P^\star \le M^\star.

Proof. For every v∈{−1,+1}N+1v \in \{-1, +1\}^{N+1}, the matrix X=vvTX = v v^T is positive semidefinite and has Xii=vi2=1X_{ii} = v_i^2 = 1, and tr(QvvT)=vTQv\mathrm{tr}(Q v v^T) = v^T Q v. 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. □\square

The feasible set is compact (all entries satisfy ∣Xij∣≤1|X_{ij}| \le 1, because every 2×22 \times 2 principal minor is nonnegative), so the minimum exists.

Theorem 3 (the bound of line L6 is valid for any unit vectors)

Let u0,…,uNu_0, \dots, u_N be any vectors, let λi=∑jQij ui⋅uj\lambda_i = \sum_j Q_{ij}\, u_i \cdot u_j (line L5), and let ee be the smallest eigenvalue of Q−Diag(λ)Q - \mathrm{Diag}(\lambda). Then ∑iλi+(N+1)e≤P⋆≤M⋆\sum_i \lambda_i + (N + 1) e \le P^\star \le M^\star.

Proof. Put μ=λ+e1\mu = \lambda + e \mathbf 1. Then Q−Diag(μ)=(Q−Diag(λ))−eI⪰0Q - \mathrm{Diag}(\mu) = (Q - \mathrm{Diag}(\lambda)) - e I \succeq 0, because its eigenvalues are those of Q−Diag(λ)Q - \mathrm{Diag}(\lambda) minus their minimum. Let XX be feasible for the SDR. The trace of the product of two positive semidefinite matrices is nonnegative (write X=CCTX = C C^T; then tr(AX)=tr(CTAC)≥0\mathrm{tr}(A X) = \mathrm{tr}(C^T A C) \ge 0 for A⪰0A \succeq 0). So

tr(QX)=tr((Q−Diag(μ))X)+∑iμiXii≥∑iμi=∑iλi+(N+1)e.\mathrm{tr}(Q X) = \mathrm{tr}((Q - \mathrm{Diag}(\mu)) X) + \sum_i \mu_i X_{ii} \ge \sum_i \mu_i = \sum_i \lambda_i + (N + 1) e.

This holds for every feasible XX, so also for the minimum P⋆P^\star. Theorem 2 gives the second inequality. □\square

This is weak duality for the dual program max⁡∑iμi\max \sum_i \mu_i subject to Q−Diag(μ)⪰0Q - \mathrm{Diag}(\mu) \succeq 0. The proof uses no property of the vectors uiu_i, 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 10−910^{-9}.

Theorem 4 (certificate)

Let b^\hat b be the vector that the algorithm returns, with metric M^=∥yr−Gb^∥2\hat M = \|y_r - G \hat b\|^2, and let ℓ\ell be the bound of line L6. Then M^−M⋆≤M^−ℓ\hat M - M^\star \le \hat M - \ell. In particular, if M^=ℓ\hat M = \ell, then b^\hat b is an ML vector.

Proof. Theorem 3 gives ℓ≤M⋆\ell \le M^\star, so M^−M⋆≤M^−ℓ\hat M - M^\star \le \hat M - \ell. If M^=ℓ\hat M = \ell, then M^≤M⋆\hat M \le M^\star, and M^≥M⋆\hat M \ge M^\star by the definition of M⋆M^\star, so M^=M⋆\hat M = M^\star. □\square

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 tt, so by Theorem 1 the metric that the algorithm compares is the true metric of that vector. Line L9 maps each abia b_i (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 f(U)=∑i,jQij ui⋅ujf(U) = \sum_{i,j} Q_{ij}\, u_i \cdot u_j with all ∥ui∥=1\|u_i\| = 1. Fix all vectors but uiu_i, and let g=∑j≠iQijujg = \sum_{j \ne i} Q_{ij} u_j. If g≠0g \ne 0, then ui=−g/∥g∥u_i = -g / \|g\| minimizes ff over the unit vectors uiu_i, and line L4 does not increase ff.

Proof. Since QQ is symmetric, the terms of ff that contain uiu_i are Qii∥ui∥2+2ui⋅g=Qii+2ui⋅gQ_{ii} \|u_i\|^2 + 2 u_i \cdot g = Q_{ii} + 2 u_i \cdot g. By the Cauchy-Schwarz inequality, ui⋅g≥−∥ui∥∥g∥=−∥g∥u_i \cdot g \ge -\|u_i\| \|g\| = -\|g\|, with equality for ui=−g/∥g∥u_i = -g / \|g\|. So this choice is a minimizer over the unit sphere, and the value after the update is at most the value before. If g=0g = 0, ff does not depend on uiu_i, and the implementation leaves uiu_i unchanged. □\square

So the values ff after each sweep form a nonincreasing sequence that is bounded below by P⋆P^\star (every UU with unit rows gives a feasible X=UUTX = U U^T), and so it converges. The proof does not show that the limit is P⋆P^\star; Theorem 3 is what makes the bound valid without that.

Theorem 6 (exact without noise)

Let w=0w = 0, so yr=Gb⋆y_r = G b^\star for the transmitted b⋆b^\star, and let GG have full column rank NN. Let v⋆=(b⋆,1)v^\star = (b^\star, 1). Then X⋆=v⋆v⋆TX^\star = v^\star v^{\star T} is the unique optimal solution of the SDR, P⋆=M⋆=0P^\star = M^\star = 0, and the rounding of lines L7 and L8 applied to any factor UU with UUT=X⋆U U^T = X^\star returns b⋆b^\star.

Proof. By Theorem 1 with t=1t = 1, vTQv=∥Gb⋆−Gb∥2v^T Q v = \|G b^\star - G b\|^2 for v=(b,1)v = (b, 1), and for a general v=(z,s)∈RN+1v = (z, s) \in \mathbb{R}^{N+1} the same expansion gives vTQv=∥G(sb⋆−z)∥2≥0v^T Q v = \|G (s b^\star - z)\|^2 \ge 0. So Q⪰0Q \succeq 0, and tr(QX)≥0\mathrm{tr}(Q X) \ge 0 for every feasible XX (as in the proof of Theorem 3). X⋆X^\star is feasible with tr(QX⋆)=v⋆TQv⋆=0\mathrm{tr}(Q X^\star) = v^{\star T} Q v^\star = 0, so it is optimal and P⋆=0P^\star = 0. Also M⋆=0M^\star = 0, attained by b⋆b^\star.

Uniqueness. The null space of QQ is the set of v=(z,s)v = (z, s) with G(sb⋆−z)=0G (s b^\star - z) = 0, which by the full column rank is z=sb⋆z = s b^\star, the line spanned by v⋆v^\star. Let XX be optimal. Then tr(QX)=0\mathrm{tr}(Q X) = 0 with X=CCTX = C C^T gives ∑kckTQck=0\sum_k c_k^T Q c_k = 0 over the columns ckc_k of CC, and each term is nonnegative, so Qck=0Q c_k = 0 for each kk. So each column is a multiple of v⋆v^\star, and X=αv⋆v⋆TX = \alpha v^\star v^{\star T} for some α≥0\alpha \ge 0. The diagonal condition gives α=1\alpha = 1.

Rounding. UUT=X⋆U U^T = X^\star means ui⋅uj=vi⋆vj⋆u_i \cdot u_j = v^\star_i v^\star_j. In particular ui⋅uN=bi⋆u_i \cdot u_N = b^\star_i for i<Ni < N, and since ∥ui∥=∥uN∥=1\|u_i\| = \|u_N\| = 1, this gives ui=bi⋆uNu_i = b^\star_i u_N. Line L7 returns sign(ui⋅uN)=bi⋆\mathrm{sign}(u_i \cdot u_N) = b^\star_i. In line L8, sign(uN⋅r)⋅sign(ui⋅r)=sign(uN⋅r)2bi⋆=bi⋆\mathrm{sign}(u_N \cdot r) \cdot \mathrm{sign}(u_i \cdot r) = \mathrm{sign}(u_N \cdot r)^2 b^\star_i = b^\star_i whenever uN⋅r≠0u_N \cdot r \ne 0, which has probability one. □\square

The solver of lines L3 and L4 reaches X⋆X^\star only up to its stopping tolerance, so the implementation gets b⋆b^\star when its vectors are close enough to X⋆X^\star 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 k=min⁡(N+1,⌈2(N+1)⌉+1)k = \min(N + 1, \lceil \sqrt{2 (N + 1)} \rceil + 1) used by the implementation is large enough to hold some optimal solution of the SDR.

Proof. The SDR has N+1N + 1 linear equality constraints. By the theorem of Barvinok and Pataki, a feasible and bounded SDP in standard form with pp linear constraints has an optimal solution of rank rr with r(r+1)/2≤pr (r + 1) / 2 \le p. Here p=N+1p = N + 1, and r(r+1)/2≤pr (r + 1) / 2 \le p gives r<2p≤kr < \sqrt{2 p} \le k (or r≤N+1=kr \le N + 1 = k in the other case of the minimum). So an optimal XX factors as UUTU U^T with UU of kk columns. □\square

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 O(N2m)O(N^2 m). A sweep of the mixing method costs O(N2k)O(N^2 k), so TT sweeps cost O(TN2k)O(T N^2 k) with k=O(N)k = O(\sqrt N). The Jacobi method costs O(N3)O(N^3) per sweep, and it needs a few sweeps JJ for full accuracy. Each rounding draw costs O(Nk+N2)O(N k + N^2) for the signs and the metric. The total is O(N2m+TN2k+JN3+RN2)O(N^2 m + T N^2 k + J N^3 + R N^2) in the real RAM (a closed form). The number of sweeps TT depends on the instance; the solver has no bound on it in terms of NN. 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 uiu_i, 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, Es/N0=5E_s / N_0 = 5 dB, 40 vectors) found this certificate on 21 vectors (a measurement).
  • Exact without noise. With w=0w = 0 and GG of full column rank, the SDR has the unique solution vvTv v^T (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 Xii=1X_{ii} = 1 models bi2=1b_i^2 = 1. 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 X=UUTX = U U^T 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 XX. Several such relaxations exist, and they are not equally tight.
  • Rounding. Use the sign of the leading eigenvector of XX, or the column of XX that belongs to tt, 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 NN 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 tr(QX)\mathrm{tr}(Q X) 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 tt; otherwise half of the rounding draws return the negated vector.
  • A singular channel. With N>mN > m, GTGG^T G is singular, the noiseless solution is no longer unique, and the relaxation is weaker.
  • Scaling of 4-QAM. The binary variables are ±1\pm 1, but the unit-energy 4-QAM points are (±1±j)/2(\pm 1 \pm j) / \sqrt 2, so GG must include the factor a=1/2a = 1/\sqrt 2.
  • Comparing metrics. The rounding must compare the true metric ∥yr−Gb∥2\|y_r - G b\|^2 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.

cbb.pyI0RawGitHub
# 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 {−1,+1}N\{-1, +1\}^N. 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

  1. 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
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example