Algorithm Search⌘K

Algorithmcore

Successive interference cancellation

Also called SIC.

Decides the strongest user, subtracts its rebuilt signal, and repeats. With Gaussian codes and whole codewords decoded, the same idea reaches the corner points of the MAC capacity region.

Time
O(K^2 N) worst
Space
O(K^2) extra
Where
K = the number of users; N = the number of chips per symbol
Properties
deterministicerror propagationnot linearnot needs noise levelorder dependent
Origin
Pulin Patel, Jack M. Holtzman, 1994

Successive interference cancellation, or SIC, solves the multiuser detection problem one user at a time. It decides the strongest user with its matched filter, rebuilds that user's signal from the decision, subtracts it from the received signal, and repeats with the next strongest user on what is left. Each step faces fewer interferers than the one before, and the last user sees none. The cost is KK matched filters and KK subtractions, so SIC is much cheaper than the optimum detector and needs no matrix inverse. It works best when the users have very different powers, which is the case where the plain matched filter fails, the near-far problem. Its weakness is error propagation: a wrong decision doubles the interference it was meant to remove. In information theory the same idea, applied to whole codewords of Gaussian codes, reaches the corner points of the MAC capacity region, and it is the receiver of NOMA and of V-BLAST.

In plain words

When many people talk at once, the loudest voice is the easiest to understand. SIC listens to the loudest user first and decides what it said. It then knows what that user's signal looked like, so it takes it out of the recording. Now the second loudest user is the loudest one left, and it is easier to hear without the first. The receiver goes on in this way until it has heard everyone. The quietest user comes last, when nobody else is left to drown it out. If the receiver gets an early user wrong, it takes out the wrong signal, and that mistake makes the later users harder to hear.

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). The receiver knows the signatures, and it may or may not know the amplitudes. 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. SIC(z, R, A) ▷ A may be unknown
  2. 1π ← the users sorted by A_k, or by |z_k|, largest first
  3. 2for i ← 1 to K, with k = π_i
  4. 3x_k ← z_k - Σ_{l<i} R_{k π_l} â_{π_l} b̂_{π_l} ▷ cancel the users decided so far
  5. 4b̂_k ← sgn(x_k)
  6. 5â_k ← A_k if known, else |x_k|
  7. 6return b̂

Line L1 fixes the order. With known amplitudes it sorts by AkA_k; without them it sorts by ∣zk∣|z_k|, which is a rough measure of strength. Line L3 is the matched filter output of user kk after the rebuilt signals a^jb^jsj\hat a_j \hat b_j s_j of the earlier users are subtracted from yy: since sk⊤sj=Rkjs_k^\top s_j = R_{kj}, the subtraction can be done on zz with the crosscorrelations or directly on the NN chips of yy. Line L4 decides the bit, with +1+1 for a zero output. Line L5 keeps the amplitude used to rebuild the signal. With a^k=∣xk∣\hat a_k = |x_k|, the rebuilt signal is xkskx_k s_k, as in the scheme of Patel and Holtzman.

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 R12=0.5R_{12} = 0.5, R13=0.25R_{13} = 0.25 and R23=−0.25R_{23} = -0.25. 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. One noisy draw gave z=(−0.47,−4.21,2.18)z = (-0.47, -4.21, 2.18), and the matched filter decides user 1 wrong. With known amplitudes, line L1 gives the order 2, 3, 1:

step user line L3 xkx_k b^k\hat b_k
1 2 −4.21-4.21 −4.21-4.21 −1-1
2 3 2.18−(−0.25)(4)(−1)2.18 - (-0.25)(4)(-1) 1.181.18 +1+1
3 1 −0.47−(0.5)(4)(−1)−(0.25)(2)(+1)-0.47 - (0.5)(4)(-1) - (0.25)(2)(+1) 1.031.03 +1+1

All three decisions are right. With estimated amplitudes, x3=2.18−(−0.25)(−4.21)=1.13x_3 = 2.18 - (-0.25)(-4.21) = 1.13 and x1=−0.47−(0.5)(−4.21)−(0.25)(1.13)=1.35x_1 = -0.47 - (0.5)(-4.21) - (0.25)(1.13) = 1.35, also right here. In a simulation of 400,000 intervals with known amplitudes, user 1 erred at a rate of about 0.023, close to its single-user bound Q(2)=0.0228Q(2) = 0.0228, and user 3 at about 1.1×10−41.1 \times 10^{-4}, better than the decorrelator (2.7×10−42.7 \times 10^{-4}) and the MMSE detector (1.7×10−41.7 \times 10^{-4}). With estimated amplitudes the rates were about 0.18 and 5.6×10−45.6 \times 10^{-4}. The reason is that x2x_2 also holds R21A1b1R_{21} A_1 b_1, so subtracting R12x2R_{12} x_2 from user 1 also removes a quarter of user 1's own signal.

