Algorithm Search⌘K

Algorithmintro

Selection combining

Also called selection diversity.

Uses only the diversity branch with the largest instantaneous SNR. It needs one receiver chain after a switch and still has diversity order L, but less SNR than maximal ratio combining.

Time
O(L) worst
Space
O(1) extra
Where
L = the number of diversity branches
Properties
not needs branch phasesneeds one receiver chainnot optimal linear combiner
Origin
D. G. Brennan, 1959

Selection combining (SC) is a diversity receiver that measures the SNR of each of LL branches and uses only the branch with the largest one. Like maximal ratio combining and equal gain combining, it has diversity order LL with independent branches, but it does not add the branches: its output SNR is the maximum of the branch SNRs, not their sum. It needs no phase alignment and only one receiver chain after an antenna switch, which makes it the simplest of the three.

In plain words

The same message arrives over several antennas, and at any moment some copies are in a deep fade while others are strong. Selection combining looks at all copies, picks the one that is cleanest right now, and ignores the others. It does not need to line up the phases of the copies or weigh them, so the receiver can be one radio behind a switch. The chance that every copy is in a deep fade at the same time is small, so the selected copy is rarely bad. The cost is that the energy of the other copies is thrown away.

The problem

Branch l=1,…,Ll = 1, \ldots, L receives yl=hlx+wly_l = h_l x + w_l, where xx is the transmitted symbol with energy EsE_s, hlh_l is the complex fading gain, and wl∼CN(0,N0,l)w_l \sim CN(0, N_{0,l}) is noise, independent across branches. The branch SNR is γl=∣hl∣2Es/N0,l\gamma_l = |h_l|^2 E_s/N_{0,l}, with mean γˉ\bar\gamma per branch. The receiver can measure the γl\gamma_l, which is CSIR on the branch qualities. The task is to choose one branch and pass its signal to a symbol detector. The gains may follow block fading, where the choice holds for a codeword, or fast fading, where it changes with every symbol. There is no CSIT.

The algorithm

  1. SELECT(h[1..L], y[1..L], N0[1..L])
  2. 1s_l ← |h_l|² / N0_l for l = 1 .. L ▷ the branch SNRs per unit symbol energy
  3. 2k ← argmax_l s_l
  4. 3x̂ ← conj(h_k) · y_k / |h_k|² ▷ the estimate from branch k alone
  5. 4return x̂, k

Line L1 computes the quality of each branch and line L2 picks the best one. Line L3 removes the gain of the chosen branch, so that x^=x+n\hat x = x + n with n∼CN(0,N0,k/∣hk∣2)n \sim CN(0, N_{0,k}/|h_k|^2), and the output SNR is γSC=max⁡lγl\gamma_{\mathrm{SC}} = \max_l \gamma_l. With a noncoherent detector, line L3 is replaced by the detector of the chosen branch, and only the amplitudes are needed for line L1.

Example

Take L=2L = 2, Es=1E_s = 1, the gains h1=2h_1 = 2 and h2=1h_2 = 1, and the noise powers N0,1=8N_{0,1} = 8 and N0,2=1N_{0,2} = 1. Line L1 gives s1=0.5s_1 = 0.5 and s2=1s_2 = 1, so branch 2 is selected, although its gain is smaller. Choosing by ∣hl∣|h_l| alone would be wrong here.

For LL independent Rayleigh branches with mean γˉ\bar\gamma each, γSC\gamma_{\mathrm{SC}} is below xx only if every branch is below xx, so the outage probability is the closed form (independent Rayleigh branches)

Pr⁡[γSC<x]=(1−e−x/γˉ)L.\Pr[\gamma_{\mathrm{SC}} < x] = (1 - e^{-x/\bar\gamma})^L .

At γˉ=10\bar\gamma = 10 dB and x=1x = 1 it is 0.0952 for L=1L = 1, 9.056⋅10−39.056 \cdot 10^{-3} for L=2L = 2 and 8.20⋅10−58.20 \cdot 10^{-5} for L=4L = 4. Maximal ratio combining gives 4.679⋅10−34.679 \cdot 10^{-3} for L=2L = 2. The mean output SNR is γˉ(1+12+⋯+1L)\bar\gamma(1 + \frac12 + \cdots + \frac1L): 1.5 times γˉ\bar\gamma for L=2L = 2 and 2.083 times for L=4L = 4.

