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
- Model
- Real RAM
- Properties
- deterministiclinearneeds channel at transmitternot needs noise levelzero interference
- Evidence
- Proof sketchCode in 1 languages
- 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 antennas serves single-antenna users and sends , where the columns of are the columns of the pseudoinverse of the channel matrix, scaled to give each user a power . Then 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 . 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 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 receives with . The matrix is known at the base station and has full row rank, so . The base station sends with independent unit-power symbols and the power constraint , and . The goal is a with for every , and among these the one with the largest sum rate , or with equal SNRs for all users.
The algorithm
ZF-PRECODE(H, P, N0, rule)- 1
G ← H Hᴴ ▷ K × K Gram matrix - 2
B ← Hᴴ G⁻¹ ▷ the pseudoinverse, H B = I - 3
c_k ← ‖b_k‖² = [G⁻¹]_kk for each user k ▷ the noise gain of user k - 4
q ← WATER-FILL(1/(c₁ N0), ..., 1/(c_K N0); P) ▷ or q_k = P/K, or q_k ∝ c_k - 5
w_k ← √(q_k / c_k) b_k for each user k - 6
return W = [w₁, ..., w_K]
Line L2 solves for and takes , which avoids an explicit inverse. Line L3 gives the gain: user receives , so its SNR is . 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, , gives every user the same SNR and the same receive amplitude, so the receivers need no gain control.
Example
Take , , and the real channel
Since is square, , and line L3 gives . The two channels and make an angle with , and each user keeps only the part of its channel gain that is orthogonal to the other user. So , which gives the gains ; user 2 pays more only because its channel is weaker. Water-filling with gives the level , above both , so . The table compares the three rules and maximum ratio transmission with equal power:
| precoder | SINRs | sum rate (bits per channel use) |
|---|---|---|
| ZF, water-filling, | 3.25, 0.70 | 2.853 |
| ZF, equal power, | 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 the interference makes maximum ratio transmission the worst choice. At 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 , so is diagonal, each user gets the SNR , and the power is . Theorem 2 shows that is the shortest vector that reaches user with amplitude 1 and is silent at the others, because every other such vector adds a component in the null space of . Theorem 3 combines this with water-filling: no linear precoder with zero interference and power has a larger sum rate than ZF with the powers of line L4. Lemma 3 and Theorem 4 show that is the squared distance from to the span of the other channels, which has the Gamma distribution with shape 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 , , with , the channel matrix of full row rank (so ), and with and the power . Let , (lines L1 and L2), column of and .
Lemma 1. is Hermitian positive definite, , and .
Proof. For , , because the rows of are independent. So is invertible, , and , whose diagonal entry is .
Theorem 1 (no interference). With (line L5), user receives . It sees no interference, its SNR is , and the total power is .
Proof. By Lemma 1, , so . The power is .
Theorem 2 (least power). Every with and for has the form with , and . So is the shortest beam that gives user the amplitude 1 and the other users nothing.
Proof. , so lies in the null space of . The vector lies in the range of , and that range is orthogonal to the null space of : for , . Pythagoras gives the norm.
Lemma 2 (water-filling). For gains , the powers with are the unique maximizer of over , . 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 in the same order. The objective grows with each , so the optimum uses the whole budget.
Theorem 3 (best zero-interference linear precoder). Among all with for and , ZF with water-filling over the gains (line L4) has the largest sum rate .
Proof. By Theorem 2, column of such a is with , so user has the SNR and the power is at least . Put . Then and the SNR of user is . By Lemma 2, the sum rate is at most the water-filling value, and Theorem 1 shows that ZF with these powers reaches it.
The equal power rule and the channel inversion rule , which gives every user the SNR , 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 be the orthogonal projection onto the orthogonal complement of the span of , . Then .
Proof. Order the users so that is the last one, and write with the matrix of the other channel vectors. Then , and the block inverse with the Schur complement of gives , with . This is Hermitian and idempotent, so .
Theorem 4 (SNR gain in Rayleigh fading). If the entries of are i.i.d. , then has the Gamma distribution with shape and scale 1. So with equal power, user has the SNR and the diversity order .
Proof. Condition on , . With probability 1 they span a subspace of dimension , so projects onto a fixed subspace of dimension . With an orthonormal basis of that subspace, . The vector is independent of the others and its law is invariant under unitary maps, so the are i.i.d. , and the sum is Gamma with shape . This law does not depend on the conditioning. Lemma 3 finishes the proof.
For the shape is 1, and is infinite. This is why channel inversion with has a poor average SNR.
The tests check Theorem 1 by against a diagonal matrix within and the power within for all three power rules, Lemma 1 by against , 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 , and the example values 2.853, 2.807 and 2.560 of the page.
Complexity
Line L1 costs multiplications. Line L2 costs for the factorization of and for the right-hand sides. Lines L3 to L5 cost . The total is per channel realization, with extra space. The precoding itself, , costs multiplications per symbol vector.
Properties
- No interference. for , so the SINR of each user is its SNR (theorem).
- Least power for zero interference. Every zero-interference beam for user costs at least per unit received power, and ZF reaches this bound (theorem).
- Noise level not needed for the beams. The directions use only . Only the water-filling powers use .
- Diversity. In i.i.d. Rayleigh fading with equal power, each user has the SNR gain and the diversity order (theorem).
- High SNR optimality. The sum rate grows as , 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 with ; see regularized zero-forcing precoding. It is never worse than ZF in the sum MSE sense and is much better when .
- 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 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 , is close to 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 is larger than , for example in time division duplex massive MIMO. It is the standard linear benchmark for multiuser precoding. With , 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 matrix fast enough, maximum ratio transmission avoids the inverse.
Pitfalls
- in Rayleigh fading. The SNR gain is a single exponential, and 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 , the nulls are in the wrong place, and the residual interference grows with , so the SINR saturates at high SNR.
- Wrong scaling. Normalizing each column to unit norm before the power rule changes the gains. Keep and scale with , or the SNR formula is wrong.
- Rank loss. If two users have parallel channels, 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 . 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.
# 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
- 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 3A1WH4 Edit this page History Report an error Markdown