Algorithm Search⌘K

Algorithmcore

MMSE MIMO detector

Also called LMMSE detector, linear MMSE MIMO receiver.

Applies the linear filter (H^H H + (N0/Es) I)^-1 H^H, which minimizes the mean squared error of the symbol estimates, then removes its bias and slices each stream to the nearest symbol.

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 mllinearmaximizes sinr among linear filtersneeds noise levelworks when n exceeds m
Origin
Jack H. Winters, 1984

The minimum mean square error (MMSE) MIMO detector is a linear receiver for spatial multiplexing that takes the noise level into account. It applies the filter W=(HHH+(N0/Es)I)−1HHW = (H^H H + (N_0/E_s) I)^{-1} H^H, which minimizes E∥Wy−x∥2E\|W y - x\|^2 over all linear filters, divides each output by its gain βk\beta_k to remove a bias, and slices each stream to the nearest constellation point. It differs from the zero-forcing MIMO detector only by the term (N0/Es)I(N_0/E_s) I: ZF removes all the interference and lets the noise grow, while MMSE leaves a little interference and much less noise. Among all linear filters, the MMSE filter gives each stream the largest SINR. As N0→0N_0 \to 0 it becomes ZF, and at low SNR it becomes the matched filter HHH^H up to a scale. It is the Wiener filter for the vector xx. The same filter appears as the MMSE linear equalizer in time, as the MMSE multiuser detector in CDMA, and as regularized ZF precoding at a transmitter. V-BLAST with MMSE nulling and the expectation propagation detector both start from this filter.

In plain words

Several transmit antennas send different symbols at once, and each receive antenna hears a mix of them plus noise. A zero-forcing receiver undoes the mix exactly, but when the mix is hard to undo, it also makes the noise huge. The MMSE receiver asks a different question: which linear combination of the received signals is, on average, closest to the sent symbols? The answer undoes most of the mix but not all of it. Where undoing the mix would amplify the noise a lot, it holds back. When the noise is small, it acts like zero forcing. When the noise is large, it simply listens for each symbol in the direction where that symbol arrives strongest.

The problem

The model is y=Hx+wy = H x + w, with H∈Cm×nH \in \mathbb{C}^{m \times n} known, x∈Snx \in \mathcal{S}^n for a constellation S\mathcal{S} of size MM with average energy EsE_s, and w∼CN(0,N0I)w \sim \mathcal{CN}(0, N_0 I). The SNR is Es/N0E_s / N_0 per complex symbol. The detector models the entries of xx as independent with mean 0 and variance EsE_s. It needs N0N_0, but unlike ZF it does not need m≥nm \ge n or full column rank when N0>0N_0 > 0. The output is a decision x^∈Sn\hat x \in \mathcal{S}^n.

The algorithm

  1. MMSE-DETECT(y, H, S, N0, Es)
  2. 1P ← (Hᴴ H + (N0/Es) I)⁻¹ ▷ N0 P is the error covariance
  3. 2W ← P Hᴴ
  4. 3z ← W y
  5. 4for k ← 1 to n
  6. 5β_k ← 1 - (N0/Es) P_kk ▷ β_k = (W H)_kk, the bias
  7. 6x̂_k ← the point of S nearest to z_k / β_k
  8. 7return x̂

Lines L1 and L2 depend only on the channel and on N0N_0, so a receiver computes them once per block. Line L1 is a Cholesky factorization of a positive definite matrix when N0>0N_0 > 0. With the push-through identity, W=HH(HHH+(N0/Es)I)−1W = H^H (H H^H + (N_0/E_s) I)^{-1}, which is cheaper when m<nm < n. Line L5 computes the gain of stream kk in its own output: E[zk∣xk]=βkxkE[z_k \mid x_k] = \beta_k x_k with 0<βk<10 < \beta_k < 1. For PSK and 4-QAM the division in line L6 does not change the decision, because the decision regions are cones. For 16-QAM and larger it does: without it, the outer points are pulled toward the origin and land in the wrong ring.

Example

