Algorithm Search⌘K

Algorithmadvanced

Vector perturbation precoding

Also called vector perturbation.

Adds an integer offset to the data before channel inversion, chosen by a lattice search to cut transmit power.

Time
O(K^2 M + K^3 + N K) worst
Space
O(M K) extra
Where
K = the number of single-antenna users; M = the number of base station antennas; N = the number of nodes the lattice search visits
Properties
deterministicexact searchnot linearneeds channel at transmitterreceiver uses modulozero interference
Origin
Bertrand M. Hochwald, Christian B. Peel, A. Lee Swindlehurst, 2005

Vector perturbation (VP) precoding sends x=P/γ HH(HHH)−1(s+τl)x = \sqrt{P / \gamma}\, H^H (H H^H)^{-1} (s + \tau l) in a multiuser downlink, where ll is a vector of complex integers chosen to make the power γ\gamma of the unscaled signal as small as possible. With l=0l = 0 it is zero-forcing precoding with channel inversion, which can need very much power when HHHH H^H is badly conditioned. The perturbation moves the data to another copy of itself on a grid of spacing τ\tau, and each user removes the offset with a modulo operation. Unlike regularized zero-forcing precoding, which accepts some interference to save power, VP keeps zero interference and saves power by the nonlinear offset; it can also be combined with the regularized inverse. It is the vector form of Tomlinson-Harashima precoding: Tomlinson-Harashima precoding chooses the offsets one user at a time, while VP chooses them jointly by a lattice search.

In plain words

A base station sends to several users at once and cancels the leaks between them. When two users are in similar directions, this canceling costs much power, and every user then hears a weak signal. Vector perturbation changes the data a little before the canceling. It adds a whole number of fixed steps to each symbol. Each user can remove these steps again, because it only looks at its symbol "modulo one step", like a clock that only shows the time and not the day. The base station tries the possible steps and picks the combination that needs the least power. The saving can be large, and users get a stronger signal.

The problem

User kk receives yk=hkHx+wky_k = h_k^H x + w_k, with H=[h1,…,hK]H∈CK×MH = [h_1, \ldots, h_K]^H \in \mathbb{C}^{K \times M} of full row rank known at the base station and wk∼CN(0,N0)w_k \sim \mathcal{CN}(0, N_0). The symbols sks_k come from a square QAM constellation whose real and imaginary parts lie in [−τ/2,τ/2)[-\tau/2, \tau/2); Hochwald, Peel and Swindlehurst take τ=2(∣c∣max⁡+Δ/2)\tau = 2(|c|_{\max} + \Delta / 2), with ∣c∣max⁡|c|_{\max} the largest absolute value of a real or imaginary part and Δ\Delta the distance between neighbor points. For QPSK with points ±1±j\pm 1 \pm j this gives τ=4\tau = 4, and for 16-QAM with parts in {±1,±3}\{\pm 1, \pm 3\} it gives τ=8\tau = 8. Every transmit vector must have power PP. The goal is to choose l∈(Z+jZ)Kl \in (\mathbb{Z} + j \mathbb{Z})^K that minimizes

γ(l)=∥HH(HHH)−1(s+τl)∥2=(s+τl)H(HHH)−1(s+τl),\gamma(l) = \|H^H (H H^H)^{-1} (s + \tau l)\|^2 = (s + \tau l)^H (H H^H)^{-1} (s + \tau l),

because the effective SNR of every user is P/(γN0)P / (\gamma N_0). This is an instance of the closest vector problem.

The algorithm

  1. VP-PRECODE(H, s, P, τ)
  2. 1F ← Hᴴ (H Hᴴ)⁻¹ ▷ the zero-forcing directions
  3. 2A ← (H Hᴴ)⁻¹ ▷ γ = uᴴ A u
  4. 3Aᵣ ← real form of A; L Lᵀ ← Aᵣ; R ← Lᵀ ▷ uᴴ A u = ‖R v‖²
  5. 4l ← argmin over integer z of ‖R (v + τ z)‖² ▷ Schnorr-Euchner search
  6. 5u ← s + τ l
  7. 6γ ← ‖F u‖²
  8. 7return x = √(P / γ) F u
  9. VP-RECEIVE(y_k, γ, P, τ)
  10. 8return mod_τ(√(γ / P) y_k) ▷ real and imaginary parts into [-τ/2, τ/2)

