Algorithm Search⌘K

Algorithmcore

Zero-forcing MIMO detector

Also called ZF detector, ZF MIMO receiver.

Applies the pseudoinverse of the channel matrix to remove the interference between streams, then slices each stream to the nearest symbol. The price is noise enhancement.

Time
O(n^2 m + n^3 + n M) worst
Space
O(n m) extra
Counts
time per vector after setup O(n m + n M) worst
Where
M = the constellation size; m = the number of receive antennas; n = the number of transmitted streams
Properties
deterministicnot exact mlexact ml if columns orthogonallinearnot needs noise level
Origin
Peter W. Wolniansky, Gerard J. Foschini, Glen D. Golden, Reinaldo A. Valenzuela, 1998

The zero-forcing (ZF) MIMO detector is the simplest receiver for spatial multiplexing. It multiplies the received vector by the pseudoinverse of the channel matrix, which removes the interference between the transmitted streams completely, and then slices each stream to the nearest constellation point on its own. So it solves the MIMO detection problem in two cheap steps instead of a search over all MnM^n symbol vectors. The price is noise enhancement: stream kk gets noise of variance N0[(HHH)−1]kkN_0 [(H^H H)^{-1}]_{kk}, which is large when the columns of HH are nearly dependent. In i.i.d. Rayleigh fading this cuts the diversity order from mm for ML to m−n+1m - n + 1. The MMSE MIMO detector adds the noise level to the same inverse and loses less, V-BLAST detects the streams one by one and cancels each decision, and lattice reduction aided detection applies ZF to a better basis of the same lattice. The same inverse appears three more times on this site, with a different meaning of the matrix: the ZF equalizer inverts a convolution in time, ZF precoding applies the inverse at the transmitter, and the decorrelating detector inverts the correlation matrix of CDMA users.

In plain words

Several antennas send different symbols at the same time on the same frequency. Each receive antenna hears a mix of all of them. If the receiver knows how the channel mixes the symbols, it can undo the mix exactly, like solving a set of linear equations. After that, each symbol stands alone, and the receiver picks the nearest valid symbol for each one. The problem is the noise. Undoing the mix also changes the noise, and when two transmit antennas look alike to the receiver, the noise grows very large. The detector ignores this risk, so it is fast but loses much of the reliability that a full search would give.

The problem

The model is y=Hx+wy = H x + w. Here H∈Cm×nH \in \mathbb{C}^{m \times n} is the known channel matrix, with mm receive antennas (rows) and nn transmitted streams (columns), x=(x1,…,xn)x = (x_1, \ldots, x_n) holds one point of a unit-energy constellation S\mathcal{S} of size MM per stream, and w∼CN(0,N0I)w \sim \mathcal{CN}(0, N_0 I). The SNR is Es/N0E_s / N_0 per complex symbol, with Es=1E_s = 1. The detector needs m≥nm \ge n and HH of full column rank, so that HHHH^H H is invertible. The output is a decision x^∈Sn\hat x \in \mathcal{S}^n. ZF does not have to be the ML decision, and in general it is not.

The algorithm

  1. ZF-DETECT(y, H, S)
  2. 1G ← Hᴴ H ▷ n × n Gram matrix
  3. 2W ← G⁻¹ Hᴴ ▷ the pseudoinverse H⁺
  4. 3z ← W y ▷ z = x + W w
  5. 4for k ← 1 to n
  6. 5x̂_k ← the point of S nearest to z_k
  7. 6return x̂

Lines L1 and L2 depend only on the channel, so a receiver computes WW once per channel use of a block fading channel and then reuses it for every received vector of the block. Line L2 solves GW=HHG W = H^H by Gaussian elimination or a Cholesky decomposition, or it uses the QR decomposition H=QRH = Q R, where W=R−1QHW = R^{-1} Q^H is better conditioned because it does not square the condition number of HH. Line L3 is the unconstrained least squares solution: it minimizes ∥y−Hz∥2\|y - H z\|^2 over all z∈Cnz \in \mathbb{C}^n, not only over Sn\mathcal{S}^n. Line L5 is the minimum distance detector for one symbol; for square QAM it is a rounding of the real and imaginary parts.

Example

Take m=n=2m = n = 2, BPSK with S={+1,−1}\mathcal{S} = \{+1, -1\}, and the real channel

H=(2111),H−1=(1−1−12).H = \begin{pmatrix} 2 & 1 \\ 1 & 1 \end{pmatrix}, \qquad H^{-1} = \begin{pmatrix} 1 & -1 \\ -1 & 2 \end{pmatrix}.

The transmitter sends x=(+1,−1)x = (+1, -1), so Hx=(1,0)H x = (1, 0). The noise is w=(−0.5,0.6)w = (-0.5, 0.6), with ∥w∥2=0.61\|w\|^2 = 0.61, and the receiver gets y=(0.5,0.6)y = (0.5, 0.6). Because HH is square, line L2 gives W=H−1W = H^{-1}, and line L3 gives

z=H−1y=(0.5−0.6,  −0.5+1.2)=(−0.1,  0.7).z = H^{-1} y = (0.5 - 0.6,\; -0.5 + 1.2) = (-0.1,\; 0.7).

Line L5 decides x^=(−1,+1)\hat x = (-1, +1). Both decisions are wrong. The ML detector compares the four candidates:

candidate xx HxH x ∥y−Hx∥2\|y - H x\|^2
(+1,+1)(+1, +1) (3,2)(3, 2) 8.21
(+1,−1)(+1, -1) (1,0)(1, 0) 0.61
(−1,+1)(-1, +1) (−1,0)(-1, 0) 2.61
(−1,−1)(-1, -1) (−3,−2)(-3, -2) 19.01

