Algorithm Search⌘K

Algorithmcore

Equal gain combining

Also called EGC.

Removes the phase of each diversity branch and adds the branches with equal weights. It needs the branch phases but not the amplitudes, and is a little worse than maximal ratio combining.

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

Equal gain combining (EGC) is a linear receiver for LL diversity branches: it turns each branch by the negative of the phase of its gain and adds the branches with the same weight. It is one of the three classic combiners whose diversity order is LL with independent branches; maximal ratio combining also weights each branch by its amplitude and gets the best SNR, and selection combining keeps only the best branch. EGC needs the phases of the branches but not their amplitudes, and its loss against maximal ratio combining in Rayleigh fading is about 0.5 to 0.7 dB.

In plain words

The same message arrives over several antennas, each copy with its own strength and its own phase. If the copies were added as they are, their phases could cancel each other. EGC first turns every copy so that all of them point the same way, and then simply adds them, all with the same weight. It does not need to know how strong each copy is, only its phase. This is simpler than giving each copy its best weight, and the loss is small when the copies have similar strengths. When one copy is very weak, EGC still adds its full noise, and then it can do worse than just picking the best copy.

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)w_l \sim CN(0, N_0) is noise with the same power on every branch, independent across branches. The branch SNR is γl=∣hl∣2Es/N0\gamma_l = |h_l|^2 E_s/N_0 with mean γˉ\bar\gamma. The receiver knows the phase arg⁡hl\arg h_l of each branch, and uses ∣hl∣|h_l| only to scale the final estimate. The task is to form one statistic from the yly_l and pass it to a symbol detector. The gains may follow block fading or fast fading; the combiner acts symbol by symbol either way, with CSIR on the phases and no CSIT.

The algorithm

  1. EGC(h[1..L], y[1..L])
  2. 1c_l ← h_l / |h_l| for l = 1 .. L ▷ unit weights with the phase of each branch
  3. 2z ← Σ_l conj(c_l) · y_l
  4. 3a ← Σ_l |h_l|
  5. 4return z / a, a ▷ z / a = x + noise of variance L N0 / a²

Line L1 keeps only the phase of each gain. Line L2 cophases and adds: each term becomes ∣hl∣x|h_l| x plus noise of the same power N0N_0, because ∣cl∣=1|c_l| = 1. Line L3 is the sum of the amplitudes, which line L4 uses to scale zz into an estimate of xx. For BPSK and other constant-energy formats with a sign or phase decision, line L3 is not needed, because scaling by a>0a > 0 does not change the decision. A branch with hl=0h_l = 0 gets the weight 0.

Example

Take L=2L = 2, N0=1N_0 = 1, Es=1E_s = 1 and the gains h1=1+jh_1 = 1 + j, h2=0.5jh_2 = 0.5j. The weights are c1=(1+j)/2c_1 = (1 + j)/\sqrt 2 and c2=jc_2 = j. With x=1x = 1 and no noise, line L2 gives z=2+0.5=1.914z = \sqrt 2 + 0.5 = 1.914 and line L3 gives a=1.914a = 1.914, so z/a=1z/a = 1. The output SNR is Esa2/(LN0)=1.9142/2=1.832E_s a^2/(L N_0) = 1.914^2/2 = 1.832, against γ1+γ2=2.25\gamma_1 + \gamma_2 = 2.25 for maximal ratio combining and max⁡γl=2\max \gamma_l = 2 for selection combining. Here EGC is the worst of the three, because the branches are unequal.

For two independent Rayleigh branches with mean γˉ\bar\gamma each, the bit error rate of coherent BPSK has the closed form (independent Rayleigh branches, equal noise powers, perfect phases)

Pb=12(1−γˉ(γˉ+2)γˉ+1).P_b = \frac12\left(1 - \frac{\sqrt{\bar\gamma(\bar\gamma + 2)}}{\bar\gamma + 1}\right).

A direct numerical integral over the two amplitudes agrees with it within a relative error of 10−610^{-6} at 0, 5 and 10 dB.

γˉ\bar\gamma per branch MRC, L=2L = 2 EGC, L=2L = 2 SC, L=2L = 2
0 dB 0.05806 0.06699 0.08157
5 dB 0.011829 0.014645 0.019701
10 dB 1.5991⋅10−31.5991 \cdot 10^{-3} 2.0704⋅10−32.0704 \cdot 10^{-3} 2.9729⋅10−32.9729 \cdot 10^{-3}
20 dB 1.8442⋅10−51.8442 \cdot 10^{-5} 2.4508⋅10−52.4508 \cdot 10^{-5} 3.6581⋅10−53.6581 \cdot 10^{-5}

