Algorithm Search⌘K

Algorithmcore

Decorrelating detector

Also called decorrelator.

A linear multiuser detector that applies the inverse of the users' crosscorrelation matrix to the matched filter outputs, which removes all multiple access interference at the cost of more 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
deterministicenhances noiselinearnear far resistantnot needs amplitudesnot needs noise levelremoves interference
Origin
Ruxandra Lupas, Sergio Verdú, 1989

The decorrelating detector, or decorrelator, is the simplest receiver for the multiuser detection problem that removes all multiple access interference. A bank of matched filters gives z=RAb+nz = R A b + n, where RR is the crosscorrelation matrix of the users' signatures. The decorrelator multiplies by R−1R^{-1} and decides each bit by its sign. Each output is then the user's own amplitude and bit plus noise, whatever the other users send and however strong they are. So it solves the near-far problem without power control and without knowing any amplitude. The price is that the noise grows by the factor (R−1)kk≥1(R^{-1})_{kk} \ge 1. Lupas and Verdú showed in 1989 that its near-far resistance equals that of the optimum detector, at a cost that is polynomial in the number of users KK. It is the CDMA form of the zero-forcing equalizer and of the zero-forcing MIMO detector. The MMSE detector adds the noise level to the same design and trades a little interference for less noise.

In plain words

Each user's code looks a little like the codes of the others, so a receiver tuned to one user also picks up a bit of every other user. When another user is much stronger, that bit can be larger than the wanted signal. The decorrelator knows how much each code looks like each other code. It combines the outputs of all the tuned receivers in exactly the way that cancels every other user. What remains for each user is its own signal and some noise. The strength of the other users no longer matters. The cost is that cancelling the others also removes the part of the wanted signal that looks like them, so the noise counts for more. If two codes are almost the same, that cost becomes very large.

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, where 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). This is the in-phase part of the complex model for coherent BPSK, with σ2=N0/2\sigma^2 = N_0/2. The receiver knows the signatures but not the amplitudes or σ\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. DECORRELATOR(y, S)
  2. 1z ← Sᵀ y ▷ one matched filter per user
  3. 2R ← Sᵀ S ▷ the crosscorrelations, 1 on the diagonal
  4. 3x ← R⁻¹ z ▷ solve R x = z by Gaussian elimination
  5. 4return b̂_k ← sgn(x_k) for every k

Line L1 correlates the received chips with each signature. Line L2 needs only the signatures, so for a fixed set of users it is computed once. Line L3 solves the linear system; it fails when RR is singular, which happens exactly when the signatures are linearly dependent, and in particular when K>NK > N. Line L4 takes the sign of each output, with +1+1 for a zero output. Since R−1S⊤R^{-1} S^\top is the pseudoinverse of SS, the vector xx is also the least squares fit of yy by the signatures.

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. Then

R=(10.50.250.51−0.250.25−0.251),R−1=13(5−3−2−352−224).R = \begin{pmatrix} 1 & 0.5 & 0.25 \\ 0.5 & 1 & -0.25 \\ 0.25 & -0.25 & 1 \end{pmatrix}, \qquad R^{-1} = \frac{1}{3}\begin{pmatrix} 5 & -3 & -2 \\ -3 & 5 & 2 \\ -2 & 2 & 4 \end{pmatrix}.

The amplitudes are A=(1,4,2)A = (1, 4, 2), so user 2 is 12 dB stronger than user 1, and the bits are b=(+1,−1,+1)b = (+1, -1, +1). Without noise, z=(−0.5,−4,3.25)z = (-0.5, -4, 3.25); the matched filter decides user 1 wrong, and R−1z=(1,−4,2)=AbR^{-1} z = (1, -4, 2) = A b exactly. With σ=0.5\sigma = 0.5, one noisy draw gave z=(−0.47,−4.21,2.18)z = (-0.47, -4.21, 2.18) and x=R−1z=(1.97,−5.09,0.41)x = R^{-1} z = (1.97, -5.09, 0.41), all three signs right. The exact error rates at σ=0.5\sigma = 0.5 are:

user single-user bound Q(Ak/σ)Q(A_k/\sigma) matched filter decorrelator 1/(R−1)kk1/(R^{-1})_{kk}
1 0.0228 0.460 0.0607 0.60
2 6.2×10−166.2 \times 10^{-16} 2.5×10−102.5 \times 10^{-10} 2.9×10−102.9 \times 10^{-10} 0.60
3 3.2×10−53.2 \times 10^{-5} 0.0183 2.7×10−42.7 \times 10^{-4} 0.75

The weak user 1 goes from an error rate near one half to 0.061. The decorrelator pays 1/0.61/0.6, or 2.2 dB, of energy for users 1 and 2, and 1.2 dB for user 3. For the strong user 2 the matched filter is slightly better: the interference it sees is small compared with its own signal, and the decorrelator's noise penalty costs more than it saves.

Correctness

Claim. If the signatures are linearly independent, then x=Ab+n~x = A b + \tilde n with n~∼N(0,σ2R−1)\tilde n \sim \mathcal{N}(0, \sigma^2 R^{-1}), so user kk errs with probability Q(Ak/(σ(R−1)kk))Q(A_k / (\sigma \sqrt{(R^{-1})_{kk}})), which depends on neither the bits nor the amplitudes of the other users. Without noise every decision is right.

Key step. R−1z=R−1RAb+R−1nR^{-1} z = R^{-1} R A b + R^{-1} n, and the covariance of R−1nR^{-1} n is σ2R−1RR−1=σ2R−1\sigma^2 R^{-1} R R^{-1} = \sigma^2 R^{-1}. The penalty 1/(R−1)kk1/(R^{-1})_{kk} is the squared length of the part of sks_k orthogonal to the other signatures, by the Schur complement. The full proof is in the proofs folder.

Proof: The decorrelator removes all multiple access interference, and its error rate does not depend on the other usersfull

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, b∈{−1,+1}Kb \in \{-1, +1\}^K, and w∼N(0,σ2IN)w \sim \mathcal{N}(0, \sigma^2 I_N). Let R=S⊤SR = S^\top S. Line L1 computes z=S⊤yz = S^\top y, line L2 computes RR, line L3 solves Rx=zR x = z, and line L4 decides b^k=sgn(xk)\hat b_k = \mathrm{sgn}(x_k).

Lemma 1 (the matched filter outputs). z=RAb+nz = R A b + n with n∼N(0,σ2R)n \sim \mathcal{N}(0, \sigma^2 R).

Proof. z=S⊤SAb+S⊤wz = S^\top S A b + S^\top w. The vector n=S⊤wn = S^\top w is Gaussian with mean zero and covariance E[S⊤ww⊤S]=σ2S⊤S=σ2RE[S^\top w w^\top S] = \sigma^2 S^\top S = \sigma^2 R. □\square

Lemma 2 (when line L3 succeeds). RR is invertible if and only if the signatures s1,…,sKs_1, \ldots, s_K are linearly independent. This needs K≤NK \le N.

Proof. For any vv, v⊤Rv=∥Sv∥2v^\top R v = \|S v\|^2. So RR is positive semidefinite, and Rv=0R v = 0 implies Sv=0S v = 0. Conversely, Sv=0S v = 0 implies Rv=S⊤Sv=0R v = S^\top S v = 0. So RR is singular exactly when some nonzero vv has Sv=0S v = 0. □\square

Theorem 1 (no interference). If the signatures are linearly independent, then

x=R−1z=Ab+n~,n~∼N(0,σ2R−1).(1)x = R^{-1} z = A b + \tilde n, \qquad \tilde n \sim \mathcal{N}(0, \sigma^2 R^{-1}). \tag{1}

So xk=Akbk+n~kx_k = A_k b_k + \tilde n_k, where n~k\tilde n_k has variance σ2(R−1)kk\sigma^2 (R^{-1})_{kk} and does not depend on bb or on the amplitudes. The error probability of user kk is

Pk=Q(Akσ(R−1)kk).(2)P_k = Q\Big( \frac{A_k}{\sigma \sqrt{(R^{-1})_{kk}}} \Big). \tag{2}