Line L3 writes u=a+jbu = a + j b as v=(a,b)∈R2Kv = (a, b) \in \mathbb{R}^{2K} and A=AR+jAIA = A_R + j A_I as the real matrix (AR−AIAIAR)\begin{pmatrix} A_R & -A_I \\ A_I & A_R \end{pmatrix}, and factors it with the Cholesky decomposition. Line L4 is a depth-first Schnorr-Euchner enumeration from the last coordinate to the first: at each level it visits the integers in the order of their distance from the real center, and it stops a branch as soon as the partial sum reaches the best value found so far. The first path it follows is the Babai nearest plane point. Lines L1 to L3 depend only on HH, so they run once per channel; lines L4 to L7 run once per data vector.

Example

Take K=M=2K = M = 2, QPSK with τ=4\tau = 4, P=4P = 4 and

H=(1201),H−1=(1−201),s=(1+j−1−j).H = \begin{pmatrix} 1 & 2 \\ 0 & 1 \end{pmatrix}, \qquad H^{-1} = \begin{pmatrix} 1 & -2 \\ 0 & 1 \end{pmatrix}, \qquad s = \begin{pmatrix} 1 + j \\ -1 - j \end{pmatrix}.

Here F=H−1F = H^{-1}. Without a perturbation, Fs=(3+3j,−1−j)F s = (3 + 3j, -1 - j) and γ=18+2=20\gamma = 18 + 2 = 20. The search finds l=(−1−j,0)l = (-1 - j, 0), so u=(−3−3j,−1−j)u = (-3 - 3j, -1 - j) and Fu=(−1−j,−1−j)F u = (-1 - j, -1 - j), with γ=4\gamma = 4. The real and the imaginary parts of this example are the same real problem. In real terms, the cost of (u1,u2)(u_1, u_2) is (u1−2u2)2+u22(u_1 - 2 u_2)^2 + u_2^2 for u1∈1+4Zu_1 \in 1 + 4 \mathbb{Z} and u2∈−1+4Zu_2 \in -1 + 4 \mathbb{Z}; the value 1 + 1 = 2 at (−3,−1)(-3, -1) is the smallest, and the next smallest is 10.

Line L7 sends x=4/4 Fu=(−1−j,−1−j)x = \sqrt{4 / 4}\, F u = (-1 - j, -1 - j), with power 4. Without noise the users receive Hx=(−3−3j,−1−j)H x = (-3 - 3j, -1 - j). User 1 reduces −3−3j-3 - 3j modulo 4 into [−2,2)[-2, 2) and gets 1+j1 + j; user 2 gets −1−j-1 - j directly. Zero forcing would send 4/20 Fs\sqrt{4 / 20}\, F s, and each user would receive 0.447 sk0.447\, s_k. For this data vector the perturbation raises the effective SNR by the factor 20/4=520 / 4 = 5, or 7.0 dB.

Correctness

The proof is in proofs/correctness.md. Lemma 1 shows that HF=IH F = I, so the users hear no signal for the other users for every ll, and that line L7 meets the power exactly. Lemma 2 shows that the modulo of line L8 removes τlk\tau l_k and returns sks_k without noise. Lemmas 3 and 4 show that γ\gamma equals ∥R(v+τz)∥2\|R (v + \tau z)\|^2 in real form. Theorem 1 shows that the Schnorr-Euchner search stops and returns a global minimizer over all integer vectors: the terms are nonnegative, so a partial sum is a lower bound for every completion, and the zigzag order makes the bounds at one level grow, so the search can stop a level at the first candidate that is not better.

Proof: Vector perturbation removes the interference, meets the power exactly, lets each user recover its symbol by a modulo, and the search finds the perturbation of least powerfull

