Algorithm Search⌘K

Algorithmintro

Maximal ratio combining

Also called maximum ratio combining.

Weights each diversity branch by the conjugate of its gain over its noise power and adds the branches. The output SNR is the sum of the branch SNRs, the largest of any linear combiner.

Time
O(L) worst
Space
O(1) extra
Where
L = the number of diversity branches
Properties
needs branch noise powersneeds branch phasesoptimal linear combiner
Origin
Leonard R. Kahn, D. G. Brennan, 1954

Maximal ratio combining (MRC) is a linear receiver for LL diversity branches that see the same symbol through different fading gains: it multiplies each branch by the conjugate of its gain, divided by its noise power, and adds the results. Among the combiners of the diversity order family, MRC has the highest output SNR; equal gain combining only aligns the phases, and selection combining keeps one branch. Maximum ratio transmission is the same weighting used at a transmitter with several antennas, and the rake receiver applies MRC to the delayed copies of one signal.

In plain words

Suppose the same message arrives over several antennas, and each copy is faded and noisy in its own way. Some copies are strong, some are weak, and each one arrives with its own phase. MRC turns each copy so that all of them point the same way, then gives each copy a weight that grows with its strength and shrinks with its noise. A strong, clean copy counts a lot and a weak, noisy copy counts little. After the copies are added, the signal parts add up in step, while the noise parts, which are independent, add up only in power. The result is as good as one copy whose quality is the total of the qualities of all the copies.

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 of the branch, 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}, and γˉ=E[γl]\bar\gamma = E[\gamma_l] is its mean. The receiver has CSIR: it knows hlh_l and N0,lN_{0,l}. The task is to form one statistic z=∑lcl∗ylz = \sum_l c_l^* y_l with the largest SNR, and to pass zz to a symbol detector. The gains may follow block fading, with one value per codeword, or fast fading, with a new value per symbol; the combiner acts symbol by symbol either way. There is no CSIT.

The algorithm

  1. MRC(h[1..L], y[1..L], N0[1..L])
  2. 1c_l ← h_l / N0_l for l = 1 .. L ▷ the combining weights
  3. 2z ← Σ_l conj(c_l) · y_l
  4. 3g ← Σ_l |h_l|² / N0_l ▷ the output SNR per unit symbol energy
  5. 4return z / g, g ▷ z / g = x + noise of variance 1 / g

Line L1 is the weight of the branch: the conjugate in line L2 removes the phase of hlh_l, and the factor ∣hl∣/N0,l|h_l|/N_{0,l} gives each branch a share that grows with its gain and falls with its noise. Line L3 is the normalization that turns zz into an unbiased estimate of xx, z/g=x+nz/g = x + n with n∼CN(0,1/g)n \sim CN(0, 1/g), so a detector for Gaussian noise, such as the minimum distance detector, can follow. When all branches have the same noise power, the weights reduce to cl=hlc_l = h_l, up to a common factor.

Example

Take L=2L = 2 branches with N0=1N_0 = 1, gains h1=1+jh_1 = 1 + j and h2=0.5jh_2 = 0.5j, and BPSK with x=1x = 1. With no noise, y1=1+jy_1 = 1 + j and y2=0.5jy_2 = 0.5j. Line L2 gives z=(1−j)(1+j)+(−0.5j)(0.5j)=2+0.25=2.25z = (1 - j)(1 + j) + (-0.5j)(0.5j) = 2 + 0.25 = 2.25, and line L3 gives g=2+0.25=2.25g = 2 + 0.25 = 2.25, so z/g=1=xz/g = 1 = x. The output SNR is Esg=γ1+γ2E_s g = \gamma_1 + \gamma_2, with γ1=2\gamma_1 = 2 and γ2=0.25\gamma_2 = 0.25 for Es=1E_s = 1. Selection combining would get only 2 from this channel.

For LL independent Rayleigh branches with mean γˉ\bar\gamma each, the output SNR γ=∑lγl\gamma = \sum_l \gamma_l has the gamma distribution with shape LL and mean LγˉL\bar\gamma. With μ=γˉ/(1+γˉ)\mu = \sqrt{\bar\gamma/(1 + \bar\gamma)}, the bit error rate of coherent BPSK is the closed form (independent Rayleigh branches, perfect CSIR)