Correctness

Claim. Without noise and with known amplitudes, SIC decides every bit right if, in the order π\pi, each user is stronger than the interference of the users after it: Aπi>∑l>iAπl∣Rπiπl∣A_{\pi_i} > \sum_{l > i} A_{\pi_l} |R_{\pi_i \pi_l}| for every ii. With noise, the first user has the matched filter error rate, and user πi\pi_i errs with probability at most q1+⋯+qiq_1 + \cdots + q_i, where qlq_l is the matched filter error rate of user πl\pi_l in the system of the users πl,…,πK\pi_l, \ldots, \pi_K alone.

Key step. If the first i−1i - 1 decisions are right, line L3 removes their terms exactly, so xk=Akbk+∑l>iRkπlAπlbπl+nkx_k = A_k b_k + \sum_{l > i} R_{k \pi_l} A_{\pi_l} b_{\pi_l} + n_k, the matched filter output in a smaller system. Induction on ii gives both statements. The full proof is in the proofs folder.

The condition fails with equal powers. Three equal users with R12=R13=0.75R_{12} = R_{13} = 0.75 and b=(+1,−1,−1)b = (+1, -1, -1) give z1=−0.5z_1 = -0.5, a wrong first decision without any noise.

Proof: Successive cancellation decides every bit right without noise when each user dominates the users after it, and each stage sees a smaller systemfull

The model is y=SAb+wy = S A b + w for one symbol interval, with unit-norm signatures sks_k, amplitudes Ak>0A_k > 0, bits bk∈{−1,+1}b_k \in \{-1, +1\} and w∼N(0,σ2IN)w \sim \mathcal{N}(0, \sigma^2 I_N). 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 L1 fixes an order π1,…,πK\pi_1, \ldots, \pi_K of the users. In step ii of line L2, with k=πik = \pi_i, line L3 computes

xk=zk−∑l<iRkπl a^πl b^πl,(1)x_k = z_k - \sum_{l < i} R_{k \pi_l}\, \hat a_{\pi_l}\, \hat b_{\pi_l}, \tag{1}

line L4 sets b^k=sgn(xk)\hat b_k = \mathrm{sgn}(x_k), and line L5 sets a^k\hat a_k to the known AkA_k or to the estimate ∣xk∣|x_k|.

Lemma 1 (cancelling on z is cancelling on y). Let y(i)=y−∑l<ia^πlb^πlsπly^{(i)} = y - \sum_{l < i} \hat a_{\pi_l} \hat b_{\pi_l} s_{\pi_l} be the received vector after the first i−1i - 1 signals are rebuilt and subtracted. Then xπi=sπi⊤y(i)x_{\pi_i} = s_{\pi_i}^\top y^{(i)}.

Proof. sk⊤y(i)=sk⊤y−∑l<ia^πlb^πl sk⊤sπls_k^\top y^{(i)} = s_k^\top y - \sum_{l < i} \hat a_{\pi_l} \hat b_{\pi_l}\, s_k^\top s_{\pi_l}, and sk⊤y=zks_k^\top y = z_k, sk⊤sπl=Rkπls_k^\top s_{\pi_l} = R_{k \pi_l}. □\square

Lemma 2 (what step i sees). With known amplitudes, if the first i−1i - 1 decisions are right, then for k=πik = \pi_i

xk=Akbk+∑l>iRkπlAπlbπl+nk.(2)x_k = A_k b_k + \sum_{l > i} R_{k \pi_l} A_{\pi_l} b_{\pi_l} + n_k. \tag{2}

Proof. By Lemma 1, zk=Akbk+∑j≠kRkjAjbj+nkz_k = A_k b_k + \sum_{j \ne k} R_{kj} A_j b_j + n_k. With a^πl=Aπl\hat a_{\pi_l} = A_{\pi_l} and b^πl=bπl\hat b_{\pi_l} = b_{\pi_l} for l<il < i, (1) removes exactly the terms of the users decided before kk. □\square