Take the channel and the received vector of the ZF example: BPSK, H=(2111)H = \begin{pmatrix} 2 & 1 \\ 1 & 1 \end{pmatrix}, x=(+1,−1)x = (+1, -1), w=(−0.5,0.6)w = (-0.5, 0.6) and y=(0.5,0.6)y = (0.5, 0.6). Let N0=0.5N_0 = 0.5, so Es/N0=2E_s / N_0 = 2 (3.0 dB). Then HHH+0.5I=(5.5332.5)H^H H + 0.5 I = \begin{pmatrix} 5.5 & 3 \\ 3 & 2.5 \end{pmatrix} has determinant 4.75, and

P=14.75(2.5−3−35.5),W=PHH=14.75(2−0.5−0.52.5).P = \frac{1}{4.75}\begin{pmatrix} 2.5 & -3 \\ -3 & 5.5 \end{pmatrix}, \qquad W = P H^H = \frac{1}{4.75}\begin{pmatrix} 2 & -0.5 \\ -0.5 & 2.5 \end{pmatrix}.
quantity stream 1 stream 2
z=Wyz = W y 0.7 / 4.75 = 0.147 1.25 / 4.75 = 0.263
βk=1−0.5 Pkk\beta_k = 1 - 0.5\, P_{kk} 3.5 / 4.75 = 0.737 2 / 4.75 = 0.421
zk/βkz_k / \beta_k 0.200 0.625
decision +1 (right) +1 (wrong)
SINR =1/(0.5 Pkk)−1= 1/(0.5\, P_{kk}) - 1 2.8 (4.5 dB) 0.727 (-1.4 dB)
ZF SNR =2/[(HHH)−1]kk= 2 / [(H^H H)^{-1}]_{kk} 1 (0.0 dB) 0.4 (-4.0 dB)

ZF decided (−1,+1)(-1, +1) on this vector, with two errors. MMSE gets the first stream right and still misses the second, while the ML detector finds (+1,−1)(+1, -1). The last two rows show why: at the same SNR, MMSE gives the two streams 4.5 dB and 2.6 dB more SINR than ZF on this channel.

Correctness

The proof is in proofs/correctness.md. It shows that WW minimizes E∥Wy−x∥2E\|W y - x\|^2 over all n×mn \times m matrices, by the orthogonality principle, and that the minimum error covariance is N0PN_0 P (a theorem). It shows that row kk of WW is proportional to hkHRk−1h_k^H R_k^{-1}, where RkR_k is the covariance of the interference and the noise seen by stream kk, so that this row maximizes the output SINR over all linear filters, and that this SINR is 1/((N0/Es)Pkk)−11/((N_0/E_s) P_{kk}) - 1 (a theorem). The same computation gives the bias βk=1−(N0/Es)Pkk\beta_k = 1 - (N_0/E_s) P_{kk}. Without noise and with full column rank, W→(HHH)−1HHW \to (H^H H)^{-1} H^H as N0→0N_0 \to 0, so the decisions become the ZF decisions, which are exact.

Proof: The MMSE filter minimizes the mean squared error, maximizes the SINR of each stream among linear filters, and has the bias 1 - (N0/Es) P_kkfull

The model is y=Hx+wy = H x + w with H∈Cm×nH \in \mathbb{C}^{m \times n}, w∼CN(0,N0Im)w \sim \mathcal{CN}(0, N_0 I_m) independent of xx, and E[x]=0E[x] = 0, E[xxH]=EsInE[x x^H] = E_s I_n. Let a=N0/Es>0a = N_0 / E_s > 0, G=HHH+aInG = H^H H + a I_n, P=G−1P = G^{-1} and W=PHHW = P H^H, as in lines L1 and L2. Let hkh_k be column kk of HH. GG is Hermitian positive definite, because uHGu=∥Hu∥2+a∥u∥2>0u^H G u = \|H u\|^2 + a \|u\|^2 > 0 for u≠0u \ne 0, so PP exists and is Hermitian positive definite.

Theorem 1 (minimum mean squared error). For every n×mn \times m matrix VV, E∥Vy−x∥2≥E∥Wy−x∥2=N0 tr(P)E\|V y - x\|^2 \ge E\|W y - x\|^2 = N_0\, \mathrm{tr}(P), and the error covariance of WW is E[(Wy−x)(Wy−x)H]=N0PE[(W y - x)(W y - x)^H] = N_0 P.