The model is yk=hkHx+wky_k = h_k^H x + w_k for k=1,…,Kk = 1, \ldots, K, with H=[h1,…,hK]H∈CK×MH = [h_1, \ldots, h_K]^H \in \mathbb{C}^{K \times M} of full row rank and wk∼CN(0,N0)w_k \sim \mathcal{CN}(0, N_0). The data symbols sks_k have real and imaginary parts in [−τ/2,τ/2)[-\tau/2, \tau/2). Lines L1 to L7 compute F=HH(HHH)−1F = H^H (H H^H)^{-1}, A=(HHH)−1A = (H H^H)^{-1}, the Cholesky factor of the real form of AA, a vector ll of Gaussian integers, u=s+τlu = s + \tau l, γ=∥Fu∥2\gamma = \|F u\|^2 and x=P/γ Fux = \sqrt{P / \gamma}\, F u. Line L8 at user kk computes modτ(γ/P yk)\mathrm{mod}_\tau(\sqrt{\gamma / P}\, y_k), where modτ\mathrm{mod}_\tau reduces the real and the imaginary part separately into [−τ/2,τ/2)[-\tau/2, \tau/2) by t↦t−τ⌊t/τ+1/2⌋t \mapsto t - \tau \lfloor t / \tau + 1/2 \rfloor.

Lemma 1 (no interference, exact power). For every ll, ∥x∥2=P\|x\|^2 = P and Hx=P/γ (s+τl)H x = \sqrt{P / \gamma}\, (s + \tau l).

Proof. ∥x∥2=(P/γ)∥Fu∥2=P\|x\|^2 = (P / \gamma) \|F u\|^2 = P. Also HF=HHH(HHH)−1=IH F = H H^H (H H^H)^{-1} = I, so Hx=P/γ uH x = \sqrt{P / \gamma}\, u. □\square

So user kk receives yk=P/γ (sk+τlk)+wky_k = \sqrt{P / \gamma}\, (s_k + \tau l_k) + w_k, with no signal for the other users.

Lemma 2 (the modulo receiver). If wk=0w_k = 0, line L8 returns sks_k. With noise, it returns modτ(sk+γ/P wk)\mathrm{mod}_\tau(s_k + \sqrt{\gamma / P}\, w_k).

Proof. Line L8 forms sk+τlk+γ/P wks_k + \tau l_k + \sqrt{\gamma / P}\, w_k. The map t↦t−τ⌊t/τ+1/2⌋t \mapsto t - \tau \lfloor t / \tau + 1/2 \rfloor does not change when an integer multiple of τ\tau is added to tt, because the floor then grows by the same integer. So the term τlk\tau l_k, whose real and imaginary parts are integer multiples of τ\tau, drops out. If t∈[−τ/2,τ/2)t \in [-\tau/2, \tau/2), then t/τ+1/2∈[0,1)t / \tau + 1/2 \in [0, 1), the floor is 0, and the map returns tt. So with wk=0w_k = 0 the result is sks_k. □\square

So the noise at user kk is scaled by γ/P\sqrt{\gamma / P}, and the effective SNR is P/(γN0)P / (\gamma N_0). A smaller γ\gamma is better for every user at once. The rest of the proof shows that lines L2 to L4 find the ll with the smallest γ\gamma.

Lemma 3 (the power as a quadratic form). γ=uHAu\gamma = u^H A u with A=(HHH)−1A = (H H^H)^{-1}, which is Hermitian positive definite.

Proof. FHF=(HHH)−1HHH(HHH)−1=AF^H F = (H H^H)^{-1} H H^H (H H^H)^{-1} = A, so ∥Fu∥2=uHFHFu=uHAu\|F u\|^2 = u^H F^H F u = u^H A u. HHHH H^H is positive definite because HH has full row rank, so its inverse is too. □\square

Lemma 4 (the real form). Let A=AR+jAIA = A_R + j A_I and Ar=(AR−AIAIAR)A_r = \begin{pmatrix} A_R & -A_I \\ A_I & A_R \end{pmatrix}. For u=a+jbu = a + j b and v=(a,b)v = (a, b), uHAu=vTArvu^H A u = v^T A_r v. The matrix ArA_r is symmetric positive definite, so Ar=LLTA_r = L L^T for a real lower triangular LL with a positive diagonal, and uHAu=∥Rv∥2u^H A u = \|R v\|^2 with the upper triangular R=LTR = L^T.

