Algorithmadvanced
Block diagonalization precoding
Also called BD precoding.
Precodes each multi-antenna user in the null space of the other users' channels, making the channel block diagonal.
- Time
- O(K N M^2) worst
- Space
- O(M^2 + M N) extra
- Where
- K = the number of users; M = the number of base station antennas; N = the total number of user antennas
- Model
- Real RAM
- Properties
- best zero interference sum ratedeterministiclinearneeds channel at transmitterzero interference
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Quentin H. Spencer, A. Lee Swindlehurst, Martin Haardt, Lai U Choi, Ross D. Murch, 2004
Block diagonalization (BD) precoding serves several users that each have more than one antenna. It puts the precoder of each user in the null space of the channels of all the other users, so that for and the overall channel becomes block diagonal. Inside its own null space, each user then gets SVD precoding, and one water-filling over all users splits the power. BD is the multi-antenna form of zero-forcing precoding. Zero forcing removes the interference between every pair of receive antennas, even two antennas of the same user. BD removes only the interference between different users, and lets each user handle the rest itself. With one antenna per user the two are the same. Among all precoders with zero interference between users, BD has the largest sum rate.
In plain words
A base station sends to several phones at once, and each phone has a few antennas. The base station wants no phone to hear the signals meant for the others. For each phone, it finds the directions that the other phones cannot hear at all, and sends that phone's signal only in those directions. After this, each phone sees a private link, as if it were alone. The base station then shapes each private link for the best rate, and gives more power to the strong links. Because the signals for different antennas of the same phone may mix, this wastes less power than canceling every leak between all antennas.
The problem
User has antennas and receives , with known at the base station and . The base station sends with unit-energy symbols and total power . Let stack the channels of all users except . The goal is to choose the with that maximize the sum rate . A solution exists only if for every ; for generic channels this means that is larger than the number of antennas of all the other users together.
The algorithm
BD-PRECODE(H₁, ..., H_K, P, N0)for each user k:- 1
H̃_k ← the channels H_j of all users j ≠ k, stacked - 2
V⁽⁰⁾_k ← orthonormal basis of the null space of H̃_k ▷ from the SVD of H̃_k - 3
U_k Σ_k V⁽¹⁾_kᴴ ← SVD of H_k V⁽⁰⁾_k - 4
g ← all values σ² / N0 of all users - 5
p ← WATER-FILL(g, P) ▷ one water level for all streams for each user k:- 6
W_k ← V⁽⁰⁾_k V⁽¹⁾_k diag(√p_k) ▷ the first r_k columns - 7
return W₁, ..., W_K and the receive filters U₁ᴴ, ..., U_Kᴴ
Line L2 takes the right singular vectors of that belong to the zero singular values. Line L3 is the singular value decomposition of the effective single-user channel. Line L5 is water-filling over the gains of all streams of all users together. User applies and sees parallel scalar channels.
Example
Take , , and two users: user 1 has two antennas and user 2 has one.
For user 1, , whose null space has the basis and . Then
whose columns are orthogonal with norms 1 and , so the gains are 1 and . For user 2, , whose null space is spanned by , and , so the gain is 1. Water-filling over the gains with first tries all three streams, with the water level , so the weak stream gets no power. With two streams the level is , and the powers are 1.5, 0 and 1.5. The sum rate is bits per channel use.
| precoder | ||
|---|---|---|
| BD | 2.644 | 5.381 |
| zero forcing with water-filling over the 3 antennas as 3 users | 2.245 | 4.966 |
Zero forcing over the three antennas has the gains , and 1, because it also cancels the interference between the two antennas of user 1. BD does not, and it loses less power.
Correctness
The proof is in proofs/correctness.md. Lemma 1 shows that line L2 gives an orthonormal basis of the null space. Theorem 1 shows that for , and Theorem 2 that the power is exactly . Lemma 2 shows that each user sees parallel channels with the gains of line L3. Theorem 3 shows that BD maximizes the sum rate over all precoders with zero inter-user interference: every such precoder has the form , the sum rate is then a log det of a block diagonal channel, and the MIMO capacity result for that channel is reached by SVD and one water-filling. A corollary shows that with one antenna per user BD is zero forcing with water-filling.
Proof: Block diagonalization removes all inter-user interference, meets the power exactly, and has the largest sum rate of all precoders with zero inter-user interferencefull
User has antennas and receives , with and . The transmitter sends with independent unit-energy Gaussian symbols , so the transmit power is . Let stack the channels , . Lines L1 to L7 compute an orthonormal basis of the null space of (line L2), the SVD (line L3), one water-filling over the gains of all users (lines L4 and L5), and with the first columns of and the diagonal power matrix (line L6). The proof uses exact arithmetic for the ranks.
Lemma 1 (the null space basis). Let with the singular values in decreasing order and rank . The last columns of are an orthonormal basis of the null space of .
Proof. is unitary, so its columns are orthonormal. For a column with , . The null space has dimension by the rank theorem, and these orthonormal vectors lie in it, so they span it.
If , user has no null space, and the implementation raises an error. So BD needs for every ; for generic channels this means .
Theorem 1 (no inter-user interference). for all .
Proof. The rows of are rows of , and the columns of are combinations of the columns of , which lie in the null space of by Lemma 1.
So : each user sees a single-user MIMO channel.
Theorem 2 (power). when at least one gain is positive.
Proof. and have orthonormal columns, so has orthonormal columns too, and . Water-filling returns powers with the sum (Lemma 1 of the SVD precoding proof).
Lemma 2 (the rate). With from line L6 and the receive filter , the streams of user are parallel scalar channels with gains , and
Proof. for the first columns, because on those columns. The columns of are orthonormal, so with white noise of variance . For the determinant, use with : the matrix becomes , which is diagonal.
Theorem 3 (best zero-interference precoder). Among all precoders with for and , BD has the largest sum rate .
Proof. Take any feasible precoder. By the condition , every column of lies in the null space of , so for some , by Lemma 1. Since has orthonormal columns, . Let , (block diagonal) and . Then the sum rate is
because the determinant of a block diagonal matrix is the product of the determinants of its blocks. Also . So the sum rate is at most the maximum of over all positive semidefinite with , block diagonal or not. By the capacity theorem of the SVD precoding proof (Theorem 2 there), this maximum is , where runs over the singular values of and is the water-filling over the gains . The singular values of the block diagonal are the union of those of the blocks , which are the values of line L3. Lines L4 and L5 do exactly this water-filling, and by Lemma 2 BD reaches the bound.
Corollary (single-antenna users). If every , the null space precoder of user is the direction of column of , and the gain is , so BD is zero-forcing precoding with water-filling.
Proof. With , is a row, and its only singular value is the norm of the projection of onto the null space of the other channels. This squared norm is by Lemma 3 of the zero-forcing precoding proof.
The tests check Theorem 1 within , Theorem 2 within , Lemma 1 (orthonormal basis and ), Lemma 2 against the log det rate with the other users treated as noise, the corollary, the KKT conditions of the water-filling, Theorem 3 against a grid over the power split on the example and against random precoders in the same null spaces, and the example of the page.
Complexity
Line L2 needs the SVD of a matrix with at most rows and columns, which costs , once for each of the users. Line L3 costs less, because has only rows. Lines L4 and L5 cost for the sort in water-filling. The total is . The extra space is for one null space basis at a time and for the precoders.
Properties
- Zero inter-user interference. for (theorem).
- Best with that constraint. No precoder with zero inter-user interference has a larger sum rate (theorem).
- Generalizes zero forcing. With for every user, BD is zero-forcing precoding with water-filling (corollary).
- Antenna condition. User has a null space of dimension ; for generic channels BD needs for every , and full multiplexing needs .
- Linear. The precoder is a matrix, so the cost per symbol is .
- Noise enhancement. Like zero forcing, BD loses power when the null spaces are small or nearly orthogonal to the user's own channel.
Variants and improvements
- Regularized BD. Replace the exact null space by a regularized inverse, which allows a little interference and loses less power at low SNR, as regularized zero-forcing precoding does for single-antenna users.
- Successive optimization. Spencer, Swindlehurst and Haardt also proposed to null the interference only toward users that are served earlier, which relaxes the antenna condition.
- Per-user power or rate targets. Replace the joint water-filling by a weighted water-filling or by fixed powers for each user.
- User and stream selection. When , serve a subset of users or fewer streams per user so that the null spaces exist.
- Weighted MMSE. Allow interference and optimize the weighted sum rate directly; see weighted MMSE precoding.
- Dirty paper coding. The capacity of the broadcast channel needs nonlinear coding; see dirty paper coding.
When to use it
Use BD in a multiuser MIMO downlink when the users have several antennas, the base station has accurate channel knowledge, and it has more antennas than the users together. It is a good choice at high SNR, where removing interference matters most. When the users have one antenna each, it is the same as zero-forcing precoding. At low SNR, or when the antenna condition is close to its limit, regularized or weighted MMSE designs do better.
Pitfalls
- Rank threshold. Line L2 decides which singular values are zero. With noisy channel estimates, a fixed relative threshold such as times the largest singular value is needed; a wrong threshold gives a null space that is too large (with interference) or too small.
- Too many user antennas. If has full column rank, user cannot be served. Check the antenna condition before calling the algorithm.
- The receivers must apply . Each user needs its own receive filter, so it must know its effective channel, for example from precoded pilots.
- Stale channel. An old estimate of leaves interference that grows with , as for zero forcing.
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
# Part of https://algorithm.tamnd.com/block-diagonalization/. The authors are listed in prov/VCA1WD.jsonl.
"""Block diagonalization (BD) precoding for the multiuser MIMO downlink.
User k has N_k antennas and receives y_k = H_k x + w_k with H_k an N_k by M
matrix and w_k ~ CN(0, N0 I). The transmitter sends x = sum_k W_k d_k. BD
puts the precoder W_k of user k in the null space of the other users'
channels, so H_j W_k = 0 for j != k, and the overall channel becomes block
diagonal. Inside its null space, each user gets SVD precoding, and one
water-filling over the singular values of all users splits the power P.
The SVD here is a one-sided Jacobi method, the same as on the SVD precoding
page; it is repeated so that this file stands alone.
"""
import math
import cbb
def svd(a: list[list[complex]], tol: float = 1e-15, max_sweeps: int = 100):
"""The SVD a = U diag(s) V^H of an m by n complex matrix, by one-sided Jacobi.
Returns (u, s, v). s has n values in decreasing order. v is n by n and
unitary. u is m by n; its column i is a_i / s_i for s_i > 0 and the zero
vector for s_i = 0.
"""
m, n = len(a), len(a[0])
cols = [[complex(a[i][k]) for i in range(m)] for k in range(n)]
vcols = [[1 + 0j if i == k else 0j for i in range(n)] for k in range(n)]
# A column with a squared norm below this is zero to rounding; rotating it only adds noise.
small = (1e-15) ** 2 * sum(abs(x) ** 2 for col in cols for x in col)
for _ in range(max_sweeps):
rotated = False
for p in range(n - 1):
for q in range(p + 1, n):
ap, aq = cols[p], cols[q]
alpha = sum(abs(x) ** 2 for x in ap)
beta = sum(abs(x) ** 2 for x in aq)
if alpha <= small or beta <= small:
continue
gamma = sum(x.conjugate() * y for x, y in zip(ap, aq))
g = abs(gamma)
if g <= tol * math.sqrt(alpha * beta):
continue
rotated = True
ph = gamma / g
ph /= abs(ph)
zeta = (beta - alpha) / (2.0 * g)
t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
c = 1.0 / math.sqrt(1.0 + t * t)
s = c * t
e = ph.conjugate()
cols[p] = [c * x - s * e * y for x, y in zip(ap, aq)]
cols[q] = [s * x + c * e * y for x, y in zip(ap, aq)]
vp, vq = vcols[p], vcols[q]
vcols[p] = [c * x - s * e * y for x, y in zip(vp, vq)]
vcols[q] = [s * x + c * e * y for x, y in zip(vp, vq)]
if not rotated:
break
norms = [math.sqrt(sum(abs(x) ** 2 for x in col)) for col in cols]
order = sorted(range(n), key=lambda k: -norms[k])
s = [norms[k] for k in order]
big = s[0] if s else 0.0
ucols = []
for k in order:
if norms[k] > 1e-13 * max(big, 1e-300):
ucols.append([x / norms[k] for x in cols[k]])
else:
ucols.append([0j] * m)
u = [[ucols[k][i] for k in range(n)] for i in range(m)]
v = [[vcols[k][i] for k in order] for i in range(n)]
return u, s, v
def water_fill(gains: list[float], p_total: float) -> list[float]:
"""Powers p_i >= 0 with sum P that maximize sum log2(1 + g_i p_i); a zero gain gets no power."""
idx = sorted((i for i in range(len(gains)) if gains[i] > 0), key=lambda i: -gains[i])
p = [0.0] * len(gains)
if not idx or p_total <= 0:
return p
inv = [1.0 / gains[i] for i in idx]
k = len(idx)
while k > 1:
mu = (p_total + sum(inv[:k])) / k
if mu > inv[k - 1]:
break
k -= 1
mu = (p_total + sum(inv[:k])) / k
for t in range(k):
p[idx[t]] = mu - inv[t]
return p
def null_space(a: list[list[complex]], m: int, rtol: float = 1e-10) -> list[list[complex]]:
"""An M by L matrix whose orthonormal columns span the null space of a (a has M columns, maybe no rows)."""
if not a:
return cbb.eye(m)
_, s, v = svd(a)
rank = sum(1 for x in s if x > rtol * s[0]) if s[0] > 0 else 0
return [row[rank:] for row in v]
def bd_precoder(h_list: list[list[list[complex]]], p_total: float, n0: float):
"""The BD precoder for the user channels h_list (H_k is N_k by M).
Returns (w_list, u_list, s_list, p_list): W_k is M by r_k, U_k holds the
r_k receive vectors of user k as columns, s_k its gains and p_k its powers.
"""
m = len(h_list[0][0])
parts = []
for k, hk in enumerate(h_list):
others = [row for j, hj in enumerate(h_list) if j != k for row in hj] # @line L1
v0 = null_space(others, m) # @line L2
if not v0[0]:
raise ValueError("user %d has no null space: too few transmit antennas" % k)
u, s, v1 = svd(cbb.matmul(hk, v0)) # @line L3
r = sum(1 for x in s if x > 1e-12 * max(s[0], 1e-300))
parts.append((v0, u, s[:r], v1, r))
gains = [x * x / n0 for (_, _, s, _, _) in parts for x in s] # @line L4
p_all = water_fill(gains, p_total) # @line L5
w_list, u_list, s_list, p_list = [], [], [], []
pos = 0
for v0, u, s, v1, r in parts:
p = p_all[pos : pos + r]
pos += r
dirs = cbb.matmul(v0, [row[:r] for row in v1])
w_list.append([[dirs[t][i] * math.sqrt(p[i]) for i in range(r)] for t in range(m)]) # @line L6
u_list.append([row[:r] for row in u])
s_list.append(s)
p_list.append(p)
return w_list, u_list, s_list, p_list # @line L7
def rate_from_gains(s_list: list[list[float]], p_list: list[list[float]], n0: float) -> float:
"""sum over users and streams of log2(1 + s^2 p / N0)."""
return sum(math.log2(1.0 + si * si * pi / n0) for s, p in zip(s_list, p_list) for si, pi in zip(s, p))
def sum_rate(h_list: list[list[list[complex]]], w_list: list[list[list[complex]]], n0: float) -> float:
"""sum_k log2 det(N0 I + sum_j H_k Q_j H_k^H) - log2 det(N0 I + sum_{j != k} H_k Q_j H_k^H), Q_j = W_j W_j^H.
This is the rate of each user when it treats the other users' signals as noise.
"""
total = 0.0
for k, hk in enumerate(h_list):
nk = len(hk)
full = [[n0 if i == t else 0j for t in range(nk)] for i in range(nk)]
intf = [row[:] for row in full]
for j, wj in enumerate(w_list):
if not wj[0]:
continue
hw = cbb.matmul(hk, wj)
c = cbb.matmul(hw, cbb.herm(hw))
full = cbb.add(full, c)
if j != k:
intf = cbb.add(intf, c)
total += math.log2(abs(cbb.det(full))) - math.log2(abs(cbb.det(intf)))
return total
cbb.py 315 lines
# 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)
test_block_diagonalization.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/block-diagonalization/. The authors are listed in prov/VCA1WD.jsonl.
import math
import random
import cbb
from block_diagonalization import bd_precoder, null_space, rate_from_gains, sum_rate
def rand_h(rng: random.Random, n: int, m: int) -> list[list[complex]]:
return [[cbb.cn(rng, 1.0) for _ in range(m)] for _ in range(n)]
def max_abs(a: list[list[complex]]) -> float:
return max((abs(x) for row in a for x in row), default=0.0)
EXAMPLE = [[[1, 0, 0], [0, 1, 0]], [[1, 1, 1]]]
def test_example() -> None:
w, u, s, p = bd_precoder(EXAMPLE, 3.0, 1.0)
assert abs(s[0][0] - 1.0) < 1e-12 and abs(s[0][1] - 1 / math.sqrt(3)) < 1e-12
assert abs(s[1][0] - 1.0) < 1e-12
assert abs(p[0][0] - 1.5) < 1e-12 and abs(p[0][1]) < 1e-12 and abs(p[1][0] - 1.5) < 1e-12
assert abs(rate_from_gains(s, p, 1.0) - 2 * math.log2(2.5)) < 1e-12
assert abs(sum_rate(EXAMPLE, w, 1.0) - 2 * math.log2(2.5)) < 1e-10
def test_zero_interference_and_power() -> None:
rng = random.Random(1)
for m, sizes in [(4, (2, 2)), (6, (1, 2, 3)), (8, (2, 2, 2, 2)), (5, (2, 1))]:
hs = [rand_h(rng, n, m) for n in sizes]
pt = rng.uniform(0.5, 50.0)
w, _, _, _ = bd_precoder(hs, pt, 1.0)
assert abs(sum(cbb.norm2(wk) for wk in w if wk[0]) - pt) < 1e-9 * pt
for j, hj in enumerate(hs):
for k, wk in enumerate(w):
if j != k and wk[0]:
assert max_abs(cbb.matmul(hj, wk)) < 1e-9
def test_null_space_is_orthonormal() -> None:
rng = random.Random(2)
a = rand_h(rng, 3, 5)
v0 = null_space(a, 5)
assert len(v0[0]) == 2
assert max_abs(cbb.sub(cbb.matmul(cbb.herm(v0), v0), cbb.eye(2))) < 1e-12
assert max_abs(cbb.matmul(a, v0)) < 1e-12
def test_rate_two_ways() -> None:
# The rate from the gains equals the log det rate with the other users treated as noise.
rng = random.Random(3)
for m, sizes in [(4, (2, 2)), (6, (2, 3, 1))]:
hs = [rand_h(rng, n, m) for n in sizes]
w, _, s, p = bd_precoder(hs, 10.0, 0.5)
assert abs(rate_from_gains(s, p, 0.5) - sum_rate(hs, w, 0.5)) < 1e-9
def test_single_antenna_users_give_zero_forcing_gains() -> None:
# With N_k = 1 the gain of user k is 1 / [(H H^H)^(-1)]_kk, the zero-forcing gain.
rng = random.Random(4)
h = rand_h(rng, 3, 4)
_, _, s, _ = bd_precoder([[row] for row in h], 1.0, 1.0)
gi = cbb.inv(cbb.matmul(h, cbb.herm(h)))
for k in range(3):
assert abs(s[k][0] ** 2 - 1.0 / gi[k][k].real) < 1e-10
def test_water_filling_kkt() -> None:
rng = random.Random(5)
hs = [rand_h(rng, 2, 6) for _ in range(3)]
n0 = 2.0
_, _, s, p = bd_precoder(hs, 4.0, n0)
inv = [n0 / (x * x) for sk in s for x in sk]
pw = [x for pk in p for x in pk]
mu = max(i + q for i, q in zip(inv, pw) if q > 0)
for i, q in zip(inv, pw):
if q > 0:
assert abs(i + q - mu) < 1e-9
else:
assert i >= mu - 1e-9
def test_grid_search_over_powers() -> None:
# On the example, no split of the power over the three streams beats BD.
w, _, s, p = bd_precoder(EXAMPLE, 3.0, 1.0)
g = [x * x for sk in s for x in sk]
best = rate_from_gains(s, p, 1.0)
grid = 0.0
steps = 150
for a in range(steps + 1):
for b in range(steps + 1 - a):
q = [3.0 * a / steps, 3.0 * b / steps, 3.0 * (steps - a - b) / steps]
grid = max(grid, sum(math.log2(1 + gi * qi) for gi, qi in zip(g, q)))
assert grid <= best + 1e-12
assert best - grid < 1e-3
def test_beats_random_null_space_precoders() -> None:
# BD is the best precoder with zero interference: random precoders in the same null spaces do not beat it.
rng = random.Random(6)
m, sizes, pt = 4, (2, 2), 6.0
hs = [rand_h(rng, n, m) for n in sizes]
w, _, s, p = bd_precoder(hs, pt, 1.0)
best = rate_from_gains(s, p, 1.0)
bases = []
for k in range(2):
others = [row for j, hj in enumerate(hs) if j != k for row in hj]
bases.append(null_space(others, m))
for _ in range(200):
ws = [cbb.matmul(v0, rand_h(rng, len(v0[0]), 2)) for v0 in bases]
c = math.sqrt(pt / sum(cbb.norm2(x) for x in ws))
ws = [cbb.scale(c, x) for x in ws]
assert sum_rate(hs, ws, 1.0) <= best + 1e-9
def test_too_few_antennas() -> None:
rng = random.Random(7)
# The 3 antennas of user 1 fill the whole space, so user 2 has no null space.
hs = [rand_h(rng, 3, 3), rand_h(rng, 1, 3)]
try:
bd_precoder(hs, 1.0, 1.0)
except ValueError:
return
raise AssertionError("expected ValueError")
History
Spencer, Swindlehurst and Haardt (2004) studied zero-forcing methods for the multiuser MIMO downlink with multi-antenna users. They described block diagonalization with the null space of the other users, the power allocation, and the condition on the number of antennas, and they also proposed successive optimization. In the same year, Choi and Murch published a transmit preprocessing technique that decomposes the multiuser channel into parallel single-user channels by null space projection, which is the same idea. Later work added regularization, user selection and comparisons with the capacity of the broadcast channel.
References
- 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, block diagonalization with the null space of the other users, the power allocation by water-filling, the antenna condition, and successive optimization
- Lai-U Choi and Ross D. Murch, A transmit preprocessing technique for multiuser MIMO systems using a decomposition approach, IEEE Transactions on Wireless Communications 3(1), 20-24, 2004, the decomposition of the multiuser channel into parallel single-user channels by null space precoding
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 VCA1WD Edit this page History Report an error Markdown