The bit error rate of coherent BPSK is Pb=12∑k=0L(−1)k(Lk)γˉ/(γˉ+k)P_b = \frac12\sum_{k=0}^{L}(-1)^k\binom{L}{k}\sqrt{\bar\gamma/(\bar\gamma + k)}:

γˉ\bar\gamma per branch L=1L = 1 L=2L = 2 L=4L = 4
5 dB 0.06418 0.019701 4.265⋅10−34.265 \cdot 10^{-3}
10 dB 0.023269 2.9729⋅10−32.9729 \cdot 10^{-3} 1.4870⋅10−41.4870 \cdot 10^{-4}
20 dB 2.4814⋅10−32.4814 \cdot 10^{-3} 3.6581⋅10−53.6581 \cdot 10^{-5} 3.003⋅10−83.003 \cdot 10^{-8}

A simulation of 20000 channels with L=2L = 2 at 10 dB (seed 6102) gives a Wilson interval with z=3.29z = 3.29 that contains the outage 9.056⋅10−39.056 \cdot 10^{-3}, and 20000 BPSK bits at 5 dB (seed 6103) give one that contains 0.019701.

Correctness

Claim. The output is x^=x+n\hat x = x + n with n∼CN(0,N0,k/∣hk∣2)n \sim CN(0, N_{0,k}/|h_k|^2), so the output SNR is max⁡lγl\max_l \gamma_l, the best that any receiver using one branch can get. For independent Rayleigh branches with mean γˉ\bar\gamma: the outage is (1−e−x/γˉ)L(1 - e^{-x/\bar\gamma})^L, the mean output SNR is γˉHL\bar\gamma H_L with HL=1+12+⋯+1LH_L = 1 + \frac12 + \cdots + \frac1L, and the BPSK error rate is the alternating sum above. These are closed forms under the stated model.

Key step. The maximum of independent variables is below xx if and only if all of them are, so its distribution function is the product of theirs. The mean follows from Eγ=∫0∞Pr⁡[γ>x] dxE\gamma = \int_0^\infty \Pr[\gamma > x]\, dx, and the error rate from expanding (1−e−x/γˉ)L(1 - e^{-x/\bar\gamma})^L by the binomial theorem and integrating each exponential against Q(2x)Q(\sqrt{2x}). The full proof is in the proofs folder.

Proof: Selection combining outputs the best branch, and for independent Rayleigh branches its outage, mean SNR and BPSK error rate have closed formsfull

Branch l=1,…,Ll = 1, \ldots, L receives yl=hlx+wly_l = h_l x + w_l with E∣x∣2=EsE|x|^2 = E_s and wl∼CN(0,N0,l)w_l \sim CN(0, N_{0,l}), independent of each other and of xx. The gains are known and not all zero. Write γl=∣hl∣2Es/N0,l\gamma_l = |h_l|^2 E_s/N_{0,l}.

Lemma 1 (the output). Let kk be the branch chosen in line L2. Then x^=x+n\hat x = x + n with n∼CN(0,N0,k/∣hk∣2)n \sim CN(0, N_{0,k}/|h_k|^2), so the output SNR is γk=max⁡lγl\gamma_k = \max_l \gamma_l. With no noise, x^=x\hat x = x.

Proof. Line L2 picks kk with the largest ∣hl∣2/N0,l|h_l|^2/N_{0,l}, hence the largest γl\gamma_l, and hk≠0h_k \ne 0 because not all gains are zero. Line L3 gives x^=hk‾(hkx+wk)/∣hk∣2=x+hk‾wk/∣hk∣2\hat x = \overline{h_k}(h_k x + w_k)/|h_k|^2 = x + \overline{h_k} w_k/|h_k|^2, and the noise term is circular Gaussian with variance ∣hk∣2N0,k/∣hk∣4|h_k|^2 N_{0,k}/|h_k|^4. □\square

No receiver that uses one branch does better: for branch ll, the best SNR of any scaling of yly_l is γl\gamma_l, and γk\gamma_k is the largest of these.