So ML finds the sent vector, and the ZF decision has the second best metric. The reason is the noise gain. The rows of H−1H^{-1} have the squared norms 2 and 5, so the two streams see noise of variance 2N02 N_0 and 5N05 N_0, losses of 3.0 dB and 7.0 dB. The noise Ww=(−1.1,1.7)W w = (-1.1, 1.7) is much larger than ww, and it moves both outputs across the decision boundary at 0. Without noise, line L3 gives z=xz = x exactly.

Correctness

The proof is in proofs/correctness.md. It shows four things. First, WH=IW H = I, so z=x+Wwz = x + W w with no interference from the other streams, and without noise ZF recovers xx exactly (a theorem). Second, the noise WwW w is CN(0,N0(HHH)−1)\mathcal{CN}(0, N_0 (H^H H)^{-1}), so stream kk has the post-detection SNR (Es/N0)/[(HHH)−1]kk(E_s / N_0) / [(H^H H)^{-1}]_{kk} (a closed form). Third, if the columns of HH are orthogonal, the ML metric separates into one term per stream, and ZF is exactly ML (a theorem). Fourth, 1/[(HHH)−1]kk1 / [(H^H H)^{-1}]_{kk} is the squared distance from column hkh_k to the span of the other n−1n - 1 columns. In i.i.d. CN(0,1)\mathcal{CN}(0, 1) fading this is a sum of m−n+1m - n + 1 independent unit exponentials, so the error probability of each stream decays as SNR−(m−n+1)\mathrm{SNR}^{-(m - n + 1)} (a theorem, Tse and Viswanath, Section 8.3.1).

Proof: ZF removes all interference, its noise covariance is N0 (H^H H)^-1, it is ML on orthogonal channels, and its diversity in i.i.d. Rayleigh fading is m - n + 1full

The model is y=Hx+wy = H x + w with H∈Cm×nH \in \mathbb{C}^{m \times n} of full column rank, x∈Snx \in \mathcal{S}^n and w∼CN(0,N0Im)w \sim \mathcal{CN}(0, N_0 I_m). Let G=HHHG = H^H H and W=G−1HHW = G^{-1} H^H, as in lines L1 and L2. Let hkh_k be column kk of HH.

Lemma 1 (GG is invertible). If HH has full column rank, GG is Hermitian positive definite.

Proof. GH=HHH=GG^H = H^H H = G. For u≠0u \ne 0, uHGu=∥Hu∥2>0u^H G u = \|H u\|^2 > 0, because Hu≠0H u \ne 0 when the columns are independent. A positive definite matrix has only positive eigenvalues, so it is invertible. □\square

Theorem 1 (no interference, exact without noise). WH=InW H = I_n, so z=Wy=x+Wwz = W y = x + W w. If w=0w = 0, lines L4 and L5 return xx.

Proof. WH=G−1HHH=G−1G=InW H = G^{-1} H^H H = G^{-1} G = I_n, so Wy=WHx+Ww=x+WwW y = W H x + W w = x + W w. If w=0w = 0, then zk=xkz_k = x_k, which is a point of S\mathcal{S}, and the point of S\mathcal{S} nearest to xkx_k is xkx_k itself at distance 0. □\square

Lemma 2 (least squares). z=Wyz = W y is the unique minimizer of ∥y−Hu∥2\|y - H u\|^2 over u∈Cnu \in \mathbb{C}^n.

Proof. For any uu, write u=z+du = z + d. Then y−Hu=(y−Hz)−Hdy - H u = (y - H z) - H d, and HH(y−Hz)=HHy−GG−1HHy=0H^H (y - H z) = H^H y - G G^{-1} H^H y = 0. So the cross term vanishes and ∥y−Hu∥2=∥y−Hz∥2+∥Hd∥2\|y - H u\|^2 = \|y - H z\|^2 + \|H d\|^2. The second term is positive for d≠0d \ne 0 by full column rank. □\square

Theorem 2 (noise covariance and post-detection SNR). The noise WwW w at the output is CN(0,N0G−1)\mathcal{CN}(0, N_0 G^{-1}). So zk=xk+νkz_k = x_k + \nu_k with νk∼CN(0,N0[G−1]kk)\nu_k \sim \mathcal{CN}(0, N_0 [G^{-1}]_{kk}), and the SNR of stream kk after ZF is (Es/N0)/[G−1]kk(E_s / N_0) / [G^{-1}]_{kk}. Also [G−1]kk=∥Wk,:∥2[G^{-1}]_{kk} = \|W_{k,:}\|^2, the squared norm of row kk of WW.

Proof. A linear map of a circularly symmetric Gaussian vector is circularly symmetric Gaussian, with covariance E[WwwHWH]=N0WWH=N0G−1HHHG−1=N0G−1E[W w w^H W^H] = N_0 W W^H = N_0 G^{-1} H^H H G^{-1} = N_0 G^{-1}, because G−1G^{-1} is Hermitian. The diagonal entry kk of WWHW W^H is the squared norm of row kk. □\square

Theorem 3 (ML on orthogonal channels). If GG is diagonal, the decision of lines L4 and L5 is an ML decision.

Proof. By the proof of Lemma 2, ∥y−Hx∥2=∥y−Hz∥2+∥H(x−z)∥2\|y - H x\|^2 = \|y - H z\|^2 + \|H(x - z)\|^2 for every xx. If G=diag(g1,…,gn)G = \mathrm{diag}(g_1, \ldots, g_n), then ∥H(x−z)∥2=(x−z)HG(x−z)=∑kgk∣xk−zk∣2\|H (x - z)\|^2 = (x - z)^H G (x - z) = \sum_k g_k |x_k - z_k|^2. The first term does not depend on xx, and each gk>0g_k > 0. So the minimum over x∈Snx \in \mathcal{S}^n is reached by minimizing each ∣xk−zk∣|x_k - z_k| over S\mathcal{S} on its own, which is what line L5 does. □\square

