Algorithm Search⌘K

Algorithmcore

MMSE multiuser detector

Also called linear MMSE multiuser detector.

A linear multiuser detector that applies (R + σ²A⁻²)⁻¹ to the matched filter outputs, which minimizes the mean square error and balances interference against noise.

Time
O(K^2 N + K^3) worst
Space
O(K^2) extra
Where
K = the number of users; N = the number of chips per symbol
Properties
deterministiclinearnear far resistantneeds amplitudesneeds noise levelnot removes interferenceworks when overloaded
Origin
Zhenhua Xie, Robert T. Short, Craig K. Rushforth, 1990

The MMSE multiuser detector is the linear receiver for the multiuser detection problem that minimizes the mean square error between each output and the user's bit. A bank of matched filters gives z=RAb+nz = R A b + n, where RR is the crosscorrelation matrix of the signatures and AA holds the amplitudes. The detector computes x=(R+σ2A−2)−1zx = (R + \sigma^2 A^{-2})^{-1} z and decides each bit by its sign. The term σ2A−2\sigma^2 A^{-2} is what separates it from the decorrelating detector: the decorrelator removes all interference and lets the noise grow, while the MMSE detector leaves a little interference to keep the noise down. As σ→0\sigma \to 0 it becomes the decorrelator, and as σ→∞\sigma \to \infty its decisions become those of the matched filter. Among all linear detectors it has the largest signal to interference plus noise ratio (SINR) for every user, and the inverse always exists when σ>0\sigma > 0, even with more users than chips. It is the multiuser form of the Wiener filter, of the MMSE equalizer and of the MMSE MIMO detector.

In plain words

A receiver tuned to one user also picks up part of every other user, plus noise. One way to fix this is to cancel the other users completely, but that also makes the noise count for more. Another way is to ignore the other users and only fight the noise. The MMSE detector finds the best balance between these two. When the noise is weak, it mostly cancels the other users. When the noise is strong, it mostly averages out the noise and accepts some leftover interference. To find the balance it must know how strong each user is and how strong the noise is. It still uses only a fixed linear mix of the tuned receivers, so it is fast.

The problem

User k=1,…,Kk = 1, \ldots, K sends one bit bk∈{−1,+1}b_k \in \{-1, +1\} per symbol interval with amplitude Ak>0A_k > 0 and a signature sks_k of NN chips with ∥sk∥=1\|s_k\| = 1. The users are synchronous, so the received chips in one interval are y=SAb+wy = S A b + w, with S=[s1,…,sK]S = [s_1, \ldots, s_K], A=diag(Ak)A = \mathrm{diag}(A_k) and w∼N(0,σ2I)w \sim \mathcal{N}(0, \sigma^2 I), where σ2=N0/2\sigma^2 = N_0/2. The receiver knows the signatures, the amplitudes and σ\sigma. The output is a decision b^k\hat b_k for each user. The matched filter outputs are z=S⊤y=RAb+nz = S^\top y = R A b + n with R=S⊤SR = S^\top S and n∼N(0,σ2R)n \sim \mathcal{N}(0, \sigma^2 R).

The algorithm

  1. MMSE-MUD(y, S, A, σ)
  2. 1z ← Sᵀ y ▷ one matched filter per user
  3. 2R ← Sᵀ S ▷ the crosscorrelations
  4. 3G ← R + σ² A⁻² ▷ add σ²/A_k² to the diagonal entry k
  5. 4x ← G⁻¹ z ▷ solve G x = z
  6. 5return b̂_k ← sgn(x_k) for every k

Lines L1 and L2 are the same as in the decorrelator. Line L3 adds σ2/Ak2\sigma^2 / A_k^2 to the diagonal entry kk, so a weak user gets a large term and a strong user a small one. Line L4 solves the system; GG is symmetric positive definite for σ>0\sigma > 0, so a Cholesky decomposition works and never fails. Line L5 takes the signs, with +1+1 for a zero output. The filter for user kk on zz is row kk of G−1G^{-1} divided by AkA_k; that positive factor does not change the sign, so line L4 omits it.

Example