Proof. The second moments are Ryy=E[yyH]=EsHHH+N0IR_{yy} = E[y y^H] = E_s H H^H + N_0 I and Rxy=E[xyH]=EsHHR_{xy} = E[x y^H] = E_s H^H. The error e=Wy−xe = W y - x is orthogonal to the data: E[e yH]=WRyy−Rxy=Es(PHHHHH+aPHH)−EsHH=EsP(HHH+aI)HH−EsHH=0E[e\, y^H] = W R_{yy} - R_{xy} = E_s (P H^H H H^H + a P H^H) - E_s H^H = E_s P (H^H H + a I) H^H - E_s H^H = 0. For any VV, write Vy−x=e+(V−W)yV y - x = e + (V - W) y. The cross term E[eH(V−W)y]=tr((V−W)E[yeH])=0E[e^H (V - W) y] = \mathrm{tr}((V - W) E[y e^H]) = 0, so E∥Vy−x∥2=E∥e∥2+E∥(V−W)y∥2≥E∥e∥2E\|V y - x\|^2 = E\|e\|^2 + E\|(V - W) y\|^2 \ge E\|e\|^2. For the covariance, E[eeH]=E[e(Wy−x)H]=−E[exH]E[e e^H] = E[e (W y - x)^H] = -E[e x^H] by the orthogonality, and −E[exH]=Rxx−WRyx=EsI−EsPHHH=EsP(G−HHH)=EsaP=N0P-E[e x^H] = R_{xx} - W R_{yx} = E_s I - E_s P H^H H = E_s P (G - H^H H) = E_s a P = N_0 P. □\square

Lemma 2 (push-through). W=HH(HHH+aIm)−1W = H^H (H H^H + a I_m)^{-1}.

Proof. (HHH+aI)HH=HH(HHH+aI)(H^H H + a I) H^H = H^H (H H^H + a I). Multiply on the left by PP and on the right by (HHH+aI)−1(H H^H + a I)^{-1}. □\square

Let R=EsHHH+N0Im=Es(HHH+aI)R = E_s H H^H + N_0 I_m = E_s (H H^H + a I), the covariance of yy, and let Rk=R−EshkhkHR_k = R - E_s h_k h_k^H, the covariance of the interference and the noise seen by stream kk. By Lemma 2, W=EsHHR−1W = E_s H^H R^{-1}, so row kk of WW is wkH=EshkHR−1w_k^H = E_s h_k^H R^{-1}.

Theorem 3 (maximum SINR, bias and SINR formula). Let sk=EshkHRk−1hks_k = E_s h_k^H R_k^{-1} h_k. Then:

  1. Row kk of WW is a positive multiple of hkHRk−1h_k^H R_k^{-1}.
  2. Among all row vectors vH≠0v^H \ne 0, the SINR Es∣vHhk∣2/(vHRkv)E_s |v^H h_k|^2 / (v^H R_k v) of the output vHyv^H y is at most sks_k, with equality for vH∝hkHRk−1v^H \propto h_k^H R_k^{-1}. So row kk of WW maximizes the SINR.
  3. βk=(WH)kk=sk/(1+sk)=1−aPkk\beta_k = (W H)_{kk} = s_k / (1 + s_k) = 1 - a P_{kk}, and so sk=1/(aPkk)−1s_k = 1 / (a P_{kk}) - 1.

Proof. (1) By the Sherman-Morrison formula, R−1hk=Rk−1hk/(1+sk)R^{-1} h_k = R_k^{-1} h_k / (1 + s_k), since R=Rk+EshkhkHR = R_k + E_s h_k h_k^H and RkR_k is positive definite. So wkH=EshkHRk−1/(1+sk)w_k^H = E_s h_k^H R_k^{-1} / (1 + s_k).