So (2) is the matched filter output of user kk in a smaller system that holds only the users πi,…,πK\pi_i, \ldots, \pi_K. The first user, π1\pi_1, is decided by its plain matched filter.

Theorem 1 (no noise). Let w=0w = 0 and the amplitudes be known. If

Aπi>∑l>iAπl∣Rπiπl∣for every i=1,…,K,(3)A_{\pi_i} > \sum_{l > i} A_{\pi_l} |R_{\pi_i \pi_l}| \quad \text{for every } i = 1, \ldots, K, \tag{3}

then every decision is right.

Proof. By induction on ii. Assume the first i−1i - 1 decisions are right. By (2) with n=0n = 0, xk=Akbk+ex_k = A_k b_k + e with ∣e∣≤∑l>iAπl∣Rkπl∣<Ak|e| \le \sum_{l > i} A_{\pi_l} |R_{k \pi_l}| < A_k by (3). So xkx_k has the sign of bkb_k, and line L4 decides bkb_k. The case i=1i = 1 needs no assumption on earlier steps. □\square

Condition (3) is the reason line L1 orders the users by decreasing amplitude: the strongest user must beat the interference of all the others, but the last user faces no interference at all. Condition (3) holds for any correlations when the amplitudes grow fast enough, for example when Aπi>∑l>iAπlA_{\pi_i} > \sum_{l > i} A_{\pi_l}. With equal amplitudes it can fail: three users with R12=R13=0.75R_{12} = R_{13} = 0.75 and b=(+1,−1,−1)b = (+1, -1, -1) give z1=1−0.75−0.75=−0.5z_1 = 1 - 0.75 - 0.75 = -0.5, a wrong first decision without noise.

Theorem 2 (with noise). With known amplitudes, let qiq_i be the error probability of the matched filter decision sgn(Akbk+∑l>iRkπlAπlbπl+nk)\mathrm{sgn}(A_k b_k + \sum_{l > i} R_{k \pi_l} A_{\pi_l} b_{\pi_l} + n_k), k=πik = \pi_i, in the smaller system of Lemma 2:

qi=2−(K−i)∑bπi+1,…,bπKQ(Ak+∑l>iRkπlAπlbπlσ).q_i = 2^{-(K - i)} \sum_{b_{\pi_{i+1}}, \ldots, b_{\pi_K}} Q\Big( \frac{A_k + \sum_{l > i} R_{k \pi_l} A_{\pi_l} b_{\pi_l}}{\sigma} \Big).

Then user π1\pi_1 has the error probability q1q_1 exactly, and user πi\pi_i has an error probability of at most q1+q2+⋯+qiq_1 + q_2 + \cdots + q_i.

Proof. The decision on π1\pi_1 is sgn(zπ1)\mathrm{sgn}(z_{\pi_1}), and nk∼N(0,σ2)n_k \sim \mathcal{N}(0, \sigma^2) because Rkk=1R_{kk} = 1. Averaging QQ over the other bits, as in the proof for any matched filter, gives q1q_1. For i>1i > 1, let ElE_l be the event that the matched filter statistic of (2) for user πl\pi_l has the wrong sign. If all of E1,…,Ei−1E_1, \ldots, E_{i-1} fail, then by induction the first i−1i - 1 decisions are right: on that event each xπlx_{\pi_l} equals the statistic of (2). Then xπix_{\pi_i} also equals its statistic in (2), so user πi\pi_i errs only if EiE_i occurs. Hence the error event of user πi\pi_i lies in E1∪⋯∪EiE_1 \cup \cdots \cup E_i, and P(El)=qlP(E_l) = q_l. □\square

The bound shows the main weakness of the method: one wrong decision doubles the interference it was meant to remove, since b−b^=2bb - \hat b = 2b, and the error propagates to every later user.

Remark (estimated amplitudes). With a^k=∣xk∣\hat a_k = |x_k|, the estimate of Patel and Holtzman, a^kb^k=xk\hat a_k \hat b_k = x_k, so (1) subtracts RjkxkR_{jk} x_k from a later user jj instead of RjkAkbkR_{jk} A_k b_k. When b^k\hat b_k is right, the difference is RjkR_{jk} times the interference and noise left in xkx_k. This is small when the correlations are small, but it is not zero, so the theorems above hold for this form only approximately.