Three users with N=8N = 8 chips use s1=(1,1,1,1,1,1,1,1)/8s_1 = (1,1,1,1,1,1,1,1)/\sqrt 8, s2=(1,1,1,1,1,1,−1,−1)/8s_2 = (1,1,1,1,1,1,-1,-1)/\sqrt 8 and s3=(1,−1,1,−1,1,−1,1,1)/8s_3 = (1,-1,1,-1,1,-1,1,1)/\sqrt 8, so

R=(10.50.250.51−0.250.25−0.251).R = \begin{pmatrix} 1 & 0.5 & 0.25 \\ 0.5 & 1 & -0.25 \\ 0.25 & -0.25 & 1 \end{pmatrix}.

The amplitudes are A=(1,4,2)A = (1, 4, 2), the bits are b=(+1,−1,+1)b = (+1, -1, +1) and σ=0.5\sigma = 0.5. Line L3 adds (0.25,0.0156,0.0625)(0.25, 0.0156, 0.0625) to the diagonal. The first row of G−1G^{-1} is (1.156,−0.675,−0.431)(1.156, -0.675, -0.431), against (1.667,−1,−0.667)(1.667, -1, -0.667) for R−1R^{-1}: the weak user 1 relies less on cancelling the others. One noisy draw gave z=(−0.47,−4.21,2.18)z = (-0.47, -4.21, 2.18). The matched filter decides user 1 wrong. The MMSE detector gives x=(1.36,−4.66,0.64)x = (1.36, -4.66, 0.64), and the decorrelator gives (1.97,−5.09,0.41)(1.97, -5.09, 0.41); both have all three signs right. The exact error rates and output SINRs at σ=0.5\sigma = 0.5 are:

user matched filter decorrelator MMSE MMSE SINR decorrelator SINR
1 0.460 0.0607 0.0584 2.46 2.40
2 2.5×10−102.5 \times 10^{-10} 2.9×10−102.9 \times 10^{-10} 1.2×10−111.2 \times 10^{-11} 43.5 38.4
3 0.0183 2.7×10−42.7 \times 10^{-4} 1.7×10−41.7 \times 10^{-4} 12.8 12.0

The MMSE detector is best for every user here. The gain is largest for the strong user 2, for which the decorrelator was slightly worse than the matched filter. At σ=0.8\sigma = 0.8 the error rates of user 3 are 0.058, 0.015 and 0.011 for the matched filter, the decorrelator and the MMSE detector.

Correctness

Claim. For each user kk, the filter wk=G−1ek/Akw_k = G^{-1} e_k / A_k on zz minimizes E[(bk−w⊤z)2]E[(b_k - w^\top z)^2] over all linear filters ww, and it maximizes the output SINR, which equals Ak2 sk⊤Ck−1skA_k^2\, s_k^\top C_k^{-1} s_k with Ck=σ2I+∑j≠kAj2sjsj⊤C_k = \sigma^2 I + \sum_{j \ne k} A_j^2 s_j s_j^\top. The decision sgn(wk⊤z)\mathrm{sgn}(w_k^\top z) is sgn(xk)\mathrm{sgn}(x_k).

Key step. The normal equations of the mean square error are (RA2R+σ2R)w=AkRek(R A^2 R + \sigma^2 R) w = A_k R e_k, and RA2R+σ2R=RA2GR A^2 R + \sigma^2 R = R A^2 G, so wkw_k solves them. The SINR bound follows from the Cauchy-Schwarz inequality, and the Sherman-Morrison formula shows that wkw_k reaches it. The full proof, with the two limits and the exact error rate, is in the proofs folder.

Proof: The MMSE detector minimizes the mean square error, maximizes the SINR among linear detectors, and lies between the matched filter and the decorrelatorfull

The model is y=SAb+wy = S A b + w for one symbol interval. The matrix SS is N×KN \times K, its column sks_k is the signature of user kk with ∥sk∥=1\|s_k\| = 1, A=diag(A1,…,AK)A = \mathrm{diag}(A_1, \ldots, A_K) with Ak>0A_k > 0, the bits bk∈{−1,+1}b_k \in \{-1, +1\} are independent and equally likely, and w∼N(0,σ2IN)w \sim \mathcal{N}(0, \sigma^2 I_N) with σ>0\sigma > 0. Let R=S⊤SR = S^\top S and z=S⊤y=RAb+nz = S^\top y = R A b + n, with n∼N(0,σ2R)n \sim \mathcal{N}(0, \sigma^2 R). Line L3 forms G=R+σ2A−2G = R + \sigma^2 A^{-2}, line L4 computes x=G−1zx = G^{-1} z, and line L5 decides b^k=sgn(xk)\hat b_k = \mathrm{sgn}(x_k).

