Algorithm Search⌘K

Algorithmcore

DFT-based channel estimation

Also called transform-domain channel estimation.

Refines a least squares OFDM channel estimate by an inverse FFT, a cut to the channel length L_t and an FFT back. This removes all but L_t / N of the noise.

Time
O(N log N) worst
Space
O(N) extra
Where
N = the number of subcarriers
Properties
deterministicexact without noiseneeds channel lengthorthogonal projection
Origin
Jan Jaap van de Beek, Ove Edfors, Magnus Sandell, Sarah Kate Wilson, Per Ola Börjesson, 1995

DFT-based channel estimation improves a noisy estimate of the OFDM channel by using what the receiver knows about the channel in time: its impulse response is short. The response H[k]H[k] on NN subcarriers is the DFT of at most LtL_t taps, with LtL_t much smaller than NN, so the NN values have only LtL_t degrees of freedom. The least squares estimate Y[k]/X[k]Y[k]/X[k] has noise on all NN values. The estimator takes the inverse DFT of it, keeps the first LtL_t taps, sets the rest to zero and takes the DFT again. The result is exact without noise and keeps only the fraction Lt/NL_t / N of the noise power, because the three steps are an orthogonal projection onto the responses of channels with LtL_t taps. The cut is to the channel length LtL_t; when LtL_t is unknown, receivers often use the cyclic prefix length plus one as a safe upper bound. The same idea interpolates comb pilots exactly. The page uses jj for the imaginary unit and the unnormalized DFT pair, so the inverse DFT of HH gives the taps.

In plain words

The receiver has a rough measurement of the channel on every subcarrier, spoiled by noise. It knows that the channel is made of a few echoes that all arrive within a short time. So it converts the measurement to the time domain, where the channel shows up as a few values at the start and the noise is spread over all the time slots. It keeps the slots where echoes can be, throws away the rest, and converts back. What it throws away is pure noise. If there are 8 possible echo slots out of 64, it keeps only an eighth of the noise.

The problem

The input is one received OFDM symbol after the DFT, Y[0],…,Y[N−1]Y[0], \ldots, Y[N-1], the known values X[k]≠0X[k] \ne 0 sent on all subcarriers (a training symbol), and the channel length Lt≤NL_t \le N. The model is Y[k]=H[k]X[k]+W[k]Y[k] = H[k] X[k] + W[k] with H[k]=∑l<Lthle−j2πkl/NH[k] = \sum_{l < L_t} h_l e^{-j 2\pi k l / N} and white noise W[k]∼CN(0,N0)W[k] \sim \mathcal{CN}(0, N_0). Output an estimate of H[k]H[k] for all kk.

The algorithm

  1. DFT-ESTIMATE(Y, X, L_t)
  2. 1Ĥ_LS[k] ← Y[k] / X[k] for k = 0, .., N-1
  3. 2g ← IDFT(Ĥ_LS) ▷ N noisy taps
  4. 3g[l] ← 0 for l = L_t, .., N-1 ▷ keep the first L_t taps
  5. 4return DFT(g)

Line L1 is the least squares estimate on each subcarrier. Line L2 moves it to the time domain, where the channel occupies the first LtL_t taps and white noise spreads evenly over all NN. Line L3 discards the taps where no channel can be. Line L4 returns to the subcarriers. Both transforms are FFTs.

Example

Take N=8N = 8, Lt=2L_t = 2, the channel h=(1,0.5)h = (1, 0.5), random 4-QAM training values (seed 6) and N0=0.1N_0 = 0.1.

kk H[k]H[k] H^LS[k]\hat H_{LS}[k] (line L1) squared error H^[k]\hat H[k] (line L4) squared error
0 1.5001.500 1.369−0.321j1.369 - 0.321j 0.120 1.407−0.122j1.407 - 0.122j 0.024
1 1.354−0.354j1.354 - 0.354j 1.153−0.092j1.153 - 0.092j 0.109 1.314−0.423j1.314 - 0.423j 0.006
2 1.000−0.500j1.000 - 0.500j 0.904−0.491j0.904 - 0.491j 0.009 1.036−0.571j1.036 - 0.571j 0.006
3 0.646−0.354j0.646 - 0.354j 0.855−1.001j0.855 - 1.001j 0.463 0.735−0.479j0.735 - 0.479j 0.023
4 0.5000.500 0.729−0.019j0.729 - 0.019j 0.053 0.587−0.200j0.587 - 0.200j 0.048
5 0.646+0.354j0.646 + 0.354j 0.402+0.108j0.402 + 0.108j 0.120 0.679+0.101j0.679 + 0.101j 0.065
6 1.000+0.500j1.000 + 0.500j 1.254+0.263j1.254 + 0.263j 0.121 0.957+0.249j0.957 + 0.249j 0.065
7 1.354+0.354j1.354 + 0.354j 1.306+0.264j1.306 + 0.264j 0.010 1.259+0.157j1.259 + 0.157j 0.048