The orthogonality is needed. When GG is not diagonal, the cross terms dˉiGikdk\bar d_i G_{ik} d_k couple the streams, and the nearest point per stream can be a worse vector, as the example on the page shows.

Lemma 3 (geometry of the noise gain). Let PP be the orthogonal projection onto the orthogonal complement of the span of the columns hjh_j, j≠kj \ne k. Then 1/[G−1]kk=∥Phk∥21 / [G^{-1}]_{kk} = \|P h_k\|^2.

Proof. Order the columns so that kk is the last one and write H=[A  hk]H = [A \; h_k]. The block inverse formula, with the Schur complement of the block AHAA^H A, gives

[G−1]kk=(hkHhk−hkHA(AHA)−1AHhk)−1=(hkH(I−A(AHA)−1AH)hk)−1.[G^{-1}]_{kk} = \bigl(h_k^H h_k - h_k^H A (A^H A)^{-1} A^H h_k\bigr)^{-1} = \bigl(h_k^H (I - A (A^H A)^{-1} A^H) h_k\bigr)^{-1}.

The matrix I−A(AHA)−1AHI - A (A^H A)^{-1} A^H is the projection PP, which is Hermitian and idempotent, so hkHPhk=∥Phk∥2h_k^H P h_k = \|P h_k\|^2. □\square

Theorem 4 (diversity m−n+1m - n + 1; Tse and Viswanath, Section 8.3.1). Let the entries of HH be i.i.d. CN(0,1)\mathcal{CN}(0, 1), with m≥nm \ge n. Then 1/[G−1]kk1 / [G^{-1}]_{kk} has the Gamma distribution with shape m−n+1m - n + 1 and scale 1, the distribution of a sum of m−n+1m - n + 1 independent unit exponentials. With BPSK, the error probability of stream kk is

Pe=(1−μ2)d∑i=0d−1(d−1+ii)(1+μ2)i,d=m−n+1,μ=SNR1+SNR,P_e = \Bigl(\frac{1 - \mu}{2}\Bigr)^{d} \sum_{i=0}^{d-1} \binom{d - 1 + i}{i} \Bigl(\frac{1 + \mu}{2}\Bigr)^{i}, \qquad d = m - n + 1, \quad \mu = \sqrt{\frac{\mathrm{SNR}}{1 + \mathrm{SNR}}},

which decays as (2d−1d)(4 SNR)−d\binom{2d - 1}{d} (4\,\mathrm{SNR})^{-d}. So the diversity order is m−n+1m - n + 1.

Proof. The columns hjh_j, j≠kj \ne k, are independent of hkh_k. Condition on them. With probability 1 they span a subspace of dimension n−1n - 1, so PP projects onto a fixed subspace of dimension d=m−n+1d = m - n + 1. Pick an orthonormal basis u1,…,udu_1, \ldots, u_d of that subspace. Since hk∼CN(0,Im)h_k \sim \mathcal{CN}(0, I_m) is unitarily invariant, the coordinates uiHhku_i^H h_k are i.i.d. CN(0,1)\mathcal{CN}(0, 1), and ∥Phk∥2=∑i∣uiHhk∣2\|P h_k\|^2 = \sum_i |u_i^H h_k|^2 is a sum of dd independent unit exponentials. This law does not depend on the conditioning, so it holds unconditionally. By Lemma 3 and Theorem 2, stream kk is BPSK in Gaussian noise with the SNR γ=SNR ∥Phk∥2\gamma = \mathrm{SNR}\, \|P h_k\|^2, so its error probability is E[Q(2γ)]E[Q(\sqrt{2 \gamma})] with γ\gamma a Gamma variable of shape dd and mean d SNRd\,\mathrm{SNR}. This is the same average as for maximal ratio combining over dd independent Rayleigh branches, which gives the closed form above and its high SNR limit. □\square

So ZF with m=nm = n has diversity 1. The tests check Theorem 1 on random channels with 16-QAM, Theorem 2 by WH=IW H = I and the row norms, Theorem 3 on channels with orthogonal columns, and Theorem 4 by the mean of 1/[G−1]111 / [G^{-1}]_{11} and by a BPSK error count against the closed form with a Wilson interval.

Complexity

Line L1 costs n2mn^2 m complex multiplications, or half of that with the symmetry of GG. Line L2 costs O(n3+n2m)O(n^3 + n^2 m). Line L3 costs nmn m multiplications per received vector, and line L5 costs O(M)O(M) per stream by a linear scan, or O(1)O(1) per stream for square QAM by rounding. So a block of TT vectors on one channel costs O(n2m+n3+Tn(m+M))O(n^2 m + n^3 + T n (m + M)) in the real RAM, with O(nm)O(n m) extra space for WW. Exhaustive ML costs MnM^n metrics of O(nm)O(n m) each per vector.

Properties

  • No interference. WH=IW H = I, so each output depends on its own symbol and on noise only.
  • Noise enhancement. Stream kk gets the noise variance N0[(HHH)−1]kk≥N0/∥hk∥2N_0 [(H^H H)^{-1}]_{kk} \ge N_0 / \|h_k\|^2, with equality when hkh_k is orthogonal to the other columns. The right side is the noise of a receiver that sees stream kk alone, the maximal ratio combining bound.
  • Diversity. In i.i.d. Rayleigh fading each stream has diversity order m−n+1m - n + 1 (theorem). With m=nm = n this is 1, the diversity of a single antenna link, while ML has diversity mm.
  • No noise level needed. The filter uses only HH. This is useful when N0N_0 is unknown, but it is also why ZF loses to MMSE at low SNR.
  • Exact on orthogonal channels. When HHHH^H H is diagonal, the decision is the ML decision.
  • Same decision for every constellation size. The filter does not depend on S\mathcal{S}. Only line L5 does.