Proof. AA Hermitian means ART=ARA_R^T = A_R and AIT=−AIA_I^T = -A_I, so ArA_r is symmetric. Expand uHAu=(a−jb)T(AR+jAI)(a+jb)u^H A u = (a - j b)^T (A_R + j A_I)(a + j b). Its real part is aTARa+bTARb−aTAIb+bTAIaa^T A_R a + b^T A_R b - a^T A_I b + b^T A_I a, which is vTArvv^T A_r v, and its imaginary part is 0 because uHAuu^H A u is real. For v≠0v \ne 0, vTArv=uHAu>0v^T A_r v = u^H A u > 0. The Cholesky factorization of a symmetric positive definite matrix exists, and the helper computes it with the real entries of ArA_r. □\square

With l=c+jdl = c + j d and the integer vector z=(c,d)∈Z2Kz = (c, d) \in \mathbb{Z}^{2K}, uu maps to v+τzv + \tau z, so the problem of lines L2 to L4 is to minimize

Φ(z)=∥R(v+τz)∥2=∑i=1n(rii(vi+τzi)+∑j>irij(vj+τzj))2,n=2K,\Phi(z) = \|R (v + \tau z)\|^2 = \sum_{i=1}^{n} \Bigl( r_{ii} (v_i + \tau z_i) + \sum_{j > i} r_{ij} (v_j + \tau z_j) \Bigr)^2, \qquad n = 2K,

over z∈Znz \in \mathbb{Z}^n. Term ii depends only on zi,…,znz_i, \ldots, z_n.

Theorem 1 (the search is exact). The Schnorr-Euchner search of line L4 stops after a finite number of steps and returns a zz with Φ(z)=min⁡z′∈ZnΦ(z′)\Phi(z) = \min_{z' \in \mathbb{Z}^n} \Phi(z'). The minimum exists.

Proof. The minimum exists: Φ(z)≥λτ2∥z+v/τ∥2\Phi(z) \ge \lambda \tau^2 \|z + v / \tau\|^2 with λ>0\lambda > 0 the smallest eigenvalue of RTRR^T R, so only finitely many zz have Φ(z)≤Φ(0)\Phi(z) \le \Phi(0).

Fix values zi+1,…,znz_{i+1}, \ldots, z_n and let DiD_i be the sum of the terms i+1,…,ni+1, \ldots, n for them (the argument partial). Term ii is (riiτ)2(zi−ci)2(r_{ii} \tau)^2 (z_i - c_i)^2 with the center ci=(−ti/rii−vi)/τc_i = (-t_i / r_{ii} - v_i) / \tau, where ti=∑j>irij(vj+τzj)t_i = \sum_{j > i} r_{ij} (v_j + \tau z_j). The search visits zi=⌊ci+1/2⌋z_i = \lfloor c_i + 1/2 \rfloor first and then alternates to the two sides. In this order ∣zi−ci∣|z_i - c_i| never decreases, so the value d=Di+(riiτ)2(zi−ci)2d = D_i + (r_{ii} \tau)^2 (z_i - c_i)^2 never decreases.