Remark (capacity, cited). With Gaussian codebooks, decoding each user's whole codeword and cancelling the re-encoded codeword reaches the corner points of the capacity region of the Gaussian multiple access channel. That statement concerns codewords decoded with a vanishing error probability, not single bits decided by their sign; see Tse and Viswanath, Section 6.1.1.

Remark (the cost). Line L1 sorts in O(Klog⁡K)O(K \log K), and step ii of line L3 costs O(i)O(i), so the loop costs O(K2)O(K^2) after zz and RR, which cost O(KN)O(K N) and O(K2N)O(K^2 N). Done on yy as in Lemma 1, each step correlates and subtracts NN chips, and the whole detector costs O(KN)O(K N) without forming RR.

Complexity

With zz and RR, which cost O(KN)O(K N) and O(K2N)O(K^2 N), line L1 costs O(Klog⁡K)O(K \log K) and step ii of line L3 costs O(i)O(i), so the loop costs O(K2)O(K^2) in the real RAM. Done on the chips, each step correlates NN chips with sks_k and subtracts NN chips, so the whole detector costs O(KN+Klog⁡K)O(K N + K \log K) without forming RR. The steps are sequential, so the delay grows with KK.

Properties

  • Ordered. The result depends on the order. Deciding a weak user first fails, since it faces the full interference of the strong users.
  • Benefits from unequal powers. The more the powers differ, the better the condition of the claim holds. Equal powers are the worst case.
  • Error propagation. A wrong decision gives b−b^=2bb - \hat b = 2b in the residual, which doubles that user's interference on all later users.
  • No matrix inverse and no noise level. It needs the signatures, and the amplitudes or their estimates.
  • The first user sees all the interference. It is decided by its matched filter, so its error rate depends on the other users' powers and bits.
  • Capacity achieving at the codeword level. With Gaussian codebooks, decoding whole codewords in order and subtracting them reaches the corner points of the capacity region of the Gaussian multiple access channel, and time sharing between orders gives the rest of the dominant face (Tse and Viswanath, Section 6.1.1). That result needs codes with a vanishing error probability, not single bits decided by their sign.

Variants and improvements

  • MMSE-SIC. Replace the matched filter in each step by an MMSE filter against the users not yet decided. With Gaussian codes this reaches the sum capacity, and it is the receiver of V-BLAST.
  • Decorrelating decision feedback. Whiten with the Cholesky factor of RR and cancel in order; it is the multiuser form of the decision feedback equalizer.
  • Soft cancellation. Subtract a^ktanh⁡(⋅)\hat a_k \tanh(\cdot) or a clipped value instead of a hard decision, which limits the damage of a wrong decision.
  • Power allocation for SIC. Choose the powers so that each user's SINR, after the users before it are removed, meets a target; this is the design rule of power domain NOMA.
  • Parallel form. Cancel all users at once in stages, which is parallel interference cancellation.

When to use it

Use SIC when the users have very different received powers, when the receiver must be cheap, or when the users send coded data that can be decoded and re-encoded before subtraction, as in NOMA and in uplink receivers. Do not use it when the powers are almost equal and the correlations are large; then a linear detector or parallel cancellation started from a linear detector is safer.

Pitfalls

  • Wrong order. Sorting by ∣zk∣|z_k| in a single interval is noisy. Average the strength over many intervals before ordering.
  • Amplitude estimates that hold the user's own signal. ∣xk∣|x_k| also holds interference and noise, and subtracting xkskx_k s_k can remove part of a later user's own signal, as the example shows.
  • Error propagation. One wrong early decision spoils the later users. Use soft decisions or decoded codewords when the error rate of the first users is not small.
  • Latency. The KK steps run in sequence. For many users, group the users and cancel each group in parallel.
  • Reading the capacity result as a bit-level fact. Corner-point optimality holds for whole Gaussian codewords, not for the uncoded sign decisions of this page.

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))
successive_interference_cancellation.py 77 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/successive-interference-cancellation/. The authors are listed in prov/TZZ989.jsonl.

"""Successive interference cancellation (SIC) 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 detector decides the users one at a time, strongest first. After each
decision it rebuilds that user's signal A_k b_k s_k and subtracts it from y,
so the next user sees less interference. Subtracting in the chip domain and
then correlating with s_k gives the same number as subtracting R_kj A_j b_j
from the matched filter output z_k, so the work is done on z and R.
"""