Variants and improvements

  • ZF with QR. Compute H=QRH = Q R and solve Rz=QHyR z = Q^H y by back substitution. This avoids forming HHHH^H H, whose condition number is the square of that of HH.
  • ZF with successive cancellation. Detect one stream, subtract it, and solve the smaller problem. With a fixed order this is the ZF decision feedback receiver, the Babai nearest plane rule of lattice theory. With the order chosen by the best post-detection SNR it is V-BLAST.
  • MMSE. Replace HHHH^H H by HHH+(N0/Es)IH^H H + (N_0 / E_s) I; see the MMSE MIMO detector.
  • Lattice reduction. Apply ZF to the channel HTH T for a unimodular TT from the LLL algorithm. With i.i.d. Rayleigh fading this reaches the receive diversity mm; see lattice reduction aided detection.
  • Soft output. For a coded system, compute bit LLRs from zkz_k with the noise variance N0[(HHH)−1]kkN_0 [(H^H H)^{-1}]_{kk}, as for a scalar channel; see soft demapping.

When to use it

Use ZF when mm is much larger than nn, as in massive MIMO uplinks, where HHHH^H H is close to a scaled identity and the noise gain is small, or when the receiver does not know N0N_0. It is also the reference that every other detector on this site must beat. On square channels (m=nm = n) at moderate SNR, the loss is large: use MMSE, V-BLAST or a lattice reduction aided detector instead, and use a sphere search such as Schnorr-Euchner enumeration when the ML decision is needed.

Pitfalls

  • Square channels. With m=nm = n and i.i.d. Rayleigh fading, the diversity is 1. The error rate falls by only a factor of 10 for each 10 dB of SNR.
  • Ill-conditioned channels. A channel with nearly dependent columns, for example from antenna correlation or a line-of-sight path, can give noise gains of 20 dB or more. Check the condition number of HH.
  • Forming HHHH^H H in floating point. This squares the condition number. Use a QR decomposition when HH is ill conditioned.
  • Bias assumptions. ZF is unbiased: E[z∣x]=xE[z \mid x] = x. Do not apply the bias correction of the MMSE detector to it.
  • Wide channels. With n>mn > m, HHHH^H H is singular and ZF is not defined. The streams cannot be separated by any linear filter.
  • Noise variance for soft output. The output noise of stream kk has variance N0[(HHH)−1]kkN_0 [(H^H H)^{-1}]_{kk}, not N0N_0. A demapper that uses N0N_0 gives LLRs that are too large.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

cbb.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the communications pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Complex baseband tools for the communications pages.

Vectors are lists of complex numbers. Matrices are lists of rows. The
functions here are plain building blocks: small linear algebra, convolution,
the DFT as a direct sum, the Gaussian Q function, dB conversion, complex
Gaussian noise and the Wilson score interval. No page algorithm (equalizer,
estimator, synchronizer, detector, precoder, demapper or power allocation)
lives in this file.

Conventions (prompts of the communications area):
- dft is X[k] = sum_n x[n] e^(-j 2 pi k n / N) with no factor; idft has 1/N.
- udft and uidft are the unitary pair, with 1/sqrt(N) on both sides.
- qfunc(x) = 0.5 erfc(x / sqrt(2)); it never computes 1 - Phi(x).
- cn(rng, var) draws CN(0, var): real and imaginary parts are independent
  with variance var / 2 each, so E|w|^2 = var.
"""

import cmath
import math
import random


# ---------------------------------------------------------------- vectors and matrices


def zeros(rows: int, cols: int | None = None) -> list:
    """A zero vector of length rows, or a rows by cols zero matrix."""
    if cols is None:
        return [0j] * rows
    return [[0j] * cols for _ in range(rows)]


def eye(n: int) -> list[list[complex]]:
    """The n by n identity matrix."""
    return [[1 + 0j if i == k else 0j for k in range(n)] for i in range(n)]


def add(a: list, b: list) -> list:
    """Elementwise a + b for two vectors or two matrices of the same shape."""
    if len(a) != len(b):
        raise ValueError("shapes differ")
    if a and isinstance(a[0], list):
        return [add(r, s) for r, s in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a: list, b: list) -> list:
    """Elementwise a - b for two vectors or two matrices of the same shape."""
    if len(a) != len(b):
        raise ValueError("shapes differ")
    if a and isinstance(a[0], list):
        return [sub(r, s) for r, s in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(c: complex, a: list) -> list:
    """The scalar c times a vector or a matrix."""
    if a and isinstance(a[0], list):
        return [scale(c, r) for r in a]
    return [c * x for x in a]


def matmul(a: list[list[complex]], b: list[list[complex]]) -> list[list[complex]]:
    """The matrix product a b."""
    if not a or not b or len(a[0]) != len(b):
        raise ValueError("inner dimensions differ")
    cols = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in cols] for row in a]


def matvec(a: list[list[complex]], x: list[complex]) -> list[complex]:
    """The matrix times vector product a x."""
    if a and len(a[0]) != len(x):
        raise ValueError("inner dimensions differ")
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def herm(a: list) -> list:
    """The conjugate transpose of a matrix. A vector gives its conjugate."""
    if a and isinstance(a[0], list):
        return [[complex(a[i][k]).conjugate() for i in range(len(a))] for k in range(len(a[0]))]
    return [complex(x).conjugate() for x in a]


def dot(x: list[complex], y: list[complex]) -> complex:
    """The inner product x^H y = sum of conj(x_i) y_i."""
    if len(x) != len(y):
        raise ValueError("lengths differ")
    return sum(complex(p).conjugate() * q for p, q in zip(x, y))


def norm2(x: list) -> float:
    """The squared Euclidean norm sum |x_i|^2 (squared Frobenius norm for a matrix)."""
    if x and isinstance(x[0], list):
        return sum(norm2(r) for r in x)
    return sum(abs(v) ** 2 for v in x)


# ---------------------------------------------------------------- linear systems


def _lu(a: list[list[complex]]) -> tuple[list[list[complex]], list[int], int]:
    """LU factorization with partial pivoting. Returns (lu, perm, sign)."""
    n = len(a)
    if any(len(r) != n for r in a):
        raise ValueError("matrix is not square")
    m = [[complex(v) for v in r] for r in a]
    perm = list(range(n))
    sign = 1
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(m[i][k]))
        if abs(m[p][k]) == 0.0:
            raise ValueError("matrix is singular")
        if p != k:
            m[k], m[p] = m[p], m[k]
            perm[k], perm[p] = perm[p], perm[k]
            sign = -sign
        for i in range(k + 1, n):
            f = m[i][k] / m[k][k]
            m[i][k] = f
            if f != 0:
                rk, ri = m[k], m[i]
                for c in range(k + 1, n):
                    ri[c] -= f * rk[c]
    return m, perm, sign


def _lu_solve(lu: list[list[complex]], perm: list[int], b: list[complex]) -> list[complex]:
    n = len(lu)
    y = [complex(b[perm[i]]) for i in range(n)]
    for i in range(n):
        for c in range(i):
            y[i] -= lu[i][c] * y[c]
    for i in range(n - 1, -1, -1):
        for c in range(i + 1, n):
            y[i] -= lu[i][c] * y[c]
        y[i] /= lu[i][i]
    return y


def solve(a: list[list[complex]], b: list) -> list:
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector, or a matrix whose columns are right-hand sides.
    Raises ValueError if a is singular.
    """
    lu, perm, _ = _lu(a)
    if b and isinstance(b[0], list):
        cols = [list(c) for c in zip(*b)]
        xs = [_lu_solve(lu, perm, c) for c in cols]
        return [list(r) for r in zip(*xs)]
    if len(b) != len(a):
        raise ValueError("lengths differ")
    return _lu_solve(lu, perm, b)