Lemma 1 (line L4 always succeeds). For σ>0\sigma > 0, GG is symmetric positive definite, even when RR is singular.

Proof. v⊤Gv=∥Sv∥2+σ2∑kvk2/Ak2v^\top G v = \|S v\|^2 + \sigma^2 \sum_k v_k^2 / A_k^2. The first term is at least 0 and the second is positive for v≠0v \ne 0. □\square

Theorem 1 (minimum mean square error). For each user kk, the linear filter wk=G−1ek/Akw_k = G^{-1} e_k / A_k on zz minimizes E[(bk−w⊤z)2]E[(b_k - w^\top z)^2] over all w∈RKw \in \mathbb{R}^K. The decision sgn(wk⊤z)\mathrm{sgn}(w_k^\top z) equals sgn(xk)\mathrm{sgn}(x_k).

Proof. The bits have E[bb⊤]=IE[b b^\top] = I and are independent of nn, so E[zz⊤]=RA2R+σ2RE[z z^\top] = R A^2 R + \sigma^2 R and E[z bk]=RAek=AkRekE[z\, b_k] = R A e_k = A_k R e_k. The mean square error 1−2w⊤E[zbk]+w⊤E[zz⊤]w1 - 2 w^\top E[z b_k] + w^\top E[z z^\top] w is a convex quadratic in ww, so ww is a minimizer if and only if it solves the normal equations (RA2R+σ2R)w=AkRek(R A^2 R + \sigma^2 R) w = A_k R e_k. Note that RA2R+σ2R=RA2(R+σ2A−2)=RA2GR A^2 R + \sigma^2 R = R A^2 (R + \sigma^2 A^{-2}) = R A^2 G. For wk=G−1ek/Akw_k = G^{-1} e_k / A_k,

RA2G G−1ek/Ak=RA2ek/Ak=AkRek,R A^2 G\, G^{-1} e_k / A_k = R A^2 e_k / A_k = A_k R e_k,

so wkw_k solves the normal equations. Since G−1G^{-1} is symmetric, wk⊤z=(G−1z)k/Ak=xk/Akw_k^\top z = (G^{-1} z)_k / A_k = x_k / A_k, and Ak>0A_k > 0, so the signs agree. □\square

Theorem 2 (maximum SINR). For a filter ww on zz, the output for user kk is w⊤z=(w⊤Rek)Akbk+∑j≠k(w⊤Rej)Ajbj+w⊤nw^\top z = (w^\top R e_k) A_k b_k + \sum_{j \ne k} (w^\top R e_j) A_j b_j + w^\top n. Define its SINR as the ratio of the signal power to the power of the other two terms,

SINRk(w)=Ak2(w⊤Rek)2∑j≠kAj2(w⊤Rej)2+σ2w⊤Rw.\mathrm{SINR}_k(w) = \frac{A_k^2 (w^\top R e_k)^2}{\sum_{j \ne k} A_j^2 (w^\top R e_j)^2 + \sigma^2 w^\top R w}.

Then SINRk(w)≤Ak2 sk⊤Ck−1sk\mathrm{SINR}_k(w) \le A_k^2\, s_k^\top C_k^{-1} s_k for every ww, where Ck=σ2I+∑j≠kAj2sjsj⊤C_k = \sigma^2 I + \sum_{j \ne k} A_j^2 s_j s_j^\top, and wkw_k attains the bound.

Proof. Put v=Swv = S w, so that w⊤z=v⊤yw^\top z = v^\top y, w⊤Rej=v⊤sjw^\top R e_j = v^\top s_j and w⊤Rw=∥v∥2w^\top R w = \|v\|^2. The denominator becomes v⊤Ckvv^\top C_k v and the numerator Ak2(v⊤sk)2A_k^2 (v^\top s_k)^2. The matrix CkC_k is positive definite, so by the Cauchy-Schwarz inequality in the inner product of CkC_k,