Proof. By Lemma 1, R−1z=Ab+R−1nR^{-1} z = A b + R^{-1} n, and R−1nR^{-1} n has covariance σ2R−1RR−1=σ2R−1\sigma^2 R^{-1} R R^{-1} = \sigma^2 R^{-1}. Given bk=+1b_k = +1, line L4 errs when n~k<−Ak\tilde n_k < -A_k, which has probability Q(Ak/(σ(R−1)kk))Q(A_k / (\sigma \sqrt{(R^{-1})_{kk}})). The case bk=−1b_k = -1 is symmetric. □\square

Corollary (no noise). If w=0w = 0, then x=Abx = A b exactly and every decision is right, for every choice of the amplitudes.

Lemma 3 (least squares). The vector xx of line L3 is the unique minimizer of ∥y−Sx∥2\|y - S x\|^2 over x∈RKx \in \mathbb{R}^K. So it is the maximum likelihood estimate of the vector AbA b when that vector is treated as an unknown real vector, with no use of the fact that bk=±1b_k = \pm 1.

Proof. The function ∥y−Sx∥2\|y - S x\|^2 is a convex quadratic with gradient 2(S⊤Sx−S⊤y)=2(Rx−z)2(S^\top S x - S^\top y) = 2(R x - z). The gradient is zero exactly when Rx=zR x = z, which has the single solution R−1zR^{-1} z. Under the Gaussian model, the log-likelihood of yy given the mean SxS x is −∥y−Sx∥2/(2σ2)-\|y - S x\|^2 / (2 \sigma^2) plus a constant. □\square

Lemma 4 (the noise penalty). Let PkP_k be the orthogonal projection onto the span of the signatures other than sks_k. Then

1(R−1)kk=∥sk−Pksk∥2=1−∥Pksk∥2≤1,\frac{1}{(R^{-1})_{kk}} = \|s_k - P_k s_k\|^2 = 1 - \|P_k s_k\|^2 \le 1,

with equality if and only if sks_k is orthogonal to every other signature.

Proof. Order the users so that kk comes first and write R=(1r⊤rR′)R = \begin{pmatrix} 1 & r^\top \\ r & R' \end{pmatrix}, where rr holds the correlations sj⊤sks_j^\top s_k for j≠kj \ne k and R′R' is the correlation matrix of the others. R′R' is invertible, because the other signatures are independent. By the formula for the inverse of a block matrix, (R−1)kk=1/(1−r⊤R′−1r)(R^{-1})_{kk} = 1 / (1 - r^\top R'^{-1} r), where 1−r⊤R′−1r1 - r^\top R'^{-1} r is the Schur complement of R′R'. With S′S' the matrix of the other signatures, Pk=S′R′−1S′⊤P_k = S' R'^{-1} S'^\top, so Pksk=S′R′−1rP_k s_k = S' R'^{-1} r and ∥Pksk∥2=r⊤R′−1R′R′−1r=r⊤R′−1r\|P_k s_k\|^2 = r^\top R'^{-1} R' R'^{-1} r = r^\top R'^{-1} r. Since ∥sk∥=1\|s_k\| = 1 and sk−Pksks_k - P_k s_k is orthogonal to PkskP_k s_k, 1−∥Pksk∥2=∥sk−Pksk∥21 - \|P_k s_k\|^2 = \|s_k - P_k s_k\|^2. This is 1 if and only if Pksk=0P_k s_k = 0, that is, if and only if r=0r = 0. □\square

So the decorrelator works as if user kk were alone with the energy Ak2/(R−1)kkA_k^2 / (R^{-1})_{kk}: the part of sks_k that lies in the span of the others is lost, and only the orthogonal part carries the bit. Compared with the single-user error rate Q(Ak/σ)Q(A_k / \sigma), the loss is the factor ηk=1/(R−1)kk\eta_k = 1 / (R^{-1})_{kk} in energy, for every σ\sigma.