def inv(a: list[list[complex]]) -> list[list[complex]]:
    """The inverse of a square matrix."""
    return solve(a, eye(len(a)))


def det(a: list[list[complex]]) -> complex:
    """The determinant of a square matrix (0 for a singular matrix)."""
    try:
        lu, _, sign = _lu(a)
    except ValueError as e:
        if "singular" in str(e):
            return 0j
        raise
    d = complex(sign)
    for i in range(len(lu)):
        d *= lu[i][i]
    return d


def cholesky(a: list[list[complex]]) -> list[list[complex]]:
    """The lower triangular L with a = L L^H, for a Hermitian positive definite a.

    Raises ValueError if a is not positive definite (to rounding).
    """
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for k in range(i + 1):
            s = complex(a[i][k]) - sum(low[i][c] * low[k][c].conjugate() for c in range(k))
            if i == k:
                if s.real <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = complex(math.sqrt(s.real))
            else:
                low[i][k] = s / low[k][k].real
    return low


# ---------------------------------------------------------------- convolution and the DFT


def conv(a: list[complex], b: list[complex]) -> list[complex]:
    """Linear convolution, of length len(a) + len(b) - 1."""
    if not a or not b:
        return []
    out = [0j] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for k, y in enumerate(b):
            out[i + k] += x * y
    return out


def cconv(a: list[complex], b: list[complex], n: int | None = None) -> list[complex]:
    """Circular convolution of length n (default: the longer length).

    Both inputs are padded with zeros to length n, or must not be longer than n.
    """
    if n is None:
        n = max(len(a), len(b))
    if len(a) > n or len(b) > n:
        raise ValueError("input longer than n")
    out = [0j] * n
    for i, x in enumerate(a):
        for k, y in enumerate(b):
            out[(i + k) % n] += x * y
    return out


def _twiddles(n: int, sign: int) -> list[complex]:
    return [cmath.exp(sign * 2j * math.pi * t / n) for t in range(n)]


def dft(x: list[complex]) -> list[complex]:
    """X[k] = sum over n of x[n] e^(-j 2 pi k n / N), as a direct O(N^2) sum."""
    n = len(x)
    w = _twiddles(n, -1)
    return [sum(x[t] * w[(k * t) % n] for t in range(n)) for k in range(n)]


def idft(xf: list[complex]) -> list[complex]:
    """x[n] = (1/N) sum over k of X[k] e^(j 2 pi k n / N), the inverse of dft."""
    n = len(xf)
    w = _twiddles(n, 1)
    return [sum(xf[k] * w[(k * t) % n] for k in range(n)) / n for t in range(n)]


def udft(x: list[complex]) -> list[complex]:
    """The unitary DFT: dft(x) / sqrt(N)."""
    s = 1.0 / math.sqrt(len(x)) if x else 1.0
    return [v * s for v in dft(x)]


def uidft(xf: list[complex]) -> list[complex]:
    """The unitary inverse DFT: sqrt(N) idft(X), the inverse of udft."""
    s = math.sqrt(len(xf)) if xf else 1.0
    return [v * s for v in idft(xf)]


# ---------------------------------------------------------------- Q function and dB


