Algorithm Search⌘K

Algorithmcore

Zero-forcing precoding

Also called channel inversion precoding, zero-forcing beamforming.

Precodes with the pseudoinverse of the multiuser channel so that each user receives no interference from the others.

Time
O(K^2 M + K^3) worst
Space
O(M K) extra
Where
K = the number of single-antenna users; M = the number of base station antennas
Properties
deterministiclinearneeds channel at transmitternot needs noise levelzero interference
Origin
Giuseppe Caire, Shlomo Shamai, 2003

Zero-forcing (ZF) precoding is the linear multiuser precoder that removes all interference between users. A base station with MM antennas serves K≤MK \le M single-antenna users and sends x=Wsx = W s, where the columns of WW are the columns of the pseudoinverse HH(HHH)−1H^H (H H^H)^{-1} of the channel matrix, scaled to give each user a power qkq_k. Then HWH W is diagonal: each user hears only its own symbol and noise. The price is power. A beam that must be orthogonal to every other user's channel points away from its own user, and the loss is the factor [(HHH)−1]kk[(H H^H)^{-1}]_{kk}. This page is the transmit side of the same inverse that the ZF MIMO detector applies at a receiver, that the decorrelating detector applies to CDMA users and that the ZF equalizer applies to a convolution. Compared with the other precoders: maximum ratio transmission maximizes each beam gain and ignores interference, regularized zero-forcing precoding adds (KN0/P)I(K N_0 / P) I to the inverse and balances the two, block diagonalization is the extension to users with several antennas, SVD precoding is the single-user method where the receiver can cooperate, and dirty paper coding is the nonlinear scheme that reaches the capacity region. The name "channel inversion" on this page means inverting the matrix channel; the scalar power rule of truncated channel inversion is a different method.

In plain words

A base station talks to several phones at the same time and on the same frequency. If it simply aims a beam at each phone, each phone also hears the beams meant for the others. Zero forcing aims each beam so that it is exactly silent at every other phone. Because the base station knows all the channels, it can solve for such beams with a set of linear equations. Each phone then hears only its own data and some noise. The cost is that a beam squeezed away from the other phones is weaker at its own phone. When two phones have similar channels, the beams lose a lot, so the base station must pick users whose channels are different.

The problem

User kk receives yk=hkHx+wky_k = h_k^H x + w_k with wk∼CN(0,N0)w_k \sim \mathcal{CN}(0, N_0). The matrix H=[h1,…,hK]H∈CK×MH = [h_1, \ldots, h_K]^H \in \mathbb{C}^{K \times M} is known at the base station and has full row rank, so K≤MK \le M. The base station sends x=Wsx = W s with independent unit-power symbols sks_k and the power constraint tr(WHW)≤P\mathrm{tr}(W^H W) \le P, and ρ=P/N0\rho = P / N_0. The goal is a WW with hkHwj=0h_k^H w_j = 0 for every j≠kj \ne k, and among these the one with the largest sum rate ∑klog⁡2(1+SNRk)\sum_k \log_2(1 + \mathrm{SNR}_k), or with equal SNRs for all users.

The algorithm

  1. ZF-PRECODE(H, P, N0, rule)
  2. 1G ← H Hᴴ ▷ K × K Gram matrix
  3. 2B ← Hᴴ G⁻¹ ▷ the pseudoinverse, H B = I
  4. 3c_k ← ‖b_k‖² = [G⁻¹]_kk for each user k ▷ the noise gain of user k
  5. 4q ← WATER-FILL(1/(c₁ N0), ..., 1/(c_K N0); P) ▷ or q_k = P/K, or q_k ∝ c_k
  6. 5w_k ← √(q_k / c_k) b_k for each user k
  7. 6return W = [w₁, ..., w_K]