Line L2 gives the taps 0.997−0.161j0.997 - 0.161j, 0.410+0.039j0.410 + 0.039j, −0.102−0.090j-0.102 - 0.090j, 0.009−0.062j0.009 - 0.062j, 0.068+0.019j0.068 + 0.019j, −0.061−0.202j-0.061 - 0.202j, 0.087+0.062j0.087 + 0.062j, −0.037+0.073j-0.037 + 0.073j. The first two are close to h=(1,0.5)h = (1, 0.5); the other six are noise only, and line L3 sets them to zero. The mean squared error drops from 0.1260.126 for least squares to 0.0360.036, close to the predicted N0=0.1N_0 = 0.1 and LtN0/N=0.025L_t N_0 / N = 0.025 for one noisy symbol.

Correctness

Claim. (a) Lines L2 to L4 form the orthogonal projection P=FTFHP = F T F^H onto the responses of channels with at most LtL_t taps, where FF is the unitary DFT and TT keeps the first LtL_t places. (b) Without noise, the output is HH exactly. (c) With noise, the mean squared error is Lt/NL_t / N times that of least squares; for ∣X[k]∣=1|X[k]| = 1 it is LtN0/NL_t N_0 / N instead of N0N_0. (d) For ∣X[k]∣=1|X[k]| = 1, the kept taps are the maximum likelihood estimate of the taps in white Gaussian noise. All are theorems in the model above.

Key invariant. The true response HH lies in the range of PP, so PP leaves it unchanged, and the output error is PP applied to the least squares error. Every diagonal entry of PP is Lt/NL_t / N, so PP keeps that fraction of the power of any noise with independent entries.

The full proof is below. It also covers the comb version, which is exact for Lt≤N/DL_t \le N / D and has the mean squared error LtN0/PL_t N_0 / P for P=N/DP = N / D pilots.

Proof: The DFT-based estimate is an orthogonal projection onto the channels of L_t taps, exact without noise, with the noise cut by L_t / Nfull

Notation. NN subcarriers, jj the imaginary unit. The DFT pair of the implementation is unnormalized: dft⁡(g)[k]=∑ng[n]e−j2πkn/N\operatorname{dft}(g)[k] = \sum_n g[n] e^{-j 2\pi k n / N} and idft⁡(G)[n]=1N∑kG[k]ej2πkn/N\operatorname{idft}(G)[n] = \frac1N \sum_k G[k] e^{j 2\pi k n / N}. With the unitary FF, F[k,n]=e−j2πkn/N/NF[k, n] = e^{-j 2\pi k n / N} / \sqrt N, this is dft⁡=NF\operatorname{dft} = \sqrt N F and idft⁡=FH/N\operatorname{idft} = F^H / \sqrt N. The channel has taps h0,…,hLt−1h_0, \ldots, h_{L_t - 1} with Lt≤NL_t \le N, so H=dft⁡(h)H = \operatorname{dft}(h) with hh padded by zeros. After the DFT, the receiver has Y[k]=H[k]X[k]+W[k]Y[k] = H[k] X[k] + W[k] with known nonzero X[k]X[k] and independent W[k]∼CN(0,N0)W[k] \sim \mathcal{CN}(0, N_0). Let TT be the diagonal matrix with ones in the first LtL_t places and zeros elsewhere, and let S={dft⁡(g):g[n]=0 for n≥Lt}\mathcal S = \{\operatorname{dft}(g) : g[n] = 0 \text{ for } n \ge L_t\}, the responses of channels with at most LtL_t taps.

Lemma 1 (the steps form a projection). Lines L2 to L4 map a vector GG to PGPG with P=FTFHP = F T F^H. PP is Hermitian, P2=PP^2 = P, its range is S\mathcal S, and every diagonal entry of PP equals Lt/NL_t / N.