(2) Write u=Rk1/2vu = R_k^{1/2} v. By the Cauchy-Schwarz inequality, ∣vHhk∣2=∣uHRk−1/2hk∣2≤∥u∥2 hkHRk−1hk=(vHRkv) sk/Es|v^H h_k|^2 = |u^H R_k^{-1/2} h_k|^2 \le \|u\|^2\, h_k^H R_k^{-1} h_k = (v^H R_k v)\, s_k / E_s, with equality if and only if u∝Rk−1/2hku \propto R_k^{-1/2} h_k, that is, v∝Rk−1hkv \propto R_k^{-1} h_k.

(3) By (1), (WH)kk=wkHhk=EshkHRk−1hk/(1+sk)=sk/(1+sk)(W H)_{kk} = w_k^H h_k = E_s h_k^H R_k^{-1} h_k / (1 + s_k) = s_k / (1 + s_k). On the other side, WH=PHHH=P(G−aI)=I−aPW H = P H^H H = P (G - a I) = I - a P, so (WH)kk=1−aPkk(W H)_{kk} = 1 - a P_{kk}. Solving 1−aPkk=sk/(1+sk)1 - a P_{kk} = s_k / (1 + s_k) gives 1+sk=1/(aPkk)1 + s_k = 1 / (a P_{kk}). □\square

The scale of a filter row does not change its SINR, so dividing by βk\beta_k in line L6 keeps the SINR sks_k and makes the output unbiased: E[zk/βk∣xk]=xkE[z_k / \beta_k \mid x_k] = x_k, because the other streams and the noise have mean zero. For a constellation with more than one amplitude, the decision regions of the nearest point rule are built for the points xkx_k themselves, so the unbiased output is the right input to the slicer. For PSK, the regions are cones from the origin and a positive scale does not change the decision.

Corollary 4 (never worse than ZF in SINR). If HH has full column rank, sk≥(Es/N0)/[(HHH)−1]kks_k \ge (E_s/N_0) / [(H^H H)^{-1}]_{kk}, the ZF post-detection SNR of stream kk.

Proof. Row kk of the ZF filter is a linear filter with no interference and the SNR (Es/N0)/[(HHH)−1]kk(E_s/N_0)/[(H^H H)^{-1}]_{kk}. By Theorem 3(2), no linear filter has a larger SINR than sks_k. □\square

Theorem 5 (ZF limit, exact without noise). If HH has full column rank, W→(HHH)−1HHW \to (H^H H)^{-1} H^H and βk→1\beta_k \to 1 as N0→0N_0 \to 0. With w=0w = 0 and N0N_0 small enough, the decisions of lines L4 to L6 equal xx.

Proof. Matrix inversion is continuous at the invertible matrix HHHH^H H, so P→(HHH)−1P \to (H^H H)^{-1} and W→(HHH)−1HHW \to (H^H H)^{-1} H^H, and aPkk→0a P_{kk} \to 0. With w=0w = 0, z/βk→xkz / \beta_k \to x_k for each kk because (HHH)−1HHHx=x(H^H H)^{-1} H^H H x = x. Each xkx_k is at distance at least dmin⁡/2>0d_{\min} / 2 > 0 from the boundary of its decision region, so for N0N_0 small enough every output lies in the right region. □\square

The tests check Theorem 1 by a simulated MSE with 16-QAM against N0PkkN_0 P_{kk}, Lemma 2 on random channels with n>mn > m and n≤mn \le m, Theorem 3 against the direct SINR formula, Theorem 5 against the ZF filter, and the numbers of the example on the page.

Complexity

Forming HHHH^H H costs n2mn^2 m multiplications, the inverse in line L1 costs O(n3)O(n^3), and line L2 costs n2mn^2 m. Per received vector, line L3 costs nmn m multiplications and lines L4 to L6 cost O(nM)O(n M) by a linear scan, or O(n)O(n) for square QAM by rounding. In the real RAM, 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)), with O(nm)O(n m) extra space. This is the same order as ZF.