Line L2 solves GX=HG X = H for X=G−1HX = G^{-1} H and takes B=XHB = X^H, which avoids an explicit inverse. Line L3 gives the gain: user kk receives qk/ck sk\sqrt{q_k / c_k}\, s_k, so its SNR is qk/(ckN0)q_k / (c_k N_0). Line L4 picks one of three power rules. Water-filling gives the best sum rate of any zero-interference linear precoder. Equal power is simple and close to it at high SNR. Channel inversion, qk=Pck/∑jcjq_k = P c_k / \sum_j c_j, gives every user the same SNR P/(N0 tr(G−1))P / (N_0\, \mathrm{tr}(G^{-1})) and the same receive amplitude, so the receivers need no gain control.

Example

Take M=K=2M = K = 2, P=10P = 10, N0=1N_0 = 1 and the real channel

H=(2111),G=HHH=(5332),G−1=(2−3−35).H = \begin{pmatrix} 2 & 1 \\ 1 & 1 \end{pmatrix}, \qquad G = H H^H = \begin{pmatrix} 5 & 3 \\ 3 & 2 \end{pmatrix}, \qquad G^{-1} = \begin{pmatrix} 2 & -3 \\ -3 & 5 \end{pmatrix}.

Since HH is square, B=H−1=(1−1−12)B = H^{-1} = \begin{pmatrix} 1 & -1 \\ -1 & 2 \end{pmatrix}, and line L3 gives c=(2,5)c = (2, 5). The two channels (2,1)(2, 1) and (1,1)(1, 1) make an angle θ\theta with cos⁡2θ=9/10\cos^2 \theta = 9/10, and each user keeps only the part sin⁡2θ=0.1\sin^2 \theta = 0.1 of its channel gain that is orthogonal to the other user. So 1/ck=0.1 ∥hk∥21/c_k = 0.1\, \|h_k\|^2, which gives the gains 1/c=(0.5,0.2)1/c = (0.5, 0.2); user 2 pays more only because its channel is weaker. Water-filling with P=10P = 10 gives the level μ=(10+2+5)/2=8.5\mu = (10 + 2 + 5)/2 = 8.5, above both ckc_k, so q=(6.5,3.5)q = (6.5, 3.5). The table compares the three rules and maximum ratio transmission with equal power:

precoder SINRs sum rate (bits per channel use)
ZF, water-filling, q=(6.5,3.5)q = (6.5, 3.5) 3.25, 0.70 2.853
ZF, equal power, q=(5,5)q = (5, 5) 2.50, 1.00 2.807
ZF, channel inversion 1.43, 1.43 2.560
maximum ratio transmission, equal power 1.06, 1.00 2.045

At P=10P = 10 the interference makes maximum ratio transmission the worst choice. At P=1P = 1 the order is reversed: ZF with water-filling gives 0.585 and maximum ratio transmission gives 1.433, because at low SNR the noise dominates and the beam gain matters more than the interference.

Correctness

The proof is in proofs/correctness.md. Lemma 1 and Theorem 1 show that HB=IH B = I, so HWH W is diagonal, each user gets the SNR qk/(ckN0)q_k / (c_k N_0), and the power is ∑kqk=P\sum_k q_k = P. Theorem 2 shows that bkb_k is the shortest vector that reaches user kk with amplitude 1 and is silent at the others, because every other such vector adds a component in the null space of HH. Theorem 3 combines this with water-filling: no linear precoder with zero interference and power PP has a larger sum rate than ZF with the powers of line L4. Lemma 3 and Theorem 4 show that 1/ck1 / c_k is the squared distance from hkh_k to the span of the other channels, which has the Gamma distribution with shape M−K+1M - K + 1 in i.i.d. Rayleigh fading.

Proof: ZF precoding removes all interference with the least power, water-filling gives the best sum rate among zero-interference linear precoders, and the SNR gain is Gamma with shape M - K + 1full

The model is the multiuser downlink yk=hkHx+wky_k = h_k^H x + w_k, k=1,…,Kk = 1, \ldots, K, with wk∼CN(0,N0)w_k \sim \mathcal{CN}(0, N_0), the channel matrix H=[h1,…,hK]H∈CK×MH = [h_1, \ldots, h_K]^H \in \mathbb{C}^{K \times M} of full row rank (so K≤MK \le M), and x=Wsx = W s with E[ssH]=IKE[s s^H] = I_K and the power tr(WHW)≤P\mathrm{tr}(W^H W) \le P. Let G=HHHG = H H^H, B=HHG−1B = H^H G^{-1} (lines L1 and L2), bkb_k column kk of BB and ck=[G−1]kkc_k = [G^{-1}]_{kk}.