Pb=(1−μ2)L∑k=0L−1(L−1+kk)(1+μ2)k.P_b = \Big(\frac{1 - \mu}{2}\Big)^L \sum_{k=0}^{L-1} \binom{L - 1 + k}{k} \Big(\frac{1 + \mu}{2}\Big)^k.
γˉ\bar\gamma per branch L=1L = 1 L=2L = 2 L=4L = 4
5 dB 0.06418 0.011829 5.073⋅10−45.073 \cdot 10^{-4}
10 dB 0.023269 1.5991⋅10−31.5991 \cdot 10^{-3} 9.698⋅10−69.698 \cdot 10^{-6}
20 dB 2.4814⋅10−32.4814 \cdot 10^{-3} 1.8442⋅10−51.8442 \cdot 10^{-5} 1.319⋅10−91.319 \cdot 10^{-9}

The high-SNR form (2L−1L)/(4γˉ)L\binom{2L - 1}{L}/(4\bar\gamma)^L gives 1.875⋅10−31.875 \cdot 10^{-3} for L=2L = 2 at 10 dB. The outage probability is Pr⁡[γ<x]=1−e−x/γˉ∑k=0L−1(x/γˉ)k/k!\Pr[\gamma < x] = 1 - e^{-x/\bar\gamma}\sum_{k=0}^{L-1}(x/\bar\gamma)^k/k!, which is 4.6788⋅10−34.6788 \cdot 10^{-3} for L=2L = 2, x=1x = 1 and γˉ=10\bar\gamma = 10 dB. A simulation of 20000 BPSK bits with L=2L = 2 at 5 dB (seed 5003) gives a Wilson interval with z=3.29z = 3.29 that contains 0.011829.

Correctness

Claim. For any weights clc_l, not all zero, the SNR of z=∑lcl∗ylz = \sum_l c_l^* y_l is Es∣∑lcl∗hl∣2/∑l∣cl∣2N0,lE_s|\sum_l c_l^* h_l|^2 / \sum_l |c_l|^2 N_{0,l}, and it is at most ∑lγl\sum_l \gamma_l, with equality if and only if cl=a hl/N0,lc_l = a\, h_l / N_{0,l} for one complex a≠0a \ne 0. So MRC maximizes the output SNR over all linear combiners, and its output SNR is γ1+⋯+γL\gamma_1 + \cdots + \gamma_L. This is a theorem.

Key step. Write cl∗hl=(cl∗N0,l)(hl/N0,l)c_l^* h_l = (c_l^* \sqrt{N_{0,l}})(h_l/\sqrt{N_{0,l}}) and apply the Cauchy-Schwarz inequality to the two vectors. The equality case of Cauchy-Schwarz gives the weights. For Gaussian noise and a known channel, z/gz/g is a sufficient statistic for xx, so MRC followed by the AWGN detector is the maximum likelihood detector. The full proof is in the proofs folder.

Proof: Maximal ratio combining gives the largest output SNR of any linear combiner, equal to the sum of the branch SNRs, and keeps all information about the symbolfull

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, and N0,l>0N_{0,l} > 0. The gains hlh_l are known and not all zero. Write γl=∣hl∣2Es/N0,l\gamma_l = |h_l|^2 E_s/N_{0,l} and g=∑l∣hl∣2/N0,l>0g = \sum_l |h_l|^2 / N_{0,l} > 0.

Lemma 1 (SNR of a linear combiner). For weights c=(c1,…,cL)≠0c = (c_1, \ldots, c_L) \ne 0, z=∑lcl∗yl=(∑lcl∗hl) x+∑lcl∗wlz = \sum_l c_l^* y_l = (\sum_l c_l^* h_l)\, x + \sum_l c_l^* w_l, and the ratio of signal energy to noise variance is

SNR(c)=Es∣∑lcl∗hl∣2∑l∣cl∣2N0,l.\mathrm{SNR}(c) = \frac{E_s \left|\sum_l c_l^* h_l\right|^2}{\sum_l |c_l|^2 N_{0,l}}.