From here on, the hlh_l are independent CN(0,Ω)CN(0, \Omega) and all N0,l=N0N_{0,l} = N_0, so the γl\gamma_l are independent exponential with mean γˉ=ΩEs/N0\bar\gamma = \Omega E_s/N_0, and Pr⁡[γl<x]=1−e−x/γˉ\Pr[\gamma_l < x] = 1 - e^{-x/\bar\gamma} for x≥0x \ge 0.

Theorem 1 (outage). Pr⁡[γSC<x]=(1−e−x/γˉ)L\Pr[\gamma_{\mathrm{SC}} < x] = (1 - e^{-x/\bar\gamma})^L.

Proof. max⁡lγl<x\max_l \gamma_l < x if and only if γl<x\gamma_l < x for every ll. By independence, the probability is the product of the LL factors 1−e−x/γˉ1 - e^{-x/\bar\gamma}. □\square

Theorem 2 (mean output SNR). E[γSC]=γˉHLE[\gamma_{\mathrm{SC}}] = \bar\gamma H_L with HL=∑i=1L1/iH_L = \sum_{i=1}^{L} 1/i.

Proof. For a nonnegative variable, Eγ=∫0∞Pr⁡[γ>x] dx=∫0∞(1−(1−e−x/γˉ)L) dxE\gamma = \int_0^\infty \Pr[\gamma > x]\, dx = \int_0^\infty (1 - (1 - e^{-x/\bar\gamma})^L)\, dx. Substitute t=1−e−x/γˉt = 1 - e^{-x/\bar\gamma}, so dx=γˉ dt/(1−t)dx = \bar\gamma\, dt/(1 - t) and tt runs from 0 to 1: Eγ=γˉ∫011−tL1−t dt=γˉ∫01∑i=0L−1ti dt=γˉ∑i=0L−11i+1E\gamma = \bar\gamma\int_0^1 \frac{1 - t^L}{1 - t}\, dt = \bar\gamma \int_0^1 \sum_{i=0}^{L-1} t^i\, dt = \bar\gamma\sum_{i=0}^{L-1}\frac{1}{i+1}. □\square

Theorem 3 (BPSK error rate). With coherent BPSK on the selected branch, Pb=12∑k=0L(−1)k(Lk)γˉ/(γˉ+k)P_b = \frac12 \sum_{k=0}^{L} (-1)^k \binom{L}{k} \sqrt{\bar\gamma/(\bar\gamma + k)}.

Proof. Given γSC=γ\gamma_{\mathrm{SC}} = \gamma, the error probability is Q(2γ)Q(\sqrt{2\gamma}), by Lemma 1. Let F(γ)=(1−e−γ/γˉ)LF(\gamma) = (1 - e^{-\gamma/\bar\gamma})^L be the distribution function of Theorem 1. Integration by parts gives Pb=E[Q(2γ)]=∫0∞F(γ) (−ddγQ(2γ)) dγP_b = E[Q(\sqrt{2\gamma})] = \int_0^\infty F(\gamma)\, \big(-\tfrac{d}{d\gamma}Q(\sqrt{2\gamma})\big)\, d\gamma, because F(0)=0F(0) = 0 and Q(2γ)→0Q(\sqrt{2\gamma}) \to 0 as γ→∞\gamma \to \infty. The derivative is −ddγQ(2γ)=e−γ2πγ-\frac{d}{d\gamma}Q(\sqrt{2\gamma}) = \frac{e^{-\gamma}}{2\sqrt{\pi\gamma}}. Expand F(γ)=∑k=0L(Lk)(−1)ke−kγ/γˉF(\gamma) = \sum_{k=0}^{L}\binom{L}{k}(-1)^k e^{-k\gamma/\bar\gamma}. For each kk, with b=1+k/γˉb = 1 + k/\bar\gamma, ∫0∞e−bγ2πγ dγ=12b\int_0^\infty \frac{e^{-b\gamma}}{2\sqrt{\pi\gamma}}\, d\gamma = \frac{1}{2\sqrt{b}}, by the substitution γ=u2/b\gamma = u^2/b and ∫0∞e−u2 du=π/2\int_0^\infty e^{-u^2}\, du = \sqrt\pi/2. Since 1/b=γˉ/(γˉ+k)1/\sqrt b = \sqrt{\bar\gamma/(\bar\gamma + k)}, the sum is the claim. □\square