At 20 dB the ratio of EGC to MRC is 1.33, so with the slope γˉ−2\bar\gamma^{-2} EGC needs about 0.6 dB more per branch for the same error rate. A simulation of 20000 BPSK bits at 5 dB (seed 6003) gives a Wilson interval with z=3.29z = 3.29 that contains 0.014645.

Correctness

Claim. The output of line L4 is z/a=x+nz/a = x + n with n∼CN(0,LN0/a2)n \sim CN(0, L N_0/a^2), so the output SNR is γEGC=Es(∑l∣hl∣)2/(LN0)\gamma_{\mathrm{EGC}} = E_s(\sum_l |h_l|)^2/(L N_0). It satisfies 1L∑lγl≤γEGC≤∑lγl\frac1L \sum_l \gamma_l \le \gamma_{\mathrm{EGC}} \le \sum_l \gamma_l, and for independent Rayleigh branches E[γEGC]=γˉ(1+(L−1)π/4)E[\gamma_{\mathrm{EGC}}] = \bar\gamma(1 + (L - 1)\pi/4). These are theorems under the stated model.

Key step. Each term of line L2 is ∣hl∣x+cl∗wl|h_l| x + c_l^* w_l, and cl∗wlc_l^* w_l has the same distribution as wlw_l because ∣cl∣=1|c_l| = 1. The upper bound is the Cauchy-Schwarz inequality (∑l∣hl∣)2≤L∑l∣hl∣2(\sum_l |h_l|)^2 \le L\sum_l |h_l|^2, and the lower bound follows from (∑l∣hl∣)2≥∑l∣hl∣2(\sum_l |h_l|)^2 \ge \sum_l |h_l|^2. The mean uses E∣hl∣=πΩ/2E|h_l| = \sqrt{\pi\Omega}/2 for a Rayleigh amplitude. The full proof is in the proofs folder.

Proof: Equal gain combining gives an unbiased estimate with output SNR E_s (sum |h_l|)^2 / (L N0), between the mean and the sum of the branch SNRsfull

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)w_l \sim CN(0, N_0), independent of each other and of xx. The gains are known and not all zero. Write γl=∣hl∣2Es/N0\gamma_l = |h_l|^2 E_s/N_0 and a=∑l∣hl∣>0a = \sum_l |h_l| > 0. Line L1 sets cl=hl/∣hl∣c_l = h_l/|h_l| for hl≠0h_l \ne 0 and cl=0c_l = 0 for hl=0h_l = 0.

Lemma 1 (one branch). cl∗yl=∣hl∣ x+cl∗wlc_l^* y_l = |h_l|\, x + c_l^* w_l, and cl∗wl∼CN(0,N0)c_l^* w_l \sim CN(0, N_0) for hl≠0h_l \ne 0.

Proof. cl∗hl=hl‾hl/∣hl∣=∣hl∣c_l^* h_l = \overline{h_l} h_l/|h_l| = |h_l|. Multiplying a circular Gaussian variable by a number of modulus 1 does not change its distribution. For hl=0h_l = 0 the term is 0, and ∣hl∣=0|h_l| = 0 as well. □\square

Theorem 1 (the output). Let L′L' be the number of branches with hl≠0h_l \ne 0. Then z/a=x+nz/a = x + n with n∼CN(0,L′N0/a2)n \sim CN(0, L' N_0/a^2), so the output SNR is γEGC=Esa2/(L′N0)\gamma_{\mathrm{EGC}} = E_s a^2/(L' N_0). With all gains nonzero, L′=LL' = L.

Proof. By Lemma 1, z=∑lcl∗yl=ax+∑lcl∗wlz = \sum_l c_l^* y_l = a x + \sum_l c_l^* w_l. The noise terms are independent, each CN(0,N0)CN(0, N_0) for the L′L' nonzero branches and 0 for the others, so their sum is CN(0,L′N0)CN(0, L' N_0). Divide by aa. □\square

The reference code sets cl=0c_l = 0 for a zero gain, as in the theorem; the page states the formula with LL, the case in which every branch has a nonzero gain, which happens with probability 1 in Rayleigh fading. If a receiver adds a branch with a zero gain but a fixed unit weight, its noise is still added, and the formula with LL holds.

Theorem 2 (the bounds). With all gains nonzero, 1L∑lγl≤γEGC≤∑lγl\frac1L \sum_l \gamma_l \le \gamma_{\mathrm{EGC}} \le \sum_l \gamma_l. The right side is an equality if and only if all ∣hl∣|h_l| are equal.

