Algorithm Search⌘K

Algorithmcore

SVD precoding

Also called eigenbeamforming, SVD transmission.

Sends streams along the right singular vectors of the channel, which turns a MIMO channel into parallel scalar channels.

Time
O(m n min(m, n)) worst
Space
O(m n) extra
Where
m = the number of receive antennas; n = the number of transmit antennas
Properties
capacity achievingdeterministiclinearneeds channel at transmittersingle user
Origin
Gregory G. Raleigh, John M. Cioffi, Emre Telatar, 1998

SVD precoding is the transmitter that reaches the capacity of a MIMO channel when the transmitter knows the channel. It computes the singular value decomposition H=UΣVHH = U \Sigma V^H, sends stream ii along the right singular vector viv_i, and gives the streams powers by water-filling over the gains si2/N0s_i^2 / N_0. The receiver multiplies by UHU^H. The result is a set of r=rank(H)r = \mathrm{rank}(H) independent scalar channels with no interference between them, so each stream can use its own scalar code and its own bit loading. This is a single-user method: one transmitter and one receiver that has all mm antennas and can apply UHU^H jointly. In a multiuser downlink the users cannot cooperate, so the base station uses zero-forcing precoding or block diagonalization instead. With r=1r = 1 or when only the strongest mode gets power, SVD precoding becomes beamforming on the principal eigenvector, which is maximum ratio transmission. Codebook-based precoding replaces VV by the nearest matrix of a finite set when the transmitter learns the channel only through a few feedback bits, and hybrid beamforming splits VV into an analog and a digital part when the array has few RF chains.

In plain words

A channel with several antennas at each end mixes the signals. Some directions in space reach the receiver strongly, some weakly and some not at all. The transmitter finds these directions and their strengths from the channel. It sends one data stream along each strong direction, so the streams arrive without disturbing each other, and the receiver unmixes them with a fixed rotation. The transmitter then shares its power between the streams. Strong directions get more power, and very weak ones get nothing, because power spent there gives little data. This gives the highest data rate that the channel can support.

The problem

The model is y=Hx+wy = H x + w with H∈Cm×nH \in \mathbb{C}^{m \times n} known at the transmitter and at the receiver, mm receive antennas, nn transmit antennas and w∼CN(0,N0Im)w \sim \mathcal{CN}(0, N_0 I_m). The input has the covariance Q=E[xxH]Q = E[x x^H] with the power constraint tr(Q)≤P\mathrm{tr}(Q) \le P, and ρ=P/N0\rho = P / N_0. The goal is a precoder F∈Cn×rF \in \mathbb{C}^{n \times r}, with x=Fdx = F d for rr unit-power streams dd, and a receive matrix that together reach the capacity

C=max⁡Q⪰0, tr(Q)≤Plog⁡2det⁡(Im+HQHHN0)C = \max_{Q \succeq 0,\ \mathrm{tr}(Q) \le P} \log_2 \det\Bigl(I_m + \frac{H Q H^H}{N_0}\Bigr)

in bits per channel use.

The algorithm

  1. SVD-PRECODE(H, P, N0)
  2. 1(U, s, V) ← SVD(H) ▷ H = U diag(s) Vᴴ, s₁ ≥ s₂ ≥ ...
  3. 2r ← the number of nonzero sᵢ
  4. 3p ← WATER-FILL(s₁²/N0, ..., s_r²/N0; P) ▷ pᵢ = (μ - N0/sᵢ²)⁺, Σ pᵢ = P
  5. 4F ← [√p₁ v₁, ..., √p_r v_r] ▷ transmit x = F d
  6. 5return (F, [u₁, ..., u_r], s, p)
  7. RECEIVE(y, U)
  8. 6z ← Uᴴ y ▷ zᵢ = sᵢ √pᵢ dᵢ + noise

Line L1 is the expensive step. The implementation uses one-sided Jacobi rotations: each rotation makes two columns of HH orthogonal, and the product of the rotations is VV. Line L3 sorts the gains and drops the weakest channel until the water level μ\mu lies above 1/gi1 / g_i for every channel that is left. Line L4 is the only step that the transmitter needs once it has FF; line L6 runs at the receiver, which must know UU or estimate the effective channel HFH F from precoded pilots.

Example

Take m=n=2m = n = 2, P=2P = 2, N0=1N_0 = 1 and