For L=1L = 1 the sum is 12(1−γˉ/(1+γˉ))\frac12(1 - \sqrt{\bar\gamma/(1 + \bar\gamma)}), the error rate of one Rayleigh branch. The test file compares Theorem 3 with a direct Simpson integral of Q(2γ)Q(\sqrt{2\gamma}) against the density of the maximum, for L=1,…,4L = 1, \ldots, 4 and 0 to 20 dB, within a relative error of 10−610^{-6}.

Remark (diversity order). For xx fixed and γˉ→∞\bar\gamma \to \infty, 1−e−x/γˉ=x/γˉ+O(γˉ−2)1 - e^{-x/\bar\gamma} = x/\bar\gamma + O(\bar\gamma^{-2}), so Pr⁡[γSC<x]=(x/γˉ)L(1+O(1/γˉ))\Pr[\gamma_{\mathrm{SC}} < x] = (x/\bar\gamma)^L(1 + O(1/\bar\gamma)), and −log⁡Pr⁡/log⁡γˉ→L-\log \Pr / \log \bar\gamma \to L.

Complexity

Lines L1 and L2 take O(L)O(L) operations per decision, in the real RAM, and line L3 takes O(1)O(1), with O(1)O(1) extra space. In hardware, the selection needs a measurement of each branch but only one demodulator, which is the main saving against the other combiners. If the choice is made once per block, the measurement cost is shared by the whole block.

Properties

  • Output SNR is the maximum. γSC=max⁡lγl≤∑lγl=γMRC\gamma_{\mathrm{SC}} = \max_l \gamma_l \le \sum_l \gamma_l = \gamma_{\mathrm{MRC}}.
  • Mean gain grows slowly. E[γSC]=γˉHLE[\gamma_{\mathrm{SC}}] = \bar\gamma H_L, and HLH_L grows like ln⁡L\ln L. Most of the benefit of SC is in the lower tail, not in the mean.
  • Diversity order LL. For independent Rayleigh branches, Pr⁡[γSC<x]≈(x/γˉ)L\Pr[\gamma_{\mathrm{SC}} < x] \approx (x/\bar\gamma)^L for large γˉ\bar\gamma, so the outage and the error rate fall as γˉ−L\bar\gamma^{-L}, the same slope as for maximal ratio combining.
  • No phase needed. SC does not combine signals, so it works with coherent and with noncoherent detection.
  • Comparison at L=2L = 2 and 10 dB. The BPSK error rate is 2.973⋅10−32.973 \cdot 10^{-3} for SC, 2.070⋅10−32.070 \cdot 10^{-3} for equal gain combining and 1.599⋅10−31.599 \cdot 10^{-3} for maximal ratio combining.

Variants and improvements

  • Selection by received power. Measuring the SNR of each branch is hard; practical receivers often select the branch with the largest total power, signal plus noise. With equal noise powers this gives the same choice.
  • Switched diversity. Switch-and-stay combining monitors only the current branch and switches when its SNR falls below a threshold. It needs one measurement at a time, at the cost of more outage than full selection.
  • Generalized selection combining. Combining the best LcL_c of the LL branches with maximal ratio weights lies between SC (Lc=1L_c = 1) and maximal ratio combining (Lc=LL_c = L).
  • Transmit antenna selection. With feedback, the transmitter can use only its best antenna. This is SC moved to the transmitter, with the same output SNR max⁡lγl\max_l \gamma_l.
  • Selection over users. Multiuser diversity schedules the user with the best channel, which is selection over users instead of antennas.

When to use it

Use SC when only one receiver chain is affordable, when the detection is noncoherent, or when the branch phases cannot be tracked. It gives the full diversity order of the antennas at the smallest hardware cost. When each branch has its own receiver chain and channel estimates, maximal ratio combining gives a higher SNR at almost no extra cost in arithmetic.

