Algorithm Search⌘K

Algorithmcore

Comb-type pilot channel estimation

Also called comb pilot interpolation.

Estimates the OFDM channel by least squares on pilot subcarriers spaced evenly across the band in every symbol, and interpolates it to the data subcarriers along frequency.

Time
O(N) worst
Space
O(N) extra
Where
N = the number of subcarriers
Properties
deterministickeeps pilotsnot needs channel statisticstracks every symbol
Origin
Sinem Coleri, Mustafa Ergen, Anuj Puri, Ahmad Bahai, 2002

Comb-type pilot channel estimation is the simplest way for an OFDM receiver to learn the channel gain H[k]H[k] of every subcarrier in every symbol. The transmitter puts known pilot values on the subcarriers k0,k0+D,k0+2D,…k_0, k_0 + D, k_0 + 2D, \ldots, a comb with spacing DD, and data on the others. After the DFT, the receiver has Y[k]=H[k]X[k]+W[k]Y[k] = H[k] X[k] + W[k]. At each pilot it takes the least squares estimate Y[p]/X[p]Y[p] / X[p], and between pilots it interpolates along frequency, here linearly or with a quadratic through three pilots. The channel response H[k]H[k] is the DFT of the taps, so it has period NN in kk and the interpolation wraps around from the last pilot to the first. The estimate is good when the channel changes slowly across the band, that is, when its delay spread is short compared with the symbol: for a channel of LL taps, the comb needs D≤N/LD \le N / L. Because every symbol carries pilots, the estimate follows a channel that changes from symbol to symbol. The page uses jj for the imaginary unit and H[k]=∑lhle−j2πlk/NH[k] = \sum_l h_l e^{-j 2\pi l k / N}.

In plain words

The receiver needs to know how much the channel boosts and turns each subcarrier, so that it can undo it. The sender reserves every fourth subcarrier, say, for a value the receiver already knows. On those, the receiver divides what it got by what was sent, which gives the channel there. For the subcarriers in between, it guesses by drawing a straight line between the two nearest known points. This works well when the channel changes smoothly from one subcarrier to the next, which is the case when the echoes in the channel are short. Long echoes make the channel change quickly across the band, and then the pilots must be closer together.

The problem

The input is one OFDM symbol after the DFT, Y[0],…,Y[N−1]Y[0], \ldots, Y[N-1], the known pilot values X[p]X[p] on the comb p=k0+iDp = k_0 + iD, i=0,…,N/D−1i = 0, \ldots, N/D - 1, with DD dividing NN, and the order of interpolation. The model is Y[k]=H[k]X[k]+W[k]Y[k] = H[k] X[k] + W[k] with an unknown channel of LL taps and white noise W[k]∼CN(0,N0)W[k] \sim \mathcal{CN}(0, N_0). Output an estimate H^[k]\hat H[k] for all NN subcarriers.

The algorithm

  1. COMB-PILOT(Y, X_p, D, k0)
  2. 1Ĥ_p[i] ← Y[k0 + iD] / X_p[i] for i = 0, .., P-1, with P = N / D
  3. 2for k ← 0, .., N-1: (i, rem) ← divmod((k - k0) mod N, D)
  4. 3t ← rem / D
  5. 4a ← Ĥ_p[i]; b ← Ĥ_p[(i + 1) mod P]
  6. 5Ĥ[k] ← (1 - t) a + t b
  7. 6return Ĥ

Line L1 is the least squares estimate at each pilot. Line L2 finds the last pilot at or before kk on the circle of subcarriers and the distance to it; line L3 turns the distance into a fraction. Line L4 takes that pilot and the next one, wrapping from the last pilot to the first. Line L5 interpolates linearly. The quadratic option of the implementation replaces line L5 by the Lagrange polynomial through the pilots at t=−1,0,1t = -1, 0, 1, with weights t(t−1)/2t(t-1)/2, (1−t)(1+t)(1-t)(1+t) and t(t+1)/2t(t+1)/2.

Example