def qfunc(x: float) -> float:
    """Q(x) = P(Z > x) for a standard normal Z, computed as 0.5 erfc(x / sqrt(2))."""
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def qinv(p: float) -> float:
    """The x with Q(x) = p, for 0 < p < 1, by bisection on Q (which decreases)."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    lo, hi = -40.0, 40.0
    for _ in range(200):
        mid = 0.5 * (lo + hi)
        if qfunc(mid) > p:
            lo = mid
        else:
            hi = mid
        if hi - lo <= 1e-15 * max(1.0, abs(mid)):
            break
    return 0.5 * (lo + hi)


def db(x: float) -> float:
    """10 log10(x), for a ratio of powers or energies."""
    return 10.0 * math.log10(x)


def undb(d: float) -> float:
    """10^(d / 10), the inverse of db."""
    return 10.0 ** (d / 10.0)


# ---------------------------------------------------------------- noise and statistics


def cn(rng: random.Random, var: float) -> complex:
    """One sample of CN(0, var): independent real and imaginary parts of variance var / 2."""
    s = math.sqrt(var / 2.0)
    return complex(rng.gauss(0.0, s), rng.gauss(0.0, s))


def awgn(rng: random.Random, x: list[complex], n0: float) -> list[complex]:
    """x plus independent CN(0, n0) noise on each sample."""
    return [v + cn(rng, n0) for v in x]


def wilson(k: int, n: int, z: float = 3.29) -> tuple[float, float]:
    """The Wilson score interval for k successes in n trials (z = 3.29 is about 0.999 two-sided)."""
    if n <= 0 or not 0 <= k <= n:
        raise ValueError("need 0 <= k <= n and n > 0")
    p = k / n
    z2 = z * z
    den = 1.0 + z2 / n
    mid = (p + z2 / (2 * n)) / den
    half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / den
    return max(0.0, mid - half), min(1.0, mid + half)
constel.py 117 lines
# SPDX-License-Identifier: MIT
# Shared helper of the communications pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Constellations, Gray labels and brute-force maximum likelihood detection.

Each constellation function returns a list of M complex points with unit
average energy, ordered by label: points[i] is the point whose bit label is
the integer i, and bits(i, log2 M) gives that label, most significant bit
first. The labels follow the communications area rules:

- M-PAM: the point with amplitude index m = 0, ..., M-1 (raw amplitude
  M - 1 - 2m, from the most positive) gets the Gray label gray(m).
  So 2-PAM maps bit 0 to +1 and bit 1 to -1.
- Square M-QAM, M = 4^k: the label is the in-phase PAM label followed by the
  quadrature PAM label, each of log2(sqrt(M)) bits.
- M-PSK: the point e^(j(2 pi m / M + phase0)) gets the label gray(m).

PAM points are returned as complex numbers with zero imaginary part.
This file imports nothing from cbb.py. It holds no demapper: soft and
max-log demapping are algorithm pages of their own.
"""

import cmath
import itertools
import math


def gray(n: int) -> int:
    """The binary reflected Gray code of n: n XOR (n >> 1)."""
    return n ^ (n >> 1)


def _gray_inv(g: int) -> int:
    n = 0
    while g:
        n ^= g
        g >>= 1
    return n


def bits(i: int, m: int) -> list[int]:
    """The m bits of the integer i, most significant bit first."""
    if i < 0 or i >= 1 << m:
        raise ValueError("i does not fit in m bits")
    return [(i >> (m - 1 - t)) & 1 for t in range(m)]


def _log2(m: int) -> int:
    if m < 2 or m & (m - 1):
        raise ValueError("M must be a power of two, at least 2")
    return m.bit_length() - 1


def pam(m: int) -> list[complex]:
    """Unit-energy M-PAM, ordered by Gray label."""
    _log2(m)
    s = math.sqrt((m * m - 1) / 3.0)
    return [complex((m - 1 - 2 * _gray_inv(lab)) / s, 0.0) for lab in range(m)]


