Algorithm Search⌘K

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
Properties
best zero interference sum ratedeterministiclinearneeds channel at transmitterzero interference
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 HjWk=0H_j W_k = 0 for j≠kj \ne k and the overall channel HWH W 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 kk has NkN_k antennas and receives yk=Hkx+wky_k = H_k x + w_k, with Hk∈CNk×MH_k \in \mathbb{C}^{N_k \times M} known at the base station and wk∼CN(0,N0I)w_k \sim \mathcal{CN}(0, N_0 I). The base station sends x=∑kWkdkx = \sum_k W_k d_k with unit-energy symbols dkd_k and total power ∑k∥Wk∥F2=P\sum_k \|W_k\|_F^2 = P. Let H~k\tilde H_k stack the channels of all users except kk. The goal is to choose the WkW_k with H~kWk=0\tilde H_k W_k = 0 that maximize the sum rate ∑klog⁡2det⁡(I+HkWkWkHHkH/N0)\sum_k \log_2 \det(I + H_k W_k W_k^H H_k^H / N_0). A solution exists only if rank(H~k)<M\mathrm{rank}(\tilde H_k) < M for every kk; for generic channels this means that MM is larger than the number of antennas of all the other users together.

The algorithm

  1. BD-PRECODE(H₁, ..., H_K, P, N0)
  2. for each user k:
  3. 1H̃_k ← the channels H_j of all users j ≠ k, stacked
  4. 2V⁽⁰⁾_k ← orthonormal basis of the null space of H̃_k ▷ from the SVD of H̃_k
  5. 3U_k Σ_k V⁽¹⁾_kᴴ ← SVD of H_k V⁽⁰⁾_k
  6. 4g ← all values σ² / N0 of all users
  7. 5p ← WATER-FILL(g, P) ▷ one water level for all streams
  8. for each user k:
  9. 6W_k ← V⁽⁰⁾_k V⁽¹⁾_k diag(√p_k) ▷ the first r_k columns
  10. 7return W₁, ..., W_K and the receive filters U₁ᴴ, ..., U_Kᴴ

Line L2 takes the right singular vectors of H~k\tilde H_k 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 kk applies UkHU_k^H and sees parallel scalar channels.

Example

Take M=3M = 3, P=3P = 3, N0=1N_0 = 1 and two users: user 1 has two antennas and user 2 has one.

H1=(100010),H2=(111).H_1 = \begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \end{pmatrix}, \qquad H_2 = \begin{pmatrix} 1 & 1 & 1 \end{pmatrix}.

For user 1, H~1=H2\tilde H_1 = H_2, whose null space has the basis (1,−1,0)/2(1, -1, 0)/\sqrt 2 and (1,1,−2)/6(1, 1, -2)/\sqrt 6. Then

H1V1(0)=(1/21/6−1/21/6),H_1 V^{(0)}_1 = \begin{pmatrix} 1/\sqrt 2 & 1/\sqrt 6 \\ -1/\sqrt 2 & 1/\sqrt 6 \end{pmatrix},

whose columns are orthogonal with norms 1 and 1/31/\sqrt 3, so the gains are 1 and 1/31/3. For user 2, H~2=H1\tilde H_2 = H_1, whose null space is spanned by e3=(0,0,1)e_3 = (0, 0, 1), and H2e3=1H_2 e_3 = 1, so the gain is 1. Water-filling over the gains (1,1/3,1)(1, 1/3, 1) with P=3P = 3 first tries all three streams, with the water level (3+1+3+1)/3=8/3<3(3 + 1 + 3 + 1)/3 = 8/3 < 3, so the weak stream gets no power. With two streams the level is (3+1+1)/2=2.5(3 + 1 + 1)/2 = 2.5, and the powers are 1.5, 0 and 1.5. The sum rate is 2log⁡22.5=2.6442 \log_2 2.5 = 2.644 bits per channel use.

precoder P=3P = 3 P=10P = 10
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 1/21/2, 1/21/2 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 HjWk=0H_j W_k = 0 for j≠kj \ne k, and Theorem 2 that the power is exactly PP. 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 Wk=Vk(0)XkW_k = V^{(0)}_k X_k, 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 kk has NkN_k antennas and receives yk=Hkx+wky_k = H_k x + w_k, with Hk∈CNk×MH_k \in \mathbb{C}^{N_k \times M} and wk∼CN(0,N0I)w_k \sim \mathcal{CN}(0, N_0 I). The transmitter sends x=∑kWkdkx = \sum_k W_k d_k with independent unit-energy Gaussian symbols dkd_k, so the transmit power is ∑k∥Wk∥F2\sum_k \|W_k\|_F^2. Let H~k\tilde H_k stack the channels HjH_j, j≠kj \ne k. Lines L1 to L7 compute an orthonormal basis Vk(0)V_k^{(0)} of the null space of H~k\tilde H_k (line L2), the SVD HkVk(0)=UkΣkVk(1)HH_k V_k^{(0)} = U_k \Sigma_k V_k^{(1)H} (line L3), one water-filling over the gains σ2/N0\sigma^2 / N_0 of all users (lines L4 and L5), and Wk=Vk(0)Vk(1)Pk1/2W_k = V_k^{(0)} V_k^{(1)} P_k^{1/2} with the first rkr_k columns of Vk(1)V_k^{(1)} and the diagonal power matrix PkP_k (line L6). The proof uses exact arithmetic for the ranks.