Proof. By the Cauchy-Schwarz inequality for the vectors (1,…,1)(1, \ldots, 1) and (∣h1∣,…,∣hL∣)(|h_1|, \ldots, |h_L|), a2=(∑l∣hl∣)2≤L∑l∣hl∣2a^2 = (\sum_l |h_l|)^2 \le L \sum_l |h_l|^2, with equality if and only if the second vector is constant. Multiply by Es/(LN0)E_s/(L N_0). For the left side, a2=∑l∣hl∣2+∑l≠k∣hl∣∣hk∣≥∑l∣hl∣2a^2 = \sum_l |h_l|^2 + \sum_{l \ne k} |h_l||h_k| \ge \sum_l |h_l|^2, because all terms are nonnegative. □\square

The left bound is reached in the limit where one gain carries all the power: with h=(1,0)h = (1, 0) and a unit weight on the second branch, γEGC=12Es/N0\gamma_{\mathrm{EGC}} = \frac12 E_s/N_0, half of the best single branch. So EGC can be worse than selection combining.

Theorem 3 (the mean in Rayleigh fading). If the hlh_l are independent CN(0,Ω)CN(0, \Omega) and γˉ=ΩEs/N0\bar\gamma = \Omega E_s/N_0, then E[γEGC]=γˉ (1+(L−1)π/4)E[\gamma_{\mathrm{EGC}}] = \bar\gamma\,(1 + (L-1)\pi/4).

Proof. The amplitude r=∣hl∣r = |h_l| has the Rayleigh density (2r/Ω)e−r2/Ω(2r/\Omega)e^{-r^2/\Omega}, with Er2=ΩE r^2 = \Omega and Er=∫0∞(2r2/Ω)e−r2/Ω dr=πΩ/2E r = \int_0^\infty (2r^2/\Omega) e^{-r^2/\Omega}\, dr = \sqrt{\pi\Omega}/2. Then Ea2=∑lE∣hl∣2+∑l≠kE∣hl∣ E∣hk∣=LΩ+L(L−1)πΩ/4E a^2 = \sum_l E|h_l|^2 + \sum_{l \ne k} E|h_l|\, E|h_k| = L\Omega + L(L-1)\pi\Omega/4, by independence. Multiply by Es/(LN0)E_s/(L N_0). □\square

Remark (the error rate for two branches). For L=2L = 2, BPSK and independent Rayleigh branches, Pb=E[Q(a2Es/(2N0))]=E[Q(aγˉ/Ω)]P_b = E[Q(a\sqrt{2E_s/(2N_0)})] = E[Q(a\sqrt{\bar\gamma/\Omega})] by Theorem 1, an integral over the two amplitudes. The page gives its closed form 12(1−γˉ(γˉ+2)/(γˉ+1))\frac12(1 - \sqrt{\bar\gamma(\bar\gamma+2)}/(\bar\gamma+1)). That closed form is not proved here: the test file compares it with a direct two-dimensional Simpson integral of this expectation in polar coordinates and finds agreement within a relative error of 10−510^{-5} at 0, 5 and 10 dB, and a simulation with a Wilson interval at 5 dB.

Complexity

Lines L1 to L3 take O(L)O(L) operations per symbol, in the real RAM, with O(1)O(1) extra space. In hardware, the cophasing of line L1 is a phase rotation per branch, with no multiplier for the amplitude. The receiver still needs one radio chain per branch and a phase estimate per branch.

Properties

  • Mean output SNR. γˉ(1+(L−1)π/4)\bar\gamma(1 + (L - 1)\pi/4) for independent Rayleigh branches: 1.785 times γˉ\bar\gamma for L=2L = 2 (2.52 dB), against 2 (3.01 dB) for maximal ratio combining and 1.5 (1.76 dB) for selection combining.
  • Diversity order LL. With independent Rayleigh branches, the error rate falls as γˉ−L\bar\gamma^{-L}. The loss against maximal ratio combining is a constant shift of the curve, not a change of slope.
  • Not always better than selection. With h=(1,0)h = (1, 0), EGC has output SNR 12Es/N0\frac12 E_s/N_0, while selection combining has Es/N0E_s/N_0. The added branch brings noise but no signal.
  • Between the bounds. 1L∑lγl≤γEGC≤∑lγl\frac1L\sum_l\gamma_l \le \gamma_{\mathrm{EGC}} \le \sum_l\gamma_l, with equality on the right when all ∣hl∣|h_l| are equal.
  • No closed form in general. The output SNR is the square of a sum of Rayleigh variables, whose distribution has no simple form. For L=2L = 2 in Rayleigh fading the BPSK error rate above is exact; for larger LL it is usually computed by numerical integration or series.