(v⊤sk)2=((Ck1/2v)⊤(Ck−1/2sk))2≤(v⊤Ckv)(sk⊤Ck−1sk),(v^\top s_k)^2 = \big( (C_k^{1/2} v)^\top (C_k^{-1/2} s_k) \big)^2 \le (v^\top C_k v)(s_k^\top C_k^{-1} s_k),

with equality if and only if vv is a multiple of Ck−1skC_k^{-1} s_k. This proves the bound. For wkw_k, let C=σ2I+SA2S⊤=Ck+Ak2sksk⊤C = \sigma^2 I + S A^2 S^\top = C_k + A_k^2 s_k s_k^\top. Then

C Swk=(σ2S+SA2R) G−1ek/Ak=SA2(σ2A−2+R) G−1ek/Ak=Aksk,C\, S w_k = (\sigma^2 S + S A^2 R)\, G^{-1} e_k / A_k = S A^2 (\sigma^2 A^{-2} + R)\, G^{-1} e_k / A_k = A_k s_k,

so Swk=AkC−1skS w_k = A_k C^{-1} s_k. By the Sherman-Morrison formula, C−1sk=Ck−1sk/(1+Ak2sk⊤Ck−1sk)C^{-1} s_k = C_k^{-1} s_k / (1 + A_k^2 s_k^\top C_k^{-1} s_k), a positive multiple of Ck−1skC_k^{-1} s_k. So v=Swkv = S w_k attains equality. □\square

Theorem 3 (the two limits). If RR is invertible, then G−1→R−1G^{-1} \to R^{-1} as σ→0\sigma \to 0, so the MMSE detector tends to the decorrelating detector. For any RR, σ2G−1→A2\sigma^2 G^{-1} \to A^2 as σ→∞\sigma \to \infty. So, for a fixed zz with no zero entry, the MMSE decisions equal the matched filter decisions sgn(zk)\mathrm{sgn}(z_k) once σ\sigma is large enough.

Proof. Matrix inversion is continuous on the invertible matrices. G=R+σ2A−2→RG = R + \sigma^2 A^{-2} \to R as σ→0\sigma \to 0. For the second limit, σ2G−1=(σ−2R+A−2)−1→(A−2)−1=A2\sigma^2 G^{-1} = (\sigma^{-2} R + A^{-2})^{-1} \to (A^{-2})^{-1} = A^2. Then σ2x=σ2G−1z→A2z\sigma^2 x = \sigma^2 G^{-1} z \to A^2 z, whose entries Ak2zkA_k^2 z_k have the signs of zkz_k. Each entry of σ2x\sigma^2 x converges, so its sign is that of the limit once σ\sigma is large enough. □\square

Theorem 4 (the exact error rate). With u=Rwu = R w, the error probability of user kk under the decision sgn(w⊤z)\mathrm{sgn}(w^\top z) is

Pk=2−(K−1)∑b: bk=+1Q(∑jujAjbjσw⊤Rw),P_k = 2^{-(K-1)} \sum_{b:\, b_k = +1} Q\Big( \frac{\sum_j u_j A_j b_j}{\sigma \sqrt{w^\top R w}} \Big),

the sum running over the 2K−12^{K-1} choices of the other bits.

Proof. Given bb, w⊤zw^\top z is Gaussian with mean u⊤Abu^\top A b and variance σ2w⊤Rw\sigma^2 w^\top R w. By symmetry under b→−bb \to -b, the error probability for bk=−1b_k = -1 equals that for bk=+1b_k = +1, and given bk=+1b_k = +1 the decision errs when w⊤z<0w^\top z < 0. Average over the other bits. □\square

Unlike the decorrelator, the MMSE output still holds some interference, so its error rate depends on the other amplitudes. Theorem 2 is a statement about SINR, not about the error rate: the residual interference is not Gaussian, and the MMSE detector does not minimize the error probability in general.