Lemma 1 (the null space basis). Let H~k=U~Σ~V~H\tilde H_k = \tilde U \tilde \Sigma \tilde V^H with the singular values in decreasing order and rank ρ\rho. The last M−ρM - \rho columns of V~\tilde V are an orthonormal basis of the null space of H~k\tilde H_k.

Proof. V~\tilde V is unitary, so its columns are orthonormal. For a column viv_i with i>ρi > \rho, H~kvi=σiu~i=0\tilde H_k v_i = \sigma_i \tilde u_i = 0. The null space has dimension M−ρM - \rho by the rank theorem, and these M−ρM - \rho orthonormal vectors lie in it, so they span it. □\square

If ρ=M\rho = M, user kk has no null space, and the implementation raises an error. So BD needs rank(H~k)<M\mathrm{rank}(\tilde H_k) < M for every kk; for generic channels this means ∑j≠kNj<M\sum_{j \ne k} N_j < M.

Theorem 1 (no inter-user interference). HjWk=0H_j W_k = 0 for all j≠kj \ne k.

Proof. The rows of HjH_j are rows of H~k\tilde H_k, and the columns of WkW_k are combinations of the columns of Vk(0)V_k^{(0)}, which lie in the null space of H~k\tilde H_k by Lemma 1. □\square

So yk=HkWkdk+wky_k = H_k W_k d_k + w_k: each user sees a single-user MIMO channel.

Theorem 2 (power). ∑k∥Wk∥F2=P\sum_k \|W_k\|_F^2 = P when at least one gain is positive.

Proof. Vk(0)V_k^{(0)} and Vk(1)V_k^{(1)} have orthonormal columns, so Vk(0)Vk(1)V_k^{(0)} V_k^{(1)} has orthonormal columns too, and ∥Wk∥F2=tr(Pk)\|W_k\|_F^2 = \mathrm{tr}(P_k). Water-filling returns powers with the sum PP (Lemma 1 of the SVD precoding proof). □\square

Lemma 2 (the rate). With WkW_k from line L6 and the receive filter UkHU_k^H, the streams of user kk are parallel scalar channels with gains σk,i2pk,i/N0\sigma_{k,i}^2 p_{k,i} / N_0, and

log⁡2det⁡(I+HkWkWkHHkH/N0)=∑ilog⁡2(1+σk,i2pk,i/N0).\log_2 \det\bigl(I + H_k W_k W_k^H H_k^H / N_0\bigr) = \sum_i \log_2 (1 + \sigma_{k,i}^2 p_{k,i} / N_0).

Proof. HkWk=HkVk(0)Vk(1)Pk1/2=UkΣkPk1/2H_k W_k = H_k V_k^{(0)} V_k^{(1)} P_k^{1/2} = U_k \Sigma_k P_k^{1/2} for the first rkr_k columns, because Vk(1)HVk(1)=IV_k^{(1)H} V_k^{(1)} = I on those columns. The columns of UkU_k are orthonormal, so UkHyk=ΣkPk1/2dk+UkHwkU_k^H y_k = \Sigma_k P_k^{1/2} d_k + U_k^H w_k with white noise of variance N0N_0. For the determinant, use det⁡(I+AB)=det⁡(I+BA)\det(I + A B) = \det(I + B A) with A=UkA = U_k: the matrix becomes I+Σk2Pk/N0I + \Sigma_k^2 P_k / N_0, which is diagonal. □\square

Theorem 3 (best zero-interference precoder). Among all precoders (W1,…,WK)(W_1, \ldots, W_K) with HjWk=0H_j W_k = 0 for j≠kj \ne k and ∑k∥Wk∥F2≤P\sum_k \|W_k\|_F^2 \le P, BD has the largest sum rate ∑klog⁡2det⁡(I+HkWkWkHHkH/N0)\sum_k \log_2 \det(I + H_k W_k W_k^H H_k^H / N_0).