Proof. Line L2 applies FH/NF^H / \sqrt N, line L3 applies TT and line L4 applies NF\sqrt N F, so the composition is FTFHF T F^H. It is Hermitian because TT is real diagonal, and P2=FTFHFTFH=FT2FH=PP^2 = F T F^H F T F^H = F T^2 F^H = P because FHF=IF^H F = I and T2=TT^2 = T. Its range is FF applied to the vectors supported on the first LtL_t places, which is S\mathcal S (the factor N\sqrt N does not change a subspace). The diagonal entry is P[k,k]=∑l<Lt∣F[k,l]∣2=Lt/NP[k, k] = \sum_{l < L_t} |F[k, l]|^2 = L_t / N. □\square

Theorem 1 (exact without noise). Without noise, the algorithm returns HH.

Proof. Line L1 gives Y[k]/X[k]=H[k]Y[k] / X[k] = H[k]. H∈SH \in \mathcal S, and a projection leaves the vectors of its range unchanged, so PH=HPH = H. □\square

Theorem 2 (the noise). With noise, the error of the output is PEP E, with E[k]=W[k]/X[k]E[k] = W[k] / X[k] the error of the least squares estimate of line L1. Its mean squared error per subcarrier is LtN\frac{L_t}{N} times that of the least squares estimate:

1NE∥PE∥2=LtN⋅1N∑kN0∣X[k]∣2.\frac1N E \|P E\|^2 = \frac{L_t}{N} \cdot \frac1N \sum_k \frac{N_0}{|X[k]|^2}.

For ∣X[k]∣=1|X[k]| = 1 this is LtN0/NL_t N_0 / N, against N0N_0 for least squares.

Proof. The output is P(H+E)=H+PEP(H + E) = H + PE by Theorem 1. The entries of EE are independent with variances N0/∣X[k]∣2N_0 / |X[k]|^2, so E∥PE∥2=tr⁡(P diag⁡(N0/∣X[k]∣2) PH)=∑k(PHP)[k,k] N0/∣X[k]∣2E\|PE\|^2 = \operatorname{tr}(P\, \operatorname{diag}(N_0 / |X[k]|^2)\, P^H) = \sum_k (P^H P)[k, k]\, N_0 / |X[k]|^2. With PHP=PP^H P = P and P[k,k]=Lt/NP[k, k] = L_t / N from Lemma 1, the sum is LtN∑kN0/∣X[k]∣2\frac{L_t}{N} \sum_k N_0 / |X[k]|^2. □\square

Theorem 3 (least squares and maximum likelihood for the taps). If ∣X[k]∣=1|X[k]| = 1 for all kk, the first LtL_t outputs of line L3 are the least squares estimate of the taps from YY, which is also the maximum likelihood estimate in white Gaussian noise.

Proof. Write Y=AhL+WY = A h_{L} + W with A=diag⁡(X) BA = \operatorname{diag}(X)\, B, where BB holds the first LtL_t columns of the unnormalized DFT matrix. The least squares estimate is (AHA)−1AHY(A^H A)^{-1} A^H Y. The columns of BB are orthogonal with squared norm NN, and ∣X[k]∣=1|X[k]| = 1, so AHA=NIA^H A = N I and the estimate is 1NBHdiag⁡(X∗)Y=1NBH(Y/X)\frac1N B^H \operatorname{diag}(X^*) Y = \frac1N B^H (Y / X), which is the first LtL_t entries of idft⁡(Y/X)\operatorname{idft}(Y / X). In white Gaussian noise the log-likelihood is a constant minus ∥Y−AhL∥2/N0\|Y - A h_L\|^2 / N_0, so the least squares estimate is the maximum likelihood estimate. □\square

The comb version (a theorem). With pilots on pi=k0+iDp_i = k_0 + iD for i=0,…,P−1i = 0, \ldots, P - 1, P=N/DP = N / D, and Lt≤PL_t \le P,

H[pi]=∑l<Lthle−j2π(k0+iD)l/N=∑l<Lt(hle−j2πk0l/N)e−j2πil/P,H[p_i] = \sum_{l < L_t} h_l e^{-j 2\pi (k_0 + iD) l / N} = \sum_{l < L_t} \left( h_l e^{-j 2\pi k_0 l / N} \right) e^{-j 2\pi i l / P},