import math


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 sic(z: list[float], r: list[list[float]], amps: list[float] | None = None, order: list[int] | None = None) -> tuple[list[int], list[int]]:
    """SIC on the matched filter outputs z with crosscorrelations r.

    With amps given, the users go in order of decreasing amplitude and the
    known amplitude is used to rebuild each signal. With amps None, the users
    go in order of decreasing |z_k| and the amplitude of each user is
    estimated as |x|, the magnitude of its output after cancellation (the
    estimate of Patel and Holtzman). An explicit order overrides both rules.
    Returns (decisions, order).
    """
    k_users = len(z)
    if amps is not None and (len(amps) != k_users or any(a <= 0.0 for a in amps)):
        raise ValueError("need one positive amplitude per user")
    if order is None:
        key = amps if amps is not None else [abs(v) for v in z]
        order = sorted(range(k_users), key=lambda u: -key[u])  # @line L1
    if sorted(order) != list(range(k_users)):
        raise ValueError("order must be a permutation of the users")
    b = [0] * k_users
    est = [0.0] * k_users
    done: list[int] = []
    for k in order:  # @line L2
        x = z[k] - math.fsum(r[k][j] * est[j] * b[j] for j in done)  # @line L3
        b[k] = 1 if x >= 0.0 else -1  # @line L4
        est[k] = amps[k] if amps is not None else abs(x)  # @line L5
        done.append(k)
    return b, order  # @line L6


def sic_detector(y: list[float], sigs: list[list[float]], amps: list[float] | None = None) -> list[int]:
    """The SIC decisions for the chip samples y."""
    z = matched_filter(y, sigs)
    r = crosscorrelation(sigs)
    return sic(z, r, amps)[0]


def sic_chip_domain(y: list[float], sigs: list[list[float]], amps: list[float]) -> list[int]:
    """The same detector with known amplitudes, written as subtraction of waveforms from y."""
    k_users = len(sigs)
    order = sorted(range(k_users), key=lambda u: -amps[u])
    res = list(y)
    b = [0] * k_users
    for k in order:
        x = math.fsum(a * c for a, c in zip(sigs[k], res))
        b[k] = 1 if x >= 0.0 else -1
        res = [v - amps[k] * b[k] * c for v, c in zip(res, sigs[k])]
    return b
test_successive_interference_cancellation.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/successive-interference-cancellation/. The authors are listed in prov/TZZ989.jsonl.

import itertools
import math
import random

import pytest

import cbb
import constel
from successive_interference_cancellation import (
    crosscorrelation,
    matched_filter,
    sic,
    sic_chip_domain,
    sic_detector,
)

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]
    z = matched_filter(chips(S_PAGE, AMPS, b), S_PAGE)
    r = crosscorrelation(S_PAGE)
    assert [round(v, 12) for v in z] == [-0.5, -4.0, 3.25]
    dec, order = sic(z, r, AMPS)
    assert order == [1, 2, 0]
    assert dec == b
    # Without the amplitudes the order comes from |z| and the estimates are |x|.
    dec, order = sic(z, r)
    assert order == [1, 2, 0]
    assert dec == b


def test_chip_domain_and_matched_filter_domain_agree() -> None:
    rng = random.Random(4401)
    for _ in range(200):
        k = rng.randint(1, 6)
        sigs = random_sigs(rng, k, 8)
        amps = [rng.uniform(0.2, 5.0) for _ in range(k)]
        b = [rng.choice((1, -1)) for _ in range(k)]
        y = chips(sigs, amps, b, 0.7, rng)
        assert sic_detector(y, sigs, amps) == sic_chip_domain(y, sigs, amps)


def test_noiseless_correct_under_dominance() -> None:
    # If A_k > sum over the users j after k of A_j |R_kj| for every k, then SIC
    # with known amplitudes decides every bit right when there is no noise.
    rng = random.Random(4402)
    checked = 0
    while checked < 300:
        k = rng.randint(1, 6)
        sigs = random_sigs(rng, k, 8)
        r = crosscorrelation(sigs)
        amps = sorted((rng.uniform(0.1, 1.0) * 3.0 ** rng.randint(0, 4) for _ in range(k)), reverse=True)
        if any(amps[u] <= math.fsum(amps[j] * abs(r[u][j]) for j in range(u + 1, k)) for u in range(k)):
            continue
        checked += 1
        for b in itertools.product((1, -1), repeat=k):
            assert sic_detector(chips(sigs, amps, list(b)), sigs, amps) == list(b)