Take N=16N = 16, D=4D = 4, k0=0k_0 = 0, the channel h=(1,0.5)h = (1, 0.5), all pilot values 1 and no noise, so the pilots on k=0,4,8,12k = 0, 4, 8, 12 see H[k]=1+0.5e−j2πk/16H[k] = 1 + 0.5 e^{-j 2\pi k / 16} exactly.

kk H[k]H[k] linear H^[k]\hat H[k] linear error quadratic H^[k]\hat H[k] quadratic error
0 1.5001.500 1.5001.500 0 1.5001.500 0
1 1.462−0.191j1.462 - 0.191j 1.375−0.125j1.375 - 0.125j 0.109 1.469−0.125j1.469 - 0.125j 0.067
2 1.354−0.354j1.354 - 0.354j 1.250−0.250j1.250 - 0.250j 0.146 1.375−0.250j1.375 - 0.250j 0.106
3 1.191−0.462j1.191 - 0.462j 1.125−0.375j1.125 - 0.375j 0.109 1.219−0.375j1.219 - 0.375j 0.091
4 1.000−0.500j1.000 - 0.500j 1.000−0.500j1.000 - 0.500j 0 1.000−0.500j1.000 - 0.500j 0
5 0.809−0.462j0.809 - 0.462j 0.875−0.375j0.875 - 0.375j 0.109 0.875−0.469j0.875 - 0.469j 0.067
6 0.646−0.354j0.646 - 0.354j 0.750−0.250j0.750 - 0.250j 0.146 0.750−0.375j0.750 - 0.375j 0.106
7 0.538−0.191j0.538 - 0.191j 0.625−0.125j0.625 - 0.125j 0.109 0.625−0.219j0.625 - 0.219j 0.091
8 0.5000.500 0.5000.500 0 0.5000.500 0

The pilots are kept exactly. The largest linear error is 0.1460.146, in the middle between pilots, and the bound of the claim below is π2⋅162⋅256⋅0.5=0.154\frac{\pi^2 \cdot 16}{2 \cdot 256} \cdot 0.5 = 0.154. The quadratic estimate is closer on this smooth channel. With D=4D = 4 and N=16N = 16, there are 4 pilots for a channel of 2 taps, so the comb is dense enough, but only just for a linear interpolator.

Measured on N=64N = 64 with three random taps of powers 0.50.5, 0.30.3, 0.20.2 and no noise, the mean squared error of the interpolation is about 3.2×10−53.2 \times 10^{-5} (linear) and 1.1×10−61.1 \times 10^{-6} (quadratic) for D=2D = 2, 6.5×10−46.5 \times 10^{-4} and 9.2×10−59.2 \times 10^{-5} for D=4D = 4, and 1.08×10−21.08 \times 10^{-2} and 5.3×10−35.3 \times 10^{-3} for D=8D = 8.

Correctness

Claim. (a) The estimate equals the least squares estimate on every pilot. (b) Without noise, ∣H^[k]−H[k]∣≤D28max⁡f∣H′′(f)∣≤π2D22N2∑ll2∣hl∣|\hat H[k] - H[k]| \le \frac{D^2}{8} \max_f |H''(f)| \le \frac{\pi^2 D^2}{2 N^2} \sum_l l^2 |h_l| for every kk, where H(f)H(f) is the channel response at a real frequency index ff. (c) On a flat channel with unit-modulus pilots, the noise in the linear estimate has the mean variance 0.6875 N00.6875\, N_0 over the band for D=4D = 4. All three are theorems in the model above.

Key invariant. H(f)=∑lhle−j2πlf/NH(f) = \sum_l h_l e^{-j 2\pi l f / N} is smooth and has period NN, so the pilot after the last one is the first pilot moved by NN, with the same value. Lines L2 to L5 therefore interpolate one smooth periodic function at equally spaced points, with no edge at the ends of the band.