Corollary (near-far resistance). The asymptotic efficiency of a detector for user kk is the supremum of the e∈[0,1]e \in [0, 1] with Pk=O(Q(e Ak/σ))P_k = O(Q(\sqrt{e}\, A_k / \sigma)) as σ→0\sigma \to 0. Its near-far resistance is the infimum of the asymptotic efficiency over all amplitudes of the other users. By (2), the decorrelator has asymptotic efficiency ηk=1/(R−1)kk\eta_k = 1/(R^{-1})_{kk} whatever the other amplitudes are, so its near-far resistance is also ηk\eta_k, which is positive whenever the signatures are independent. Lupas and Verdú proved that no detector has a larger near-far resistance; that result is cited, not proved here. For two users with correlation ρ\rho, ηk=1−ρ2\eta_k = 1 - \rho^2.

Remark (the cost). Line L1 costs O(KN)O(K N), line L2 costs O(K2N)O(K^2 N), and line L3 costs O(K3)O(K^3) with Gaussian elimination. When the signatures do not change from one interval to the next, R−1R^{-1}, or a Cholesky factor of RR, 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 L3 costs O(K3)O(K^3) in the real RAM. When the signatures stay the same over many intervals, R−1R^{-1} or a Cholesky factor of RR is computed once, and each interval then costs O(KN+K2)O(K N + K^2). In an asynchronous system with MM symbols per user, RR is a block Toeplitz matrix of size KMK M with bandwidth about 2K2K, and a banded solver costs O(MK3)O(M K^3).

Properties

  • No interference. Each output is AkbkA_k b_k plus Gaussian noise. The detector is the zero-forcing solution of the multiuser problem.
  • Near-far resistant. The asymptotic efficiency 1/(R−1)kk1/(R^{-1})_{kk} does not depend on the amplitudes, so it is also the near-far resistance. No detector, linear or not, has a larger near-far resistance (Lupas and Verdú).
  • Needs no amplitudes and no noise level. It uses only the signatures, unlike the optimum and the MMSE detectors.
  • Noise enhancement. (R−1)kk≥1(R^{-1})_{kk} \ge 1, with equality only when sks_k is orthogonal to all the others. For two users with correlation ρ\rho, the loss is 1/(1−ρ2)1/(1 - \rho^2).
  • Least squares and maximum likelihood. xx minimizes ∥y−Sx∥2\|y - S x\|^2, so it is the maximum likelihood estimate of AbA b when that vector is treated as an unknown real vector.

Variants and improvements

  • Asynchronous decorrelator. Apply the inverse of the block Toeplitz crosscorrelation matrix of a whole frame, or a one-shot decorrelator that treats each partial overlap as an extra virtual user.
  • Decorrelating decision feedback. Factor R=F⊤FR = F^\top F by Cholesky, whiten with F−⊤F^{-\top}, and cancel the users one at a time with decisions, as in a decision feedback equalizer.
  • Decorrelator as a first stage. Use its decisions to start parallel interference cancellation, as in the multistage detector of Varanasi and Aazhang.
  • Adaptive and blind forms. For the user kk alone, the decorrelating filter is the projection of sks_k orthogonal to the other signatures. It can be learned from the received data without knowing the other signatures, which led to blind adaptive multiuser detection.
  • Regularized form. Adding σ2A−2\sigma^2 A^{-2} to RR gives the MMSE detector.

When to use it

Use the decorrelator when the users have very different powers and the receiver does not know the amplitudes or the noise level, and when K≤NK \le N with signatures that are not nearly dependent. It is also a good first stage for cancellation methods. At low SNR, or when two signatures are highly correlated, the MMSE detector has a lower error rate.

Pitfalls

  • More users than chips. With K>NK > N, RR is singular and the decorrelator does not exist. Use the MMSE detector, which is defined for any KK when σ>0\sigma > 0.
  • Nearly dependent signatures. When RR is ill conditioned, (R−1)kk(R^{-1})_{kk} is large and the noise swamps the signal. Check the condition number of RR or the penalties 1/(R−1)kk1/(R^{-1})_{kk}.
  • Using it for the strongest user. A strong user loses energy to the noise penalty and gains little from the removed interference. The table above shows a case where its matched filter is slightly better.
  • Signature mismatch. The exact cancellation relies on the exact RR. Errors in the chip timing or the channel change RR and leave residual interference, which is again near-far sensitive.
  • Forming R−1R^{-1} in each interval. Solve the system once per set of signatures and reuse the factor; do not invert RR for every symbol.

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))
decorrelating_detector.py 74 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/decorrelating-detector/. The authors are listed in prov/X81J9E.jsonl.