H=(2112).H = \begin{pmatrix} 2 & 1 \\ 1 & 2 \end{pmatrix}.

HH is real and symmetric with the eigenvectors (1,1)/2(1, 1)/\sqrt{2} and (1,−1)/2(1, -1)/\sqrt{2} and the eigenvalues 3 and 1, so line L1 gives s=(3,1)s = (3, 1) and V=UV = U with these two columns. The gains are g=(9,1)g = (9, 1). Line L3 tries both channels: μ=(2+1/9+1)/2=14/9\mu = (2 + 1/9 + 1)/2 = 14/9, which is above 1/g2=11/g_2 = 1, so both stay on, with

p1=149−19=139≈1.444,p2=149−1=59≈0.556.p_1 = \frac{14}{9} - \frac{1}{9} = \frac{13}{9} \approx 1.444, \qquad p_2 = \frac{14}{9} - 1 = \frac{5}{9} \approx 0.556.

The rate is log⁡2(1+9⋅13/9)+log⁡2(1+5/9)=log⁡214+log⁡2(14/9)=4.4448\log_2(1 + 9 \cdot 13/9) + \log_2(1 + 5/9) = \log_2 14 + \log_2(14/9) = 4.4448 bits per channel use. The two other simple choices do worse:

power split rate (bits per channel use)
water-filling (1.444,0.556)(1.444, 0.556) 4.4448
equal power (1,1)(1, 1) log⁡210+log⁡22=4.3219\log_2 10 + \log_2 2 = 4.3219
strongest mode only (2,0)(2, 0) log⁡219=4.2479\log_2 19 = 4.2479

The last row is beamforming on v1v_1. It loses 0.20 bits, and at this SNR the weak mode is still worth some power. At P=0.5P = 0.5 the water level is below 1/g21/g_2, and water-filling itself puts all power on v1v_1.

Correctness

The proof is in proofs/correctness.md. Theorem 1 shows UrHHF=diag(sipi)U_r^H H F = \mathrm{diag}(s_i \sqrt{p_i}), so the receiver sees rr scalar channels with noise CN(0,N0)\mathcal{CN}(0, N_0) each and no crosstalk, and ∥F∥F2=∑ipi=P\|F\|_F^2 = \sum_i p_i = P. Lemma 1 proves from the KKT conditions that pi=(μ−1/gi)+p_i = (\mu - 1/g_i)^+ is the unique best power split, and that the drop loop of line L3 finds the right water level. Theorem 2 uses Hadamard's inequality on VHQVV^H Q V to show that no input covariance of trace PP does better, so SVD precoding reaches the capacity CC.

Proof: SVD precoding turns the channel into parallel scalar channels, water-filling picks the best powers, and the result reaches the MIMO capacityfull

The model is y=Hx+wy = H x + w with H∈Cm×nH \in \mathbb{C}^{m \times n}, w∼CN(0,N0Im)w \sim \mathcal{CN}(0, N_0 I_m) and the power constraint tr(Q)≤P\mathrm{tr}(Q) \le P on the input covariance Q=E[xxH]Q = E[x x^H]. Line L1 computes H=UΣVHH = U \Sigma V^H with U∈Cm×mU \in \mathbb{C}^{m \times m} and V∈Cn×nV \in \mathbb{C}^{n \times n} unitary and Σ\Sigma an m×nm \times n matrix with the singular values s1≥s2≥⋯≥sr>0s_1 \ge s_2 \ge \cdots \ge s_r > 0 on its diagonal, where rr is the rank of HH. Let uiu_i and viv_i be column ii of UU and VV. Line L4 sets F=[p1v1,…,prvr]F = [\sqrt{p_1} v_1, \ldots, \sqrt{p_r} v_r], and the transmitter sends x=Fdx = F d with E[ddH]=IrE[d d^H] = I_r.

Theorem 1 (parallel channels). UrHHF=diag(s1p1,…,srpr)U_r^H H F = \mathrm{diag}(s_1 \sqrt{p_1}, \ldots, s_r \sqrt{p_r}), where Ur=[u1,…,ur]U_r = [u_1, \ldots, u_r]. So the output of line L6 is zi=sipi di+νiz_i = s_i \sqrt{p_i}\, d_i + \nu_i for i=1,…,ri = 1, \ldots, r, with ν∼CN(0,N0Ir)\nu \sim \mathcal{CN}(0, N_0 I_r). Also ∥F∥F2=∑ipi\|F\|_F^2 = \sum_i p_i.