Variants and improvements

  • Maximal ratio combining. Adding the amplitude weights gives the best linear combiner; see maximal ratio combining.
  • Equal gain transmission. With CSIT, a transmitter with LL antennas can send xx with the phases e−jarg⁡hl/Le^{-j\arg h_l}/\sqrt L and constant amplitude, which gives the same output SNR as EGC at the receiver. It suits power amplifiers that need a constant envelope per antenna.
  • Noncoherent EGC. For noncoherent detection, such as FSK with envelope detectors, or differential PSK, the detector outputs of the branches are added with equal weights. No phase estimate is needed, but the result is a different receiver with its own error rate.
  • Generalized selection. Adding the best LcL_c of LL branches with MRC or EGC lies between selection combining and full combining.

When to use it

Use EGC when the branch phases can be tracked but the amplitudes are hard to estimate, or when a simple analog combiner is wanted, for example with phase shifters. In Rayleigh fading with branches of equal mean power, it is within about 0.5 to 0.7 dB of maximal ratio combining. With branches of very different mean power, use maximal ratio combining or selection combining instead, because EGC adds the full noise of the weak branches.

Pitfalls

  • Unequal noise powers. EGC assumes the same N0N_0 on every branch. With different noise powers, scale each branch to the same noise level first, or use maximal ratio combining.
  • A dead branch. A branch in a deep fade or with a failed receiver adds noise and almost no signal. EGC can then be worse than one good branch.
  • Phase errors. EGC depends fully on the phase estimates. A phase error per branch reduces the signal sum by the cosine of the error.
  • The scale in line L3. For amplitude-dependent formats such as 16-QAM, the estimate must be divided by aa; omitting line L3 gives a wrong decision region.

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)
equal_gain_combining.py 74 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/equal-gain-combining/. The authors are listed in prov/FAG3FG.jsonl.

"""Equal gain combining (EGC) of L diversity branches.

Branch l receives y_l = h_l x + w_l with w_l ~ CN(0, N0), the same N0 on every
branch. EGC removes the phase of each branch, multiplying by
e^(-j arg h_l), and adds the branches with equal weights. The sum is
(sum |h_l|) x plus noise of variance L N0, so the output SNR is
E_s (sum |h_l|)^2 / (L N0). It needs the phases, not the amplitudes.

The error rate functions are for coherent BPSK and i.i.d. Rayleigh branches
with mean SNR gamma_bar per branch.
"""

import math

import cbb


def egc(h: list[complex], y: list[complex]) -> tuple[complex, float]:
    """The EGC estimate of x and the amplitude sum a = sum |h_l|."""
    if len(h) != len(y) or not h:
        raise ValueError("need L >= 1 branches with h and y each")
    c = [v / abs(v) if v != 0 else 0j for v in h]  # @line L1
    z = sum(c[l].conjugate() * y[l] for l in range(len(h)))  # @line L2
    a = sum(abs(v) for v in h)  # @line L3
    if a == 0.0:
        raise ValueError("all branch gains are zero")
    return z / a, a  # @line L4


def egc_snr(h: list[complex], n0: float, es: float = 1.0) -> float:
    """The output SNR of EGC: E_s (sum |h_l|)^2 / (L N0)."""
    return es * sum(abs(v) for v in h) ** 2 / (len(h) * n0)


def mean_snr_gain(branches: int) -> float:
    """E[output SNR] / gamma_bar for L i.i.d. Rayleigh branches: 1 + (L - 1) pi / 4."""
    return 1.0 + (branches - 1) * math.pi / 4.0


def ber_bpsk_rayleigh_dual(gbar: float) -> float:
    """Exact BPSK bit error rate of EGC with two i.i.d. Rayleigh branches: (1 - sqrt(g (g + 2)) / (g + 1)) / 2."""
    return 0.5 * (1.0 - math.sqrt(gbar * (gbar + 2.0)) / (gbar + 1.0))


def ber_bpsk_rayleigh_dual_integral(gbar: float, nr: int = 600, nphi: int = 120) -> float:
    """The same error rate by direct integration over the two amplitudes, in polar form.

    With E|h_l|^2 = 1 the amplitudes r_1, r_2 have the density 4 r_1 r_2 e^(-r_1^2 - r_2^2),
    and the error rate given them is Q((r_1 + r_2) sqrt(gamma_bar)). Simpson's
    rule is used in r on [0, 8] and in the angle on [0, pi / 2].
    """
    rmax = 8.0
    hr = rmax / nr
    hp = (math.pi / 2.0) / nphi
    sg = math.sqrt(gbar)

    def inner(phi):
        cs = math.cos(phi) + math.sin(phi)
        s = 0.0
        for k in range(1, nr + 1):
            r = k * hr
            w = 1 if k == nr else (4 if k % 2 else 2)
            s += w * r ** 3 * math.exp(-r * r) * cbb.qfunc(r * cs * sg)
        return s * hr / 3.0

    tot = 0.0
    for k in range(1, nphi):
        phi = k * hp
        w = 4 if k % 2 else 2
        tot += w * 4.0 * math.cos(phi) * math.sin(phi) * inner(phi)
    return tot * hp / 3.0