Properties

  • Minimum mean square error. Among linear filters, WW gives the smallest E∥Wy−x∥2E\|W y - x\|^2, equal to N0 tr(P)N_0\, \mathrm{tr}(P) (theorem).
  • Maximum SINR. Each row of WW maximizes the SINR of its stream among all linear filters (theorem). After the bias removal, the SINR is 1/((N0/Es)Pkk)−11/((N_0/E_s) P_{kk}) - 1, which is never smaller than the ZF post-detection SNR.
  • Biased output. E[zk∣xk]=βkxkE[z_k \mid x_k] = \beta_k x_k with βk=SINRk/(1+SINRk)\beta_k = \mathrm{SINR}_k / (1 + \mathrm{SINR}_k).
  • Limits. As N0→0N_0 \to 0 with full column rank, MMSE becomes ZF. As N0→∞N_0 \to \infty, WW tends to (Es/N0)HH(E_s/N_0) H^H, the matched filter.
  • Diversity. Tse and Viswanath (Section 8.3.1 and its exercises) give the MMSE receiver the same diversity as ZF, m−n+1m - n + 1 in i.i.d. Rayleigh fading. Mehana and Nosratinia (2012) refined this: the diversity of the MMSE receiver depends on the rate, and at low rates it is larger, up to the ML value. So the MMSE gain over ZF is large at low and moderate SNR and shrinks to a fixed SNR offset at high SNR.
  • Capacity with cancellation. With Gaussian codes and successive cancellation of decoded streams, MMSE nulling at each step reaches log⁡2det⁡(I+(Es/N0)HHH)\log_2 \det(I + (E_s/N_0) H H^H), the capacity with equal power (theorem, Tse and Viswanath, Section 8.3.4). The D-BLAST page uses this.
  • Not ML. For a fixed vector, the decision can differ from the ML decision, as in the example.

Variants and improvements

  • MMSE with successive cancellation. Detect the stream with the largest SINR, cancel it, and recompute the filter for the rest. This is V-BLAST with MMSE nulling.
  • MMSE with soft output. Treat zk/βkz_k / \beta_k as xkx_k plus Gaussian noise of variance Es(1−βk)/βkE_s (1 - \beta_k) / \beta_k and compute bit LLRs as in soft demapping. This is the first stage of many coded receivers.
  • Soft interference cancellation. With prior means and variances of the symbols from a decoder, replace EsIE_s I by the diagonal of the prior variances and subtract the prior means. This is the soft interference cancellation equalizer of turbo receivers.
  • Expectation propagation. Run the MMSE filter again and again, each time with a Gaussian prior on each symbol that is fitted to the constellation; see the expectation propagation detector.
  • Lattice reduction with MMSE. Apply lattice reduction to the extended matrix (HN0/Es I)\begin{pmatrix} H \\ \sqrt{N_0/E_s}\, I \end{pmatrix}. ZF on this matrix is the MMSE filter, so MMSE inherits the gains of lattice reduction aided detection.

When to use it

Use MMSE when a linear detector is enough and the receiver has an estimate of N0N_0. It is never worse than ZF in SINR, it costs the same, and it works when the channel is ill conditioned or when n>mn > m. In massive MIMO uplinks with m≫nm \gg n, MMSE is close to optimal and is the default. On square channels at high SNR, its error rate is far from ML; use V-BLAST, a lattice reduction aided detector or a sphere search such as Schnorr-Euchner enumeration instead.

Pitfalls

  • Forgetting the bias. For 16-QAM and larger, slicing zkz_k without dividing by βk\beta_k adds errors on the outer points. The tests on this page measure this effect.
  • The wrong N0N_0. An N0N_0 that is much too small turns MMSE into ZF, and one that is much too large shrinks the outputs toward 0. Check the noise estimate.
  • Mixing up N0N_0 and N0/EsN_0/E_s. The regularization is the ratio N0/EsN_0 / E_s. With a unit-energy constellation it is N0N_0; with a constellation of energy Es≠1E_s \ne 1 it is not.
  • Treating the residual interference as white Gaussian noise. The error zk−βkxkz_k - \beta_k x_k holds interference from discrete symbols, so it is not exactly Gaussian. Using a Gaussian model for LLRs is an approximation (a rule).
  • Calling it ML. The MMSE detector minimizes the mean squared error of a linear estimate. It does not minimize the error probability of the vector.

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))
mmse_mimo_detector.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mmse-mimo-detector/. The authors are listed in prov/ZA2PHJ.jsonl.