Proof. Hvi=UΣVHvi=UΣei=siuiH v_i = U \Sigma V^H v_i = U \Sigma e_i = s_i u_i, because the columns of VV are orthonormal. So HFH F has column ii equal to sipi uis_i \sqrt{p_i}\, u_i, and ukHui=δkiu_k^H u_i = \delta_{ki} gives the diagonal form. The noise term is ν=UrHw\nu = U_r^H w, a linear map of a circularly symmetric Gaussian vector, with covariance N0UrHUr=N0IrN_0 U_r^H U_r = N_0 I_r. Finally ∥F∥F2=∑ipi∥vi∥2=∑ipi\|F\|_F^2 = \sum_i p_i \|v_i\|^2 = \sum_i p_i. □\square

So the receiver sees rr independent scalar channels with the gains gi=si2/N0g_i = s_i^2 / N_0, and the rate with Gaussian dd is ∑ilog⁡2(1+gipi)\sum_i \log_2(1 + g_i p_i). Also FFH=Vr diag(p) VrHF F^H = V_r \,\mathrm{diag}(p)\, V_r^H, and det⁡(I+HFFHHH/N0)=∏i(1+gipi)\det(I + H F F^H H^H / N_0) = \prod_i (1 + g_i p_i) by Theorem 1 and det⁡(I+AB)=det⁡(I+BA)\det(I + A B) = \det(I + B A).

Lemma 1 (water-filling). For gains g1≥⋯≥gr>0g_1 \ge \cdots \ge g_r > 0 and P>0P > 0, the problem "maximize ∑ilog⁡2(1+gipi)\sum_i \log_2(1 + g_i p_i) subject to pi≥0p_i \ge 0 and ∑ipi=P\sum_i p_i = P" has the unique solution pi=(μ−1/gi)+p_i = (\mu - 1/g_i)^+, where μ\mu solves ∑i(μ−1/gi)+=P\sum_i (\mu - 1/g_i)^+ = P. The loop of water_fill finds this μ\mu.

Proof. The objective is strictly concave and the constraints are linear, so the KKT conditions are necessary and sufficient and the solution is unique. With a multiplier λ\lambda for the sum and ηi≥0\eta_i \ge 0 for pi≥0p_i \ge 0, stationarity reads gi/(1+gipi)=λln⁡2−ηig_i / (1 + g_i p_i) = \lambda \ln 2 - \eta_i. Write μ=1/(λln⁡2)\mu = 1/(\lambda \ln 2). If pi>0p_i > 0, then ηi=0\eta_i = 0 and pi=μ−1/gip_i = \mu - 1/g_i. If pi=0p_i = 0, then gi≤λln⁡2g_i \le \lambda \ln 2, that is 1/gi≥μ1/g_i \ge \mu. Both cases give pi=(μ−1/gi)+p_i = (\mu - 1/g_i)^+.

Now the loop. Let ai=1/gia_i = 1/g_i, so a1≤⋯≤ara_1 \le \cdots \le a_r, and let f(t)=∑i(t−ai)+f(t) = \sum_i (t - a_i)^+. The function ff is continuous, f(a1)=0f(a_1) = 0, and ff increases strictly for t>a1t > a_1 without bound, so there is a unique μ\mu with f(μ)=Pf(\mu) = P, and μ>a1\mu > a_1. Let μk=(P+a1+⋯+ak)/k\mu_k = (P + a_1 + \cdots + a_k)/k. Then μk>ak\mu_k > a_k holds exactly when P>∑i≤k(ak−ai)=f(ak)P > \sum_{i \le k} (a_k - a_i) = f(a_k), that is when ak<μa_k < \mu. Since the aia_i increase, the set of such kk is {1,…,k∗}\{1, \ldots, k^*\}, where k∗k^* is the number of channels with ai<μa_i < \mu. The loop starts at k=rk = r and stops at the first kk with μk>ak\mu_k > a_k, which is k∗k^*; the case k=1k = 1 always passes because P>0P > 0. On the set i≤k∗i \le k^*, μk∗\mu_{k^*} solves f(t)=Pf(t) = P, so μk∗=μ\mu_{k^*} = \mu. □\square