Pruning is safe. All terms are nonnegative, so every completion of a prefix has Φ≥d\Phi \ge d. The loop at level ii stops at the first candidate with d≥d \ge best, and every later candidate at that level has a dd at least as large. So every leaf that is skipped has Φ≥\Phi \ge best at that time, and best only decreases. Every leaf that is not skipped is compared with best. So at the end, best is at most Φ(z′)\Phi(z') for every z′∈Znz' \in \mathbb{Z}^n, and it is the value of the stored leaf.

Termination. The first call at each level starts while best may be ∞\infty; it then never stops at its first candidate, so the first path goes to a leaf and best becomes finite. After that, the loop at level ii visits only candidates with $(r_{ii} \tau)^2 (z_i - c_i)^2 < $ best, and there are finitely many, because riiτ>0r_{ii} \tau > 0. By induction on the depth, every call returns. □\square

Theorem 2 (correctness of vector perturbation). The transmit signal has power exactly PP, user kk sees no signal for the other users, without noise it recovers sks_k exactly, and the effective SNR P/(γN0)P / (\gamma N_0) is the largest over all Gaussian integer perturbations ll.

Proof. Lemma 1 gives the power and the absence of interference, and Lemma 2 gives the recovery. By Lemmas 3 and 4, γ(l)=Φ(z)\gamma(l) = \Phi(z) for l=c+jdl = c + j d, z=(c,d)z = (c, d), and Theorem 1 shows that line L4 minimizes Φ\Phi over Z2K\mathbb{Z}^{2K}, that is over all Gaussian integer vectors ll. □\square

With l=0l = 0 the precoder is zero forcing with channel inversion, so γVP≤γZF\gamma_{\mathrm{VP}} \le \gamma_{\mathrm{ZF}} for every channel and data vector.

The tests check Lemma 1 within 10−910^{-9}, Lemma 2 without noise, Lemma 4 on random Hermitian matrices, Theorem 1 against a search over a box of integer vectors for K=1,2,3K = 1, 2, 3 (the search result lies in the box, so the two minima must agree), γVP≤γZF\gamma_{\mathrm{VP}} \le \gamma_{\mathrm{ZF}}, and the example of the page.

Complexity

Lines L1 to L3 cost O(K2M+K3)O(K^2 M + K^3) per channel. Line L4 costs O(K)O(K) per visited node of the search tree, so O(NK)O(N K) for NN nodes. Lines L6 and L7 cost O(MK)O(M K). In the worst case NN grows exponentially with KK; the closest vector problem is NP-hard in general, so no exact method is known to be polynomial. For small KK and well conditioned channels NN is small. The extra space is O(MK)O(M K) for FF and O(K2)O(K^2) for RR.

Properties

  • Zero interference. HxH x is a scaled copy of s+τls + \tau l for every ll (theorem).
  • Never worse than channel inversion. l=0l = 0 is a candidate, so γVP≤γZF\gamma_{\mathrm{VP}} \le \gamma_{\mathrm{ZF}} for every channel and data vector.
  • Nonlinear. The transmit signal is not a linear function of ss, because ll depends on ss.
  • Simple receiver. Each user needs only a scale and a modulo, and no knowledge of the other users.
  • Common scale. The scale γ/P\sqrt{\gamma / P} changes with every data vector, so each user must know it or estimate it.
  • Large power saving on bad channels. The saving is largest when HHHH H^H is close to singular, which is when channel inversion fails.

Variants and improvements

  • Regularized VP. Replace (HHH)−1(H H^H)^{-1} by (HHH+αI)−1(H H^H + \alpha I)^{-1} in the search and in the precoder, as in Part II of Hochwald, Peel and Swindlehurst. Then some interference remains, but less noise is amplified, which helps at low SNR.
  • Approximate search. Round the center at each level once (Babai nearest plane), or keep the BB best partial vectors per level, to bound the cost.
  • Lattice reduction. Reduce the basis τR\tau R with the LLL algorithm first and then round; the result is a good approximate perturbation at polynomial cost, the transmit counterpart of lattice-reduction-aided detection.
  • Tomlinson-Harashima precoding. Choose lkl_k one user at a time after a QR factorization of HH, which is the successive form of VP; see Tomlinson-Harashima precoding.
  • Other enumerations. The Fincke-Pohst enumeration searches in the natural order inside a fixed radius.

When to use it

Use VP when the base station has accurate channel knowledge, the number of users is close to the number of antennas, and the base station can afford a lattice search per data vector. These are the cases where linear precoders lose much power. When KK is much smaller than MM, HHHH H^H is well conditioned and zero-forcing precoding or regularized zero-forcing precoding is almost as good at a much lower cost. When the search is too costly, use Tomlinson-Harashima precoding or a lattice-reduction-aided approximation.

Pitfalls

  • The modulo needs the right τ\tau. If τ\tau is too small the constellation copies overlap and the modulo receiver makes errors without noise.
  • Modulo loss. Noise near the edge of [−τ/2,τ/2)[-\tau/2, \tau/2) wraps to the other side, and the perturbed signal has a different energy per symbol than the plain constellation. Compare VP with linear precoders at the same transmit power and with the same receiver.
  • Soft decisions. The modulo makes the log-likelihood ratios for a channel decoder harder to compute, because each symbol has many copies.
  • Search cost. The worst-case cost of an exact search grows exponentially with KK; set a node limit in real time systems, and accept a small loss.
  • Stale channel. A wrong HH leaves interference that is then also reduced modulo τ\tau, which can map it to a large error.

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)
vector_perturbation_precoding.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vector-perturbation-precoding/. The authors are listed in prov/RSA6ZS.jsonl.