Remark (the cost). Line L1 costs O(KN)O(K N), line L2 costs O(K2N)O(K^2 N) and line L4 costs O(K3)O(K^3). When the signatures, the amplitudes and σ\sigma do not change, G−1G^{-1} is computed once and each interval costs O(KN+K2)O(K N + K^2).

Complexity

Line L1 costs O(KN)O(K N), line L2 costs O(K2N)O(K^2 N) and line L4 costs O(K3)O(K^3) in the real RAM, the same as the decorrelator. When the signatures, the amplitudes and σ\sigma stay the same, the factor of GG is computed once and each interval costs O(KN+K2)O(K N + K^2). When the amplitudes change, GG must be factored again, which the decorrelator never needs.

Properties

  • Minimum mean square error and maximum SINR among linear detectors, for every user at the same time.
  • Between two known detectors. It tends to the decorrelator as σ→0\sigma \to 0, and its decisions tend to those of the matched filter as σ→∞\sigma \to \infty.
  • Always defined for σ>0\sigma > 0. GG is positive definite even when RR is singular, so the detector works with more users than chips.
  • Needs amplitudes and the noise level. Errors in these estimates move the detector away from the optimum.
  • Residual interference. The outputs still hold some interference, so the error rate depends on the other users' amplitudes. The near-far resistance equals that of the decorrelator, because the two detectors agree as σ→0\sigma \to 0.
  • Not minimum error probability. The residual interference is not Gaussian, so maximum SINR does not always give the lowest bit error rate, although it is close in practice.

Variants and improvements

  • Adaptive MMSE. For one user, the filter can be learned from training bits with the LMS algorithm or recursive least squares, without knowing the other signatures or amplitudes. Madhow and Honig studied this form.
  • Blind MMSE. With only the wanted user's signature, minimizing the output energy under a constraint on the response to that signature gives the same filter up to scale.
  • Large systems. With random signatures and KK and NN both large at a fixed ratio, the SINR of each user tends to a fixed value that solves a simple equation in the load K/NK/N and the other users' powers.
  • MMSE with cancellation. Factoring GG by Cholesky gives an MMSE decision feedback detector, which cancels the decided users one at a time, as in successive interference cancellation.
  • Asynchronous and multipath channels. Use the block matrices of a whole frame, or a finite window of chips, and the same formula.

When to use it

Use the MMSE detector when the receiver can estimate the amplitudes and the noise level, when the system may be loaded with more users than chips, or when some signatures are highly correlated. It is the usual choice of linear detector in practice, and an adaptive form needs only training bits for the wanted user. When the amplitudes are unknown and change fast, the decorrelator is simpler.

Pitfalls

  • Wrong noise level. Using σ=0\sigma = 0 gives the decorrelator, and a very large σ\sigma gives the matched filter. A badly wrong estimate loses the gain.
  • Forgetting the amplitude scaling. The diagonal term is σ2/Ak2\sigma^2 / A_k^2, not σ2\sigma^2. Using σ2I\sigma^2 I is right only when all users have unit amplitude.
  • Expecting zero interference. The output still holds interference. Analyses that treat it as Gaussian noise are approximations.
  • Recomputing per symbol. Factor GG once while the signatures, amplitudes and σ\sigma stay the same.

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_multiuser_detector.py 91 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mmse-multiuser-detector/. The authors are listed in prov/1NBA15.jsonl.

"""The linear MMSE multiuser detector for synchronous CDMA.

Model (real, coherent BPSK, one symbol interval): y = S A b + w, where the
column s_k of S is the unit-energy signature of user k (N chips), A is the
diagonal matrix of the amplitudes A_k > 0, b is in {-1, +1}^K and w has
independent N(0, sigma^2) chips (sigma^2 = N0 / 2 in the complex model).

The matched filter bank gives z = S^T y = R A b + n with R = S^T S. The MMSE
detector computes x = (R + sigma^2 A^-2)^-1 z and decides b_k = sgn(x_k).
Row k of (R + sigma^2 A^-2)^-1, scaled by 1 / A_k, is the linear filter on z
that minimizes E[(b_k - w^T z)^2].
"""

import itertools
import math

import cbb


def matched_filter(y: list[float], sigs: list[list[float]]) -> list[float]:
    """z_k = s_k^T y for each user k."""
    return [math.fsum(a * b for a, b in zip(s, y)) for s in sigs]


