Algorithmadvanced
Parallel interference cancellation
Also called multistage interference cancellation.
Decides all users at once, subtracts each user's rebuilt interference from every other user, and repeats in stages; right decisions are a fixed point, but the stages can oscillate.
- Solves
- Multiuser detection
- Time
- O(K^2 N + J K^2) worst
- Space
- O(K^2) extra
- Where
- J = the number of stages; K = the number of users; N = the number of chips per symbol
- Model
- Real RAM
- Properties
- not always convergesdeterministiciterativenot linearneeds amplitudesnot needs noise level
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mahesh K. Varanasi, Behnaam Aazhang, 1990
Parallel interference cancellation, or PIC, solves the multiuser detection problem in stages. Stage 0 decides every user, usually with its matched filter. Each later stage rebuilds the signals of all users from the previous decisions, subtracts from each user the rebuilt signals of all the others, and decides again. All users are handled at the same time, so a stage has the delay of one cancellation, unlike successive interference cancellation, which handles the users one after another. If the decisions of a stage are all right, the next stage sees no interference at all and stays at the right answer. The method is not guaranteed to get there: a wrong decision doubles the interference it should remove, and with high correlations the stages can oscillate for ever, even without noise. A good first stage, such as the decorrelating detector, helps a lot. Without the sign decisions, PIC is the Jacobi method for , and it converges to the decorrelator when the eigenvalues of lie between 0 and 2.
In plain words
Every user's signal leaks a little into the receivers of the other users. PIC first makes a rough guess of what every user sent. Then, for each user, it takes out the leak that the guessed signals of all the other users would cause, and guesses again. It does this for all users at once and repeats a few times. If the guesses are right, taking out the leaks leaves each user alone with its noise, and the guesses stay right. If a guess is wrong, the receiver takes out the wrong leak, which makes things worse for the others. With strongly overlapping users, the guesses can flip back and forth and never settle.
The problem
User sends one bit per symbol interval with amplitude and a signature of chips with . The users are synchronous, so the received chips in one interval are , with , and . The receiver knows the signatures and the amplitudes. The output is a decision for each user. The matched filter outputs are , with and .
The algorithm
PIC(z, R, A, J, b̂⁰) ▷ b̂⁰ defaults to sgn(z)- 1
b̂ ← b̂⁰ ▷ stage 0 - 2
repeat J times - 3
for every user k, at the same time - 4
x_k ← z_k - Σ_{j≠k} R_kj A_j b̂_j ▷ cancel all other users - 5
b̂'_k ← sgn(x_k) - 6
b̂ ← b̂' ▷ all users change together - 7
return b̂
Line L1 takes the first decisions, by default the matched filter signs; the decorrelator decisions are a better start. Lines L3 to L5 compute the new decision of every user from the old decisions of the others. Line L4 is the matched filter output of user after the rebuilt signals of all other users are subtracted from . Line L6 replaces all the decisions at once; using a new decision as soon as it is made would give a Gauss-Seidel form, which is a different method. Line L5 takes for a zero output.
Example
Three users with chips use , and , so , and . The amplitudes are , the bits are , and . One noisy draw gave .
| stage | decisions | |||
|---|---|---|---|---|
| 0 | , from | |||
| 1 | ||||
| 2 |
At stage 1, user 1 gets , because the strong user 2 was decided right at stage 0. User 2 still carries the wrong stage 0 decision on user 1, so , but it is strong enough to stay right. The stage 1 decisions are all right, so from stage 2 on each is and nothing changes.
The stages can also fail. Take two users with , , and no noise. Then , and the stages give , , , and so on for ever.
Correctness
Claim. If the decisions of a stage are all right, then at the next stage for every user, so without noise all later stages stay right, and with noise each user decides with the single-user error rate . For two users without noise and , stage 1 is right for both users when . In general the stages need not converge.
Key step. At stage , , where holds the decisions of stage . Each term is 0 for a right decision and for a wrong one. The full proof, with the oscillation example and the Jacobi form, is in the proofs folder.
Proof: Right decisions are a fixed point of parallel cancellation, the stages can oscillate, and the linear form is Jacobi iteration toward the decorrelatorfull
The model is for one symbol interval, with unit-norm signatures , known amplitudes , bits and . Let and , with . Line L1 sets the stage 0 decisions . Lines L3 to L5 compute, for every user at the same time,
Lemma 1 (what stage m sees). For every stage ,
Proof. Substitute into (1).
Each term is 0 for a right decision and for a wrong one. So a stage removes the interference of the users that the previous stage decided right, and doubles the interference of the users it decided wrong.
Theorem 1 (right decisions are a fixed point). If , then for every , with . Without noise, , and all later stages stay at . With noise, each user then errs with probability , the single-user error rate.
Proof. All terms of the sum in (2) vanish. , so has variance . Without noise, , and induction on gives the rest.
Corollary (decorrelator start). If the signatures are linearly independent and , the decorrelating detector decides exactly, so a PIC that starts from it stays at for every stage.
Theorem 2 (two users without noise). Let , , , and label the users so that . If , then stage 1 is right for both users, and so is every later stage.
Proof. At stage 0, and , so . By (2), , so . Also , and the second term has absolute value at most , so . Theorem 1 does the rest.
Theorem 3 (the stages can oscillate, even without noise). Take , , , and . Then the stages alternate between and and never reach .
Proof. , so . From , (1) gives , so the next stage is . From , (1) gives , so the next stage is again.
Here , so Theorem 2 does not apply. The stage 0 error on the weak user doubles its interference on the strong user, and each user's error then flips the other.
Theorem 4 (linear PIC is Jacobi iteration). Remove the sign: let and . If is invertible, then
So , the decorrelator output, for every if and only if the spectral radius of is less than 1, that is, if and only if every eigenvalue of lies in the open interval .
Proof. The update is the Jacobi method for , because the diagonal of is the identity. Let . Since , subtracting gives , and gives the first formula. The second follows by unrolling the update. is symmetric, so tends to 0 for every if and only if all its eigenvalues have absolute value less than 1.
For the three users of the page, has the eigenvalues and , so its spectral radius is , and the error shrinks by that factor at each stage. For three users with all correlations , has the eigenvalue , and linear PIC diverges.
Remark (the cost). Each stage computes sums of terms, so stages cost after and , which cost and . Done on , a stage rebuilds the sum of the signals once and subtracts it, at per stage.
Complexity
With and , which cost and , each stage computes sums of terms, so stages cost in the real RAM. Done on the chips, a stage rebuilds the sum of all signals once, at , and gives each user the sum minus its own signal; this avoids . The users in one stage are independent, so a stage runs in parallel on processors.
Properties
- Right decisions are a fixed point. From there every user sees only its own signal and noise.
- Error doubling. A wrong decision on user adds to user , twice the interference that the matched filter sees.
- No convergence guarantee. The stages can cycle, as the two-user example shows. In practice two to four stages are used.
- Needs amplitudes. The rebuilt signals need , or estimates of it.
- Linear form. Removing the signs gives , the Jacobi iteration for . It tends to if and only if every eigenvalue of lies in . For the example, the spectral radius of is . Three users with all correlations 0.6 give the eigenvalue 2.2, and the linear form diverges.
- Low delay. All users are processed together, so the delay is cancellations, not .
Variants and improvements
- Decorrelator first stage. Varanasi and Aazhang start from the decorrelator. Without noise its decisions are already right, so the later stages keep them.
- Partial cancellation. Subtract only a fraction of the rebuilt interference at early stages, with growing toward 1. This limits the damage of wrong early decisions.
- Soft decisions. Rebuild with or a clipped value instead of the sign, which also limits error doubling.
- Linear multistage detectors. Truncating the series or using a better polynomial in gives an approximation of the decorrelator or the MMSE detector without a matrix inverse.
- Group-wise and hybrid forms. Cancel successively between groups of users and in parallel within a group.
- Iterative receivers for coded data. Replace the sign by a soft decoder output, which leads to turbo multiuser detection.
When to use it
Use PIC when the delay of successive cancellation is too large, when the hardware can process all users in parallel, and when the powers are similar, where SIC orders badly. Start from a decorrelator or an MMSE detector when the correlations are large, and stop after a small fixed number of stages.
Pitfalls
- Assuming convergence. The stages can cycle. Fix the number of stages, or stop when two stages agree.
- Poor first stage with a strong interferer. A wrong matched filter decision on a strong user doubles a large interference term. Start from a linear detector in near-far conditions.
- Gauss-Seidel by accident. Writing the new decisions into the same array during a stage gives a different, successive update. Keep the old decisions until the stage ends.
- Wrong amplitudes. Rebuilt signals with wrong amplitudes leave residual interference on every user at every stage.
- The linear form with large correlations. It diverges when an eigenvalue of is 2 or more, which can happen with many correlated users.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the communications pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Complex baseband tools for the communications pages.
Vectors are lists of complex numbers. Matrices are lists of rows. The
functions here are plain building blocks: small linear algebra, convolution,
the DFT as a direct sum, the Gaussian Q function, dB conversion, complex
Gaussian noise and the Wilson score interval. No page algorithm (equalizer,
estimator, synchronizer, detector, precoder, demapper or power allocation)
lives in this file.
Conventions (prompts of the communications area):
- dft is X[k] = sum_n x[n] e^(-j 2 pi k n / N) with no factor; idft has 1/N.
- udft and uidft are the unitary pair, with 1/sqrt(N) on both sides.
- qfunc(x) = 0.5 erfc(x / sqrt(2)); it never computes 1 - Phi(x).
- cn(rng, var) draws CN(0, var): real and imaginary parts are independent
with variance var / 2 each, so E|w|^2 = var.
"""
import cmath
import math
import random
# ---------------------------------------------------------------- vectors and matrices
def zeros(rows: int, cols: int | None = None) -> list:
"""A zero vector of length rows, or a rows by cols zero matrix."""
if cols is None:
return [0j] * rows
return [[0j] * cols for _ in range(rows)]
def eye(n: int) -> list[list[complex]]:
"""The n by n identity matrix."""
return [[1 + 0j if i == k else 0j for k in range(n)] for i in range(n)]
def add(a: list, b: list) -> list:
"""Elementwise a + b for two vectors or two matrices of the same shape."""
if len(a) != len(b):
raise ValueError("shapes differ")
if a and isinstance(a[0], list):
return [add(r, s) for r, s in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a: list, b: list) -> list:
"""Elementwise a - b for two vectors or two matrices of the same shape."""
if len(a) != len(b):
raise ValueError("shapes differ")
if a and isinstance(a[0], list):
return [sub(r, s) for r, s in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(c: complex, a: list) -> list:
"""The scalar c times a vector or a matrix."""
if a and isinstance(a[0], list):
return [scale(c, r) for r in a]
return [c * x for x in a]
def matmul(a: list[list[complex]], b: list[list[complex]]) -> list[list[complex]]:
"""The matrix product a b."""
if not a or not b or len(a[0]) != len(b):
raise ValueError("inner dimensions differ")
cols = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in cols] for row in a]
def matvec(a: list[list[complex]], x: list[complex]) -> list[complex]:
"""The matrix times vector product a x."""
if a and len(a[0]) != len(x):
raise ValueError("inner dimensions differ")
return [sum(p * q for p, q in zip(row, x)) for row in a]
def herm(a: list) -> list:
"""The conjugate transpose of a matrix. A vector gives its conjugate."""
if a and isinstance(a[0], list):
return [[complex(a[i][k]).conjugate() for i in range(len(a))] for k in range(len(a[0]))]
return [complex(x).conjugate() for x in a]
def dot(x: list[complex], y: list[complex]) -> complex:
"""The inner product x^H y = sum of conj(x_i) y_i."""
if len(x) != len(y):
raise ValueError("lengths differ")
return sum(complex(p).conjugate() * q for p, q in zip(x, y))
def norm2(x: list) -> float:
"""The squared Euclidean norm sum |x_i|^2 (squared Frobenius norm for a matrix)."""
if x and isinstance(x[0], list):
return sum(norm2(r) for r in x)
return sum(abs(v) ** 2 for v in x)
# ---------------------------------------------------------------- linear systems
def _lu(a: list[list[complex]]) -> tuple[list[list[complex]], list[int], int]:
"""LU factorization with partial pivoting. Returns (lu, perm, sign)."""
n = len(a)
if any(len(r) != n for r in a):
raise ValueError("matrix is not square")
m = [[complex(v) for v in r] for r in a]
perm = list(range(n))
sign = 1
for k in range(n):
p = max(range(k, n), key=lambda i: abs(m[i][k]))
if abs(m[p][k]) == 0.0:
raise ValueError("matrix is singular")
if p != k:
m[k], m[p] = m[p], m[k]
perm[k], perm[p] = perm[p], perm[k]
sign = -sign
for i in range(k + 1, n):
f = m[i][k] / m[k][k]
m[i][k] = f
if f != 0:
rk, ri = m[k], m[i]
for c in range(k + 1, n):
ri[c] -= f * rk[c]
return m, perm, sign
def _lu_solve(lu: list[list[complex]], perm: list[int], b: list[complex]) -> list[complex]:
n = len(lu)
y = [complex(b[perm[i]]) for i in range(n)]
for i in range(n):
for c in range(i):
y[i] -= lu[i][c] * y[c]
for i in range(n - 1, -1, -1):
for c in range(i + 1, n):
y[i] -= lu[i][c] * y[c]
y[i] /= lu[i][i]
return y
def solve(a: list[list[complex]], b: list) -> list:
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector, or a matrix whose columns are right-hand sides.
Raises ValueError if a is singular.
"""
lu, perm, _ = _lu(a)
if b and isinstance(b[0], list):
cols = [list(c) for c in zip(*b)]
xs = [_lu_solve(lu, perm, c) for c in cols]
return [list(r) for r in zip(*xs)]
if len(b) != len(a):
raise ValueError("lengths differ")
return _lu_solve(lu, perm, b)
def inv(a: list[list[complex]]) -> list[list[complex]]:
"""The inverse of a square matrix."""
return solve(a, eye(len(a)))
def det(a: list[list[complex]]) -> complex:
"""The determinant of a square matrix (0 for a singular matrix)."""
try:
lu, _, sign = _lu(a)
except ValueError as e:
if "singular" in str(e):
return 0j
raise
d = complex(sign)
for i in range(len(lu)):
d *= lu[i][i]
return d
def cholesky(a: list[list[complex]]) -> list[list[complex]]:
"""The lower triangular L with a = L L^H, for a Hermitian positive definite a.
Raises ValueError if a is not positive definite (to rounding).
"""
n = len(a)
low = zeros(n, n)
for i in range(n):
for k in range(i + 1):
s = complex(a[i][k]) - sum(low[i][c] * low[k][c].conjugate() for c in range(k))
if i == k:
if s.real <= 0.0:
raise ValueError("matrix is not positive definite")
low[i][i] = complex(math.sqrt(s.real))
else:
low[i][k] = s / low[k][k].real
return low
# ---------------------------------------------------------------- convolution and the DFT
def conv(a: list[complex], b: list[complex]) -> list[complex]:
"""Linear convolution, of length len(a) + len(b) - 1."""
if not a or not b:
return []
out = [0j] * (len(a) + len(b) - 1)
for i, x in enumerate(a):
for k, y in enumerate(b):
out[i + k] += x * y
return out
def cconv(a: list[complex], b: list[complex], n: int | None = None) -> list[complex]:
"""Circular convolution of length n (default: the longer length).
Both inputs are padded with zeros to length n, or must not be longer than n.
"""
if n is None:
n = max(len(a), len(b))
if len(a) > n or len(b) > n:
raise ValueError("input longer than n")
out = [0j] * n
for i, x in enumerate(a):
for k, y in enumerate(b):
out[(i + k) % n] += x * y
return out
def _twiddles(n: int, sign: int) -> list[complex]:
return [cmath.exp(sign * 2j * math.pi * t / n) for t in range(n)]
def dft(x: list[complex]) -> list[complex]:
"""X[k] = sum over n of x[n] e^(-j 2 pi k n / N), as a direct O(N^2) sum."""
n = len(x)
w = _twiddles(n, -1)
return [sum(x[t] * w[(k * t) % n] for t in range(n)) for k in range(n)]
def idft(xf: list[complex]) -> list[complex]:
"""x[n] = (1/N) sum over k of X[k] e^(j 2 pi k n / N), the inverse of dft."""
n = len(xf)
w = _twiddles(n, 1)
return [sum(xf[k] * w[(k * t) % n] for k in range(n)) / n for t in range(n)]
def udft(x: list[complex]) -> list[complex]:
"""The unitary DFT: dft(x) / sqrt(N)."""
s = 1.0 / math.sqrt(len(x)) if x else 1.0
return [v * s for v in dft(x)]
def uidft(xf: list[complex]) -> list[complex]:
"""The unitary inverse DFT: sqrt(N) idft(X), the inverse of udft."""
s = math.sqrt(len(xf)) if xf else 1.0
return [v * s for v in idft(xf)]
# ---------------------------------------------------------------- Q function and dB
def qfunc(x: float) -> float:
"""Q(x) = P(Z > x) for a standard normal Z, computed as 0.5 erfc(x / sqrt(2))."""
return 0.5 * math.erfc(x / math.sqrt(2.0))
def qinv(p: float) -> float:
"""The x with Q(x) = p, for 0 < p < 1, by bisection on Q (which decreases)."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
lo, hi = -40.0, 40.0
for _ in range(200):
mid = 0.5 * (lo + hi)
if qfunc(mid) > p:
lo = mid
else:
hi = mid
if hi - lo <= 1e-15 * max(1.0, abs(mid)):
break
return 0.5 * (lo + hi)
def db(x: float) -> float:
"""10 log10(x), for a ratio of powers or energies."""
return 10.0 * math.log10(x)
def undb(d: float) -> float:
"""10^(d / 10), the inverse of db."""
return 10.0 ** (d / 10.0)
# ---------------------------------------------------------------- noise and statistics
def cn(rng: random.Random, var: float) -> complex:
"""One sample of CN(0, var): independent real and imaginary parts of variance var / 2."""
s = math.sqrt(var / 2.0)
return complex(rng.gauss(0.0, s), rng.gauss(0.0, s))
def awgn(rng: random.Random, x: list[complex], n0: float) -> list[complex]:
"""x plus independent CN(0, n0) noise on each sample."""
return [v + cn(rng, n0) for v in x]
def wilson(k: int, n: int, z: float = 3.29) -> tuple[float, float]:
"""The Wilson score interval for k successes in n trials (z = 3.29 is about 0.999 two-sided)."""
if n <= 0 or not 0 <= k <= n:
raise ValueError("need 0 <= k <= n and n > 0")
p = k / n
z2 = z * z
den = 1.0 + z2 / n
mid = (p + z2 / (2 * n)) / den
half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / den
return max(0.0, mid - half), min(1.0, mid + half)
constel.py 117 lines
# SPDX-License-Identifier: MIT
# Shared helper of the communications pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Constellations, Gray labels and brute-force maximum likelihood detection.
Each constellation function returns a list of M complex points with unit
average energy, ordered by label: points[i] is the point whose bit label is
the integer i, and bits(i, log2 M) gives that label, most significant bit
first. The labels follow the communications area rules:
- M-PAM: the point with amplitude index m = 0, ..., M-1 (raw amplitude
M - 1 - 2m, from the most positive) gets the Gray label gray(m).
So 2-PAM maps bit 0 to +1 and bit 1 to -1.
- Square M-QAM, M = 4^k: the label is the in-phase PAM label followed by the
quadrature PAM label, each of log2(sqrt(M)) bits.
- M-PSK: the point e^(j(2 pi m / M + phase0)) gets the label gray(m).
PAM points are returned as complex numbers with zero imaginary part.
This file imports nothing from cbb.py. It holds no demapper: soft and
max-log demapping are algorithm pages of their own.
"""
import cmath
import itertools
import math
def gray(n: int) -> int:
"""The binary reflected Gray code of n: n XOR (n >> 1)."""
return n ^ (n >> 1)
def _gray_inv(g: int) -> int:
n = 0
while g:
n ^= g
g >>= 1
return n
def bits(i: int, m: int) -> list[int]:
"""The m bits of the integer i, most significant bit first."""
if i < 0 or i >= 1 << m:
raise ValueError("i does not fit in m bits")
return [(i >> (m - 1 - t)) & 1 for t in range(m)]
def _log2(m: int) -> int:
if m < 2 or m & (m - 1):
raise ValueError("M must be a power of two, at least 2")
return m.bit_length() - 1
def pam(m: int) -> list[complex]:
"""Unit-energy M-PAM, ordered by Gray label."""
_log2(m)
s = math.sqrt((m * m - 1) / 3.0)
return [complex((m - 1 - 2 * _gray_inv(lab)) / s, 0.0) for lab in range(m)]
def qam(m: int) -> list[complex]:
"""Unit-energy square M-QAM (M = 4, 16, 64, ...), ordered by label (in-phase bits first)."""
k = _log2(m)
if k % 2:
raise ValueError("square QAM needs M = 4^k")
side = 1 << (k // 2)
s = math.sqrt(2.0 * (m - 1) / 3.0)
raw = [side - 1 - 2 * _gray_inv(lab) for lab in range(side)]
return [complex(raw[lab // side], raw[lab % side]) / s for lab in range(m)]
def psk(m: int, phase0: float = 0.0) -> list[complex]:
"""Unit-energy M-PSK with first point at angle phase0, ordered by Gray label."""
_log2(m)
return [cmath.exp(1j * (2.0 * math.pi * _gray_inv(lab) / m + phase0)) for lab in range(m)]
def energy(points: list[complex]) -> float:
"""The average energy (1/M) sum |p|^2 of equally likely points."""
return sum(abs(p) ** 2 for p in points) / len(points)
def ml_detect(y: complex, points: list[complex], h: complex = 1) -> int:
"""The index of the point p that minimizes |y - h p|^2, by brute force (lowest index on a tie)."""
best, arg = math.inf, -1
for i, p in enumerate(points):
d = abs(y - h * p) ** 2
if d < best:
best, arg = d, i
return arg
def ml_vector(y: list[complex], h: list[list[complex]], points: list[complex]) -> list[int]:
"""The index vector that minimizes ||y - H x||^2 over all M^n vectors x, by brute force.
h is the m by n channel matrix as a list of rows; the result has n indices.
The first minimizer in lexicographic order of the indices wins a tie.
"""
n = len(h[0])
best, arg = math.inf, None
for idx in itertools.product(range(len(points)), repeat=n):
x = [points[i] for i in idx]
d = 0.0
for yi, row in zip(y, h):
d += abs(yi - sum(a * b for a, b in zip(row, x))) ** 2
if d < best:
best, arg = d, idx
return list(arg)
def bit_errors(a, b) -> int:
"""The number of differing bits between two integer labels, or summed over two equal-length lists."""
if isinstance(a, int) and isinstance(b, int):
return bin(a ^ b).count("1")
if len(a) != len(b):
raise ValueError("lengths differ")
return sum(bit_errors(x, y) for x, y in zip(a, b))
parallel_interference_cancellation.py 77 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parallel-interference-cancellation/. The authors are listed in prov/9G0E22.jsonl.
"""Parallel (multistage) interference cancellation 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 known 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. Stage 0
makes tentative decisions (the signs of z, or the decorrelator decisions).
Every later stage subtracts, for each user at the same time, the interference
that the decisions of the previous stage predict, and takes the sign again.
"""
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 _sgn(v: float) -> int:
return 1 if v >= 0.0 else -1
def pic(z: list[float], r: list[list[float]], amps: list[float], stages: int, start: list[int] | None = None) -> list[list[int]]:
"""The decisions of stages 0, 1, ..., J on the matched filter outputs z.
start gives the stage 0 decisions; None means the signs of z.
"""
k_users = len(z)
if len(amps) != k_users or any(a <= 0.0 for a in amps):
raise ValueError("need one positive amplitude per user")
if stages < 0:
raise ValueError("the number of stages must not be negative")
b = list(start) if start is not None else [_sgn(v) for v in z] # @line L1
history = [b]
for _ in range(stages): # @line L2
new = []
for k in range(k_users): # @line L3
x = z[k] - math.fsum(r[k][j] * amps[j] * b[j] for j in range(k_users) if j != k) # @line L4
new.append(_sgn(x)) # @line L5
b = new # @line L6
history.append(b)
return history # @line L7
def pic_detector(y: list[float], sigs: list[list[float]], amps: list[float], stages: int, start: str = "mf") -> list[int]:
"""The decisions of the last stage. start is "mf" (signs of z) or "decorrelator"."""
z = matched_filter(y, sigs)
r = crosscorrelation(sigs)
if start == "mf":
b0 = None
elif start == "decorrelator":
b0 = [_sgn(v.real) for v in cbb.solve(r, z)]
else:
raise ValueError("start must be 'mf' or 'decorrelator'")
return pic(z, r, amps, stages, b0)[-1]
def linear_pic(z: list[float], r: list[list[float]], stages: int) -> list[float]:
"""PIC without the sign: x <- z - (R - I) x from x = z, which is Jacobi iteration on R x = z."""
k_users = len(z)
x = list(z)
for _ in range(stages):
x = [z[k] - math.fsum(r[k][j] * x[j] for j in range(k_users) if j != k) for k in range(k_users)]
return x
test_parallel_interference_cancellation.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parallel-interference-cancellation/. The authors are listed in prov/9G0E22.jsonl.
import itertools
import math
import random
import pytest
import cbb
import constel
from parallel_interference_cancellation import (
crosscorrelation,
linear_pic,
matched_filter,
pic,
pic_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)
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:
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]
assert pic(z, r, AMPS, 3) == [[-1, -1, 1], b, b, b]
def test_right_decisions_are_a_fixed_point_without_noise() -> None:
rng = random.Random(4501)
for _ in range(200):
k = rng.randint(1, 6)
sigs = random_sigs(rng, k, 8)
amps = [rng.uniform(0.1, 5.0) for _ in range(k)]
b = [rng.choice((1, -1)) for _ in range(k)]
z = matched_filter(chips(sigs, amps, b), sigs)
assert pic(z, crosscorrelation(sigs), amps, 4, start=b)[1:] == [b] * 4
def test_decorrelator_start_is_right_without_noise() -> None:
rng = random.Random(4502)
for _ in range(200):
k = rng.randint(1, 6)
sigs = random_sigs(rng, k, 8)
amps = [rng.uniform(0.1, 5.0) for _ in range(k)]
b = [rng.choice((1, -1)) for _ in range(k)]
assert pic_detector(chips(sigs, amps, b), sigs, amps, 3, start="decorrelator") == b
def test_hard_decisions_can_oscillate() -> None:
# Two equal users with correlation 0.9 and z = (0.5, 0.5): the stages
# swing between (+1, +1) and (-1, -1) and never settle.
r = [[1.0, 0.9], [0.9, 1.0]]
hist = pic([0.5, 0.5], r, [1.0, 1.0], 6)
assert hist == [[1, 1], [-1, -1]] * 3 + [[1, 1]]
def test_linear_pic_is_jacobi_and_tends_to_the_decorrelator() -> None:
r = crosscorrelation(S_PAGE)
z = [-0.5, -4.0, 3.25]
assert [round(v, 12) for v in linear_pic(z, r, 1)] == [0.6875, -2.9375, 2.375]
# The eigenvalues of R - I are 0.5 and (-1 +- sqrt 3) / 4, so the spectral radius is about 0.683 < 1.
x = linear_pic(z, r, 80)
assert x == pytest.approx([1.0, -4.0, 2.0], abs=1e-10)
def test_linear_pic_diverges_when_spectral_radius_exceeds_one() -> None:
# R - I with all off-diagonal entries 0.6 has the eigenvalue 1.2.
r = [[1.0, 0.6, 0.6], [0.6, 1.0, 0.6], [0.6, 0.6, 1.0]]
z = [1.0, -0.5, 0.25]
norms = [max(abs(v) for v in linear_pic(z, r, m)) for m in (10, 20, 40)]
assert norms[0] < norms[1] < norms[2]
assert norms[2] > 100.0
def test_noiseless_oscillation_with_two_users() -> None:
# A = (1, 0.8), correlation 0.9, b = (+1, -1), no noise. The stages swing
# between (+1, +1) and (-1, -1) and never reach the sent bits.
r = [[1.0, 0.9], [0.9, 1.0]]
amps = [1.0, 0.8]
z = [1.0 - 0.9 * 0.8, -0.8 + 0.9 * 1.0]
assert pic(z, r, amps, 5) == [[1, 1], [-1, -1], [1, 1], [-1, -1], [1, 1], [-1, -1]]
def test_two_users_converge_in_one_stage_without_noise() -> None:
# For K = 2 without noise, if the stronger amplitude exceeds 2 |rho| times
# the weaker one, stage 1 is right for both users and stays right.
rng = random.Random(4503)
checked = 0
while checked < 200:
rho = rng.uniform(-0.95, 0.95)
r = [[1.0, rho], [rho, 1.0]]
amps = [rng.uniform(0.1, 3.0), rng.uniform(0.1, 3.0)]
if max(amps) <= 2.0 * abs(rho) * min(amps):
continue
checked += 1
for b in itertools.product((1, -1), repeat=2):
z = [amps[0] * b[0] + rho * amps[1] * b[1], amps[1] * b[1] + rho * amps[0] * b[0]]
assert pic(z, r, amps, 3)[1:] == [list(b)] * 3
def test_agrees_with_ml_most_of_the_time() -> None:
# Seed 4504: two stages from the decorrelator at sigma = 0.3 give the ML
# decisions on at least 90 percent of 300 vectors.
rng = random.Random(4504)
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 += pic_detector(y, sigs, amps, 2, start="decorrelator") == ml
assert same >= 0.90 * trials
def test_errors() -> None:
r = [[1.0, 0.0], [0.0, 1.0]]
with pytest.raises(ValueError):
pic([1.0, 1.0], r, [1.0], 1)
with pytest.raises(ValueError):
pic([1.0, 1.0], r, [1.0, 1.0], -1)
with pytest.raises(ValueError):
pic_detector([0.0] * 8, S_PAGE[:2], [1.0, 1.0], 1, start="sic")
History
Varanasi and Aazhang proposed the multistage detector for asynchronous CDMA in 1990. Its first stage is a conventional or decorrelating detector, and each later stage cancels the interference estimated from the previous stage. In 1991 they analyzed the synchronous case and showed that, with a decorrelator first stage, the error rate can come close to that of the optimum detector at a much lower cost. Later work added partial and soft cancellation to reduce error doubling, and the same structure returned in iterative receivers for coded CDMA.
References
- Mahesh K. Varanasi and Behnaam Aazhang, Multistage detection in asynchronous code-division multiple-access communications, IEEE Transactions on Communications 38(4), 1990, the multistage detector, its stages, and its error analysis
- Mahesh K. Varanasi and Behnaam Aazhang, Near-optimum detection in synchronous code-division multiple-access systems, IEEE Transactions on Communications 39(5), 1991, the multistage detector for synchronous users and the decorrelator as its first stage
- Sergio Verdú, Multiuser Detection, Cambridge University Press, 1998, Chapter 7, Decision-driven multiuser detectors
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 9G0E22 Edit this page History Report an error Markdown