Lemma 1. GG is Hermitian positive definite, HB=IKH B = I_K, and ck=∥bk∥2c_k = \|b_k\|^2.

Proof. For u≠0u \ne 0, uHGu=∥HHu∥2>0u^H G u = \|H^H u\|^2 > 0, because the rows of HH are independent. So GG is invertible, HB=GG−1=IH B = G G^{-1} = I, and BHB=G−1HHHG−1=G−1B^H B = G^{-1} H H^H G^{-1} = G^{-1}, whose diagonal entry kk is ∥bk∥2\|b_k\|^2. □\square

Theorem 1 (no interference). With wk=qk/ck bkw_k = \sqrt{q_k / c_k}\, b_k (line L5), user kk receives yk=qk/ck sk+wky_k = \sqrt{q_k / c_k}\, s_k + w_k. It sees no interference, its SNR is qk/(ckN0)q_k / (c_k N_0), and the total power is ∑kqk\sum_k q_k.

Proof. By Lemma 1, hkHbj=[HB]kj=δkjh_k^H b_j = [H B]_{kj} = \delta_{kj}, so hkHx=∑jqj/cj hkHbjsj=qk/ck skh_k^H x = \sum_j \sqrt{q_j / c_j}\, h_k^H b_j s_j = \sqrt{q_k / c_k}\, s_k. The power is ∑k(qk/ck)∥bk∥2=∑kqk\sum_k (q_k / c_k) \|b_k\|^2 = \sum_k q_k. □\square

Theorem 2 (least power). Every w∈CMw \in \mathbb{C}^M with hkHw=ah_k^H w = a and hjHw=0h_j^H w = 0 for j≠kj \ne k has the form w=abk+nw = a b_k + n with Hn=0H n = 0, and ∥w∥2=∣a∣2ck+∥n∥2≥∣a∣2ck\|w\|^2 = |a|^2 c_k + \|n\|^2 \ge |a|^2 c_k. So bkb_k is the shortest beam that gives user kk the amplitude 1 and the other users nothing.

Proof. Hw=aek=H(abk)H w = a e_k = H (a b_k), so n=w−abkn = w - a b_k lies in the null space of HH. The vector bk=HH(G−1ek)b_k = H^H (G^{-1} e_k) lies in the range of HHH^H, and that range is orthogonal to the null space of HH: for Hn=0H n = 0, (HHu)Hn=uHHn=0(H^H u)^H n = u^H H n = 0. Pythagoras gives the norm. □\square

Lemma 2 (water-filling). For gains gk>0g_k > 0, the powers qk=(μ−1/gk)+q_k = (\mu - 1/g_k)^+ with ∑kqk=P\sum_k q_k = P are the unique maximizer of ∑klog⁡2(1+gkqk)\sum_k \log_2(1 + g_k q_k) over q≥0q \ge 0, ∑kqk≤P\sum_k q_k \le P. The function water_fill computes them.

Proof. This is the water-filling result; the KKT argument and the proof that the drop loop finds the right water level are on the page water-filling power allocation and in the proof of SVD precoding, Lemma 1. The loop here tests the same condition μk>1/gk\mu_k > 1/g_k in the same order. The objective grows with each qkq_k, so the optimum uses the whole budget. □\square

Theorem 3 (best zero-interference linear precoder). Among all WW with hkHwj=0h_k^H w_j = 0 for j≠kj \ne k and tr(WHW)≤P\mathrm{tr}(W^H W) \le P, ZF with water-filling over the gains gk=1/(ckN0)g_k = 1/(c_k N_0) (line L4) has the largest sum rate ∑klog⁡2(1+SNRk)\sum_k \log_2(1 + \mathrm{SNR}_k).