Part (b) is the error of linear interpolation in the Peano kernel form, which holds for complex functions, together with ∣H′′(f)∣≤(2π/N)2∑ll2∣hl∣|H''(f)| \le (2\pi/N)^2 \sum_l l^2 |h_l|. Part (c) is the variance of (1−t)Wa+tWb(1 - t) W_a + t W_b. The full proof is below.

Proof: Comb pilot interpolation keeps the pilots, wraps around the band correctly, and has a bounded error on a short channelfull

Notation. NN subcarriers, pilots on pi=k0+iDp_i = k_0 + iD for i=0,…,P−1i = 0, \ldots, P - 1 with P=N/DP = N / D, and Y[k]=H[k]X[k]+W[k]Y[k] = H[k] X[k] + W[k] after the DFT. The channel has taps h0,…,hL−1h_0, \ldots, h_{L-1}, and H[k]=∑lhle−j2πlk/NH[k] = \sum_l h_l e^{-j 2\pi l k / N}, the unnormalized DFT of the taps, as on the OFDM page. Write H(f)H(f) for the same sum at a real argument ff; it is smooth and has period NN in ff.

Lemma 1 (least squares at the pilots). Line L1 gives H^pi=H[pi]+W[pi]/X[pi]\hat H_{p_i} = H[p_i] + W[p_i] / X[p_i]. Without noise it is exact.

Proof. Divide Y[pi]Y[p_i] by the known nonzero X[pi]X[p_i]. □\square

Lemma 2 (the interpolant). For every kk, lines L2 to L5 return (1−t)H^pi+t H^pi+1(1 - t)\hat H_{p_i} + t\, \hat H_{p_{i+1}}, where pip_i is the last pilot at or before kk on the circle, t=(k−pi)/D∈[0,1)t = (k - p_i)/D \in [0, 1), and pPp_P means p0+Np_0 + N. On the pilots (t=0t = 0) it returns the pilot estimate.

Proof. Line L2 writes (k−k0) mod N=iD+rem(k - k_0) \bmod N = iD + \text{rem} with 0≤rem<D0 \le \text{rem} < D, so pi=k0+iDp_i = k_0 + iD is the last pilot at or before kk, counting around the circle, and rem\text{rem} is the distance from it. Line L3 sets t=rem/Dt = \text{rem}/D. Line L4 takes the pilot ii and the next one, index (i+1) mod P(i + 1) \bmod P, which for i=P−1i = P - 1 is p0p_0, the first pilot of the next period. Line L5 is the linear formula. □\square

Because H(f)H(f) has period NN, the value at p0+Np_0 + N is H[p0]H[p_0], so the wrap of line L4 interpolates the periodic function H(f)H(f) on an unrolled axis, with no edge effect at the band ends.

Theorem 1 (error bound without noise). Without noise, for every kk,

∣H^[k]−H[k]∣≤D28max⁡f∣H′′(f)∣≤π2D22N2∑l=0L−1l2∣hl∣.|\hat H[k] - H[k]| \le \frac{D^2}{8} \max_f |H''(f)| \le \frac{\pi^2 D^2}{2 N^2} \sum_{l=0}^{L-1} l^2 |h_l|.

Proof. By Lemmas 1 and 2, H^[k]\hat H[k] is the linear interpolant of H(f)H(f) between a=pia = p_i and b=a+Db = a + D, evaluated at x=kx = k. For a twice differentiable complex function gg on [a,b][a, b], the Peano kernel form of the linear interpolation error is

g(x)−(b−xb−ag(a)+x−ab−ag(b))=−∫abK(x,s) g′′(s) ds,g(x) - \left( \tfrac{b - x}{b - a} g(a) + \tfrac{x - a}{b - a} g(b) \right) = -\int_a^b K(x, s)\, g''(s)\, ds,