def crosscorrelation(sigs: list[list[float]]) -> list[list[float]]:
    """R[i][j] = s_i^T s_j."""
    return [[math.fsum(a * b for a, b in zip(si, sj)) for sj in sigs] for si in sigs]


def regularized(r: list[list[float]], amps: list[float], sigma: float) -> list[list[float]]:
    """R + sigma^2 A^-2."""
    k = len(r)
    return [[r[i][j] + (sigma * sigma / (amps[i] * amps[i]) if i == j else 0.0) for j in range(k)] for i in range(k)]


def mmse_detector(y: list[float], sigs: list[list[float]], amps: list[float], sigma: float) -> list[int]:
    """The decisions sgn((R + sigma^2 A^-2)^-1 S^T y), with +1 for a zero output."""
    if any(a <= 0.0 for a in amps) or sigma < 0.0:
        raise ValueError("amplitudes must be positive and sigma must not be negative")
    z = matched_filter(y, sigs)  # @line L1
    r = crosscorrelation(sigs)  # @line L2
    m = regularized(r, amps, sigma)  # @line L3
    x = [v.real for v in cbb.solve(m, z)]  # @line L4
    return [1 if v >= 0.0 else -1 for v in x]  # @line L5


def mmse_rows(r: list[list[float]], amps: list[float], sigma: float) -> list[list[float]]:
    """The rows of (R + sigma^2 A^-2)^-1; row k is the filter on z for user k."""
    return [[v.real for v in row] for row in cbb.inv(regularized(r, amps, sigma))]


def output_sinr(w: list[float], k: int, r: list[list[float]], amps: list[float], sigma: float) -> float:
    """The SINR of user k at the output w^T z of any linear filter w on z."""
    kk = len(r)
    wr = [math.fsum(w[i] * r[i][j] for i in range(kk)) for j in range(kk)]
    sig = (wr[k] * amps[k]) ** 2
    mai = math.fsum((wr[j] * amps[j]) ** 2 for j in range(kk) if j != k)
    noise = sigma * sigma * math.fsum(wr[j] * w[j] for j in range(kk))
    return sig / (mai + noise)


def mmse_sinr(k: int, sigs: list[list[float]], amps: list[float], sigma: float) -> float:
    """A_k^2 s_k^T (sigma^2 I + sum over j != k of A_j^2 s_j s_j^T)^-1 s_k."""
    n = len(sigs[0])
    cov = [[(sigma * sigma if a == c else 0.0) + math.fsum(amps[j] ** 2 * sigs[j][a] * sigs[j][c] for j in range(len(sigs)) if j != k) for c in range(n)] for a in range(n)]
    u = [v.real for v in cbb.solve(cov, sigs[k])]
    return amps[k] ** 2 * math.fsum(p * q for p, q in zip(sigs[k], u))


def linear_ber(w: list[float], k: int, r: list[list[float]], amps: list[float], sigma: float) -> float:
    """The exact bit error rate of user k when the receiver decides sgn(w^T z).

    The other bits are equally likely and independent, so the rate is the
    average over them of Q(w^T R A b / (sigma sqrt(w^T R w))) with b_k = +1.
    """
    kk = len(r)
    wr = [math.fsum(w[i] * r[i][j] for i in range(kk)) for j in range(kk)]
    sd = sigma * math.sqrt(math.fsum(wr[j] * w[j] for j in range(kk)))
    others = [j for j in range(kk) if j != k]
    total = 0.0
    for signs in itertools.product((1, -1), repeat=len(others)):
        b = [0] * kk
        b[k] = 1
        for j, s in zip(others, signs):
            b[j] = s
        mean = math.fsum(wr[j] * amps[j] * b[j] for j in range(kk))
        total += cbb.qfunc(mean / sd)
    return total / (2 ** len(others))
test_mmse_multiuser_detector.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mmse-multiuser-detector/. The authors are listed in prov/1NBA15.jsonl.

import math
import random

import pytest

import cbb
import constel
from mmse_multiuser_detector import (
    crosscorrelation,
    linear_ber,
    matched_filter,
    mmse_detector,
    mmse_rows,
    mmse_sinr,
    output_sinr,
)