because D/N=1/PD / N = 1 / P. So an inverse DFT of size PP of the pilot estimates gives hle−j2πk0l/Nh_l e^{-j 2\pi k_0 l / N} for l<Ltl < L_t and zero for the other P−LtP - L_t places without noise. Multiplying by ej2πk0l/Ne^{j 2\pi k_0 l / N} gives hlh_l, and a DFT of size NN gives HH on all subcarriers. With noise of variance N0N_0 on each pilot estimate, each output of the inverse DFT of size PP has the variance N0/PN_0 / P, the phase factors do not change it, and the DFT of size NN adds the LtL_t independent tap errors with unit-modulus weights, so the mean squared error on every subcarrier is LtN0/PL_t N_0 / P.

A delay between samples (a remark). If a path has a delay that is not a whole number of samples, HH is not in S\mathcal S for any Lt<NL_t < N: its inverse DFT has a sinc-like spread over all taps, including the taps near NN that stand for negative delays. The projection then has the bias (I−P)H≠0(I - P) H \ne 0, which no amount of SNR removes. The tests measure this floor for a delay of 2.5 samples.

Complexity

Lines L2 and L4 are FFTs of size NN, O(Nlog⁡N)O(N \log N) time, and lines L1 and L3 are O(N)O(N). The extra space is O(N)O(N) in the real RAM. The comb version uses an inverse FFT of size PP and an FFT of size NN.

Properties

  • Noise gain. The factor Lt/NL_t / N is 1/81/8 for Lt=8L_t = 8 and N=64N = 64, a gain of 9 dB over least squares, as the tests check within 10 percent.
  • Needs the length. A cut shorter than the channel removes channel taps and leaves a bias; a cut longer than needed keeps more noise. With an unknown delay profile, the prefix length is the safe choice.
  • Delays between samples. A path at a delay that is not a whole number of samples leaks into all taps, as the spectral leakage of a sinusoid between DFT bins does. The cut then leaves an error floor that more SNR cannot remove. For a single path at delay 2.5 samples and N=64N = 64, the tests measure a floor that falls slowly with the cut, from about 0.1280.128 for Lt=4L_t = 4 to 0.0530.053 for Lt=8L_t = 8 and 0.0400.040 for Lt=16L_t = 16.
  • No statistics. Unlike LMMSE estimation, it needs only LtL_t, not the delay profile or the SNR.
  • Comb pilots. With pilots every DD subcarriers, the same steps interpolate exactly when Lt≤N/DL_t \le N / D, which is the sampling limit of the comb, where linear interpolation along frequency still has a bias.

Variants and improvements

  • Comb pilots. Take the inverse DFT of size P=N/DP = N / D of the pilot estimates, multiply tap ll by ej2πk0l/Ne^{j 2\pi k_0 l / N} to undo the comb offset k0k_0, pad to NN and take the DFT. The implementation offers this as a second function.
  • Keep the taps near both ends. Leakage from delays between samples goes partly to the taps near NN, which stand for small negative delays. Keeping a few of those taps as well lowers the floor.
  • Most significant taps. Keep only the taps whose power is above a threshold, which removes more noise in sparse channels.
  • Low rank. Edfors and coauthors derived low-rank versions of the LMMSE estimator from the singular value decomposition of the channel correlation; the DFT-based estimate is a simpler relative that needs no statistics.
  • Null subcarriers. When the band edges carry no pilots, filling the empty places with zeros before line L2 is no longer an orthogonal projection of the estimate, and the estimate develops errors near the edges; least squares over the used subcarriers fixes this at a higher cost.

When to use it

Use it after least squares estimation when the channel is short compared with the symbol, the delay spread is roughly known, and the receiver already has FFT hardware. It gives most of the gain of LMMSE estimation without channel statistics. Prefer LMMSE or two-dimensional Wiener interpolation when the delay profile is known and the paths fall between samples, and plain comb pilot interpolation when the cost of two FFTs per symbol is too high.