with K(x,s)=(s−a)(b−x)b−aK(x, s) = \frac{(s - a)(b - x)}{b - a} for s≤xs \le x and (x−a)(b−s)b−a\frac{(x - a)(b - s)}{b - a} for s≥xs \ge x. The kernel is nonnegative and ∫abK(x,s) ds=(x−a)(b−x)2≤(b−a)28\int_a^b K(x, s)\, ds = \frac{(x - a)(b - x)}{2} \le \frac{(b - a)^2}{8}. Taking absolute values inside the integral gives the first bound with b−a=Db - a = D; the argument applies to complex gg because it does not use the mean value theorem. For the second bound, H′′(f)=∑l(−j2πl/N)2hle−j2πlf/NH''(f) = \sum_l (-j 2\pi l / N)^2 h_l e^{-j 2\pi l f / N}, so ∣H′′(f)∣≤(2π/N)2∑ll2∣hl∣|H''(f)| \le (2\pi / N)^2 \sum_l l^2 |h_l|. □\square

The bound shows the design rule: the error scales as (D⋅delay/N)2(D \cdot \text{delay} / N)^2, so the pilot spacing DD must be small compared with NN divided by the delay spread in samples.

Theorem 2 (noise on a flat channel). If H[k]=HH[k] = H for all kk, the pilot values have ∣X[p]∣=1|X[p]| = 1 and the noise on the pilots is independent CN(0,N0)\mathcal{CN}(0, N_0), then the linear estimate at fraction tt has the error (1−t)Wa+tWb(1 - t) W_a + t W_b with variance ((1−t)2+t2)N0((1 - t)^2 + t^2) N_0, and the mean over the DD positions t=0,1/D,…,(D−1)/Dt = 0, 1/D, \ldots, (D-1)/D is

N0D∑r=0D−1((1−rD)2+(rD)2),\frac{N_0}{D} \sum_{r=0}^{D-1} \left( \left(1 - \tfrac{r}{D}\right)^2 + \left(\tfrac{r}{D}\right)^2 \right),

which is 0.6875 N00.6875\, N_0 for D=4D = 4.

Proof. On a flat channel the interpolant of the true values is HH itself, so the error is the interpolant of the noise terms W[p]/X[p]W[p] / X[p], which are independent CN(0,N0)\mathcal{CN}(0, N_0) because ∣X[p]∣=1|X[p]| = 1. The variance of a weighted sum of independent terms is the sum of the squared weights times N0N_0. For D=4D = 4 the four terms are 11, 0.6250.625, 0.50.5 and 0.6250.625, whose mean is 0.68750.6875. □\square