"""The linear MMSE MIMO detector.

The model is y = H x + w, with H an m by n complex matrix, x a vector of n
points of a constellation with average energy Es and w ~ CN(0, N0 I).
With a = N0 / Es and P = (H^H H + a I)^(-1), the linear filter that
minimizes E||W y - x||^2 is W = P H^H. Its error covariance is N0 P.
The output W y is biased: E[(W y)_k | x_k] = beta_k x_k with
beta_k = (W H)_kk = 1 - a P_kk. The detector divides by beta_k before it
slices, which matters for constellations with more than one amplitude.
Stream k then has the SINR 1 / (a P_kk) - 1.
"""

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 mmse_parts(h: list[list[complex]], n0: float, es: float = 1.0) -> tuple[list[list[complex]], list[list[complex]]]:
    """(P, W) with P = (H^H H + (N0/Es) I)^(-1) and W = P H^H."""
    if n0 < 0 or es <= 0:
        raise ValueError("need N0 >= 0 and Es > 0")
    n = len(h[0])
    a = n0 / es
    hh = cbb.herm(h)
    g = cbb.matmul(hh, h)
    for k in range(n):
        g[k][k] += a
    try:
        p = cbb.inv(g)  # @line L1
    except ValueError:
        raise ValueError("H^H H + (N0/Es) I is singular: N0 = 0 and H has dependent columns") from None
    w = cbb.matmul(p, hh)  # @line L2
    return p, w


def mmse_matrix(h: list[list[complex]], n0: float, es: float = 1.0) -> list[list[complex]]:
    """The n by m MMSE filter W = (H^H H + (N0/Es) I)^(-1) H^H."""
    return mmse_parts(h, n0, es)[1]


def bias(h: list[list[complex]], n0: float, es: float = 1.0) -> list[float]:
    """beta_k = (W H)_kk = 1 - (N0/Es) P_kk, the gain of stream k in the output W y."""
    p, _ = mmse_parts(h, n0, es)
    return [1.0 - (n0 / es) * p[k][k].real for k in range(len(p))]


def mmse_outputs(y: list[complex], h: list[list[complex]], n0: float, es: float = 1.0, unbiased: bool = True) -> list[complex]:
    """The filter outputs W y, divided by beta_k if unbiased is true."""
    p, w = mmse_parts(h, n0, es)
    z = cbb.matvec(w, y)
    if not unbiased:
        return z
    return [z[k] / (1.0 - (n0 / es) * p[k][k].real) for k in range(len(z))]


def mmse_detect(y: list[complex], h: list[list[complex]], points: list[complex], n0: float, es: float = 1.0, unbiased: bool = True) -> list[int]:
    """The MMSE decisions: the nearest point to each output, after the bias correction if unbiased is true."""
    p, w = mmse_parts(h, n0, es)
    a = n0 / es
    z = cbb.matvec(w, y)  # @line L3
    out = []
    for k in range(len(z)):  # @line L4
        beta = 1.0 - a * p[k][k].real if unbiased else 1.0  # @line L5
        out.append(nearest(z[k] / beta, points))  # @line L6
    return out  # @line L7


def error_covariance(h: list[list[complex]], n0: float, es: float = 1.0) -> list[list[complex]]:
    """E[(W y - x)(W y - x)^H] = N0 (H^H H + (N0/Es) I)^(-1), for x with covariance Es I."""
    p, _ = mmse_parts(h, n0, es)
    return cbb.scale(n0, p)


def sinr(h: list[list[complex]], n0: float, es: float = 1.0) -> list[float]:
    """The SINR of each stream at the unbiased MMSE output: 1 / ((N0/Es) P_kk) - 1."""
    if n0 <= 0:
        raise ValueError("the SINR is infinite or undefined for N0 = 0")
    p, _ = mmse_parts(h, n0, es)
    return [1.0 / ((n0 / es) * p[k][k].real) - 1.0 for k in range(len(p))]
test_mmse_mimo_detector.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mmse-mimo-detector/. The authors are listed in prov/ZA2PHJ.jsonl.