"""The decorrelating detector of Lupas and Verdu 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 and
n ~ N(0, sigma^2 R). The decorrelator solves R x = z, so x = A b + R^-1 n has
no multiple access interference, and decides b_k = sgn(x_k).
"""

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 decorrelate(z: list[float], r: list[list[float]]) -> list[float]:
    """The solution x of R x = z (raises ValueError if R is singular)."""
    return [v.real for v in cbb.solve(r, z)]


def decorrelating_detector(y: list[float], sigs: list[list[float]]) -> list[int]:
    """The decisions sgn(R^-1 S^T y), with +1 for a zero output."""
    z = matched_filter(y, sigs)  # @line L1
    r = crosscorrelation(sigs)  # @line L2
    x = decorrelate(z, r)  # @line L3
    return [1 if v >= 0.0 else -1 for v in x]  # @line L4


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))


def decorrelator_ber(k: int, r: list[list[float]], amps: list[float], sigma: float) -> float:
    """The closed form Q(A_k / (sigma sqrt((R^-1)_kk)))."""
    rinv_kk = cbb.inv(r)[k][k].real
    return cbb.qfunc(amps[k] / (sigma * math.sqrt(rinv_kk)))


def near_far_resistance(r: list[list[float]], k: int) -> float:
    """1 / (R^-1)_kk, the near-far resistance of the decorrelator (and of the optimum detector)."""
    return 1.0 / cbb.inv(r)[k][k].real
test_decorrelating_detector.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/decorrelating-detector/. The authors are listed in prov/X81J9E.jsonl.

import math
import random

import pytest

import cbb
import constel
from decorrelating_detector import (
    crosscorrelation,
    decorrelate,
    decorrelating_detector,
    decorrelator_ber,
    linear_ber,
    matched_filter,
    near_far_resistance,
)

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)],
]


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)
    while True:
        sigs = [[s * rng.choice((1, -1)) for _ in range(n)] for _ in range(k)]
        if abs(cbb.det(crosscorrelation(sigs))) > 1e-6:
            return sigs


def test_page_example() -> None:
    amps = [1.0, 4.0, 2.0]
    b = [1, -1, 1]
    y = chips(S_PAGE, amps, b)
    r = crosscorrelation(S_PAGE)
    assert [[round(v, 12) for v in row] for row in r] == [[1.0, 0.5, 0.25], [0.5, 1.0, -0.25], [0.25, -0.25, 1.0]]
    z = matched_filter(y, S_PAGE)
    assert [round(v, 12) for v in z] == [-0.5, -4.0, 3.25]
    # The matched filter alone gets user 1 wrong with no noise at all.
    assert [1 if v >= 0 else -1 for v in z] == [-1, -1, 1]
    assert [round(v, 12) for v in decorrelate(z, r)] == [1.0, -4.0, 2.0]
    assert decorrelating_detector(y, S_PAGE) == b


def test_noiseless_recovery_for_any_amplitudes() -> None:
    rng = random.Random(4201)
    for _ in range(200):
        k = rng.randint(1, 6)
        sigs = random_sigs(rng, k, 8)
        amps = [10 ** rng.uniform(-2, 2) for _ in range(k)]
        b = [rng.choice((1, -1)) for _ in range(k)]
        assert decorrelating_detector(chips(sigs, amps, b), sigs) == b


def test_output_is_least_squares_fit() -> None:
    # x = R^-1 S^T y minimizes ||y - S x||^2: the residual is orthogonal to every signature.
    rng = random.Random(4202)
    for _ in range(50):
        k = rng.randint(1, 5)
        sigs = random_sigs(rng, k, 9)
        y = [rng.gauss(0.0, 1.0) for _ in range(9)]
        x = decorrelate(matched_filter(y, sigs), crosscorrelation(sigs))
        res = [y[c] - math.fsum(x[u] * sigs[u][c] for u in range(k)) for c in range(9)]
        for s in sigs:
            assert abs(math.fsum(a * e for a, e in zip(s, res))) < 1e-9