Proof. The noise term ∑lcl∗wl\sum_l c_l^* w_l is a sum of independent zero-mean terms, so its variance is ∑l∣cl∣2E∣wl∣2=∑l∣cl∣2N0,l\sum_l |c_l|^2 E|w_l|^2 = \sum_l |c_l|^2 N_{0,l}, which is positive because c≠0c \ne 0. The signal term has energy ∣∑lcl∗hl∣2Es|\sum_l c_l^* h_l|^2 E_s. □\square

Theorem 1 (MRC is the best linear combiner). SNR(c)≤∑lγl\mathrm{SNR}(c) \le \sum_l \gamma_l for every c≠0c \ne 0, with equality if and only if cl=a hl/N0,lc_l = a\, h_l/N_{0,l} for all ll, for some complex a≠0a \ne 0.

Proof. Let ul=clN0,lu_l = c_l \sqrt{N_{0,l}} and vl=hl/N0,lv_l = h_l / \sqrt{N_{0,l}}. Then ∑lcl∗hl=∑lul∗vl\sum_l c_l^* h_l = \sum_l u_l^* v_l, and the Cauchy-Schwarz inequality gives ∣∑lul∗vl∣2≤∑l∣ul∣2∑l∣vl∣2=∑l∣cl∣2N0,l⋅g|\sum_l u_l^* v_l|^2 \le \sum_l |u_l|^2 \sum_l |v_l|^2 = \sum_l |c_l|^2 N_{0,l} \cdot g. Divide by ∑l∣cl∣2N0,l\sum_l |c_l|^2 N_{0,l} and multiply by EsE_s: SNR(c)≤Esg=∑lγl\mathrm{SNR}(c) \le E_s g = \sum_l \gamma_l. Equality in Cauchy-Schwarz holds if and only if u=avu = a v for a scalar aa (with u≠0u \ne 0, so a≠0a \ne 0), which is clN0,l=a hl/N0,lc_l\sqrt{N_{0,l}} = a\, h_l/\sqrt{N_{0,l}}, that is cl=a hl/N0,lc_l = a\, h_l / N_{0,l}. □\square

Corollary (the output of the algorithm). With cl=hl/N0,lc_l = h_l/N_{0,l} as in line L1, line L2 gives z=gx+n′z = g x + n' with n′=∑l(hl∗/N0,l)wln' = \sum_l (h_l^*/N_{0,l}) w_l of variance ∑l∣hl∣2/N0,l=g\sum_l |h_l|^2/N_{0,l} = g. So z/g=x+nz/g = x + n with n∼CN(0,1/g)n \sim CN(0, 1/g), and the output SNR is Esg=∑lγlE_s g = \sum_l \gamma_l. With no noise, z/g=xz/g = x exactly.

Proof. ∑l(hl∗/N0,l)hl=g\sum_l (h_l^*/N_{0,l}) h_l = g, and Lemma 1 with cl=hl/N0,lc_l = h_l / N_{0,l} gives the variance ∑l∣hl∣2N0,l/N0,l2=g\sum_l |h_l|^2 N_{0,l}/N_{0,l}^2 = g. A sum of independent circular Gaussian variables is circular Gaussian. □\square

Theorem 2 (no loss of information). Given hh and the N0,lN_{0,l}, zz is a sufficient statistic for xx. So for any finite set of symbols with any prior, the maximum likelihood (or maximum a posteriori) decision from z/gz/g in Gaussian noise of variance 1/g1/g is the same as the decision from all of y1,…,yLy_1, \ldots, y_L.

Proof. The likelihood is p(y∣x)=∏l1πN0,lexp⁡(−∣yl−hlx∣2/N0,l)p(y \mid x) = \prod_l \frac{1}{\pi N_{0,l}} \exp(-|y_l - h_l x|^2 / N_{0,l}). Expand the exponent: ∑l∣yl−hlx∣2/N0,l=∑l∣yl∣2/N0,l−2Re⁡(x∗z)+g∣x∣2\sum_l |y_l - h_l x|^2/N_{0,l} = \sum_l |y_l|^2/N_{0,l} - 2\operatorname{Re}(x^* z) + g|x|^2, with z=∑lhl∗yl/N0,lz = \sum_l h_l^* y_l / N_{0,l}. The first term does not depend on xx, and the rest depends on yy only through zz. By the factorization theorem, zz is sufficient. The same expansion with one observation z/g=x+nz/g = x + n, n∼CN(0,1/g)n \sim CN(0, 1/g), gives the exponent g∣z/g−x∣2=∣z∣2/g−2Re⁡(x∗z)+g∣x∣2g|z/g - x|^2 = |z|^2/g - 2\operatorname{Re}(x^* z) + g|x|^2, which differs from the one above by a term free of xx, so both give the same ranking of the candidates xx. □\square