Pitfalls

  • Cutting to the wrong length. Line L3 must keep LtL_t taps, the length of the channel. Keeping NN taps changes nothing, and keeping fewer than the channel has removes signal.
  • Keeping the wrong end. Line L3 must keep the taps 0,…,Lt−10, \ldots, L_t - 1 after line L2. With a DFT convention that puts delay ll at index N−lN - l, the channel sits at the other end, and line L3 then keeps only noise.
  • Mixing normalizations. Line L2 and line L4 must be inverse to each other. A unitary inverse with an unnormalized forward transform scales the result by N\sqrt N.
  • Forgetting the comb offset. With pilots starting at k0≠0k_0 \ne 0, the comb version must multiply tap ll by ej2πk0l/Ne^{j 2\pi k_0 l / N} before the DFT of size NN. Without it, the estimate is the channel shifted by k0k_0 subcarriers.
  • A cut longer than the pilots allow. In the comb version, LtL_t must be at most P=N/DP = N / D. A longer cut has no data to fill it, and the channel aliases.

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)
dft_based_channel_estimation.py 47 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dft-based-channel-estimation/. The authors are listed in prov/Q4YZBD.jsonl.

"""DFT-based (transform-domain) channel estimation for OFDM.

The channel has at most L_t taps, so its frequency response H[k] = sum over
l < L_t of h[l] e^(-j 2 pi k l / N) lives in an L_t-dimensional subspace of
the N values. The least squares estimate Y[k] / X[k] has noise on all N
values. The estimator takes the inverse DFT of the least squares estimate,
keeps the first L_t taps, sets the rest to zero and takes the DFT again. This
projects the estimate onto the subspace and keeps only L_t / N of the noise.

dft and idft here are the unnormalized pair of the area (idft has the 1/N),
so idft of H gives the taps h. The comb version uses P = N / D pilots spaced
D apart from k0: an inverse DFT of size P gives h[l] e^(-j 2 pi k0 l / N),
which is exact when the channel has at most P taps.
"""

import cmath
import math

import cbb


def estimate(y: list[complex], x: list[complex], taps: int) -> list[complex]:
    """The estimate of H from a symbol with known values x on all N subcarriers."""
    n = len(y)
    if len(x) != n or not 1 <= taps <= n:
        raise ValueError("need len(x) = N and 1 <= taps <= N")
    h_ls = [a / b for a, b in zip(y, x)]  # @line L1
    g = cbb.idft(h_ls)  # @line L2
    g = g[:taps] + [0j] * (n - taps)  # @line L3
    return cbb.dft(g)  # @line L4


def estimate_comb(y: list[complex], pilot_values: list[complex], spacing: int, taps: int, k0: int = 0) -> list[complex]:
    """The estimate of H on all N subcarriers from comb pilots on k0, k0 + D, ..."""
    n = len(y)
    if spacing < 1 or n % spacing or not 0 <= k0 < spacing:
        raise ValueError("need N a multiple of D and 0 <= k0 < D")
    p = n // spacing
    if len(pilot_values) != p or not 1 <= taps <= p:
        raise ValueError("need one value per pilot and 1 <= taps <= N / D")
    hp = [y[k0 + i * spacing] / pilot_values[i] for i in range(p)]
    g = cbb.idft(hp)
    g = [g[l] * cmath.exp(2j * math.pi * k0 * l / n) for l in range(taps)]
    return cbb.dft(g + [0j] * (n - taps))
test_dft_based_channel_estimation.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dft-based-channel-estimation/. The authors are listed in prov/Q4YZBD.jsonl.

import cmath
import math
import random

import cbb
from dft_based_channel_estimation import estimate, estimate_comb

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 response(h: list[complex], n: int) -> list[complex]:
    return cbb.dft(list(h) + [0j] * (n - len(h)))


def mse(a: list[complex], b: list[complex]) -> float:
    return sum(abs(u - v) ** 2 for u, v in zip(a, b)) / len(a)


def test_exact_without_noise() -> None:
    rng = random.Random(1)
    n = 32
    for length, taps in ((1, 1), (3, 3), (4, 8), (8, 8)):
        h = [cbb.cn(rng, 1 / length) for _ in range(length)]
        hf = response(h, n)
        x = qpsk(rng, n)
        y = [a * b for a, b in zip(hf, x)]
        assert mse(estimate(y, x, taps), hf) < 1e-24