def test_agrees_with_ml_most_of_the_time_at_high_snr() -> None:
    # Seed 4203: at sigma = 0.15 the decorrelator and the brute-force ML detector
    # give the same decisions on at least 97 percent of the 300 vectors.
    rng = random.Random(4203)
    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.15, 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 += decorrelating_detector(y, sigs) == ml
    assert same >= 0.97 * trials


def test_closed_form_equals_exact_linear_ber() -> None:
    r = crosscorrelation(S_PAGE)
    rinv = [[v.real for v in row] for row in cbb.inv(r)]
    amps = [1.0, 4.0, 2.0]
    for sigma in (0.3, 0.5, 1.0):
        for k in range(3):
            assert linear_ber(rinv[k], k, r, amps, sigma) == pytest.approx(decorrelator_ber(k, r, amps, sigma), rel=1e-12)


def test_ber_does_not_depend_on_interferer_amplitudes() -> None:
    r = crosscorrelation(S_PAGE)
    rinv = [[v.real for v in row] for row in cbb.inv(r)]
    base = linear_ber(rinv[0], 0, r, [1.0, 1.0, 1.0], 0.5)
    for a2, a3 in ((4.0, 2.0), (100.0, 0.01), (1e4, 1e4)):
        assert linear_ber(rinv[0], 0, r, [1.0, a2, a3], 0.5) == pytest.approx(base, rel=1e-12)
    # The matched filter row e_1 does depend on them.
    mf = [1.0, 0.0, 0.0]
    assert linear_ber(mf, 0, r, [1.0, 4.0, 2.0], 0.5) > 0.4
    assert linear_ber(mf, 0, r, [1.0, 0.1, 0.1], 0.5) < 0.04


def test_near_far_resistance_two_users() -> None:
    for rho in (0.0, 0.3, -0.7, 0.95):
        r = [[1.0, rho], [rho, 1.0]]
        assert near_far_resistance(r, 0) == pytest.approx(1.0 - rho * rho, rel=1e-12)


def test_simulated_ber_matches_closed_form() -> None:
    # Seed 4204: 2000 symbol intervals at sigma = 0.8, where the closed form
    # predicts about 333 errors for user 1.
    rng = random.Random(4204)
    amps = [1.0, 4.0, 2.0]
    sigma = 0.8
    r = crosscorrelation(S_PAGE)
    p = decorrelator_ber(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 += decorrelating_detector(y, S_PAGE)[0] != b[0]
    lo, hi = cbb.wilson(errors, trials)
    assert lo <= p <= hi


def test_singular_correlation_raises() -> None:
    s = [R8] * 8
    with pytest.raises(ValueError):
        decorrelating_detector([0.1] * 8, [s, list(s)])
    # Three users on two chips cannot have independent signatures.
    sigs = [[1.0, 0.0], [0.0, 1.0], [math.sqrt(0.5), math.sqrt(0.5)]]
    with pytest.raises(ValueError):
        decorrelating_detector([0.3, -0.2], sigs)

History

Earlier work on code division multiplexing had already used the inverse of the crosscorrelations to remove the interference between users. Lupas and Verdú gave the full analysis of the decorrelating detector for synchronous CDMA in 1989. They showed that its error probability does not depend on the energies of the other users, defined the near-far resistance of a detector, and proved that the decorrelator reaches the near-far resistance of the optimum detector at polynomial cost. A paper of 1990 extended the analysis to asynchronous users. The decorrelator became the baseline linear multiuser detector, and the MMSE detector followed it a few years later.

References

  1. Ruxandra Lupas and Sergio Verdú, Linear multiuser detectors for synchronous code-division multiple-access channels, IEEE Transactions on Information Theory 35(1), 1989, pp. 123 to 136 (the decorrelating detector, its error probability, and its near-far resistance, equal to that of the optimum detector)
  2. Sergio Verdú, Multiuser Detection, Cambridge University Press, 1998, Chapter 5, Decorrelating detector
  3. David Tse and Pramod Viswanath, Fundamentals of Wireless Communication, Cambridge University Press, 2005, Section 8.3.1, Linear decorrelator, and Discussion 8.1, Connections with CDMA multiuser detection

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
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