import random

import pytest

import cbb
import constel
from mmse_mimo_detector import (
    bias,
    error_covariance,
    mmse_detect,
    mmse_matrix,
    mmse_outputs,
    mmse_parts,
    nearest,
    sinr,
)


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


def close(a, b, tol=1e-9):
    return all(abs(p - q) <= tol for p, q in zip(a, b))


def test_example_on_the_page() -> None:
    h = [[2, 1], [1, 1]]
    y = [0.5, 0.6]
    bpsk = constel.pam(2)
    p, w = mmse_parts(h, 0.5)
    assert close([p[0][0], p[0][1], p[1][1]], [2.5 / 4.75, -3 / 4.75, 5.5 / 4.75])
    assert close([w[0][0], w[0][1], w[1][0], w[1][1]], [2 / 4.75, -0.5 / 4.75, -0.5 / 4.75, 2.5 / 4.75])
    assert close(mmse_outputs(y, h, 0.5, unbiased=False), [0.7 / 4.75, 1.25 / 4.75])
    assert close(bias(h, 0.5), [3.5 / 4.75, 2 / 4.75])
    assert close(mmse_outputs(y, h, 0.5), [0.2, 0.625])
    assert mmse_detect(y, h, bpsk, 0.5) == [0, 0]  # (+1, +1): the first stream is now right
    assert close(sinr(h, 0.5), [2.8, 8 / 11])


def test_push_through_form_and_zf_limit() -> None:
    rng = random.Random(1301)
    for _ in range(40):
        n = rng.randint(1, 4)
        m = rng.randint(1, 5)
        h = rayleigh(rng, m, n)
        n0 = rng.uniform(0.05, 2.0)
        w = mmse_matrix(h, n0)
        # W = H^H (H H^H + N0 I)^-1, which also holds when n > m
        hh = cbb.herm(h)
        g = cbb.matmul(h, hh)
        for i in range(m):
            g[i][i] += n0
        w2 = cbb.matmul(hh, cbb.inv(g))
        assert all(close(r, s) for r, s in zip(w, w2))
        if m >= n:
            wz = cbb.solve(cbb.matmul(hh, h), hh)
            assert all(close(r, s, 1e-6) for r, s in zip(mmse_matrix(h, 1e-12), wz))


def test_bias_is_the_diagonal_of_wh_and_sinr_matches_the_direct_formula() -> None:
    rng = random.Random(1302)
    for _ in range(40):
        n = rng.randint(1, 4)
        m = rng.randint(1, 5)
        h = rayleigh(rng, m, n)
        n0, es = rng.uniform(0.05, 2.0), rng.uniform(0.5, 2.0)
        w = mmse_matrix(h, n0, es)
        wh = cbb.matmul(w, h)
        assert close(bias(h, n0, es), [wh[k][k].real for k in range(n)])
        for k, s in enumerate(sinr(h, n0, es)):
            sig = abs(wh[k][k]) ** 2 * es
            intf = sum(abs(wh[k][j]) ** 2 for j in range(n) if j != k) * es
            noise = n0 * cbb.norm2(w[k])
            assert abs(s - sig / (intf + noise)) < 1e-9 * (1 + s)


def test_mse_matches_the_closed_form() -> None:
    # closed form: E|(W y)_k - x_k|^2 = N0 P_kk for x with i.i.d. entries of energy Es
    rng = random.Random(1303)
    h = [[0.9 + 0.2j, 0.4 - 0.3j, 0.1j], [0.3, -0.7 + 0.5j, 0.6], [0.2 - 0.6j, 0.5, 1.1 - 0.1j], [0.4j, 0.3 + 0.3j, -0.5]]
    pts = constel.qam(16)
    n0 = 0.3
    e = error_covariance(h, n0)
    w = mmse_matrix(h, n0)
    trials = 4000
    acc = [0.0] * 3
    for _ in range(trials):
        x = [pts[rng.randrange(16)] for _ in range(3)]
        z = cbb.matvec(w, cbb.awgn(rng, cbb.matvec(h, x), n0))
        for k in range(3):
            acc[k] += abs(z[k] - x[k]) ** 2
    for k in range(3):
        assert abs(acc[k] / trials - e[k][k].real) < 0.08 * e[k][k].real