R8 = 1.0 / math.sqrt(8.0)
# The signatures of the page: s1 s2 = 0.5, s1 s3 = 0.25, s2 s3 = -0.25.
S_PAGE = [
    [R8 * c for c in (1, 1, 1, 1, 1, 1, 1, 1)],
    [R8 * c for c in (1, 1, 1, 1, 1, 1, -1, -1)],
    [R8 * c for c in (1, -1, 1, -1, 1, -1, 1, 1)],
]
AMPS = [1.0, 4.0, 2.0]


def chips(sigs, amps, b, sigma=0.0, rng=None):
    n = len(sigs[0])
    y = [math.fsum(amps[k] * b[k] * sigs[k][c] for k in range(len(sigs))) for c in range(n)]
    if rng is not None:
        y = [v + rng.gauss(0.0, sigma) for v in y]
    return y


def random_sigs(rng, k, n):
    s = 1.0 / math.sqrt(n)
    return [[s * rng.choice((1, -1)) for _ in range(n)] for _ in range(k)]


def test_page_example() -> None:
    b = [1, -1, 1]
    y = chips(S_PAGE, AMPS, b)
    assert [round(v, 12) for v in matched_filter(y, S_PAGE)] == [-0.5, -4.0, 3.25]
    assert mmse_detector(y, S_PAGE, AMPS, 0.5) == b
    m = mmse_rows(crosscorrelation(S_PAGE), AMPS, 0.5)
    assert [round(v, 4) for v in m[0]] == [1.1563, -0.6754, -0.431]


def test_small_noise_gives_the_decorrelator() -> None:
    r = crosscorrelation(S_PAGE)
    rinv = [[v.real for v in row] for row in cbb.inv(r)]
    m = mmse_rows(r, AMPS, 1e-5)
    for i in range(3):
        for j in range(3):
            assert m[i][j] == pytest.approx(rinv[i][j], abs=1e-8)


def test_large_noise_gives_matched_filter_decisions() -> None:
    rng = random.Random(4302)
    for _ in range(200):
        k = rng.randint(1, 5)
        sigs = random_sigs(rng, k, 8)
        amps = [rng.uniform(0.5, 2.0) for _ in range(k)]
        y = [rng.gauss(0.0, 1.0) for _ in range(8)]
        z = matched_filter(y, sigs)
        if min(abs(v) for v in z) < 1e-3:
            continue
        assert mmse_detector(y, sigs, amps, 1e4) == [1 if v >= 0 else -1 for v in z]


def test_works_when_correlation_is_singular() -> None:
    # Two users share one signature; R is singular but R + sigma^2 A^-2 is not.
    s = [R8] * 8
    y = chips([s, list(s)], [2.0, 1.0], [1, -1])
    assert mmse_detector(y, [s, list(s)], [2.0, 1.0], 0.3) == [1, 1]
    with pytest.raises(ValueError):
        mmse_detector(y, [s, list(s)], [2.0, 1.0], 0.0)


def test_sinr_closed_form_and_maximality() -> None:
    rng = random.Random(4303)
    for _ in range(40):
        k = rng.randint(1, 5)
        sigs = random_sigs(rng, k, 8)
        amps = [rng.uniform(0.3, 3.0) for _ in range(k)]
        sigma = rng.uniform(0.2, 1.5)
        r = crosscorrelation(sigs)
        m = mmse_rows(r, amps, sigma)
        for u in range(k):
            best = output_sinr(m[u], u, r, amps, sigma)
            assert best == pytest.approx(mmse_sinr(u, sigs, amps, sigma), rel=1e-9)
            mf = [1.0 if j == u else 0.0 for j in range(k)]
            assert output_sinr(mf, u, r, amps, sigma) <= best * (1 + 1e-12)
            for _ in range(20):
                w = [m[u][j] + rng.gauss(0.0, 0.3) for j in range(k)]
                assert output_sinr(w, u, r, amps, sigma) <= best * (1 + 1e-12)