Proof. By Theorem 2, column kk of such a WW is akbk+nka_k b_k + n_k with Hnk=0H n_k = 0, so user kk has the SNR ∣ak∣2/N0|a_k|^2 / N_0 and the power is at least ∑k∣ak∣2ck\sum_k |a_k|^2 c_k. Put qk=∣ak∣2ckq_k = |a_k|^2 c_k. Then ∑kqk≤P\sum_k q_k \le P and the SNR of user kk is qk/(ckN0)=gkqkq_k / (c_k N_0) = g_k q_k. By Lemma 2, the sum rate is at most the water-filling value, and Theorem 1 shows that ZF with these powers reaches it. □\square

The equal power rule qk=P/Kq_k = P/K and the channel inversion rule qk=Pck/∑jcjq_k = P c_k / \sum_j c_j, which gives every user the SNR P/(N0 tr(G−1))P / (N_0\, \mathrm{tr}(G^{-1})), also meet the power constraint by Theorem 1, but they do not maximize the sum rate in general.

Lemma 3 (geometry of the noise gain). Let Πk\Pi_k be the orthogonal projection onto the orthogonal complement of the span of hjh_j, j≠kj \ne k. Then 1/ck=∥Πkhk∥21 / c_k = \|\Pi_k h_k\|^2.

Proof. Order the users so that kk is the last one, and write HH=[A hk]H^H = [A\ h_k] with AA the matrix of the other channel vectors. Then G=(AHAAHhkhkHAhkHhk)G = \begin{pmatrix} A^H A & A^H h_k \\ h_k^H A & h_k^H h_k \end{pmatrix}, and the block inverse with the Schur complement of AHAA^H A gives ck=(hkHhk−hkHA(AHA)−1AHhk)−1=(hkHΠkhk)−1c_k = \bigl(h_k^H h_k - h_k^H A (A^H A)^{-1} A^H h_k\bigr)^{-1} = (h_k^H \Pi_k h_k)^{-1}, with Πk=I−A(AHA)−1AH\Pi_k = I - A (A^H A)^{-1} A^H. This Πk\Pi_k is Hermitian and idempotent, so hkHΠkhk=∥Πkhk∥2h_k^H \Pi_k h_k = \|\Pi_k h_k\|^2. □\square

Theorem 4 (SNR gain in Rayleigh fading). If the entries of HH are i.i.d. CN(0,1)\mathcal{CN}(0, 1), then 1/ck1 / c_k has the Gamma distribution with shape M−K+1M - K + 1 and scale 1. So with equal power, user kk has the SNR (P/(KN0))⋅Γ(M−K+1,1)(P / (K N_0)) \cdot \Gamma(M - K + 1, 1) and the diversity order M−K+1M - K + 1.

Proof. Condition on hjh_j, j≠kj \ne k. With probability 1 they span a subspace of dimension K−1K - 1, so Πk\Pi_k projects onto a fixed subspace of dimension d=M−K+1d = M - K + 1. With an orthonormal basis u1,…,udu_1, \ldots, u_d of that subspace, ∥Πkhk∥2=∑i∣uiHhk∣2\|\Pi_k h_k\|^2 = \sum_i |u_i^H h_k|^2. The vector hkh_k is independent of the others and its law is invariant under unitary maps, so the uiHhku_i^H h_k are i.i.d. CN(0,1)\mathcal{CN}(0, 1), and the sum is Gamma with shape dd. This law does not depend on the conditioning. Lemma 3 finishes the proof. □\square

For K=MK = M the shape is 1, and E[ck]=E[1/Γ(1,1)]E[c_k] = E[1/\Gamma(1, 1)] is infinite. This is why channel inversion with K=MK = M has a poor average SNR.

The tests check Theorem 1 by HWH W against a diagonal matrix within 10−910^{-9} and the power within 10−910^{-9} for all three power rules, Lemma 1 by ckc_k against [G−1]kk[G^{-1}]_{kk}, Theorem 2 with random null space vectors, Lemma 2 by its KKT conditions, Theorem 3 by a grid over the power splits of 2 and 3 users, Theorem 4 by the sample mean and variance of 1/ck1/c_k, and the example values 2.853, 2.807 and 2.560 of the page.