test_equal_gain_combining.py 84 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/equal-gain-combining/. The authors are listed in prov/FAG3FG.jsonl.

import math
import random

import cbb
from equal_gain_combining import (
    ber_bpsk_rayleigh_dual,
    ber_bpsk_rayleigh_dual_integral,
    egc,
    egc_snr,
    mean_snr_gain,
)


def snr_of_weights(c, h, n0):
    """Brute-force SNR of z = sum conj(c_l) y_l with the same noise N0 on every branch."""
    return abs(sum(a.conjugate() * b for a, b in zip(c, h))) ** 2 / (n0 * sum(abs(a) ** 2 for a in c))


def test_noiseless_recovery() -> None:
    rng = random.Random(6001)
    for _ in range(200):
        branches = rng.randint(1, 8)
        h = [cbb.cn(rng, 1.0) for _ in range(branches)]
        x = complex(rng.choice((-1, 1)), rng.choice((-1, 1)))
        est, a = egc(h, [v * x for v in h])
        assert abs(est - x) < 1e-12
        assert abs(a - sum(abs(v) for v in h)) < 1e-12


def test_snr_between_selection_and_mrc_bounds() -> None:
    rng = random.Random(6002)
    for _ in range(300):
        branches = rng.randint(1, 8)
        h = [cbb.cn(rng, 1.0) for _ in range(branches)]
        n0 = rng.uniform(0.1, 2.0)
        s = egc_snr(h, n0)
        c = [v / abs(v) for v in h]
        assert abs(s - snr_of_weights(c, h, n0)) < 1e-9 * s
        mrc = sum(abs(v) ** 2 for v in h) / n0
        assert s <= mrc * (1 + 1e-12)  # Cauchy-Schwarz
        assert s >= mrc / branches * (1 - 1e-12)


def test_egc_can_lose_to_selection() -> None:
    h = [1 + 0j, 0j]
    assert abs(egc_snr(h, 1.0) - 0.5) < 1e-15
    assert max(abs(v) ** 2 for v in h) == 1.0


def test_dual_branch_closed_form() -> None:
    assert abs(ber_bpsk_rayleigh_dual(1.0) - 0.5 * (1 - math.sqrt(3) / 2)) < 1e-15
    for gdb in (0, 5, 10):
        g = cbb.undb(gdb)
        a = ber_bpsk_rayleigh_dual(g)
        assert abs(a - ber_bpsk_rayleigh_dual_integral(g)) < 1e-5 * a
    assert abs(ber_bpsk_rayleigh_dual(10.0) - 2.0704e-3) < 1e-7


def test_ber_by_simulation() -> None:
    # L = 2, gamma_bar = 5 dB, BPSK: Pb = 0.014645, so n = 20000 bits give about 293 errors.
    rng = random.Random(6003)
    n, g = 20000, cbb.undb(5.0)
    n0 = 1.0 / g
    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) for v in h]
        est, _ = egc(h, y)
        errors += (est.real >= 0) != (x > 0)
    lo, hi = cbb.wilson(errors, n, 3.29)
    assert lo <= ber_bpsk_rayleigh_dual(g) <= hi


def test_mean_snr_gain() -> None:
    rng = random.Random(6004)
    n = 20000
    for branches in (2, 4):
        total = sum(egc_snr([cbb.cn(rng, 1.0) for _ in range(branches)], 1.0) for _ in range(n))
        assert abs(total / n - mean_snr_gain(branches)) < 0.03 * mean_snr_gain(branches)
    assert abs(mean_snr_gain(2) - 1.7854) < 1e-4 and abs(mean_snr_gain(4) - 3.3562) < 1e-4

History

Brennan (1959) surveyed linear diversity combining, analyzed equal gain combining next to maximal ratio and selection combining, and showed that it comes close to maximal ratio combining in Rayleigh fading. Equal gain combining was attractive in early analog receivers because cophasing is easier to build than accurate gain weighting. Its error rates for more branches and for other fading models need numerical methods; Simon and Alouini (2005, Section 9.3) treat EGC over generalized fading channels.

References

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

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