def test_minimizes_mean_square_error() -> None:
    # E[(b_k - w^T z)^2] = 1 - 2 A_k w^T R e_k + w^T (R A^2 R + sigma^2 R) w.
    rng = random.Random(4304)
    sigs = random_sigs(rng, 4, 8)
    amps = [0.7, 1.5, 2.5, 1.0]
    sigma = 0.6
    r = crosscorrelation(sigs)
    k = len(r)
    cov = [[math.fsum(r[i][t] * amps[t] ** 2 * r[t][j] for t in range(k)) + sigma * sigma * r[i][j] for j in range(k)] for i in range(k)]

    def mse(w, u):
        quad = math.fsum(w[i] * cov[i][j] * w[j] for i in range(k) for j in range(k))
        return 1.0 - 2.0 * amps[u] * math.fsum(w[i] * r[i][u] for i in range(k)) + quad

    m = mmse_rows(r, amps, sigma)
    for u in range(k):
        w0 = [v / amps[u] for v in m[u]]
        for _ in range(50):
            w = [v + rng.gauss(0.0, 0.2) for v in w0]
            assert mse(w0, u) <= mse(w, u) + 1e-12


def test_agrees_with_ml_most_of_the_time() -> None:
    # Seed 4305: at sigma = 0.3 the MMSE and brute-force ML decisions agree on
    # at least 95 percent of the 300 vectors.
    rng = random.Random(4305)
    pts = constel.pam(2)
    same = 0
    trials = 300
    for _ in range(trials):
        k = rng.randint(2, 5)
        sigs = random_sigs(rng, k, 8)
        amps = [rng.uniform(0.5, 2.0) for _ in range(k)]
        b = [rng.choice((1, -1)) for _ in range(k)]
        y = chips(sigs, amps, b, 0.3, rng)
        h = [[amps[u] * sigs[u][c] for u in range(k)] for c in range(8)]
        ml = [1 if i == 0 else -1 for i in constel.ml_vector([complex(v) for v in y], h, pts)]
        same += mmse_detector(y, sigs, amps, 0.3) == ml
    assert same >= 0.95 * trials


def test_simulated_ber_matches_exact_value() -> None:
    # Seed 4301: 2000 symbol intervals at sigma = 0.8; the exact rate predicts about 319 errors for user 1.
    rng = random.Random(4301)
    sigma = 0.8
    r = crosscorrelation(S_PAGE)
    p = linear_ber(mmse_rows(r, AMPS, sigma)[0], 0, r, AMPS, sigma)
    trials = 2000
    assert p * trials >= 100
    errors = 0
    for _ in range(trials):
        b = [rng.choice((1, -1)) for _ in range(3)]
        y = chips(S_PAGE, AMPS, b, sigma, rng)
        errors += mmse_detector(y, S_PAGE, AMPS, sigma)[0] != b[0]
    lo, hi = cbb.wilson(errors, trials)
    assert lo <= p <= hi


def test_errors() -> None:
    with pytest.raises(ValueError):
        mmse_detector([0.0] * 8, S_PAGE, [1.0, 0.0, 1.0], 0.5)
    with pytest.raises(ValueError):
        mmse_detector([0.0] * 8, S_PAGE, AMPS, -1.0)

History

Xie, Short and Rushforth proposed the linear MMSE detector for synchronous multiuser channels in 1990, as one of a family of suboptimum detectors. Madhow and Honig analyzed MMSE interference suppression for direct-sequence CDMA in 1994 and gave adaptive forms that need only the wanted user's signature and training data. These adaptive and blind forms made the MMSE detector the practical linear multiuser receiver. Its analysis for large random CDMA systems in the late 1990s gave simple formulas for the SINR as a function of the system load.

References

  1. Upamanyu Madhow and Michael L. Honig, MMSE interference suppression for direct-sequence spread-spectrum CDMA, IEEE Transactions on Communications 42(12), 1994, pp. 3178 to 3188 (the MMSE detector, its SINR, and adaptive forms)
  2. Sergio Verdú, Multiuser Detection, Cambridge University Press, 1998, Chapter 6, Non-decorrelating linear multiuser detection
  3. David Tse and Pramod Viswanath, Fundamentals of Wireless Communication, Cambridge University Press, 2005, Section 8.3.2, Linear MMSE receiver, and Discussion 8.1, Connections with CDMA multiuser detection

About this page

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

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