Lemma 2 (Hadamard's inequality). For a Hermitian positive semidefinite matrix AA, det⁡A≤∏iAii\det A \le \prod_i A_{ii}, with equality for a positive definite AA only if AA is diagonal.

Proof. If some Aii=0A_{ii} = 0, then row ii and column ii of AA are zero (a 2×22 \times 2 principal minor would be negative otherwise), so det⁡A=0\det A = 0. Otherwise let D=diag(A11,…,Ann)D = \mathrm{diag}(A_{11}, \ldots, A_{nn}) and B=D−1/2AD−1/2B = D^{-1/2} A D^{-1/2}. BB is positive semidefinite with unit diagonal, so its eigenvalues λi≥0\lambda_i \ge 0 add up to nn. By the inequality of arithmetic and geometric means, det⁡B=∏iλi≤1\det B = \prod_i \lambda_i \le 1, with equality only if every λi=1\lambda_i = 1, that is B=IB = I. Then det⁡A=det⁡Ddet⁡B≤∏iAii\det A = \det D \det B \le \prod_i A_{ii}. □\square

Theorem 2 (capacity). For every Q⪰0Q \succeq 0 with tr(Q)≤P\mathrm{tr}(Q) \le P,

log⁡2det⁡(Im+HQHHN0)≤∑i=1rlog⁡2(1+gipi),\log_2 \det\Bigl(I_m + \frac{H Q H^H}{N_0}\Bigr) \le \sum_{i=1}^{r} \log_2(1 + g_i p_i),

with the water-filling powers pip_i of Lemma 1. The SVD precoder reaches the right side, so it reaches the capacity of the channel with HH known at both ends.

Proof. Let Q~=VHQV\tilde Q = V^H Q V. It is positive semidefinite with tr(Q~)=tr(Q)≤P\mathrm{tr}(\tilde Q) = \mathrm{tr}(Q) \le P. By det⁡(I+AB)=det⁡(I+BA)\det(I + A B) = \det(I + B A),

det⁡(I+UΣQ~ΣHUHN0)=det⁡(I+ΣQ~ΣHN0).\det\Bigl(I + \frac{U \Sigma \tilde Q \Sigma^H U^H}{N_0}\Bigr) = \det\Bigl(I + \frac{\Sigma \tilde Q \Sigma^H}{N_0}\Bigr).

The matrix ΣQ~ΣH\Sigma \tilde Q \Sigma^H is zero outside its leading r×rr \times r block, and that block is SQ~rSS \tilde Q_r S with S=diag(s1,…,sr)S = \mathrm{diag}(s_1, \ldots, s_r) and Q~r\tilde Q_r the leading block of Q~\tilde Q. Lemma 2 applied to I+SQ~rS/N0I + S \tilde Q_r S / N_0 gives the bound ∏i≤r(1+giQ~ii)\prod_{i \le r} (1 + g_i \tilde Q_{ii}). The numbers qi=Q~iiq_i = \tilde Q_{ii} are nonnegative with ∑i≤rqi≤P\sum_{i \le r} q_i \le P, and the rate grows with each qiq_i, so by Lemma 1 the bound is at most the water-filling value. By Theorem 1 the precoder of line L4 reaches it. □\square

The tests check Theorem 1 by UrHHFU_r^H H F against the diagonal and by the power ∥F∥F2=P\|F\|_F^2 = P, Theorem 2 against random covariances of trace PP and the log-det formula, Lemma 1 by its KKT conditions and by a fine grid over the power split of two modes, and the check values 5.1699 and 2.1699 of the area.

Complexity

The SVD of line L1 costs O(mnmin⁡(m,n))O(m n \min(m, n)) by the usual bidiagonalization methods, to a fixed precision. A one-sided Jacobi sweep costs O(mn2)O(m n^2), and a few sweeps are enough in practice because the method converges quadratically near the end. Line L3 costs O(rlog⁡r)O(r \log r) for the sort and O(r)O(r) for the loop. Line L4 costs O(nr)O(n r), and line L6 costs O(mr)O(m r) per received vector. The extra space is O(mn)O(m n) for UU and VV. In a block fading channel lines L1 to L4 run once per channel realization.

Properties

  • Capacity achieving. With Gaussian codebooks on the streams, the rate equals the capacity of the known channel (theorem).
  • No interference between streams. The receiver needs no joint detection. Each stream sees a scalar AWGN channel with the gain si2s_i^2.
  • Needs the channel at both ends. The transmitter needs VV and the receiver needs UU, or the effective channel HFH F.
  • Unique power split. The powers are unique. The singular vectors are unique only up to a phase per stream, and up to a rotation inside a group of equal singular values; any choice gives the same rate.
  • High and low SNR limits. At high SNR water-filling tends to equal power on the rr modes, and the rate grows as rlog⁡2ρr \log_2 \rho. At low SNR only the strongest mode gets power, and SVD precoding becomes beamforming on v1v_1.

Variants and improvements

  • Equal power. Give P/rP/r to each mode. This is near optimal at high SNR and needs no water level.
  • Dominant eigenmode. Use only v1v_1. This is maximum ratio transmission for a MIMO channel, with the gain s12s_1^2.
  • Bit loading with real constellations. Replace the Shannon rate by a gap to capacity and integer bits per mode; see bit loading.
  • Limited feedback. Quantize VV with a codebook known at both ends; see codebook-based precoding.
  • Fewer RF chains. Approximate FF by FRFFBBF_{RF} F_{BB} with a phase-only analog part; see hybrid beamforming.
  • Multiuser. For several receivers with several antennas each, block diagonalization first removes the interference between users and then applies SVD precoding to each user.
  • Statistical channel knowledge. If the transmitter knows only the transmit correlation of a Kronecker channel, it sends along the eigenvectors of that correlation matrix instead.

When to use it

Use SVD precoding on a point-to-point link where the transmitter has a good channel estimate, for example in time division duplex from the reverse link, or with fine feedback in a slowly varying channel. It is the reference for every other MIMO precoder, because no linear or nonlinear scheme beats its rate on a known single-user channel. With OFDM it runs once per subcarrier. If the channel changes faster than the feedback, or if the transmitter knows only statistics, use space-time codes or open-loop spatial multiplexing instead.

Pitfalls

  • Stale channel. If HH changes after the transmitter computes VV, the streams leak into each other and the rate falls quickly at high SNR.
  • Phase of the singular vectors. Two SVD routines can return viv_i with different phases. The receiver must use the uiu_i that match the viv_i of the transmitter, or estimate HFH F from precoded pilots.
  • Power units. The gains in line L3 are si2/N0s_i^2 / N_0, not si/N0s_i / N_0. Using sis_i gives the wrong water level.
  • Rank. Give no stream to a singular value that is zero to rounding. Use a relative threshold such as si>10−12s1s_i > 10^{-12} s_1.
  • Sum of powers. The power constraint is on tr(FFH)\mathrm{tr}(F F^H). If FF is rescaled after rounding, rescale all columns by the same factor.

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)
svd_precoding.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/svd-precoding/. The authors are listed in prov/8XKR8Q.jsonl.