def test_wide_channels_work_and_n0_zero_needs_full_rank() -> None:
    rng = random.Random(1304)
    h = rayleigh(rng, 2, 3)
    assert len(mmse_detect(cbb.awgn(rng, [0j, 0j], 0.1), h, constel.qam(4), 0.1)) == 3
    with pytest.raises(ValueError):
        mmse_matrix([[1, 2], [2, 4]], 0.0)
    with pytest.raises(ValueError):
        sinr(h, 0.0)
    assert nearest(0j, constel.pam(2)) == 0


def run(rng, m, n, snr_db, pts, trials, with_ml):
    n0 = 1 / cbb.undb(snr_db)
    out = {"agree": 0, "mmse": 0, "zf": 0, "biased": 0}
    for _ in range(trials):
        h = rayleigh(rng, m, n)
        idx = [rng.randrange(len(pts)) for _ in range(n)]
        y = cbb.awgn(rng, cbb.matvec(h, [pts[i] for i in idx]), n0)
        d = mmse_detect(y, h, pts, n0)
        if with_ml:
            out["agree"] += d == constel.ml_vector(y, h, pts)
        out["mmse"] += sum(a != b for a, b in zip(d, idx))
        out["zf"] += sum(a != b for a, b in zip(mmse_detect(y, h, pts, 0.0), idx))
        out["biased"] += sum(a != b for a, b in zip(mmse_detect(y, h, pts, n0, unbiased=False), idx))
    return out


def test_most_decisions_match_ml_and_mmse_beats_zf() -> None:
    # measured: 4-QAM, m = n = 4, Es/N0 = 15 dB, seed 1305, 200 vectors:
    # 192 agree with ML; 9 symbol errors for MMSE against 29 for ZF
    out = run(random.Random(1305), 4, 4, 15.0, constel.qam(4), 200, True)
    assert out["agree"] >= 185
    assert out["mmse"] < out["zf"]


def test_bias_removal_helps_16qam() -> None:
    # measured: 16-QAM, m = n = 2, Es/N0 = 15 dB, seed 1306, 1500 vectors:
    # the unbiased slicer makes fewer symbol errors than the biased one
    out = run(random.Random(1306), 2, 2, 15.0, constel.qam(16), 1500, False)
    assert out["mmse"] < out["biased"]

History

Jack Winters introduced optimum combining for antenna arrays with cochannel interference in 1984: weights that maximize the SINR at the output of the array, which is the MMSE filter of a single stream. The same linear MMSE idea appeared for CDMA multiuser detection in the early 1990s. With the Bell Labs layered space-time systems of Foschini and his colleagues in the late 1990s, the MMSE filter, with or without successive cancellation, became a standard MIMO detector. Tse and Viswanath (2005) showed how the MMSE filter with successive cancellation reaches the capacity of the MIMO channel, which links the simple receiver to the information theory.

References

  1. David Tse and Pramod Viswanath, Fundamentals of Wireless Communication, Cambridge University Press, 2005, Section 8.3.3, Linear MMSE receiver (the SINR-maximizing filter and its MMSE form), and Section 8.3.4, Information theoretic optimality (MMSE-SIC achieves the capacity)
  2. Arogyaswami Paulraj, Rohit Nabar and Dhananjay Gore, Introduction to Space-Time Wireless Communications, Cambridge University Press, 2003, Chapter 7, Space-time receivers (the MMSE receiver and its comparison with ZF and ML)
  3. Erik G. Larsson, MIMO detection methods - how they work, IEEE Signal Processing Magazine 26(3), 91-95, 2009, the section on linear receivers (the MMSE filter as a regularized ZF)
  4. Ahmed Hesham Mehana and Aria Nosratinia, Diversity of MMSE MIMO receivers, IEEE Transactions on Information Theory 58(11), 6788-6805, 2012, the main results (the diversity of the MMSE receiver depends on the rate, from the ML value at low rates to the ZF value at high rates)

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