Complexity

Line L1 costs K2MK^2 M multiplications. Line L2 costs O(K3)O(K^3) for the factorization of GG and O(K2M)O(K^2 M) for the MM right-hand sides. Lines L3 to L5 cost O(MK+Klog⁡K)O(M K + K \log K). The total is O(K2M+K3)O(K^2 M + K^3) per channel realization, with O(MK)O(M K) extra space. The precoding itself, x=Wsx = W s, costs MKM K multiplications per symbol vector.

Properties

  • No interference. hkHwj=0h_k^H w_j = 0 for j≠kj \ne k, so the SINR of each user is its SNR (theorem).
  • Least power for zero interference. Every zero-interference beam for user kk costs at least ckc_k per unit received power, and ZF reaches this bound (theorem).
  • Noise level not needed for the beams. The directions bkb_k use only HH. Only the water-filling powers use N0N_0.
  • Diversity. In i.i.d. Rayleigh fading with equal power, each user has the SNR gain Γ(M−K+1,1)\Gamma(M - K + 1, 1) and the diversity order M−K+1M - K + 1 (theorem).
  • High SNR optimality. The sum rate grows as Klog⁡2ρK \log_2 \rho, the same slope as dirty paper coding. The gap to the capacity region stays bounded at high SNR for a fixed channel.
  • Low SNR loss. At low SNR the beam gain matters more than interference, and maximum ratio transmission is better.

Variants and improvements

  • Regularized ZF. Use HH(HHH+αI)−1H^H (H H^H + \alpha I)^{-1} with α=KN0/P\alpha = K N_0 / P; see regularized zero-forcing precoding. It is never worse than ZF in the sum MSE sense and is much better when K=MK = M.
  • User selection. Serve a subset of users with nearly orthogonal channels. Yoo and Goldsmith (2006) showed that ZF with semi-orthogonal user selection reaches the same sum rate growth as dirty paper coding when the number of candidate users grows.
  • Per-antenna power constraints. Under a power limit on each antenna, the pseudoinverse is no longer optimal, and other generalized inverses of HH do better (Wiesel, Eldar and Shamai, 2008).
  • Multi-antenna users. Replace the null space of single vectors by the null space of whole channel matrices; see block diagonalization.
  • Nonlinear. Precode with successive interference presubtraction; see Tomlinson-Harashima precoding and vector perturbation precoding, which perturbs the data before the same inverse.
  • Massive MIMO. With M≫KM \gg K, HHHH H^H is close to MIM I by favorable propagation, and ZF approaches maximum ratio transmission in direction but keeps zero interference.

When to use it

Use ZF in a multiuser downlink at moderate and high SNR when the base station has accurate channel estimates and MM is larger than KK, for example in time division duplex massive MIMO. It is the standard linear benchmark for multiuser precoding. With K=MK = M, or with users whose channels are nearly parallel, use regularized ZF or user selection instead. At low SNR, or when the channel estimates are poor, maximum ratio transmission is often better. When the base station cannot invert a K×KK \times K matrix fast enough, maximum ratio transmission avoids the inverse.

Pitfalls

  • K=MK = M in Rayleigh fading. The SNR gain 1/ck1/c_k is a single exponential, and E[ck]E[c_k] is infinite. Channel inversion with a fixed power then has a very low average SNR.
  • Channel estimation errors. ZF sends nulls toward the other users. With an estimate H^≠H\hat H \ne H, the nulls are in the wrong place, and the residual interference grows with PP, so the SINR saturates at high SNR.
  • Wrong scaling. Normalizing each column bkb_k to unit norm before the power rule changes the gains. Keep ck=∥bk∥2c_k = \|b_k\|^2 and scale with qk/ck\sqrt{q_k / c_k}, or the SNR formula is wrong.
  • Rank loss. If two users have parallel channels, GG is singular and ZF does not exist. Select users or regularize.
  • Two meanings of "channel inversion". In the precoding literature it means the pseudoinverse of HH. In link adaptation it means a power rule that inverts a scalar fading gain. Do not confuse the two.

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)
zero_forcing_precoding.py 74 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zero-forcing-precoding/. The authors are listed in prov/3A1WH4.jsonl.