def test_equal_powers_can_fail_without_noise() -> None:
    s1 = [R8] * 8
    s2 = [R8] * 7 + [-R8]
    s3 = [-R8] + [R8] * 7
    sigs = [s1, s2, s3]
    r = crosscorrelation(sigs)
    assert [round(r[0][1], 12), round(r[0][2], 12)] == [0.75, 0.75]
    b = [1, -1, -1]
    y = chips(sigs, [1.0, 1.0, 1.0], b)
    assert sic_detector(y, sigs, [1.0, 1.0, 1.0])[0] == -1


def test_weak_user_first_fails_without_noise() -> None:
    s1 = S_PAGE[0]
    s2 = S_PAGE[1]
    amps = [1.0, 4.0]
    b = [1, -1]
    z = matched_filter(chips([s1, s2], amps, b), [s1, s2])
    r = crosscorrelation([s1, s2])
    assert sic(z, r, amps)[0] == b
    assert sic(z, r, amps, order=[0, 1])[0] == [-1, -1]


def test_first_user_has_the_matched_filter_error_rate() -> None:
    # Seed 4403: the strongest user is decided before any cancellation, so its
    # error rate is the exact matched filter rate; about 150 errors are expected.
    rng = random.Random(4403)
    amps = [1.0, 1.5, 0.8]
    sigma = 0.8
    r = crosscorrelation(S_PAGE)
    k = 1
    p = 0.0
    for b1, b3 in itertools.product((1, -1), repeat=2):
        p += cbb.qfunc((amps[1] + r[1][0] * amps[0] * b1 + r[1][2] * amps[2] * b3) / sigma) / 4
    trials = 2500
    assert p * trials >= 100
    errors = 0
    for _ in range(trials):
        b = [rng.choice((1, -1)) for _ in range(3)]
        errors += sic_detector(chips(S_PAGE, amps, b, sigma, rng), S_PAGE, amps)[k] != b[k]
    lo, hi = cbb.wilson(errors, trials)
    assert lo <= p <= hi


def test_agrees_with_ml_most_of_the_time_with_spread_powers() -> None:
    # Seed 4404: amplitudes 3 times apart and sigma = 0.2; SIC with known
    # amplitudes gives the ML decisions on at least 90 percent of 300 vectors.
    rng = random.Random(4404)
    pts = constel.pam(2)
    same = 0
    trials = 300
    for _ in range(trials):
        k = rng.randint(2, 5)
        sigs = random_sigs(rng, k, 8)
        amps = [3.0 ** u for u in range(k)]
        rng.shuffle(amps)
        b = [rng.choice((1, -1)) for _ in range(k)]
        y = chips(sigs, amps, b, 0.2, 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 += sic_detector(y, sigs, amps) == ml
    assert same >= 0.90 * trials


def test_errors() -> None:
    with pytest.raises(ValueError):
        sic([1.0, 2.0], [[1.0, 0.0], [0.0, 1.0]], [1.0])
    with pytest.raises(ValueError):
        sic([1.0, 2.0], [[1.0, 0.0], [0.0, 1.0]], [1.0, -1.0])
    with pytest.raises(ValueError):
        sic([1.0, 2.0], [[1.0, 0.0], [0.0, 1.0]], order=[0, 0])

History

The idea of decoding one user, subtracting it, and decoding the next is old in information theory, where successive decoding is the standard proof that the corner points of the multiple access capacity region are achievable. For uncoded direct-sequence CDMA, Patel and Holtzman analyzed a simple scheme in 1994 that orders the users by their matched filter outputs and uses those outputs as amplitude estimates. Verdú's 1998 book treats SIC among the decision-driven detectors. In the 2010s, SIC became the receiver of power domain NOMA, where the transmitter assigns the powers to make the cancellation order work.

References

  1. Pulin Patel and Jack M. Holtzman, Analysis of a simple successive interference cancellation scheme in a DS/CDMA system, IEEE Journal on Selected Areas in Communications 12(5), 1994, pp. 796 to 807 (the scheme, its amplitude estimates, and its error analysis)
  2. Sergio Verdú, Multiuser Detection, Cambridge University Press, 1998, Chapter 7, Decision-driven multiuser detectors
  3. David Tse and Pramod Viswanath, Fundamentals of Wireless Communication, Cambridge University Press, 2005, Section 6.1.1, Capacity via successive interference cancellation, and Section 8.3.2, MMSE-SIC

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