Remark (Rayleigh branches). If the hlh_l are independent CN(0,Ω)CN(0, \Omega) and all N0,l=N0N_{0,l} = N_0, the γl\gamma_l are independent exponential with mean γˉ=ΩEs/N0\bar\gamma = \Omega E_s/N_0, so γ=∑lγl\gamma = \sum_l \gamma_l has the gamma distribution with shape LL and scale γˉ\bar\gamma. Its distribution function is 1−e−x/γˉ∑k=0L−1(x/γˉ)k/k!1 - e^{-x/\bar\gamma}\sum_{k=0}^{L-1}(x/\bar\gamma)^k/k!, which is the outage formula of the page, and its moment generating function Ee−sγ=(1+sγˉ)−LE e^{-s\gamma} = (1 + s\bar\gamma)^{-L} with Craig's form of the Q function, Q(2γ)=1π∫0π/2e−γ/sin⁡2θ dθQ(\sqrt{2\gamma}) = \frac1\pi\int_0^{\pi/2} e^{-\gamma/\sin^2\theta}\, d\theta, gives the BPSK error rate Pb=1π∫0π/2(1+γˉ/sin⁡2θ)−LdθP_b = \frac1\pi\int_0^{\pi/2}(1 + \bar\gamma/\sin^2\theta)^{-L} d\theta. The test file checks that this integral equals the closed form with μ\mu within a relative error of 10−910^{-9}.

Complexity

Lines L1 to L3 take O(L)O(L) complex multiplications and additions per symbol, in the real RAM, with O(1)O(1) extra space besides the inputs. The cost of MRC is not in the arithmetic but in the inputs: each branch needs its own receiver chain and an estimate of hlh_l, and of N0,lN_{0,l} when the noise powers differ.

Properties

  • Output SNR is the sum. γMRC=∑lγl\gamma_{\mathrm{MRC}} = \sum_l \gamma_l. Its mean is LγˉL\bar\gamma, an array gain of LL, against γˉ(1+1/2+⋯+1/L)\bar\gamma(1 + 1/2 + \cdots + 1/L) for selection combining and γˉ(1+(L−1)π/4)\bar\gamma(1 + (L - 1)\pi/4) for equal gain combining.
  • Diversity order LL. With LL independent Rayleigh branches, PbP_b falls as γˉ−L\bar\gamma^{-L} at high γˉ\bar\gamma; see diversity order. Selection and equal gain combining have the same diversity order and differ only by a constant.
  • Maximum likelihood. With perfect CSIR and independent Gaussian noise, MRC loses no information about xx.
  • Scale-free weights. Multiplying all weights by one complex number does not change the SNR or the detection. Only the relative weights matter, so a common unknown phase is harmless, but a phase error per branch is not.
  • Comparison at L=2L = 2. For BPSK in Rayleigh fading at 10 dB per branch, the bit error rates are 1.599⋅10−31.599 \cdot 10^{-3} for MRC, 2.070⋅10−32.070 \cdot 10^{-3} for equal gain combining and 2.973⋅10−32.973 \cdot 10^{-3} for selection combining.

Variants and improvements

  • Maximum ratio transmission. With LL transmit antennas and CSIT, sending xx with weights hl∗/∥h∥h_l^*/\|h\| gives the same output SNR ∥h∥2Es/N0\|h\|^2 E_s/N_0 at the receiver. See maximum ratio transmission.
  • Rake receiver. In a frequency-selective channel with resolvable paths, the rake receiver uses MRC over the delayed copies, for example in CDMA.
  • Correlated noise. When the noise is correlated across branches with covariance RR, the optimal weights are c=R−1hc = R^{-1} h, the optimum combiner. MRC is the case RR diagonal. With interference, this is beamforming for the largest SINR.
  • Space-time codes. The Alamouti code gets the diversity of MRC from two transmit antennas without CSIT, at a 3 dB loss in array gain.
  • Packet combining. Chase combining in hybrid ARQ applies MRC to retransmissions of the same packet, which are branches in time.