def qam(m: int) -> list[complex]:
    """Unit-energy square M-QAM (M = 4, 16, 64, ...), ordered by label (in-phase bits first)."""
    k = _log2(m)
    if k % 2:
        raise ValueError("square QAM needs M = 4^k")
    side = 1 << (k // 2)
    s = math.sqrt(2.0 * (m - 1) / 3.0)
    raw = [side - 1 - 2 * _gray_inv(lab) for lab in range(side)]
    return [complex(raw[lab // side], raw[lab % side]) / s for lab in range(m)]


def psk(m: int, phase0: float = 0.0) -> list[complex]:
    """Unit-energy M-PSK with first point at angle phase0, ordered by Gray label."""
    _log2(m)
    return [cmath.exp(1j * (2.0 * math.pi * _gray_inv(lab) / m + phase0)) for lab in range(m)]


def energy(points: list[complex]) -> float:
    """The average energy (1/M) sum |p|^2 of equally likely points."""
    return sum(abs(p) ** 2 for p in points) / len(points)


def ml_detect(y: complex, points: list[complex], h: complex = 1) -> int:
    """The index of the point p that minimizes |y - h p|^2, by brute force (lowest index on a tie)."""
    best, arg = math.inf, -1
    for i, p in enumerate(points):
        d = abs(y - h * p) ** 2
        if d < best:
            best, arg = d, i
    return arg


def ml_vector(y: list[complex], h: list[list[complex]], points: list[complex]) -> list[int]:
    """The index vector that minimizes ||y - H x||^2 over all M^n vectors x, by brute force.

    h is the m by n channel matrix as a list of rows; the result has n indices.
    The first minimizer in lexicographic order of the indices wins a tie.
    """
    n = len(h[0])
    best, arg = math.inf, None
    for idx in itertools.product(range(len(points)), repeat=n):
        x = [points[i] for i in idx]
        d = 0.0
        for yi, row in zip(y, h):
            d += abs(yi - sum(a * b for a, b in zip(row, x))) ** 2
        if d < best:
            best, arg = d, idx
    return list(arg)


def bit_errors(a, b) -> int:
    """The number of differing bits between two integer labels, or summed over two equal-length lists."""
    if isinstance(a, int) and isinstance(b, int):
        return bin(a ^ b).count("1")
    if len(a) != len(b):
        raise ValueError("lengths differ")
    return sum(bit_errors(x, y) for x, y in zip(a, b))
zero_forcing_mimo_detector.py 63 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zero-forcing-mimo-detector/. The authors are listed in prov/Q1ZTZN.jsonl.

"""The zero-forcing (ZF) MIMO detector.

The model is y = H x + w, with H an m by n complex matrix of full column rank
(so m >= n), x a vector of n constellation points and w ~ CN(0, N0 I).
The detector applies the pseudoinverse W = (H^H H)^(-1) H^H, so that
W y = x + W w, and then slices each entry to the nearest constellation point.
Stream k sees noise of variance N0 [(H^H H)^(-1)]_kk, so its post-detection
SNR is (Es / N0) / [(H^H H)^(-1)]_kk.
"""

import cbb


def nearest(z: complex, points: list[complex]) -> int:
    """The index of the point nearest to z (the lowest index on a tie)."""
    best, arg = float("inf"), -1
    for i, p in enumerate(points):
        d = abs(z - p) ** 2
        if d < best:
            best, arg = d, i
    return arg


def zf_matrix(h: list[list[complex]]) -> list[list[complex]]:
    """The n by m pseudoinverse (H^H H)^(-1) H^H. Raises ValueError if H has dependent columns."""
    if len(h) < len(h[0]):
        raise ValueError("ZF needs at least as many receive antennas as streams")
    hh = cbb.herm(h)
    g = cbb.matmul(hh, h)  # @line L1
    try:
        return cbb.solve(g, hh)  # @line L2
    except ValueError:
        raise ValueError("H^H H is singular: the columns of H are dependent") from None


def zf_outputs(y: list[complex], h: list[list[complex]]) -> list[complex]:
    """The unquantized ZF outputs z = W y = x + W w."""
    return cbb.matvec(zf_matrix(h), y)


def zf_detect(y: list[complex], h: list[list[complex]], points: list[complex]) -> list[int]:
    """The ZF decisions: the index of the nearest point to each entry of W y."""
    w = zf_matrix(h)
    z = cbb.matvec(w, y)  # @line L3
    out = []
    for k in range(len(z)):  # @line L4
        out.append(nearest(z[k], points))  # @line L5
    return out  # @line L6


def noise_gains(h: list[list[complex]]) -> list[float]:
    """The diagonal of (H^H H)^(-1): stream k has output noise variance N0 times this value."""
    hh = cbb.herm(h)
    p = cbb.inv(cbb.matmul(hh, h))
    return [p[k][k].real for k in range(len(p))]


def post_detection_snr(h: list[list[complex]], es: float, n0: float) -> list[float]:
    """The SNR of each stream after ZF: (Es / N0) / [(H^H H)^(-1)]_kk."""
    return [es / (n0 * g) for g in noise_gains(h)]
test_zero_forcing_mimo_detector.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zero-forcing-mimo-detector/. The authors are listed in prov/Q1ZTZN.jsonl.

import math
import random

import pytest

import cbb
import constel
from zero_forcing_mimo_detector import (
    nearest,
    noise_gains,
    post_detection_snr,
    zf_detect,
    zf_matrix,
    zf_outputs,
)


def rayleigh(rng, m, n):
    return [[cbb.cn(rng, 1.0) for _ in range(n)] for _ in range(m)]


def test_example_on_the_page() -> None:
    h = [[2, 1], [1, 1]]
    y = [0.5, 0.6]
    bpsk = constel.pam(2)  # index 0 is +1, index 1 is -1
    z = zf_outputs(y, h)
    assert abs(z[0] - (-0.1)) < 1e-12 and abs(z[1] - 0.7) < 1e-12
    assert zf_detect(y, h, bpsk) == [1, 0]  # (-1, +1): both decisions wrong
    assert constel.ml_vector(y, h, bpsk) == [0, 1]  # ML finds the sent (+1, -1)
    g = noise_gains(h)
    assert abs(g[0] - 2) < 1e-12 and abs(g[1] - 5) < 1e-12
    snr = post_detection_snr(h, 1.0, 1.0)
    assert abs(cbb.db(1 / snr[0]) - 3.0103) < 1e-4 and abs(cbb.db(1 / snr[1]) - 6.9897) < 1e-4


def test_w_is_a_left_inverse_and_its_row_norms_are_the_noise_gains() -> None:
    rng = random.Random(1201)
    for _ in range(50):
        n = rng.randint(1, 4)
        m = rng.randint(n, 6)
        h = rayleigh(rng, m, n)
        w = zf_matrix(h)
        wh = cbb.matmul(w, h)
        for i in range(n):
            for k in range(n):
                assert abs(wh[i][k] - (1 if i == k else 0)) < 1e-9
        for k, g in enumerate(noise_gains(h)):
            assert abs(cbb.norm2(w[k]) - g) < 1e-9 * g


def test_noiseless_recovery_is_exact() -> None:
    rng = random.Random(1202)
    pts = constel.qam(16)
    for _ in range(100):
        n = rng.randint(1, 4)
        m = rng.randint(n, 6)
        h = rayleigh(rng, m, n)
        idx = [rng.randrange(16) for _ in range(n)]
        y = cbb.matvec(h, [pts[i] for i in idx])
        assert zf_detect(y, h, pts) == idx


def test_zf_is_ml_when_the_columns_are_orthogonal() -> None:
    # theorem 3: H^H H diagonal makes the ML metric separate per stream
    rng = random.Random(1206)
    pts = constel.qam(4)
    for _ in range(60):
        a, b = cbb.cn(rng, 1.0), cbb.cn(rng, 1.0)
        c = rng.uniform(0.3, 2.0)
        # columns (a, b, 0) and c (-conj(b), conj(a), 0) are orthogonal; the third column is e3
        h = [[a, -c * b.conjugate(), 0], [b, c * a.conjugate(), 0], [0, 0, rng.uniform(0.2, 1.5)]]
        idx = [rng.randrange(4) for _ in range(3)]
        y = cbb.awgn(rng, cbb.matvec(h, [pts[i] for i in idx]), 0.5)
        assert zf_detect(y, h, pts) == constel.ml_vector(y, h, pts)


def test_square_channel_uses_the_inverse() -> None:
    h = [[1, 2j], [0.5, -1 + 1j]]
    w, hinv = zf_matrix(h), cbb.inv(h)
    assert all(abs(w[i][k] - hinv[i][k]) < 1e-12 for i in range(2) for k in range(2))


def test_dependent_columns_and_wide_channels_are_rejected() -> None:
    with pytest.raises(ValueError):
        zf_matrix([[1, 2], [2, 4]])
    with pytest.raises(ValueError):
        zf_matrix([[1, 2, 3], [4, 5, 6]])


def test_nearest_breaks_ties_to_the_lowest_index() -> None:
    assert nearest(0j, constel.pam(2)) == 0
    assert nearest(0.2 - 0.9j, constel.qam(4)) == 1


def test_post_detection_snr_is_chi_square_with_2_times_m_minus_n_plus_1_degrees() -> None:
    # theorem: for i.i.d. CN(0, 1) entries, 1 / [(H^H H)^-1]_kk is Gamma(m - n + 1, 1),
    # so its mean and its variance are both m - n + 1
    rng = random.Random(1203)
    for m, n in ((2, 2), (3, 2), (4, 2)):
        d = m - n + 1
        trials = 1500
        vals = [1.0 / noise_gains(rayleigh(rng, m, n))[0] for _ in range(trials)]
        mean = sum(vals) / trials
        assert abs(mean - d) < 4.0 * math.sqrt(d / trials)


def mrc_bpsk_ber(snr: float, branches: int) -> float:
    # closed form: E[Q(sqrt(2 g))] for g ~ Gamma(branches, snr)
    mu = math.sqrt(snr / (1 + snr))
    a, b = (1 - mu) / 2, (1 + mu) / 2
    return a**branches * sum(math.comb(branches - 1 + k, k) * b**k for k in range(branches))


def test_bpsk_error_rate_matches_the_diversity_closed_form() -> None:
    # each ZF stream is BPSK on a channel with m - n + 1 Rayleigh branches
    rng = random.Random(1204)
    bpsk = constel.pam(2)
    for m, n, snr_db in ((2, 2, 10.0), (3, 2, 4.0)):
        snr = cbb.undb(snr_db)
        p = mrc_bpsk_ber(snr, m - n + 1)
        trials = math.ceil(150 / (p * n))
        errors = 0
        for _ in range(trials):
            h = rayleigh(rng, m, n)
            idx = [rng.randrange(2) for _ in range(n)]
            y = cbb.awgn(rng, cbb.matvec(h, [bpsk[i] for i in idx]), 1.0 / snr)
            errors += sum(a != b for a, b in zip(zf_detect(y, h, bpsk), idx))
        lo, hi = cbb.wilson(errors, trials * n)
        assert lo <= p <= hi


def test_most_decisions_match_ml_at_high_snr() -> None:
    # measured: 4-QAM, m = 4, n = 3, Es/N0 = 20 dB, seed 1205: at least 190 of 200 vectors agree with ML
    rng = random.Random(1205)
    pts = constel.qam(4)
    n0 = 1 / cbb.undb(20.0)
    agree = 0
    for _ in range(200):
        h = rayleigh(rng, 4, 3)
        idx = [rng.randrange(4) for _ in range(3)]
        y = cbb.awgn(rng, cbb.matvec(h, [pts[i] for i in idx]), n0)
        agree += zf_detect(y, h, pts) == constel.ml_vector(y, h, pts)
    assert agree >= 190

History

Linear receivers that null interfering signals with an antenna array were studied for adaptive arrays long before MIMO. The same inverse was the decorrelating detector for synchronous CDMA in the late 1980s. When Foschini and his colleagues at Bell Labs built the first spatial multiplexing systems, the V-BLAST receiver of Wolniansky, Foschini, Golden and Valenzuela in 1998 used the rows of the pseudoinverse as nulling vectors, and ZF became the reference linear MIMO detector. The diversity result m−n+1m - n + 1 for i.i.d. Rayleigh fading is part of the standard analysis of linear MIMO receivers, as in Tse and Viswanath (2005).

References

  1. David Tse and Pramod Viswanath, Fundamentals of Wireless Communication, Cambridge University Press, 2005, Section 8.3.1, Linear decorrelator (the ZF receiver, the projection onto the orthogonal complement of the other columns and the diversity nr - nt + 1 in i.i.d. Rayleigh fading)
  2. Arogyaswami Paulraj, Rohit Nabar and Dhananjay Gore, Introduction to Space-Time Wireless Communications, Cambridge University Press, 2003, Chapter 7, Space-time receivers (the ZF receiver for spatial multiplexing and its comparison with ML and MMSE)
  3. Erik G. Larsson, MIMO detection methods - how they work, IEEE Signal Processing Magazine 26(3), 91-95, 2009, the section on linear receivers (ZF as the least squares solution followed by a per-stream decision)
  4. Peter W. Wolniansky, Gerard J. Foschini, Glen D. Golden and Reinaldo A. Valenzuela, V-BLAST - an architecture for realizing very high data rates over the rich-scattering wireless channel, Proc. URSI International Symposium on Signals, Systems and Electronics, Pisa, 1998, pages 295-300, the nulling vectors (the rows of the pseudoinverse) that the V-BLAST receiver uses at each step

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of time_per_vector_after_setup.worst
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example