"""Vector perturbation (VP) precoding for the multiuser MISO downlink.

User k receives y_k = h_k^H x + w_k with w_k ~ CN(0, N0). The K by M matrix H
has row k equal to h_k^H and full row rank. For a data vector s of QAM
symbols with real and imaginary parts in [-tau/2, tau/2), the transmitter
sends

    x = sqrt(P / gamma) F (s + tau l),   F = H^H (H H^H)^(-1),
    gamma = ||F (s + tau l)||^2,

where l is the vector of Gaussian integers that makes gamma smallest. The
search for l is a closest vector problem. It is solved exactly here: the
quadratic form (s + tau l)^H (H H^H)^(-1) (s + tau l) is written in real
form, factored by Cholesky as ||R v||^2 with R upper triangular, and searched
by Schnorr-Euchner enumeration. User k multiplies its sample by
sqrt(gamma / P) and reduces it modulo tau.
"""

import math

import cbb


def mod_tau(z: complex, tau: float) -> complex:
    """Reduce the real and imaginary parts of z into [-tau/2, tau/2)."""
    re = z.real - tau * math.floor(z.real / tau + 0.5)
    im = z.imag - tau * math.floor(z.imag / tau + 0.5)
    return complex(re, im)


def real_form(a: list[list[complex]]) -> list[list[float]]:
    """The 2K by 2K real matrix [[Re A, -Im A], [Im A, Re A]], so u^H A u = v^T A_r v for v = [Re u; Im u]."""
    k = len(a)
    out = [[0.0] * (2 * k) for _ in range(2 * k)]
    for i in range(k):
        for j in range(k):
            z = complex(a[i][j])
            out[i][j] = z.real
            out[i][j + k] = -z.imag
            out[i + k][j] = z.imag
            out[i + k][j + k] = z.real
    return out