The quadratic option (closed form). With order 2, the estimate is the Lagrange polynomial through the pilots at t=−1,0,1t = -1, 0, 1, with weights t(t−1)/2t(t - 1)/2, (1−t)(1+t)(1 - t)(1 + t) and t(t+1)/2t(t + 1)/2. It reproduces every quadratic exactly, so its error term involves H′′′H''' instead of H′′H'', which makes it smaller on smooth channels. Its noise factor is the mean of the squared weights, 0.81543 N00.81543\, N_0 for D=4D = 4, larger than for the linear estimate, because the weights sum to 1 and one of them is negative, so the other two sum to more than 1.

Complexity

Line L1 is P=N/DP = N / D divisions and lines L2 to L5 cost O(1)O(1) per subcarrier, so the time is O(N)O(N) and the extra space is O(N)O(N) for the output in the real RAM. The receiver needs no channel statistics and no matrix.

Properties

  • Pilot overhead. One subcarrier in DD carries no data, a rate loss of 1/D1/D in every symbol.
  • Spacing rule. H[k]H[k] is a sum of LL complex exponentials in kk, so P≥LP \ge L equally spaced samples determine it, which is the condition D≤N/LD \le N / L. Interpolation by low-degree polynomials needs a denser comb than this limit to keep the bias small.
  • Bias and noise. The bias grows as D2D^2 for linear interpolation (Claim (b)). The noise is never amplified above N0N_0: linear weights are in [0,1][0, 1] and sum to 1, so the noise factor is between 1/21/2 and 11, and 0.68750.6875 on average for D=4D = 4. The quadratic option has less bias and a larger noise factor, 0.815430.81543 for D=4D = 4.
  • Tracking. Each symbol is estimated on its own, so the estimate follows fast fading in time, unlike block-type pilots, which send a full pilot symbol now and then.
  • Model-free. It needs no knowledge of the delay profile or the SNR, unlike LMMSE estimation.

Variants and improvements

  • Higher-order interpolation. Coleri and coauthors compared linear, second order, low-pass and spline interpolation for comb pilots; smoother interpolators have less bias on channels with longer delays.
  • Through the DFT. Taking the inverse DFT of the pilot estimates, keeping the first LL taps and transforming back is exact for P≥LP \ge L without noise and removes most of the noise; see DFT-based channel estimation.
  • LMMSE across frequency. A Wiener filter with the frequency correlation of the channel gives the smallest mean squared error when the statistics are known.
  • Scattered pilots in two dimensions. Pilots spread over both time and frequency, as in DVB-T and LTE, need fewer pilots per symbol; two-dimensional Wiener interpolation is the optimal filter for that layout.
  • Block-type pilots. All subcarriers carry pilots in some symbols, which suits slow channels with long delays.

When to use it

Use comb pilots with linear interpolation when the receiver must be simple, the channel changes from symbol to symbol, and the delay spread is short compared with N/DN / D samples. Use a smoother interpolator or the DFT-based estimate for longer delays, and the Wiener or LMMSE estimates when the delay profile and the SNR are known and the cost of a matrix is acceptable.

Pitfalls

  • No wrap at the band edge. Line L4 must take the next pilot as index (i+1) mod P(i + 1) \bmod P. Without the wrap, the subcarriers after the last pilot have no right neighbor, and holding the last value gives a large error there.
  • Spacing too large. Line L1 samples HH every DD subcarriers. If D>N/LD > N / L, the comb aliases the channel, and no interpolation in line L5 can recover it.
  • The wrong offset. Line L2 must subtract the comb offset k0k_0 before the division. Without it, tt is wrong for every subcarrier when k0≠0k_0 \ne 0.
  • Dividing by the wrong pilot. Line L1 must divide by the known value on the same subcarrier, Xp[i]X_p[i] for p=k0+iDp = k_0 + iD, not by the first pilot value or by the received pilot.
  • Null subcarriers. Real systems leave the DC and edge subcarriers empty, so the comb is not periodic over NN. Line L4 then wraps across a gap, and the estimate near the edges needs extrapolation instead.

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)
comb_pilot_channel_estimation.py 50 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/comb-pilot-channel-estimation/. The authors are listed in prov/VPF3QG.jsonl.

"""Channel estimation in OFDM from comb-type pilots.

Every OFDM symbol carries known pilot values on the subcarriers
k0, k0 + D, k0 + 2D, ... (a comb with spacing D). The receiver sees
Y[k] = H[k] X[k] + W[k] on each subcarrier. It takes the least squares
estimate H_p = Y[p] / X[p] at each pilot and interpolates between pilots
along frequency. H[k] is periodic in k with period N (it is the DFT of the
taps), so the interpolation wraps around from the last pilot to the first.

order=1 is linear interpolation between the two nearest pilots.
order=2 is quadratic Lagrange interpolation through three pilots: the one
before k, the one after k and the one before that.
"""


def pilot_positions(n: int, spacing: int, k0: int = 0) -> list[int]:
    """The pilot subcarriers k0, k0 + D, ..., below N. N must be a multiple of D."""
    if spacing < 1 or n % spacing or not 0 <= k0 < spacing:
        raise ValueError("need N a multiple of D and 0 <= k0 < D")
    return list(range(k0, n, spacing))


def estimate(y: list[complex], pilot_values: list[complex], spacing: int, k0: int = 0, order: int = 1) -> list[complex]:
    """The channel estimate on all N subcarriers.

    y is the received symbol after the DFT. pilot_values[i] is the known value
    sent on subcarrier k0 + i D.
    """
    n = len(y)
    ps = pilot_positions(n, spacing, k0)
    if len(pilot_values) != len(ps):
        raise ValueError("one pilot value per pilot subcarrier")
    if order not in (1, 2):
        raise ValueError("order is 1 or 2")
    count = len(ps)
    hp = [y[p] / x for p, x in zip(ps, pilot_values)]  # @line L1
    out = []
    for k in range(n):
        i, rem = divmod((k - k0) % n, spacing)  # @line L2
        t = rem / spacing  # @line L3
        a, b = hp[i], hp[(i + 1) % count]  # @line L4
        if order == 1:
            out.append((1 - t) * a + t * b)  # @line L5
        else:
            c = hp[(i - 1) % count]
            out.append(t * (t - 1) / 2 * c + (1 - t) * (1 + t) * a + t * (t + 1) / 2 * b)
    return out  # @line L6
test_comb_pilot_channel_estimation.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/comb-pilot-channel-estimation/. The authors are listed in prov/VPF3QG.jsonl.

import math
import random

import cbb
from comb_pilot_channel_estimation import estimate, pilot_positions

S = 1 / math.sqrt(2)


def qpsk(rng: random.Random, n: int) -> list[complex]:
    return [complex(rng.choice((S, -S)), rng.choice((S, -S))) for _ in range(n)]


def channel(rng: random.Random, powers: tuple[float, ...], n: int) -> tuple[list[complex], list[complex]]:
    h = [cbb.cn(rng, p) for p in powers]
    return h, cbb.dft(h + [0j] * (n - len(h)))


def linear_reference(points: list[tuple[float, complex]], k: float) -> complex:
    """Piecewise linear interpolation by a search over the sorted points (a plain reference)."""
    for (u, a), (v, b) in zip(points, points[1:]):
        if u <= k <= v:
            return a + (b - a) * (k - u) / (v - u)
    raise ValueError("k outside the points")


def test_pilots_are_kept_and_spacing_one_is_plain_least_squares() -> None:
    rng = random.Random(1)
    n = 32
    _, hf = channel(rng, (0.5, 0.3, 0.2), n)
    x = qpsk(rng, n)
    y = cbb.awgn(rng, [a * b for a, b in zip(hf, x)], 0.1)
    assert max(abs(e - yk / xk) for e, yk, xk in zip(estimate(y, x, 1), y, x)) < 1e-12
    for d, k0 in ((4, 0), (4, 3), (8, 5)):
        ps = pilot_positions(n, d, k0)
        xp = [x[p] for p in ps]
        for order in (1, 2):
            est = estimate(y, xp, d, k0, order)
            assert max(abs(est[p] - y[p] / x[p]) for p in ps) < 1e-12


def test_linear_matches_a_reference_with_wrap_around() -> None:
    rng = random.Random(2)
    n, d, k0 = 32, 4, 2
    ps = pilot_positions(n, d, k0)
    y = [cbb.cn(rng, 1.0) for _ in range(n)]
    xp = qpsk(rng, len(ps))
    hp = [y[p] / x for p, x in zip(ps, xp)]
    # The pilots on an unrolled axis: the last one moved down by N and the first one moved up by N.
    points = [(ps[-1] - n, hp[-1])] + list(zip(ps, hp)) + [(ps[0] + n, hp[0])]
    est = estimate(y, xp, d, k0)
    for k in range(n):
        kk = k if k >= ps[0] - d else k + n
        assert abs(est[k] - linear_reference(points, kk)) < 1e-12


def test_error_bound_without_noise() -> None:
    # Theorem: |error| <= (D^2 / 8) max |H''| <= (pi^2 D^2 / (2 N^2)) sum of l^2 |h_l|.
    rng = random.Random(3)
    n = 64
    for d in (2, 4, 8):
        for _ in range(20):
            h, hf = channel(rng, (0.4, 0.3, 0.2, 0.1), n)
            est = estimate(hf, [1] * (n // d), d)
            bound = math.pi ** 2 * d * d / (2 * n * n) * sum(l * l * abs(c) for l, c in enumerate(h))
            assert max(abs(a - b) for a, b in zip(est, hf)) <= bound + 1e-12


def test_quadratic_has_less_bias_on_a_smooth_channel() -> None:
    # Measurement: 3 taps of power 0.5, 0.3, 0.2, N = 64, no noise, 30 channels.
    # D = 4: linear about 6.5e-4, quadratic about 9e-5 mean squared error.
    rng = random.Random(4)
    n, d = 64, 4
    e1 = e2 = 0.0
    for _ in range(30):
        _, hf = channel(rng, (0.5, 0.3, 0.2), n)
        a = estimate(hf, [1] * (n // d), d, order=1)
        b = estimate(hf, [1] * (n // d), d, order=2)
        e1 += sum(abs(u - v) ** 2 for u, v in zip(a, hf))
        e2 += sum(abs(u - v) ** 2 for u, v in zip(b, hf))
    assert e2 < e1 / 3


def test_noise_gain_on_a_flat_channel() -> None:
    # Closed form for a flat channel: at fraction t between two pilots the error is (1 - t) W_a + t W_b,
    # so the mean squared error over the spacing is mean of ((1 - t)^2 + t^2) N0 = 0.6875 N0 for D = 4.
    # Quadratic: mean of the squared Lagrange weights = 0.81543 N0. 400 symbols of N = 64, seed 5.
    rng = random.Random(5)
    n, d, n0, hval = 64, 4, 0.1, 0.7 - 0.2j
    f1 = sum((1 - r / d) ** 2 + (r / d) ** 2 for r in range(d)) / d
    f2 = 0.0
    for r in range(d):
        t = r / d
        f2 += ((t * (t - 1) / 2) ** 2 + ((1 - t) * (1 + t)) ** 2 + (t * (t + 1) / 2) ** 2) / d
    assert abs(f1 - 0.6875) < 1e-12
    assert abs(f2 - 0.81543) < 1e-5
    e1 = e2 = 0.0
    trials = 400
    for _ in range(trials):
        xp = qpsk(rng, n // d)
        y = [0j] * n
        for i, p in enumerate(range(0, n, d)):
            y[p] = hval * xp[i] + cbb.cn(rng, n0)
        a = estimate(y, xp, d, order=1)
        b = estimate(y, xp, d, order=2)
        e1 += sum(abs(u - hval) ** 2 for u in a)
        e2 += sum(abs(u - hval) ** 2 for u in b)
    assert 0.93 < e1 / (trials * n) / (f1 * n0) < 1.07
    assert 0.93 < e2 / (trials * n) / (f2 * n0) < 1.07

History

Pilot-symbol-assisted modulation for fading channels was analyzed for single-carrier systems before OFDM receivers used it. For OFDM, van de Beek, Edfors, Sandell, Wilson and Börjesson studied least squares and LMMSE estimates in 1995, Hoeher, Kaiser and Robertson in 1997 treated pilots spread in time and frequency with two-dimensional Wiener filters, and Coleri, Ergen, Puri and Bahai in 2002 gave a widely cited comparison of block-type and comb-type arrangements and of the interpolators for comb pilots. Comb and scattered pilots with simple interpolation are the usual design in DVB-T, LTE and 5G NR receivers.

References

  1. S. Coleri, M. Ergen, A. Puri and A. Bahai, Channel estimation techniques based on pilot arrangement in OFDM systems, IEEE Transactions on Broadcasting 48(3), 2002, pages 223 to 229 (block-type and comb-type pilot arrangements, least squares at the pilots, and the comparison of interpolation methods)
  2. J.-J. van de Beek, O. Edfors, M. Sandell, S. K. Wilson and P. O. Börjesson, On channel estimation in OFDM systems, IEEE 45th Vehicular Technology Conference, 1995, pages 815 to 819 (least squares and linear minimum mean squared error estimates, and the estimate through the DFT)
  3. P. Hoeher, S. Kaiser and P. Robertson, Two-dimensional pilot-symbol-aided channel estimation by Wiener filtering, IEEE ICASSP, 1997, volume 3, pages 1845 to 1848 (pilots spread in time and frequency, and their interpolation by two-dimensional Wiener filters)

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