"""SVD precoding for a single-user MIMO channel.

The model is y = H x + w, with H an m by n complex matrix (m receive antennas,
n transmit antennas), w ~ CN(0, N0 I) and the power constraint E[x^H x] <= P.
The transmitter knows H. It computes H = U S V^H, sends stream i along the
right singular vector v_i with power p_i, and chooses the powers by
water-filling over the gains s_i^2 / N0. The receiver applies U^H, which
turns the channel into parallel scalar channels z_i = s_i sqrt(p_i) d_i + noise.
"""

import math

import cbb


def svd(a: list[list[complex]], tol: float = 1e-15, max_sweeps: int = 100):
    """The SVD a = U diag(s) V^H of an m by n complex matrix, by one-sided Jacobi.

    Returns (u, s, v). s has n values in decreasing order. v is n by n and
    unitary. u is m by n; its column i is a_i / s_i for s_i > 0 and the zero
    vector for s_i = 0. Each sweep rotates every pair of columns of a so that
    the pair becomes orthogonal; the same rotations applied to I give V.
    """
    m, n = len(a), len(a[0])
    cols = [[complex(a[i][k]) for i in range(m)] for k in range(n)]
    vcols = [[1 + 0j if i == k else 0j for i in range(n)] for k in range(n)]
    # A column with a squared norm below this is zero to rounding; rotating it only adds noise.
    small = (1e-15) ** 2 * sum(abs(x) ** 2 for col in cols for x in col)
    for _ in range(max_sweeps):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                ap, aq = cols[p], cols[q]
                alpha = sum(abs(x) ** 2 for x in ap)
                beta = sum(abs(x) ** 2 for x in aq)
                if alpha <= small or beta <= small:
                    continue
                gamma = sum(x.conjugate() * y for x, y in zip(ap, aq))
                g = abs(gamma)
                if g <= tol * math.sqrt(alpha * beta):
                    continue
                rotated = True
                ph = gamma / g  # e^(j phi)
                ph /= abs(ph)
                zeta = (beta - alpha) / (2.0 * g)
                t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
                c = 1.0 / math.sqrt(1.0 + t * t)
                s = c * t
                e = ph.conjugate()
                cols[p] = [c * x - s * e * y for x, y in zip(ap, aq)]
                cols[q] = [s * x + c * e * y for x, y in zip(ap, aq)]
                vp, vq = vcols[p], vcols[q]
                vcols[p] = [c * x - s * e * y for x, y in zip(vp, vq)]
                vcols[q] = [s * x + c * e * y for x, y in zip(vp, vq)]
        if not rotated:
            break
    norms = [math.sqrt(sum(abs(x) ** 2 for x in col)) for col in cols]
    order = sorted(range(n), key=lambda k: -norms[k])
    s = [norms[k] for k in order]
    big = s[0] if s else 0.0
    ucols = []
    for k in order:
        if norms[k] > 1e-13 * max(big, 1e-300):
            ucols.append([x / norms[k] for x in cols[k]])
        else:
            ucols.append([0j] * m)
    u = [[ucols[k][i] for k in range(n)] for i in range(m)]
    v = [[vcols[k][i] for k in order] for i in range(n)]
    return u, s, v