When to use it

Use MRC whenever the receiver can estimate the gain of each branch, as with multiple receive antennas and coherent detection. It gives the best SNR of any linear combiner at the same cost in arithmetic as equal gain combining. Use equal gain combining when the branch amplitudes are not reliable, and selection combining when only one receiver chain is available. With noncoherent or differential detection, where the phases are not known, combine the detector outputs, not the signals.

Pitfalls

  • Unequal noise powers ignored. Using cl=hlc_l = h_l when the N0,lN_{0,l} differ is not MRC, and it can lose SNR. Divide by the noise power, as in line L1.
  • Channel estimation errors. The output SNR is the sum only with perfect CSIR. With estimated gains the noise of the estimate adds a loss, and a branch with a poor estimate can harm the result. See channel estimation.
  • Correlated branches. The diversity order is LL only for independent branches. Antennas spaced too closely have correlated fades; the mean output SNR stays LγˉL\bar\gamma, but the error rate falls more slowly.
  • Mean per branch against total. Error rates for LL branches are often given against γˉ\bar\gamma per branch. Against the total received power LγˉL\bar\gamma, the array gain disappears from the curve and only the diversity gain remains.

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)
maximal_ratio_combining.py 63 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximal-ratio-combining/. The authors are listed in prov/5E6BSS.jsonl.