"""Zero-forcing precoding for the multiuser MISO downlink.

User k has one antenna and 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, with K <= M and full row rank.
The transmitter sends x = W s with E[s s^H] = I and the power tr(W^H W) = P.

B = H^H (H H^H)^(-1) is the pseudoinverse of H, so H B = I. Column k of W is
b_k sqrt(q_k / c_k) with c_k = ||b_k||^2 = [(H H^H)^(-1)]_kk, so user k gets
h_k^H w_k = sqrt(q_k / c_k), no interference, and the SNR q_k / (c_k N0).
The powers q_k come from one of three rules:
- "waterfill": water-filling over the gains 1 / (c_k N0), the best sum rate;
- "equal": q_k = P / K;
- "inversion": the same SNR P / (N0 tr((H H^H)^(-1))) for every user.
"""

import math

import cbb


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)."""
    idx = sorted(range(len(gains)), key=lambda i: -gains[i])
    inv = [1.0 / gains[i] for i in idx]
    k = len(idx)
    while k > 1 and (p_total + sum(inv[:k])) / k <= inv[k - 1]:
        k -= 1
    mu = (p_total + sum(inv[:k])) / k
    p = [0.0] * len(gains)
    for t in range(k):
        p[idx[t]] = mu - inv[t]
    return p


def zf_precoder(h: list[list[complex]], p_total: float, n0: float, mode: str = "waterfill"):
    """The ZF precoder of the K by M channel h. Returns (w, q, c).

    w is M by K (column k serves user k), q holds the user powers and c the
    noise gains c_k = [(H H^H)^(-1)]_kk.
    """
    k_users = len(h)
    hh = cbb.herm(h)  # M by K
    g = cbb.matmul(h, hh)  # @line L1
    b = cbb.herm(cbb.solve(g, h))  # @line L2
    # cbb.solve(g, h) is G^(-1) H, and its conjugate transpose is H^H G^(-1), since G is Hermitian.
    c = [sum(abs(b[i][k]) ** 2 for i in range(len(b))) for k in range(k_users)]  # @line L3
    if mode == "waterfill":
        q = water_fill([1.0 / (ck * n0) for ck in c], p_total)  # @line L4
    elif mode == "equal":
        q = [p_total / k_users] * k_users
    elif mode == "inversion":
        q = [p_total * ck / sum(c) for ck in c]
    else:
        raise ValueError("unknown mode")
    w = [[b[i][k] * math.sqrt(q[k] / c[k]) for k in range(k_users)] for i in range(len(b))]  # @line L5
    return w, q, c  # @line L6


def sinr(h: list[list[complex]], w: list[list[complex]], n0: float) -> list[float]:
    """SINR_k = |h_k^H w_k|^2 / (sum over j != k of |h_k^H w_j|^2 + N0)."""
    e = cbb.matmul(h, w)
    out = []
    for k in range(len(h)):
        sig = abs(e[k][k]) ** 2
        out.append(sig / (sum(abs(x) ** 2 for x in e[k]) - sig + n0))
    return out


def sum_rate(h: list[list[complex]], w: list[list[complex]], n0: float) -> float:
    """The sum rate sum log2(1 + SINR_k) in bits per channel use."""
    return sum(math.log2(1.0 + s) for s in sinr(h, w, n0))
test_zero_forcing_precoding.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zero-forcing-precoding/. The authors are listed in prov/3A1WH4.jsonl.

import math
import random

import cbb
from zero_forcing_precoding import sinr, sum_rate, water_fill, zf_precoder


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 test_example() -> None:
    h = [[2, 1], [1, 1]]
    w, q, c = zf_precoder(h, 10.0, 1.0)
    assert max(abs(a - b) for a, b in zip(c, [2.0, 5.0])) < 1e-12
    assert max(abs(a - b) for a, b in zip(q, [6.5, 3.5])) < 1e-12
    s = sinr(h, w, 1.0)
    assert abs(s[0] - 3.25) < 1e-12 and abs(s[1] - 0.7) < 1e-12
    assert abs(sum_rate(h, w, 1.0) - math.log2(4.25 * 1.7)) < 1e-12
    assert abs(sum_rate(h, w, 1.0) - 2.853) < 5e-4
    w, _, _ = zf_precoder(h, 10.0, 1.0, "equal")
    assert abs(sum_rate(h, w, 1.0) - math.log2(3.5 * 2)) < 1e-12
    w, _, _ = zf_precoder(h, 10.0, 1.0, "inversion")
    assert abs(sum_rate(h, w, 1.0) - 2 * math.log2(1 + 10 / 7)) < 1e-12
    assert abs(sum_rate(h, w, 1.0) - 2.560) < 5e-4


def test_zero_interference_and_power() -> None:
    rng = random.Random(1)
    for k, m in [(1, 1), (2, 2), (2, 4), (3, 3), (4, 8), (8, 8)]:
        for mode in ("waterfill", "equal", "inversion"):
            h = rand_h(rng, k, m)
            pt, n0 = rng.uniform(0.5, 50.0), rng.uniform(0.1, 2.0)
            w, q, c = zf_precoder(h, pt, n0, mode)
            assert abs(cbb.norm2(w) - pt) < 1e-9
            e = cbb.matmul(h, w)
            for i in range(k):
                for j in range(k):
                    if i != j:
                        assert abs(e[i][j]) < 1e-9
                assert abs(abs(e[i][i]) ** 2 - q[i] / c[i]) < 1e-9 * max(1.0, q[i] / c[i])
            if mode == "inversion":
                s = sinr(h, w, n0)
                assert max(s) - min(s) < 1e-9 * max(s)


def test_noise_gain_is_diagonal_of_inverse() -> None:
    rng = random.Random(2)
    h = rand_h(rng, 3, 5)
    _, _, c = zf_precoder(h, 1.0, 1.0)
    g_inv = cbb.inv(cbb.matmul(h, cbb.herm(h)))
    for k in range(3):
        assert abs(c[k] - g_inv[k][k].real) < 1e-10


def test_pseudoinverse_columns_have_minimum_norm() -> None:
    # Any other column with h_k^H w = 1 and h_j^H w = 0 for j != k is b_k plus a null space vector, and is longer.
    rng = random.Random(3)
    h = rand_h(rng, 2, 5)
    w, q, c = zf_precoder(h, 2.0, 1.0, "equal")
    b0 = [w[i][0] / math.sqrt(q[0] / c[0]) for i in range(5)]
    hh = cbb.herm(h)
    pinv_h = cbb.matmul(hh, cbb.inv(cbb.matmul(h, hh)))
    proj = cbb.sub(cbb.eye(5), cbb.matmul(pinv_h, h))
    for _ in range(50):
        z = [cbb.cn(rng, 1.0) for _ in range(5)]
        other = cbb.add(b0, cbb.matvec(proj, z))
        hv = cbb.matvec(h, other)
        assert abs(hv[0] - 1) < 1e-9 and abs(hv[1]) < 1e-9
        assert cbb.norm2(other) >= c[0] - 1e-9


def test_water_fill_kkt() -> None:
    rng = random.Random(4)
    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 and min(p) >= 0.0
        mu = max(p[i] + 1 / g[i] for i in range(n) if p[i] > 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_power_split_grid_two_and_three_users() -> None:
    # With the ZF beams fixed, water-filling beats every power split on a grid.
    rng = random.Random(5)
    for k in (2, 3):
        for _ in range(4):
            h = rand_h(rng, k, 4)
            pt, n0 = rng.uniform(1.0, 20.0), 1.0
            w, q, c = zf_precoder(h, pt, n0)
            best = sum_rate(h, w, n0)
            steps = 400 if k == 2 else 60
            grid = 0.0
            for i in range(steps + 1):
                for j in range(steps + 1 - i if k == 3 else 1):
                    if k == 2:
                        split = [pt * i / steps, pt * (1 - i / steps)]
                    else:
                        split = [pt * i / steps, pt * j / steps, pt * (steps - i - j) / steps]
                    r = sum(math.log2(1 + s / (ck * n0)) for s, ck in zip(split, c))
                    grid = max(grid, r)
            assert best >= grid - 1e-12
            assert best - grid < 1e-2


def test_mean_snr_gain_in_rayleigh_fading() -> None:
    # 1 / c_k is Gamma with shape M - K + 1 and scale 1 in i.i.d. CN(0, 1) fading.
    rng = random.Random(6)
    for k, m in [(2, 2), (2, 4), (3, 6)]:
        t = 1000
        acc = acc2 = 0.0
        for _ in range(t):
            _, _, c = zf_precoder(rand_h(rng, k, m), 1.0, 1.0, "equal")
            acc += 1 / c[0]
            acc2 += (1 / c[0]) ** 2
        mean = acc / t
        shape = m - k + 1
        assert abs(mean - shape) < 5 * math.sqrt(shape / t)
        # The Gamma variance equals its shape.
        assert abs(acc2 / t - mean * mean - shape) < 0.4 * shape


def test_orthogonal_channels_give_matched_beams() -> None:
    h = [[2, 0, 0], [0, 0, 1j]]
    w, q, c = zf_precoder(h, 2.0, 1.0, "equal")
    # Column k is parallel to h_k: |h_k^H w_k|^2 = ||h_k||^2 ||w_k||^2.
    for k in range(2):
        col = [w[i][k] for i in range(3)]
        hk = [complex(v).conjugate() for v in h[k]]
        assert abs(abs(cbb.dot(hk, col)) ** 2 - cbb.norm2(hk) * cbb.norm2(col)) < 1e-12

History

Linear transmit processing that nulls interference toward other receivers is an old idea in array processing. For the multiuser MIMO downlink, Caire and Shamai (2003) used zero-forcing beamforming as a simple scheme and compared its throughput with the dirty paper coding rate. Spencer, Swindlehurst and Haardt (2004) treated channel inversion and its block form for users with several antennas, and Peel, Hochwald and Swindlehurst (2005) showed that plain channel inversion performs poorly when the number of users equals the number of antennas, which led them to regularization and vector perturbation. Yoo and Goldsmith (2006) showed that ZF with user selection keeps the sum rate growth of the optimal scheme when there are many users, and Wiesel, Eldar and Shamai (2008) clarified when the pseudoinverse is the optimal ZF matrix.

References

  1. Giuseppe Caire and Shlomo Shamai, On the achievable throughput of a multiantenna Gaussian broadcast channel, IEEE Transactions on Information Theory 49(7), 1691-1706, 2003, the zero-forcing beamforming scheme and its comparison with the dirty paper coding rate
  2. Quentin H. Spencer, A. Lee Swindlehurst and Martin Haardt, Zero-forcing methods for downlink spatial multiplexing in multiuser MIMO channels, IEEE Transactions on Signal Processing 52(2), 461-471, 2004, the channel inversion precoder for single-antenna users and the power allocation over the users
  3. 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 channel inversion precoder and its poor performance when the number of users equals the number of antennas
  4. Taesang Yoo and Andrea Goldsmith, On the optimality of multiantenna broadcast scheduling using zero-forcing beamforming, IEEE Journal on Selected Areas in Communications 24(3), 528-541, 2006, zero-forcing beamforming with semi-orthogonal user selection and its sum rate scaling with many users
  5. Ami Wiesel, Yonina C. Eldar and Shlomo Shamai, Zero-forcing precoding and generalized inverses, IEEE Transactions on Signal Processing 56(9), 4409-4418, 2008, the optimality of the pseudoinverse under a total power constraint and the other generalized inverses under per-antenna constraints

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