def water_fill(gains: list[float], p_total: float) -> list[float]:
    """Powers p_i >= 0 with sum P that maximize sum log2(1 + g_i p_i).

    A channel with gain 0 gets no power. The water level mu solves
    sum (mu - 1/g_i)^+ = P.
    """
    idx = sorted((i for i in range(len(gains)) if gains[i] > 0), key=lambda i: -gains[i])
    p = [0.0] * len(gains)
    if not idx or p_total <= 0:
        return p
    inv = [1.0 / gains[i] for i in idx]
    k = len(idx)
    while k > 1:
        mu = (p_total + sum(inv[:k])) / k
        if mu > inv[k - 1]:
            break
        k -= 1
    mu = (p_total + sum(inv[:k])) / k
    for t in range(k):
        p[idx[t]] = mu - inv[t]
    return p


def svd_precode(h: list[list[complex]], p_total: float, n0: float):
    """The SVD precoder of H for the power P and the noise level N0.

    Returns (f, u, s, p): f is the n by r precoder (column i is sqrt(p_i) v_i),
    u holds the r receive vectors as columns, s the r nonzero singular values
    and p the powers. The transmitter sends x = f d for r unit-energy symbols d.
    """
    u, s, v = svd(h)  # @line L1
    r = sum(1 for x in s if x > 1e-12 * s[0])  # @line L2
    p = water_fill([s[i] ** 2 / n0 for i in range(r)], p_total)  # @line L3
    f = [[v[t][i] * math.sqrt(p[i]) for i in range(r)] for t in range(len(v))]  # @line L4
    ur = [row[:r] for row in u]
    return f, ur, s[:r], p  # @line L5


def receive(y: list[complex], u: list[list[complex]]) -> list[complex]:
    """The receiver step z = U^H y, one output per stream."""
    return cbb.matvec(cbb.herm(u), y)  # @line L6


def rate(s: list[float], p: list[float], n0: float) -> float:
    """The rate sum log2(1 + s_i^2 p_i / N0) of the parallel channels, in bits per channel use."""
    return sum(math.log2(1.0 + si * si * pi / n0) for si, pi in zip(s, p))


def logdet_rate(h: list[list[complex]], q: list[list[complex]], n0: float) -> float:
    """log2 det(I + H Q H^H / N0) for an input covariance Q."""
    hq = cbb.matmul(cbb.matmul(h, q), cbb.herm(h))
    m = len(h)
    a = [[(1.0 if i == k else 0.0) + hq[i][k] / n0 for k in range(m)] for i in range(m)]
    return math.log2(abs(cbb.det(a)))