def test_projection_is_idempotent_and_keeps_the_taps() -> None:
    # The steps L2 to L4 form an orthogonal projection: applying them twice changes nothing.
    rng = random.Random(2)
    n, taps = 16, 5
    y = [cbb.cn(rng, 1.0) for _ in range(n)]
    ones = [1 + 0j] * n
    once = estimate(y, ones, taps)
    assert mse(estimate(once, ones, taps), once) < 1e-24
    g = cbb.idft(once)
    assert max(abs(v) for v in g[taps:]) < 1e-12
    assert cbb.norm2(once) <= cbb.norm2(y) + 1e-9


def test_noise_drops_to_taps_over_n() -> None:
    # Closed form with |X[k]| = 1: least squares MSE = N0, DFT-based MSE = L_t N0 / N.
    # N = 64, L_t = 8, N0 = 0.1, 200 symbols, seed 3.
    rng = random.Random(3)
    n, taps, n0 = 64, 8, 0.1
    h = [cbb.cn(rng, p) for p in (0.4, 0.3, 0.2, 0.1)]
    hf = response(h, n)
    e_ls = e_dft = 0.0
    trials = 200
    for _ in range(trials):
        x = qpsk(rng, n)
        y = cbb.awgn(rng, [a * b for a, b in zip(hf, x)], n0)
        e_ls += mse([a / b for a, b in zip(y, x)], hf)
        e_dft += mse(estimate(y, x, taps), hf)
    assert 0.95 < e_ls / trials / n0 < 1.05
    assert 0.9 < e_dft / trials / (taps * n0 / n) < 1.1


def test_comb_version_is_exact_and_has_the_predicted_noise() -> None:
    rng = random.Random(4)
    n, d = 64, 4
    p = n // d
    h = [cbb.cn(rng, q) for q in (0.4, 0.3, 0.2, 0.1)]
    hf = response(h, n)
    for k0 in (0, 1, 3):
        xp = qpsk(rng, p)
        y = [0j] * n
        for i in range(p):
            y[k0 + i * d] = hf[k0 + i * d] * xp[i]
        assert mse(estimate_comb(y, xp, d, 4, k0), hf) < 1e-24
        assert mse(estimate_comb(y, xp, d, p, k0), hf) < 1e-24
    # Closed form: each kept tap has noise variance N0 / P, so the MSE is L_t N0 / P.
    n0, taps, k0 = 0.1, 6, 2
    acc = 0.0
    trials = 300
    for _ in range(trials):
        xp = qpsk(rng, p)
        y = [0j] * n
        for i in range(p):
            y[k0 + i * d] = hf[k0 + i * d] * xp[i] + cbb.cn(rng, n0)
        acc += mse(estimate_comb(y, xp, d, taps, k0), hf)
    assert 0.9 < acc / trials / (taps * n0 / p) < 1.1


def test_a_delay_between_samples_leaks_into_all_taps() -> None:
    # A path at delay 2.5 samples: H[k] = e^(-j 2 pi k 2.5 / N) for k < N / 2, a smooth phase ramp
    # (taken on the symmetric index range). Its inverse DFT spreads over all N taps, so cutting at
    # L_t leaves an error floor even with no noise. A measurement: the floor falls as L_t grows.
    n = 64
    hf = [cmath.exp(-2j * math.pi * (k if k < n // 2 else k - n) * 2.5 / n) for k in range(n)]
    ones = [1 + 0j] * n
    floors = [mse(estimate(hf, ones, t), hf) for t in (4, 8, 16)]
    assert floors[0] > 1e-2
    assert floors[0] > floors[1] > floors[2] > 0

History

The use of the time domain for OFDM channel estimation goes back to the group of van de Beek, Edfors, Sandell, Wilson and Börjesson at Luleå. Their 1995 paper at the Vehicular Technology Conference compared least squares, LMMSE and estimators that use the short length of the channel, and their 1998 paper derived low-rank estimators from the singular value decomposition. Later studies, such as the comparison of pilot arrangements by Coleri, Ergen, Puri and Bahai in 2002, included interpolation in the time domain among the methods for comb pilots.

References

  1. 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 LMMSE estimators, and the estimator that transforms to the time domain and uses the short length of the channel)
  2. O. Edfors, M. Sandell, J.-J. van de Beek, S. K. Wilson and P. O. Börjesson, OFDM channel estimation by singular value decomposition, IEEE Transactions on Communications 46(7), 1998, pages 931 to 939 (low-rank channel estimators for OFDM, which keep the few strongest dimensions of the channel)
  3. 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 (interpolation of comb pilots in the time domain, compared with interpolation along frequency)

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