Proof. Take any feasible precoder. By the condition H~kWk=0\tilde H_k W_k = 0, every column of WkW_k lies in the null space of H~k\tilde H_k, so Wk=Vk(0)XkW_k = V_k^{(0)} X_k for some XkX_k, by Lemma 1. Since Vk(0)V_k^{(0)} has orthonormal columns, ∥Wk∥F=∥Xk∥F\|W_k\|_F = \|X_k\|_F. Let Gk=HkVk(0)G_k = H_k V_k^{(0)}, G=diag(G1,…,GK)G = \mathrm{diag}(G_1, \ldots, G_K) (block diagonal) and Q=diag(X1X1H,…,XKXKH)Q = \mathrm{diag}(X_1 X_1^H, \ldots, X_K X_K^H). Then the sum rate is

∑klog⁡2det⁡(I+GkXkXkHGkH/N0)=log⁡2det⁡(I+GQGH/N0),\sum_k \log_2 \det(I + G_k X_k X_k^H G_k^H / N_0) = \log_2 \det(I + G Q G^H / N_0),

because the determinant of a block diagonal matrix is the product of the determinants of its blocks. Also tr(Q)=∑k∥Xk∥F2≤P\mathrm{tr}(Q) = \sum_k \|X_k\|_F^2 \le P. So the sum rate is at most the maximum of log⁡2det⁡(I+GQGH/N0)\log_2 \det(I + G Q G^H / N_0) over all positive semidefinite QQ with tr(Q)≤P\mathrm{tr}(Q) \le P, block diagonal or not. By the capacity theorem of the SVD precoding proof (Theorem 2 there), this maximum is ∑ilog⁡2(1+σi2pi/N0)\sum_i \log_2 (1 + \sigma_i^2 p_i / N_0), where σi\sigma_i runs over the singular values of GG and pp is the water-filling over the gains σi2/N0\sigma_i^2 / N_0. The singular values of the block diagonal GG are the union of those of the blocks GkG_k, which are the values of line L3. Lines L4 and L5 do exactly this water-filling, and by Lemma 2 BD reaches the bound. □\square

Corollary (single-antenna users). If every Nk=1N_k = 1, the null space precoder of user kk is the direction of column kk of HH(HHH)−1H^H (H H^H)^{-1}, and the gain is σk2=1/[(HHH)−1]kk\sigma_k^2 = 1 / [(H H^H)^{-1}]_{kk}, so BD is zero-forcing precoding with water-filling.

Proof. With Nk=1N_k = 1, Gk=hkHVk(0)G_k = h_k^H V_k^{(0)} is a row, and its only singular value is the norm of the projection of hkh_k onto the null space of the other channels. This squared norm is 1/[(HHH)−1]kk1 / [(H H^H)^{-1}]_{kk} by Lemma 3 of the zero-forcing precoding proof. □\square

The tests check Theorem 1 within 10−910^{-9}, Theorem 2 within 10−910^{-9}, Lemma 1 (orthonormal basis and H~kVk(0)=0\tilde H_k V_k^{(0)} = 0), 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 NN rows and MM columns, which costs O(MNmin⁡(M,N))⊆O(NM2)O(M N \min(M, N)) \subseteq O(N M^2), once for each of the KK users. Line L3 costs less, because HkVk(0)H_k V^{(0)}_k has only NkN_k rows. Lines L4 and L5 cost O(Nlog⁡N)O(N \log N) for the sort in water-filling. The total is O(KNM2)O(K N M^2). The extra space is O(M2)O(M^2) for one null space basis at a time and O(MN)O(M N) for the precoders.

Properties

  • Zero inter-user interference. HjWk=0H_j W_k = 0 for j≠kj \ne k (theorem).
  • Best with that constraint. No precoder with zero inter-user interference has a larger sum rate (theorem).
  • Generalizes zero forcing. With Nk=1N_k = 1 for every user, BD is zero-forcing precoding with water-filling (corollary).
  • Antenna condition. User kk has a null space of dimension M−rank(H~k)M - \mathrm{rank}(\tilde H_k); for generic channels BD needs M>∑j≠kNjM > \sum_{j \ne k} N_j for every kk, and full multiplexing needs M≥∑kNkM \ge \sum_k N_k.
  • Linear. The precoder is a matrix, so the cost per symbol is O(MN)O(M N).
  • 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 ∑kNk>M\sum_k N_k > M, 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 10−1010^{-10} 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 H~k\tilde H_k has full column rank, user kk cannot be served. Check the antenna condition before calling the algorithm.
  • The receivers must apply UkHU_k^H. 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 HjH_j leaves interference that grows with PP, 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.

block_diagonalization.pyI0RawGitHub
# 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

  1. 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
  2. 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.

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
  • at least three sources
  • a scene preset for the example