test_svd_precoding.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/svd-precoding/. The authors are listed in prov/8XKR8Q.jsonl.

import math
import random

import cbb
from svd_precoding import logdet_rate, rate, receive, svd, svd_precode, water_fill


def rand_h(rng: random.Random, m: int, n: int) -> list[list[complex]]:
    return [[cbb.cn(rng, 1.0) for _ in range(n)] for _ in range(m)]


def max_abs(a: list[list[complex]]) -> float:
    return max(abs(x) for row in a for x in row)


def test_svd_reconstructs_the_matrix() -> None:
    rng = random.Random(1)
    for m, n in [(2, 2), (3, 2), (2, 3), (4, 4), (8, 5), (3, 8)]:
        for _ in range(5):
            a = rand_h(rng, m, n)
            u, s, v = svd(a)
            assert all(s[i] >= s[i + 1] for i in range(n - 1))
            us = [[u[i][k] * s[k] for k in range(n)] for i in range(m)]
            back = cbb.matmul(us, cbb.herm(v))
            assert max_abs(cbb.sub(back, a)) < 1e-10
            vhv = cbb.matmul(cbb.herm(v), v)
            assert max_abs(cbb.sub(vhv, cbb.eye(n))) < 1e-10
            r = min(m, n)
            ur = [row[:r] for row in u]
            assert max_abs(cbb.sub(cbb.matmul(cbb.herm(ur), ur), cbb.eye(r))) < 1e-10


def test_svd_singular_values_match_eigenvalues_of_gram() -> None:
    # For a 2 by 2 matrix the squared singular values are the roots of t^2 - tr t + det = 0.
    rng = random.Random(2)
    for _ in range(20):
        a = rand_h(rng, 2, 2)
        g = cbb.matmul(cbb.herm(a), a)
        tr = (g[0][0] + g[1][1]).real
        dt = cbb.det(g).real
        disc = math.sqrt(max(tr * tr - 4 * dt, 0.0))
        _, s, _ = svd(a)
        assert abs(s[0] ** 2 - (tr + disc) / 2) < 1e-10
        assert abs(s[1] ** 2 - (tr - disc) / 2) < 1e-10


def test_water_fill_check_value() -> None:
    p = water_fill([1.0, 0.5, 0.25], 3.0)
    assert max(abs(a - b) for a, b in zip(p, [2.0, 1.0, 0.0])) < 1e-12
    r = sum(math.log2(1 + g * q) for g, q in zip([1.0, 0.5, 0.25], p))
    assert abs(r - 2.1699) < 5e-5


def test_water_fill_kkt() -> None:
    rng = random.Random(3)
    for _ in range(200):
        n = rng.randint(1, 8)
        g = [rng.uniform(0.01, 10.0) for _ in range(n)]
        pt = rng.uniform(0.01, 20.0)
        p = water_fill(g, pt)
        assert abs(sum(p) - pt) < 1e-9
        assert min(p) >= 0.0
        on = [i for i in range(n) if p[i] > 0]
        mu = p[on[0]] + 1 / g[on[0]]
        for i in range(n):
            if p[i] > 0:
                assert abs(p[i] + 1 / g[i] - mu) < 1e-9
            else:
                assert 1 / g[i] >= mu - 1e-9


def test_identity_check_value() -> None:
    h = cbb.eye(2)
    f, u, s, p = svd_precode(h, 10.0, 1.0)
    assert abs(rate(s, p, 1.0) - 5.1699) < 5e-5
    assert abs(cbb.norm2(f) - 10.0) < 1e-9


def test_worked_example() -> None:
    h = [[2, 1], [1, 2]]
    f, u, s, p = svd_precode(h, 2.0, 1.0)
    assert abs(s[0] - 3) < 1e-12 and abs(s[1] - 1) < 1e-12
    assert abs(p[0] - 13 / 9) < 1e-12 and abs(p[1] - 5 / 9) < 1e-12
    assert abs(rate(s, p, 1.0) - math.log2(14 * 14 / 9)) < 1e-12
    assert abs(rate(s, p, 1.0) - 4.4448) < 5e-5