def closest_point(r: list[list[float]], v: list[float], tau: float) -> tuple[list[int], float]:
    """Minimize ||R (v + tau l)||^2 over integer vectors l, for upper triangular R with a positive diagonal.

    Schnorr-Euchner enumeration: a depth-first search from the last
    coordinate to the first. At each level the candidates for l_i are visited
    in the order of their distance from the real center, and a branch stops
    as soon as its partial sum reaches the best value found so far.
    Returns (l, value).
    """
    n = len(r)
    best = [math.inf]
    best_l: list[list[int]] = [[0] * n]
    lv = [0] * n

    def search(i: int, partial: float) -> None:
        if i < 0:
            if partial < best[0]:
                best[0] = partial
                best_l[0] = lv[:]
            return
        tail = sum(r[i][j] * (v[j] + tau * lv[j]) for j in range(i + 1, n))
        center = (-tail / r[i][i] - v[i]) / tau
        step = r[i][i] * tau
        c0 = math.floor(center + 0.5)
        sign = 1 if center >= c0 else -1
        t = 0
        while True:
            if t == 0:
                cand = c0
            elif t % 2 == 1:
                cand = c0 + sign * ((t + 1) // 2)
            else:
                cand = c0 - sign * (t // 2)
            d = partial + (step * (cand - center)) ** 2
            if d >= best[0]:
                break  # the zigzag order makes d grow, so no later candidate is better
            lv[i] = cand
            search(i - 1, d)
            t += 1

    search(n - 1, 0.0)
    return best_l[0], best[0]


def vp_precode(h: list[list[complex]], s: list[complex], p_total: float, tau: float):
    """Precode one data vector s. Returns (x, l, gamma)."""
    k_users = len(h)
    g = cbb.matmul(h, cbb.herm(h))
    f = cbb.herm(cbb.solve(g, h))  # @line L1
    a = cbb.inv(g)  # @line L2
    low = cbb.cholesky(real_form(a))  # @line L3
    r = [[low[j][i].real for j in range(2 * k_users)] for i in range(2 * k_users)]
    v = [complex(z).real for z in s] + [complex(z).imag for z in s]
    li, _ = closest_point(r, v, tau)  # @line L4
    l_vec = [complex(li[i], li[i + k_users]) for i in range(k_users)]
    u = [complex(s[i]) + tau * l_vec[i] for i in range(k_users)]  # @line L5
    xt = cbb.matvec(f, u)
    gamma = cbb.norm2(xt)  # @line L6
    x = cbb.scale(math.sqrt(p_total / gamma), xt)  # @line L7
    return x, l_vec, gamma


def vp_receive(y: complex, gamma: float, p_total: float, tau: float) -> complex:
    """The receiver of one user: undo the common scale, then reduce modulo tau."""
    return mod_tau(y * math.sqrt(gamma / p_total), tau)  # @line L8
test_vector_perturbation_precoding.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vector-perturbation-precoding/. The authors are listed in prov/RSA6ZS.jsonl.

import itertools
import math
import random

import cbb
from vector_perturbation_precoding import closest_point, mod_tau, real_form, vp_precode, vp_receive

QPSK = [complex(a, b) for a in (-1, 1) for b in (-1, 1)]
QAM16 = [complex(a, b) for a in (-3, -1, 1, 3) for b in (-3, -1, 1, 3)]


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


def quad(a: list[list[complex]], u: list[complex]) -> float:
    return cbb.dot(u, cbb.matvec(a, u)).real


def test_example() -> None:
    h = [[1, 2], [0, 1]]
    s = [1 + 1j, -1 - 1j]
    x, l_vec, gamma = vp_precode(h, s, 4.0, 4.0)
    assert l_vec == [-1 - 1j, 0j]
    assert abs(gamma - 4.0) < 1e-12
    assert max(abs(a - b) for a, b in zip(x, [-1 - 1j, -1 - 1j])) < 1e-12
    y = cbb.matvec(h, x)
    assert max(abs(a - b) for a, b in zip(y, [-3 - 3j, -1 - 1j])) < 1e-12
    assert max(abs(vp_receive(v, gamma, 4.0, 4.0) - z) for v, z in zip(y, s)) < 1e-12
    # Zero forcing without the perturbation needs 5 times the power.
    assert abs(cbb.norm2(cbb.matvec(cbb.inv(h), s)) - 20.0) < 1e-12


def test_real_form() -> None:
    rng = random.Random(1)
    a = [[cbb.cn(rng, 1.0) for _ in range(3)] for _ in range(3)]
    a = cbb.matmul(a, cbb.herm(a))
    ar = real_form(a)
    for _ in range(20):
        u = [cbb.cn(rng, 1.0) for _ in range(3)]
        v = [z.real for z in u] + [z.imag for z in u]
        vt = sum(v[i] * ar[i][j] * v[j] for i in range(6) for j in range(6))
        assert abs(vt - quad(a, u)) < 1e-10


def test_search_against_brute_force() -> None:
    # The sphere search is exact over all integer vectors; a box search gives an upper bound.
    # When the search result lies in the box, the two must agree.
    rng = random.Random(2)
    tau = 4.0
    for k, box, trials in [(1, 3, 5), (2, 3, 4), (3, 2, 1)]:
        for _ in range(trials):
            h = rand_h(rng, k, k)
            s = [rng.choice(QPSK) for _ in range(k)]
            a = cbb.inv(cbb.matmul(h, cbb.herm(h)))
            _, l_vec, gamma = vp_precode(h, s, 1.0, tau)
            assert all(abs(z.real) <= box and abs(z.imag) <= box for z in l_vec)
            best = math.inf
            for c in itertools.product(range(-box, box + 1), repeat=2 * k):
                u = [s[i] + tau * complex(c[i], c[i + k]) for i in range(k)]
                best = min(best, quad(a, u))
            assert abs(gamma - best) < 1e-9 * best


def test_closest_point_small_real() -> None:
    # A real 2 by 2 lattice where the answer is known by hand.
    r = [[1.0, 2.0], [0.0, 1.0]]
    # ||R (v + tau l)||^2 with v = (0.4, 0) and tau = 1: l = (-1, ...) checks the coupling.
    lv, val = closest_point(r, [0.4, 0.0], 1.0)
    best = min(
        ((0.4 + a) + 2 * b) ** 2 + b**2 for a in range(-5, 6) for b in range(-5, 6)
    )
    assert abs(val - best) < 1e-12
    assert abs(((0.4 + lv[0]) + 2 * lv[1]) ** 2 + lv[1] ** 2 - best) < 1e-12


def test_power_and_zero_interference() -> None:
    rng = random.Random(3)
    tau = 8.0
    for k, m in [(2, 2), (3, 4), (4, 4), (6, 8)]:
        h = rand_h(rng, k, m)
        s = [rng.choice(QAM16) for _ in range(k)]
        pt = rng.uniform(0.5, 50.0)
        x, l_vec, gamma = vp_precode(h, s, pt, tau)
        assert abs(cbb.norm2(x) - pt) < 1e-9 * pt
        y = cbb.matvec(h, x)
        c = math.sqrt(pt / gamma)
        assert max(abs(y[i] - c * (s[i] + tau * l_vec[i])) for i in range(k)) < 1e-9
        # Without noise, the modulo receiver gives back the data exactly.
        assert max(abs(vp_receive(v, gamma, pt, tau) - z) for v, z in zip(y, s)) < 1e-9


def test_never_worse_than_zero_forcing() -> None:
    rng = random.Random(4)
    ratios = []
    for _ in range(30):
        h = rand_h(rng, 4, 4)
        s = [rng.choice(QPSK) for _ in range(4)]
        a = cbb.inv(cbb.matmul(h, cbb.herm(h)))
        _, _, gamma = vp_precode(h, s, 1.0, 4.0)
        gzf = quad(a, s)
        assert gamma <= gzf + 1e-9 * gzf
        ratios.append(gzf / gamma)
    # On K = M = 4 Rayleigh channels the power saving is large on average.
    assert sum(ratios) / len(ratios) > 2.0


def test_mod_tau() -> None:
    assert mod_tau(3 + 5j, 4.0) == -1 + 1j
    assert mod_tau(-2 + 1.999j, 4.0) == -2 + 1.999j
    assert mod_tau(2 + 0j, 4.0) == -2 + 0j
    for z in QAM16:
        assert mod_tau(z + 8 * (2 - 3j), 8.0) == z

History

Tomlinson (1971) and Harashima and Miyakawa (1972) used a modulo at the transmitter and the receiver to remove intersymbol interference. Peel, Hochwald and Swindlehurst (2005, Part I) showed that channel inversion in a multiuser downlink with as many users as antennas has a poor sum rate, and introduced the regularized inverse. In Part II, Hochwald, Peel and Swindlehurst (2005) added the integer perturbation of the data, chose it with a sphere search, and reported performance close to the sum capacity at high SNR. The search builds on the enumeration of Schnorr and Euchner (1994) and on the survey of closest point search by Agrell, Eriksson, Vardy and Zeger (2002). Later work replaced the exact search by lattice-reduction-aided approximations.

References

  1. Bertrand M. Hochwald, Christian B. Peel and A. Lee Swindlehurst, A vector-perturbation technique for near-capacity multiantenna multiuser communication, Part II: perturbation, IEEE Transactions on Communications 53(3), 537-544, 2005, the perturbed channel inverse, the choice of tau, the modulo receiver, the sphere encoder and the regularized form
  2. Christian B. Peel, Bertrand M. Hochwald and A. Lee Swindlehurst, A vector-perturbation technique for near-capacity multiantenna multiuser communication, Part I: channel inversion and regularization, IEEE Transactions on Communications 53(1), 195-202, 2005, the loss of plain channel inversion that motivates the perturbation
  3. Erik Agrell, Thomas Eriksson, Alexander Vardy and Kenneth Zeger, Closest point search in lattices, IEEE Transactions on Information Theory 48(8), 2201-2214, 2002, the Schnorr-Euchner enumeration for the closest point problem with an upper triangular generator
  4. Claus P. Schnorr and M. Euchner, Lattice basis reduction: improved practical algorithms and solving subset sum problems, Mathematical Programming 66, 181-199, 1994, the enumeration order that visits candidates by their distance from the center

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