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.
- Solves
- MIMO detection
- 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
- Model
- Real RAM
- Properties
- deterministicnot exact mlexact ml if columns orthogonallinearnot needs noise level
- Evidence
- Proof sketchCode in 1 languages
- 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 symbol vectors. The price is noise enhancement: stream gets noise of variance , which is large when the columns of are nearly dependent. In i.i.d. Rayleigh fading this cuts the diversity order from for ML to . 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 . Here is the known channel matrix, with receive antennas (rows) and transmitted streams (columns), holds one point of a unit-energy constellation of size per stream, and . The SNR is per complex symbol, with . The detector needs and of full column rank, so that is invertible. The output is a decision . ZF does not have to be the ML decision, and in general it is not.
The algorithm
ZF-DETECT(y, H, S)- 1
G ← Hᴴ H ▷ n × n Gram matrix - 2
W ← G⁻¹ Hᴴ ▷ the pseudoinverse H⁺ - 3
z ← W y ▷ z = x + W w - 4
for k ← 1 to n - 5
x̂_k ← the point of S nearest to z_k - 6
return x̂
Lines L1 and L2 depend only on the channel, so a receiver computes once per channel use of a block fading channel and then reuses it for every received vector of the block. Line L2 solves by Gaussian elimination or a Cholesky decomposition, or it uses the QR decomposition , where is better conditioned because it does not square the condition number of . Line L3 is the unconstrained least squares solution: it minimizes over all , not only over . 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 , BPSK with , and the real channel
The transmitter sends , so . The noise is , with , and the receiver gets . Because is square, line L2 gives , and line L3 gives
Line L5 decides . Both decisions are wrong. The ML detector compares the four candidates:
| candidate | ||
|---|---|---|
| 8.21 | ||
| 0.61 | ||
| 2.61 | ||
| 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 have the squared norms 2 and 5, so the two streams see noise of variance and , losses of 3.0 dB and 7.0 dB. The noise is much larger than , and it moves both outputs across the decision boundary at 0. Without noise, line L3 gives exactly.
Correctness
The proof is in proofs/correctness.md. It shows four things. First, , so with no interference from the other streams, and without noise ZF recovers exactly (a theorem). Second, the noise is , so stream has the post-detection SNR (a closed form). Third, if the columns of are orthogonal, the ML metric separates into one term per stream, and ZF is exactly ML (a theorem). Fourth, is the squared distance from column to the span of the other columns. In i.i.d. fading this is a sum of independent unit exponentials, so the error probability of each stream decays as (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 with of full column rank, and . Let and , as in lines L1 and L2. Let be column of .
Lemma 1 ( is invertible). If has full column rank, is Hermitian positive definite.
Proof. . For , , because when the columns are independent. A positive definite matrix has only positive eigenvalues, so it is invertible.
Theorem 1 (no interference, exact without noise). , so . If , lines L4 and L5 return .
Proof. , so . If , then , which is a point of , and the point of nearest to is itself at distance 0.
Lemma 2 (least squares). is the unique minimizer of over .
Proof. For any , write . Then , and . So the cross term vanishes and . The second term is positive for by full column rank.
Theorem 2 (noise covariance and post-detection SNR). The noise at the output is . So with , and the SNR of stream after ZF is . Also , the squared norm of row of .
Proof. A linear map of a circularly symmetric Gaussian vector is circularly symmetric Gaussian, with covariance , because is Hermitian. The diagonal entry of is the squared norm of row .
Theorem 3 (ML on orthogonal channels). If is diagonal, the decision of lines L4 and L5 is an ML decision.
Proof. By the proof of Lemma 2, for every . If , then . The first term does not depend on , and each . So the minimum over is reached by minimizing each over on its own, which is what line L5 does.
The orthogonality is needed. When is not diagonal, the cross terms 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 be the orthogonal projection onto the orthogonal complement of the span of the columns , . Then .
Proof. Order the columns so that is the last one and write . The block inverse formula, with the Schur complement of the block , gives
The matrix is the projection , which is Hermitian and idempotent, so .
Theorem 4 (diversity ; Tse and Viswanath, Section 8.3.1). Let the entries of be i.i.d. , with . Then has the Gamma distribution with shape and scale 1, the distribution of a sum of independent unit exponentials. With BPSK, the error probability of stream is
which decays as . So the diversity order is .
Proof. The columns , , are independent of . Condition on them. With probability 1 they span a subspace of dimension , so projects onto a fixed subspace of dimension . Pick an orthonormal basis of that subspace. Since is unitarily invariant, the coordinates are i.i.d. , and is a sum of independent unit exponentials. This law does not depend on the conditioning, so it holds unconditionally. By Lemma 3 and Theorem 2, stream is BPSK in Gaussian noise with the SNR , so its error probability is with a Gamma variable of shape and mean . This is the same average as for maximal ratio combining over independent Rayleigh branches, which gives the closed form above and its high SNR limit.
So ZF with has diversity 1. The tests check Theorem 1 on random channels with 16-QAM, Theorem 2 by and the row norms, Theorem 3 on channels with orthogonal columns, and Theorem 4 by the mean of and by a BPSK error count against the closed form with a Wilson interval.
Complexity
Line L1 costs complex multiplications, or half of that with the symmetry of . Line L2 costs . Line L3 costs multiplications per received vector, and line L5 costs per stream by a linear scan, or per stream for square QAM by rounding. So a block of vectors on one channel costs in the real RAM, with extra space for . Exhaustive ML costs metrics of each per vector.
Properties
- No interference. , so each output depends on its own symbol and on noise only.
- Noise enhancement. Stream gets the noise variance , with equality when is orthogonal to the other columns. The right side is the noise of a receiver that sees stream alone, the maximal ratio combining bound.
- Diversity. In i.i.d. Rayleigh fading each stream has diversity order (theorem). With this is 1, the diversity of a single antenna link, while ML has diversity .
- No noise level needed. The filter uses only . This is useful when is unknown, but it is also why ZF loses to MMSE at low SNR.
- Exact on orthogonal channels. When is diagonal, the decision is the ML decision.
- Same decision for every constellation size. The filter does not depend on . Only line L5 does.
Variants and improvements
- ZF with QR. Compute and solve by back substitution. This avoids forming , whose condition number is the square of that of .
- 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 by ; see the MMSE MIMO detector.
- Lattice reduction. Apply ZF to the channel for a unimodular from the LLL algorithm. With i.i.d. Rayleigh fading this reaches the receive diversity ; see lattice reduction aided detection.
- Soft output. For a coded system, compute bit LLRs from with the noise variance , as for a scalar channel; see soft demapping.
When to use it
Use ZF when is much larger than , as in massive MIMO uplinks, where is close to a scaled identity and the noise gain is small, or when the receiver does not know . It is also the reference that every other detector on this site must beat. On square channels () 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 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 .
- Forming in floating point. This squares the condition number. Use a QR decomposition when is ill conditioned.
- Bias assumptions. ZF is unbiased: . Do not apply the bias correction of the MMSE detector to it.
- Wide channels. With , 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 has variance , not . A demapper that uses 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.
# 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 for i.i.d. Rayleigh fading is part of the standard analysis of linear MIMO receivers, as in Tse and Viswanath (2005).
References
- 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)
- 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)
- 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)
- 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.
| 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 Q1ZTZN Edit this page History Report an error Markdown