"""Maximal ratio combining (MRC) of L diversity branches.

Branch l receives y_l = h_l x + w_l with w_l ~ CN(0, N0_l), independent. MRC
weights branch l by conj(h_l) / N0_l and adds the branches. The result,
divided by g = sum |h_l|^2 / N0_l, is x plus noise of variance 1 / g, so the
output SNR is E_s g = sum of the branch SNRs. No other linear combiner has a
higher output SNR (Cauchy-Schwarz).

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

import math


def mrc(h: list[complex], y: list[complex], n0: list[float]) -> tuple[complex, float]:
    """The MRC estimate of x and the gain g = sum |h_l|^2 / N0_l (the output SNR per unit symbol energy)."""
    if not len(h) == len(y) == len(n0) or not h:
        raise ValueError("need L >= 1 branches with h, y and N0 each")
    w = [h[l] / n0[l] for l in range(len(h))]  # @line L1
    z = sum(w[l].conjugate() * y[l] for l in range(len(h)))  # @line L2
    g = sum(abs(h[l]) ** 2 / n0[l] for l in range(len(h)))  # @line L3
    if g == 0.0:
        raise ValueError("all branch gains are zero")
    return z / g, g  # @line L4


def output_snr(weights: list[complex], h: list[complex], n0: list[float], es: float = 1.0) -> float:
    """The SNR of z = sum conj(c_l) y_l for any weights c: E_s |sum conj(c_l) h_l|^2 / sum |c_l|^2 N0_l."""
    sig = abs(sum(c.conjugate() * g for c, g in zip(weights, h))) ** 2 * es
    noise = sum(abs(c) ** 2 * v for c, v in zip(weights, n0))
    return sig / noise


def ber_bpsk_rayleigh(branches: int, gbar: float) -> float:
    """Exact BPSK bit error rate of MRC over L i.i.d. Rayleigh branches with mean SNR gamma_bar each."""
    mu = math.sqrt(gbar / (1.0 + gbar))
    return ((1.0 - mu) / 2.0) ** branches * sum(
        math.comb(branches - 1 + k, k) * ((1.0 + mu) / 2.0) ** k for k in range(branches)
    )


def ber_bpsk_rayleigh_craig(branches: int, gbar: float, points: int = 400) -> float:
    """The same error rate by the MGF method: (1 / pi) integral over (0, pi / 2) of (1 + gamma_bar / sin^2 t)^(-L) dt.

    The integrand, a function of sin^2 t, is smooth and even around both ends,
    so the midpoint rule converges very fast.
    """
    h = (math.pi / 2.0) / points
    s = 0.0
    for k in range(points):
        t = (k + 0.5) * h
        s += (1.0 + gbar / math.sin(t) ** 2) ** (-branches)
    return s * h / math.pi


def outage_rayleigh(branches: int, x: float, gbar: float) -> float:
    """P(output SNR < x) for MRC of L i.i.d. Rayleigh branches: 1 - e^(-x / gamma_bar) sum_{k<L} (x / gamma_bar)^k / k!."""
    u = x / gbar
    return 1.0 - math.exp(-u) * sum(u ** k / math.factorial(k) for k in range(branches))
test_maximal_ratio_combining.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximal-ratio-combining/. The authors are listed in prov/5E6BSS.jsonl.

import math
import random

import cbb
from maximal_ratio_combining import (
    ber_bpsk_rayleigh,
    ber_bpsk_rayleigh_craig,
    mrc,
    outage_rayleigh,
    output_snr,
)


def test_noiseless_recovery() -> None:
    rng = random.Random(5001)
    for _ in range(200):
        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, g = mrc(h, [v * x for v in h], n0)
        assert abs(est - x) < 1e-12
        assert abs(g - sum(abs(v) ** 2 / s for v, s in zip(h, n0))) < 1e-12


def test_output_snr_is_the_sum_and_is_maximal() -> None:
    rng = random.Random(5002)
    for _ in range(200):
        branches = rng.randint(1, 6)
        h = [cbb.cn(rng, 1.0) for _ in range(branches)]
        n0 = [rng.uniform(0.1, 3.0) for _ in range(branches)]
        best = output_snr([v / s for v, s in zip(h, n0)], h, n0)
        assert abs(best - sum(abs(v) ** 2 / s for v, s in zip(h, n0))) < 1e-9
        for _ in range(20):
            c = [cbb.cn(rng, 1.0) for _ in range(branches)]
            assert output_snr(c, h, n0) <= best * (1 + 1e-12)
        # scaling all weights by one complex number changes nothing
        a = complex(rng.uniform(-2, 2), rng.uniform(-2, 2))
        assert abs(output_snr([a * v / s for v, s in zip(h, n0)], h, n0) - best) < 1e-9 * best


def test_check_values() -> None:
    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) - 1.5991e-3) < 1e-7
    assert abs(ber_bpsk_rayleigh(4, 10.0) - 9.698e-6) < 1e-9
    # the high-SNR form C(2L - 1, L) / (4 gamma_bar)^L for L = 2 at 10 dB
    assert abs(math.comb(3, 2) / 40.0 ** 2 - 1.875e-3) < 1e-15


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


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


def test_mean_output_snr_and_outage() -> None:
    # mean output SNR L gamma_bar, and the outage at x = 1 for L = 2 at 10 dB: 4.68e-3,
    # so n = 25000 channels give about 117 outages
    rng = random.Random(5004)
    n, branches, g = 25000, 2, 10.0
    total, below = 0.0, 0
    for _ in range(n):
        h = [cbb.cn(rng, 1.0) for _ in range(branches)]
        snr = g * sum(abs(v) ** 2 for v in h)
        total += snr
        below += snr < 1.0
    assert abs(total / n - branches * g) < 0.05 * branches * g
    p = outage_rayleigh(branches, 1.0, g)
    assert abs(p - 4.6788e-3) < 1e-6
    lo, hi = cbb.wilson(below, n, 3.29)
    assert lo <= p <= hi

History

Kahn (1954) described a ratio squarer for diversity radio reception, a combiner that weights the receiver outputs by their signal levels. Brennan (1959) gave the name maximal ratio combining, showed that it maximizes the output SNR among linear combiners, and compared it with equal gain and selection combining in Rayleigh fading. MRC became the reference against which other diversity receivers are measured, and the rake receiver applies the same weighting to the delayed copies of a multipath signal.

References

  1. D. G. Brennan, Linear diversity combining techniques, Proceedings of the IRE 47(6), 1959, pages 1075 to 1102, the analysis of maximal ratio, equal gain and selection combining
  2. Andrea Goldsmith, Wireless Communications, Cambridge University Press, 2005, Section 7.2.4 (maximal-ratio combining)
  3. Marvin K. Simon and Mohamed-Slim Alouini, Digital Communication over Fading Channels, 2nd edition, Wiley, 2005, Chapter 9, Section 9.2 (maximal-ratio combining)
  4. David Tse and Pramod Viswanath, Fundamentals of Wireless Communication, Cambridge University Press, 2005, Section 5.4.2 (receive diversity)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example