Pitfalls

  • Selecting by gain instead of SNR. With different noise powers, the branch with the largest ∣hl∣|h_l| is not the best one, as in the example. Select by ∣hl∣2/N0,l|h_l|^2/N_{0,l}.
  • Stale selection. The choice is based on a measurement. If the fading changes before the selection takes effect, which happens in fast fading or with a slow switch, the selected branch is no longer the best one and the diversity gain falls. Compare the measurement delay with the coherence time.
  • Correlated branches. The product formula for the outage needs independent branches. Closely spaced antennas fade together, and SC then gains much less.
  • Switching transients. Switching an analog front end during a symbol creates phase and amplitude jumps. Switch at symbol or block boundaries.

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)
selection_combining.py 65 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/selection-combining/. The authors are listed in prov/611EDQ.jsonl.

"""Selection combining (SC) of L diversity branches.

Branch l receives y_l = h_l x + w_l with w_l ~ CN(0, N0_l). SC computes the SNR
|h_l|^2 / N0_l of each branch, keeps the branch with the largest one, and
detects x from that branch alone. The output SNR is the maximum of the branch
SNRs.

The distribution functions are for L i.i.d. Rayleigh branches with mean SNR
gamma_bar per branch: the outage (1 - e^(-x / gamma_bar))^L, the mean output
SNR gamma_bar (1 + 1/2 + ... + 1/L) and the BPSK bit error rate.
"""

import math


def select(h: list[complex], y: list[complex], n0: list[float]) -> tuple[complex, int]:
    """The SC estimate of x and the index of the selected branch."""
    if not len(h) == len(y) == len(n0) or not h:
        raise ValueError("need L >= 1 branches with h, y and N0 each")
    snr = [abs(h[l]) ** 2 / n0[l] for l in range(len(h))]  # @line L1
    k = max(range(len(h)), key=lambda l: snr[l])  # @line L2
    if snr[k] == 0.0:
        raise ValueError("all branch gains are zero")
    est = h[k].conjugate() * y[k] / abs(h[k]) ** 2  # @line L3
    return est, k  # @line L4


def outage_rayleigh(branches: int, x: float, gbar: float) -> float:
    """P(max branch SNR < x) = (1 - e^(-x / gamma_bar))^L."""
    return (1.0 - math.exp(-x / gbar)) ** branches


def mean_snr_gain(branches: int) -> float:
    """E[output SNR] / gamma_bar = 1 + 1/2 + ... + 1/L."""
    return sum(1.0 / k for k in range(1, branches + 1))


def ber_bpsk_rayleigh(branches: int, gbar: float) -> float:
    """Exact BPSK bit error rate: (1/2) sum_{k=0}^{L} (-1)^k C(L, k) sqrt(gamma_bar / (gamma_bar + k))."""
    return 0.5 * sum((-1) ** k * math.comb(branches, k) * math.sqrt(gbar / (gbar + k)) for k in range(branches + 1))


def ber_bpsk_rayleigh_integral(branches: int, gbar: float, points: int = 4000) -> float:
    """The same error rate by integration of Q(sqrt(2 g)) against the density of the maximum SNR.

    The density is (L / gamma_bar) e^(-g / gamma_bar) (1 - e^(-g / gamma_bar))^(L - 1).
    The substitution g = u^2 removes the square root at 0, and Simpson's rule
    is used in u on [0, sqrt(50 gamma_bar)].
    """
    umax = math.sqrt(50.0 * gbar)
    h = umax / points

    def f(u):
        g = u * u
        e = math.exp(-g / gbar)
        dens = branches / gbar * e * (1.0 - e) ** (branches - 1)
        return 0.5 * math.erfc(u) * dens * 2.0 * u

    s = f(0.0) + f(umax)
    for k in range(1, points):
        s += (4 if k % 2 else 2) * f(k * h)
    return s * h / 3.0
test_selection_combining.py 81 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/selection-combining/. The authors are listed in prov/611EDQ.jsonl.

import math
import random

import cbb
from selection_combining import (
    ber_bpsk_rayleigh,
    ber_bpsk_rayleigh_integral,
    mean_snr_gain,
    outage_rayleigh,
    select,
)