def test_precoder_diagonalizes_and_meets_power() -> None:
    rng = random.Random(4)
    for m, n in [(2, 2), (4, 2), (2, 4), (4, 4), (8, 8)]:
        for _ in range(3):
            h = rand_h(rng, m, n)
            pt, n0 = rng.uniform(0.5, 20.0), rng.uniform(0.1, 2.0)
            f, u, s, p = svd_precode(h, pt, n0)
            assert abs(cbb.norm2(f) - pt) < 1e-9
            d = cbb.matmul(cbb.herm(u), cbb.matmul(h, f))
            r = len(s)
            for i in range(r):
                for k in range(r):
                    want = s[i] * math.sqrt(p[i]) if i == k else 0.0
                    assert abs(d[i][k] - want) < 1e-9
            q = cbb.matmul(f, cbb.herm(f))
            assert abs(rate(s, p, n0) - logdet_rate(h, q, n0)) < 1e-9


def test_receiver_recovers_streams_without_noise() -> None:
    rng = random.Random(5)
    h = rand_h(rng, 3, 3)
    f, u, s, p = svd_precode(h, 3.0, 0.01)
    d = [complex(rng.choice([-1, 1]), rng.choice([-1, 1])) for _ in range(len(s))]
    z = receive(cbb.matvec(h, cbb.matvec(f, d)), u)
    for i in range(len(s)):
        if p[i] > 0:
            assert abs(z[i] / (s[i] * math.sqrt(p[i])) - d[i]) < 1e-9


def random_cov(rng: random.Random, n: int, pt: float) -> list[list[complex]]:
    a = rand_h(rng, n, n)
    q = cbb.matmul(a, cbb.herm(a))
    tr = sum(q[i][i].real for i in range(n))
    return cbb.scale(pt / tr, q)


def test_beats_random_covariances() -> None:
    # The SVD precoder reaches the capacity, so no input covariance of trace P does better.
    rng = random.Random(6)
    for _ in range(10):
        h = rand_h(rng, 3, 3)
        f, u, s, p = svd_precode(h, 5.0, 1.0)
        best = rate(s, p, 1.0)
        for _ in range(40):
            assert logdet_rate(h, random_cov(rng, 3, 5.0), 1.0) <= best + 1e-9


def test_power_split_grid() -> None:
    # Two eigenmodes: the water-filling split beats every split on a fine grid.
    rng = random.Random(7)
    for _ in range(10):
        h = rand_h(rng, 2, 2)
        pt, n0 = rng.uniform(0.1, 10.0), 1.0
        f, u, s, p = svd_precode(h, pt, n0)
        best = rate(s, p, n0)
        grid = max(rate(s, [pt * t / 2000, pt * (1 - t / 2000)], n0) for t in range(2001))
        assert best >= grid - 1e-12
        assert best - grid < 1e-5

History

The idea is the vector form of the classic water-filling result for parallel Gaussian channels: a unitary change of basis at each end makes a matrix channel parallel. For wireless links with antenna arrays, Raleigh and Cioffi (1998) used the SVD of the channel to send parallel streams, and Telatar (1999, first circulated as a Bell Labs report in 1995) proved that the SVD with water-filling gives the capacity of a MIMO channel known at the transmitter. Today the same structure appears in LTE and 5G NR as closed-loop precoding, usually through a codebook rather than an exact VV.

References

  1. Emre Telatar, Capacity of multi-antenna Gaussian channels, European Transactions on Telecommunications 10(6), 585-595, 1999, the section on the capacity of a channel with a fixed and known H (the SVD of H and water-filling over its singular values)
  2. Gregory G. Raleigh and John M. Cioffi, Spatio-temporal coding for wireless communication, IEEE Transactions on Communications 46(3), 357-366, 1998, the transmission of parallel streams along the singular vectors of the channel
  3. David Tse and Pramod Viswanath, Fundamentals of Wireless Communication, Cambridge University Press, 2005, Section 7.1.1, Capacity via singular value decomposition (the parallel channels, water-filling and the precoder V)
  4. Arogyaswami Paulraj, Rohit Nabar and Dhananjay Gore, Introduction to Space-Time Wireless Communications, Cambridge University Press, 2003, the chapter on the capacity of MIMO channels (the channel known at the transmitter and water-filling over the eigenmodes)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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