def test_noiseless_recovery_and_choice() -> None:
    rng = random.Random(6101)
    for _ in range(300):
        branches = rng.randint(1, 8)
        h = [cbb.cn(rng, 1.0) for _ in range(branches)]
        n0 = [rng.uniform(0.1, 3.0) for _ in range(branches)]
        x = complex(rng.choice((-1, 1)), rng.choice((-1, 1)))
        est, k = select(h, [v * x for v in h], n0)
        assert abs(est - x) < 1e-12
        snr = [abs(v) ** 2 / s for v, s in zip(h, n0)]
        assert snr[k] == max(snr)


def test_noise_level_matters() -> None:
    # the larger gain is not the better branch when its noise is stronger
    _, k = select([2 + 0j, 1 + 0j], [0j, 0j], [8.0, 1.0])
    assert k == 1


def test_check_values() -> None:
    assert abs(outage_rayleigh(2, 1.0, 10.0) - 9.0559e-3) < 1e-7
    assert abs(ber_bpsk_rayleigh(1, 10.0) - 0.5 * (1 - math.sqrt(10 / 11))) < 1e-15
    assert abs(ber_bpsk_rayleigh(2, 10.0) - 2.9729e-3) < 1e-7
    assert abs(ber_bpsk_rayleigh(4, 10.0) - 1.4870e-4) < 1e-8
    assert abs(mean_snr_gain(2) - 1.5) < 1e-15
    assert abs(mean_snr_gain(4) - 25 / 12) < 1e-15


def test_closed_form_against_integral() -> None:
    for branches in (1, 2, 3, 4):
        for gdb in (0, 5, 10, 20):
            g = cbb.undb(gdb)
            a = ber_bpsk_rayleigh(branches, g)
            assert abs(a - ber_bpsk_rayleigh_integral(branches, g)) < 1e-6 * a


def test_outage_by_simulation() -> None:
    # L = 2, gamma_bar = 10 dB, threshold x = 1: 9.06e-3, so n = 20000 channels give about 181 outages.
    rng = random.Random(6102)
    n, g = 20000, 10.0
    below = 0
    total = 0.0
    for _ in range(n):
        best = max(g * abs(cbb.cn(rng, 1.0)) ** 2 for _ in range(2))
        below += best < 1.0
        total += best
    lo, hi = cbb.wilson(below, n, 3.29)
    assert lo <= outage_rayleigh(2, 1.0, g) <= hi
    assert abs(total / n - 1.5 * g) < 0.04 * 1.5 * g


def test_ber_by_simulation() -> None:
    # L = 2, gamma_bar = 5 dB, BPSK: Pb = 0.019701, so n = 20000 bits give about 394 errors.
    rng = random.Random(6103)
    n, g = 20000, cbb.undb(5.0)
    n0 = [1.0 / g] * 2
    errors = 0
    for _ in range(n):
        x = rng.choice((-1.0, 1.0))
        h = [cbb.cn(rng, 1.0) for _ in range(2)]
        y = [v * x + cbb.cn(rng, n0[0]) for v in h]
        est, _ = select(h, y, n0)
        errors += (est.real >= 0) != (x > 0)
    lo, hi = cbb.wilson(errors, n, 3.29)
    assert lo <= ber_bpsk_rayleigh(2, g) <= hi

History

Choosing the best of several antennas or receivers is the simplest diversity method, because it needs no combining of signals. Brennan (1959) gave a unified analysis of linear diversity combining, in which selection diversity is compared with maximal ratio and equal gain combining for Rayleigh fading. Later work added switched diversity for simple receivers, generalized selection combining, and transmit antenna selection with feedback.

References

  1. D. G. Brennan, Linear diversity combining techniques, Proceedings of the IRE 47(6), 1959, pages 1075 to 1102, the analysis of selection diversity and its comparison with maximal ratio and equal gain combining
  2. Andrea Goldsmith, Wireless Communications, Cambridge University Press, 2005, Section 7.2.2 (selection combining)
  3. Marvin K. Simon and Mohamed-Slim Alouini, Digital Communication over Fading Channels, 2nd edition, Wiley, 2005, Chapter 9 (diversity combining), including the selection combining receivers

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