Algorithm Search⌘K

Algorithmadvanced

Two-dimensional Wiener pilot interpolation

Also called 2D Wiener channel interpolation.

Interpolates OFDM pilot estimates over time and frequency with the Wiener filter of the channel correlation. It gives the least mean squared error of all linear estimates from the chosen pilots.

Time
O(T (M log M + K^3)) worst
Space
O(K^2 + M) extra
Where
K = the number of pilots used per target; M = the number of pilots; T = the number of target positions
Properties
deterministiclinear mmseneeds channel statisticsweights independent of data
Origin
Peter Hoeher, Stefan Kaiser, Patrick Robertson, 1997

Two-dimensional Wiener pilot interpolation estimates the channel H(n,k)H(n, k) of an OFDM system on every OFDM symbol nn and subcarrier kk from noisy estimates at a sparse grid of pilot positions, using the statistics of the channel. The channel changes slowly along frequency, because the delays are short, and slowly along time, because the Doppler shifts are small, so neighboring positions are strongly correlated. The receiver models this by the correlation r(Δn,Δk)r(\Delta n, \Delta k), and for each target position it computes the weights of the Wiener filter, w=(R+σ2I)−1cw = (R + \sigma^2 I)^{-1} c, from the correlations between the pilots, RR, and between the pilots and the target, cc. The estimate is H^(t)=∑iwi∗yi\hat H(t) = \sum_i w_i^* y_i, the linear estimate with the least mean squared error, r(0,0)−cH(R+σ2I)−1cr(0,0) - c^H (R + \sigma^2 I)^{-1} c. It extends LMMSE channel estimation from one OFDM symbol to the time-frequency grid, and it is the optimal counterpart of the simple comb pilot interpolation. Each target uses only its KK nearest pilots, so the matrices stay small, and the weights depend on the pilot layout and the statistics, not on the data. The page uses jj for the imaginary unit.

In plain words

The receiver knows the channel roughly at a few spots of a grid of time and frequency, the pilots. It wants the channel everywhere else. It also knows, from the physics of the channel, how much the channel at one spot tells about the channel at another: spots close in frequency and close in time are almost the same, spots far apart are nearly unrelated. For each spot it wants, it mixes the nearby pilot values with weights. The Wiener weights are the mix that is wrong by the least on average. They give more weight to the pilots that are most related to the spot, they account for the pilots repeating each other's information, and they shrink toward zero when the pilots are noisy.

The problem

The input is the pilot positions p1,…,pMp_1, \ldots, p_M on the grid of symbols and subcarriers, their noisy values yi=H(pi)+eiy_i = H(p_i) + e_i, for example least squares estimates Y/XY/X with σ2=N0/∣Xp∣2\sigma^2 = N_0 / |X_p|^2, the correlation function r(Δn,Δk)=E[H(n+Δn,k+Δk) H(n,k)∗]r(\Delta n, \Delta k) = E[H(n + \Delta n, k + \Delta k)\, H(n, k)^*] of the channel, the noise variance σ2\sigma^2, the target positions, and the number KK of pilots per target. The channel is a zero-mean, wide-sense stationary field, and the errors are independent with variance σ2\sigma^2. Output the linear estimate of H(t)H(t) with the least mean squared error from the KK pilots nearest to each target tt.

The algorithm

  1. WIENER-2D(targets, p_1..p_M, y, r, σ², K)
  2. 1for each target t: S ← the K pilots nearest to t
  3. 2R[i][j] ← r(p_i - p_j) for i, j in S
  4. 3R[i][i] ← R[i][i] + σ²
  5. 4c[i] ← r(p_i - t) for i in S
  6. 5w ← the solution of R w = c
  7. 6Ĥ(t) ← Σ_{i in S} conj(w_i) y_i

Line L1 picks the nearest pilots, by Euclidean distance on the grid in the implementation. Lines L2 and L3 build the covariance of the pilot values, where the noise adds σ2\sigma^2 on the diagonal. Line L4 builds the correlation of the pilot values with the unknown target. Line L5 solves the normal equations; the matrix is Hermitian positive definite, so a Cholesky solve works. Line L6 applies the weights. Lines L2 to L5 do not use the received values, so a receiver with a fixed pilot layout and fixed statistics computes the weights once and stores them.

Example

The tests use N=16N = 16 subcarriers and 9 symbols. The channel has three taps at delays 0, 1, 2 with powers 0.50.5, 0.30.3, 0.20.2, and each tap changes in time as a first-order autoregressive process with coefficient 0.90.9, so r(Δn,Δk)=0.9∣Δn∣∑lPle−j2πlΔk/Nr(\Delta n, \Delta k) = 0.9^{|\Delta n|} \sum_l P_l e^{-j 2\pi l \Delta k / N}. Pilots are on symbols 0, 4, 8 and subcarriers 0,3,…,150, 3, \ldots, 15, 18 in all, with σ2=0.05\sigma^2 = 0.05. Take the target t=(2,1)t = (2, 1) and its four corner pilots (0,0)(0, 0), (0,3)(0, 3), (4,0)(4, 0), (4,3)(4, 3).

pilot (0,0)(0, 0) (0,3)(0, 3) (4,0)(4, 0) (4,3)(4, 3) MSE
Wiener weight wiw_i 0.323+0.119j0.323 + 0.119j 0.142−0.119j0.142 - 0.119j 0.323+0.119j0.323 + 0.119j 0.142−0.119j0.142 - 0.119j 0.2276
bilinear weight 0.333 0.167 0.333 0.167 0.2715

The Wiener weights are complex: the mean delay of the channel makes HH turn along frequency, and the weights follow that turn, which bilinear interpolation cannot do. The two symbols get equal weight because the target is halfway between them. With more pilots for the same target, the error falls: 0.4320.432 for K=1K = 1, 0.3010.301 for K=2K = 2, 0.2280.228 for K=4K = 4, 0.22350.2235 for K=6K = 6, 0.22330.2233 for K=9K = 9 and 0.2180.218 for all 18. Averaged over all 144 positions of the grid, the closed-form error is 0.14390.1439 for K=4K = 4, 0.14220.1422 for K=6K = 6, 0.13860.1386 for K=9K = 9 and 0.13300.1330 for K=18K = 18; the tests check the prediction against a simulation of 300 channels within 10 percent.

Correctness

Claim. For any weights bb, the mean squared error of ∑ibi∗yi\sum_i b_i^* y_i is r0−2Re⁡(bHc)+bH(R+σ2I)br_0 - 2 \operatorname{Re}(b^H c) + b^H (R + \sigma^2 I) b. With σ2>0\sigma^2 > 0, it has the unique minimum r0−cH(R+σ2I)−1cr_0 - c^H (R + \sigma^2 I)^{-1} c at the weights of line L5. So line L6 returns the linear estimate with the least mean squared error from the pilots of line L1. More pilots never increase the error. This is a theorem for any wide-sense stationary channel with independent pilot errors; for jointly Gaussian channels and noise, the estimate is also the best of all estimates, linear or not.

Key invariant. With Q=R+σ2IQ = R + \sigma^2 I and w=Q−1cw = Q^{-1} c, the error of any weights is the Wiener error plus (b−w)HQ(b−w)(b - w)^H Q (b - w), a nonnegative quadratic form.

The tests check this by brute force: random changes of the weights and bilinear weights never do better than the Wiener weights on the same pilots. The full proof is below.

Proof: The two-dimensional Wiener weights give the smallest mean squared error of all linear estimates from the chosen pilotsfull

Notation. H(n,k)H(n, k) is the channel on OFDM symbol nn and subcarrier kk, a zero-mean random field with the correlation r(Δn,Δk)=E[H(n+Δn,k+Δk) H(n,k)∗]r(\Delta n, \Delta k) = E[H(n + \Delta n, k + \Delta k)\, H(n, k)^*], the same for every (n,k)(n, k) (wide-sense stationary), so r(−Δn,−Δk)=r(Δn,Δk)∗r(-\Delta n, -\Delta k) = r(\Delta n, \Delta k)^*. The pilots chosen for a target tt are at the positions p1,…,pKp_1, \ldots, p_K and give the values yi=H(pi)+eiy_i = H(p_i) + e_i, where the errors eie_i have zero mean, the variance σ2\sigma^2, and are independent of each other and of the channel. Vectors are columns, bHb^H is the conjugate transpose and r0=r(0,0)r_0 = r(0, 0). For weights b∈CKb \in \mathbb{C}^K, the linear estimate is bHy=∑ibi∗yib^H y = \sum_i b_i^* y_i.

Lemma 1 (the moments). E[yyH]=R+σ2IE[y y^H] = R + \sigma^2 I with R[i,j]=r(pi−pj)R[i, j] = r(p_i - p_j), and E[y H(t)∗]=cE[y\, H(t)^*] = c with c[i]=r(pi−t)c[i] = r(p_i - t).

Proof. E[yiyj∗]=E[H(pi)H(pj)∗]+E[eiej∗]E[y_i y_j^*] = E[H(p_i) H(p_j)^*] + E[e_i e_j^*], because the cross terms vanish by independence and zero mean. The first term is r(pi−pj)r(p_i - p_j) by stationarity and the second is σ2\sigma^2 if i=ji = j and 00 otherwise. Similarly E[yiH(t)∗]=E[H(pi)H(t)∗]=r(pi−t)E[y_i H(t)^*] = E[H(p_i) H(t)^*] = r(p_i - t). □\square

Lemma 2 (the error of any weights). For every bb,

E∣H(t)−bHy∣2=r0−2Re⁡(bHc)+bH(R+σ2I) b.E\left|H(t) - b^H y\right|^2 = r_0 - 2 \operatorname{Re}(b^H c) + b^H (R + \sigma^2 I)\, b.

Proof. Expand E[(H(t)−bHy)(H(t)−bHy)∗]=E∣H(t)∣2−bHE[yH(t)∗]−E[H(t)yH]b+bHE[yyH]bE[(H(t) - b^H y)(H(t) - b^H y)^*] = E|H(t)|^2 - b^H E[y H(t)^*] - E[H(t) y^H] b + b^H E[y y^H] b, and use Lemma 1 with E[H(t)yH]=cHE[H(t) y^H] = c^H, so that the two middle terms add up to 2Re⁡(bHc)2 \operatorname{Re}(b^H c). □\square

Theorem (the Wiener weights are optimal). Let Q=R+σ2IQ = R + \sigma^2 I with σ2>0\sigma^2 > 0. Then QQ is Hermitian positive definite, the weights w=Q−1cw = Q^{-1} c of lines L2 to L5 minimize the error of Lemma 2 over all b∈CKb \in \mathbb{C}^K, the minimum is unique, and

E∣H(t)−wHy∣2=r0−cHQ−1c.E\left|H(t) - w^H y\right|^2 = r_0 - c^H Q^{-1} c.

Line L6 returns wHyw^H y.

Proof. RR is a covariance matrix, so uHRu=E∣∑iui∗H(pi)∣2≥0u^H R u = E|\sum_i u_i^* H(p_i)|^2 \ge 0, and adding σ2I\sigma^2 I makes QQ positive definite. Lines L2 and L3 build QQ, line L4 builds cc and line L5 solves Qw=cQ w = c. Completing the square in Lemma 2,

r0−2Re⁡(bHc)+bHQb=r0−cHQ−1c+(b−w)HQ (b−w),r_0 - 2 \operatorname{Re}(b^H c) + b^H Q b = r_0 - c^H Q^{-1} c + (b - w)^H Q\, (b - w),

which can be checked by expanding the last term with Qw=cQ w = c and wHQw=cHQ−1cw^H Q w = c^H Q^{-1} c. The last term is positive unless b=wb = w, because QQ is positive definite. Line L6 computes ∑iwi∗yi=wHy\sum_i w_i^* y_i = w^H y. □\square

Corollary 1 (more pilots never hurt). If the pilot set SS is contained in the pilot set S′S', the Wiener error from S′S' is at most that from SS.

Proof. Any weights on SS are weights on S′S' with zeros on S′∖SS' \setminus S, and they give the same error, so the minimum over S′S' is not larger. □\square

Corollary 2 (a clean pilot is kept). If tt is a pilot position pip_i and σ2→0\sigma^2 \to 0, the error tends to 0 and the estimate tends to yiy_i.

Proof. The weights b=eib = e_i (one on pilot ii, zero elsewhere) give the error σ2\sigma^2 by Lemma 2, because c[i]=r0=Q[i,i]−σ2c[i] = r_0 = Q[i, i] - \sigma^2. The Wiener error is at most this, so it tends to 0. □\square

The Gaussian case. If the channel and the errors are jointly circular complex Gaussian, the conditional mean E[H(t)∣y]E[H(t) \mid y] is linear in yy, so the Wiener estimate is also the minimum mean squared error estimate among all functions of the chosen pilot values. This is a theorem of Gaussian estimation. For other distributions it is the best linear estimate only.

Mismatch (a remark). If the receiver uses a correlation r~\tilde r or a noise variance σ~2\tilde\sigma^2 that differ from the true ones, the weights are w~=Q~−1c~\tilde w = \tilde Q^{-1} \tilde c, and the true error is Lemma 2 evaluated at b=w~b = \tilde w with the true RR, cc and σ2\sigma^2. By the theorem, it is at least the optimal error, and the difference is (w~−w)HQ(w~−w)(\tilde w - w)^H Q (\tilde w - w).

Complexity

For each of the TT targets, line L1 sorts the MM pilots by distance, O(Mlog⁡M)O(M \log M), lines L2 to L4 cost O(K2)O(K^2), and the solve of line L5 costs O(K3)O(K^3). The total is O(T(Mlog⁡M+K3))O(T (M \log M + K^3)) time and O(K2+M)O(K^2 + M) extra space in the real RAM. With a regular pilot grid, the targets fall into a few classes with the same relative layout, so a receiver computes O(K3)O(K^3) work once per class, and the cost per target is then O(K)O(K) for line L6.

Properties

  • Optimal among linear estimates. For the chosen pilots, no other weights give a smaller mean squared error, by the claim.
  • Needs statistics. The receiver must know or estimate r(Δn,Δk)r(\Delta n, \Delta k), which depends on the delay profile and the Doppler spectrum, and σ2\sigma^2. Wrong statistics raise the error by (w~−w)HQ(w~−w)(\tilde w - w)^H Q (\tilde w - w).
  • Shrinks with noise. When σ2\sigma^2 is large, the weights shrink toward zero and the estimate toward the mean 0, which lowers the error compared with an unbiased interpolator.
  • Diminishing returns. The error falls fast for the first few pilots and slowly after, as in the example, so KK between 4 and 10 is common.
  • Sampling limit. The pilot grid must sample the channel finely enough: the spacing in symbols must be small against the inverse of the Doppler spread, and the spacing in subcarriers small against NN divided by the delay spread in samples. A coarser grid cannot be repaired by any filter.

Variants and improvements

  • Two cascaded filters. A one-dimensional Wiener filter along time on the pilot subcarriers, followed by one along frequency, costs much less than the full two-dimensional filter and loses little, because the correlation of many channels factors into a part in time and a part in frequency.
  • Robust design. When the statistics are unknown, the receiver can design the filter for a uniform delay profile over the prefix length and a uniform Doppler spectrum up to the largest expected Doppler shift, which covers the worst case at a small loss.
  • Low rank. The eigenvectors of RR with the largest eigenvalues hold most of the channel energy; keeping only those reduces the cost, as in the low-rank LMMSE estimators of Edfors and coauthors.
  • Frequency only. With pilots in every symbol, a one-dimensional filter along frequency is the LMMSE estimate for one symbol.
  • Kriging. The same weights appear in geostatistics as kriging, which interpolates a spatial field from scattered samples with its covariance.

When to use it

Use it when the pilots are scattered over time and frequency, as in DVB-T and LTE, the channel statistics are known or can be estimated, and the receiver needs the best channel estimate for coherent detection at a low SNR. Use DFT-based channel estimation when only the channel length is known, and plain comb pilot interpolation when the cost must be minimal.

Pitfalls

  • Conjugating the wrong side. With w=Q−1cw = Q^{-1} c and c[i]=r(pi−t)c[i] = r(p_i - t), line L6 must use ∑iconj⁡(wi)yi\sum_i \operatorname{conj}(w_i) y_i. Using ∑iwiyi\sum_i w_i y_i turns the phase the wrong way whenever the weights are complex, as in the example.
  • Reversing the correlation. Line L4 must use r(pi−t)r(p_i - t), the pilot minus the target, consistent with line L2. With r(t−pi)r(t - p_i) the vector is conjugated, and the weights follow the turn of the channel in the wrong direction.
  • Leaving out the noise. Line L3 must add σ2\sigma^2 to the diagonal. Without it the filter trusts noisy pilots fully, and the solve of line L5 can be badly conditioned.
  • Statistics that are too narrow. If the assumed delay or Doppler spread in lines L2 and L4 is smaller than the true one, the filter smooths away real changes of the channel. Designing for a slightly wider spread is safer than for a narrower one.
  • A pilot grid that aliases. Line L1 can only use the pilots that exist. If the grid is too sparse for the Doppler or the delay spread, the error stays high for every KK.

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)
two_dimensional_wiener_pilot_interpolation.py 57 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/two-dimensional-wiener-pilot-interpolation/. The authors are listed in prov/G9C3T4.jsonl.

"""Two-dimensional Wiener interpolation of OFDM pilot estimates.

The channel H(n, k) is a function of the OFDM symbol n and the subcarrier k.
Pilots at the positions p_1, ..., p_K give noisy values y_i = H(p_i) + e_i,
where e_i has variance sigma^2 (N0 / |X_p|^2 for a least squares pilot
estimate). The channel has the correlation r(dn, dk) = E[H(n + dn, k + dk) conj(H(n, k))].
The linear estimate of H at a target t with the least mean squared error is

    w = (R + sigma^2 I)^(-1) c,   R[i][j] = r(p_i - p_j),   c[i] = r(p_i - t)
    H_hat(t) = sum over i of conj(w_i) y_i
    MSE = r(0, 0) - c^H (R + sigma^2 I)^(-1) c

Each target uses only its nearest pilots, so every solve is small. The
weights depend on the pilot pattern, the correlation and sigma^2, not on the
received data, so a receiver computes them once.
"""

import cbb

Position = tuple[int, int]


def nearest(target: Position, pilots: list[Position], count: int) -> list[int]:
    """Indices of the count pilots nearest to target (Euclidean distance in symbols and subcarriers)."""
    n, k = target
    order = sorted(range(len(pilots)), key=lambda i: ((pilots[i][0] - n) ** 2 + (pilots[i][1] - k) ** 2, i))
    return order[:count]


def wiener_weights(target: Position, pilots: list[Position], corr, noise_var: float) -> tuple[list[complex], float]:
    """The Wiener weights w for target from the given pilots, and the resulting MSE.

    corr(dn, dk) returns r(dn, dk); it must satisfy r(-dn, -dk) = conj(r(dn, dk)).
    """
    m = len(pilots)
    a = [[complex(corr(pilots[i][0] - pilots[j][0], pilots[i][1] - pilots[j][1])) for j in range(m)] for i in range(m)]  # @line L2
    for i in range(m):
        a[i][i] += noise_var  # @line L3
    c = [complex(corr(p[0] - target[0], p[1] - target[1])) for p in pilots]  # @line L4
    w = cbb.solve(a, c)  # @line L5
    mse = complex(corr(0, 0)).real - cbb.dot(c, w).real
    return w, mse


def estimate(targets: list[Position], pilots: list[Position], values: list[complex], corr, noise_var: float, count: int) -> list[complex]:
    """H_hat at each target from the pilot values, with count nearest pilots per target."""
    if len(values) != len(pilots) or not 1 <= count <= len(pilots):
        raise ValueError("one value per pilot and 1 <= count <= number of pilots")
    out = []
    for t in targets:
        idx = nearest(t, pilots, count)  # @line L1
        w, _ = wiener_weights(t, [pilots[i] for i in idx], corr, noise_var)
        out.append(sum(wi.conjugate() * values[i] for wi, i in zip(w, idx)))  # @line L6
    return out
test_two_dimensional_wiener_pilot_interpolation.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/two-dimensional-wiener-pilot-interpolation/. The authors are listed in prov/G9C3T4.jsonl.

import cmath
import math
import random

import cbb
from two_dimensional_wiener_pilot_interpolation import estimate, nearest, wiener_weights

# Test model: N = 16 subcarriers, 9 OFDM symbols, 3 taps at delays 0, 1, 2 with powers 0.5, 0.3, 0.2.
# Each tap is an AR(1) process in n with coefficient 0.9, so r(dn, dk) = 0.9^|dn| sum_l P_l e^(-j 2 pi l dk / N).
# Pilots on symbols 0, 4, 8 and subcarriers 0, 3, ..., 15; pilot noise variance 0.05.
N = 16
POWERS = (0.5, 0.3, 0.2)
A = 0.9
SIGMA2 = 0.05
PILOTS = [(n, k) for n in (0, 4, 8) for k in range(0, 16, 3)]
TARGETS = [(n, k) for n in range(9) for k in range(N)]


def corr(dn: int, dk: int) -> complex:
    return A ** abs(dn) * sum(p * cmath.exp(-2j * math.pi * l * dk / N) for l, p in enumerate(POWERS))


def mse_of(b: list[complex], target: tuple[int, int], pilots: list[tuple[int, int]]) -> float:
    """E|H(t) - b^H y|^2 = r(0, 0) - 2 Re(b^H c) + b^H (R + sigma^2 I) b, for any weights b."""
    c = [corr(p[0] - target[0], p[1] - target[1]) for p in pilots]
    ry = [[corr(p[0] - q[0], p[1] - q[1]) + (SIGMA2 if i == j else 0) for j, q in enumerate(pilots)] for i, p in enumerate(pilots)]
    return corr(0, 0).real - 2 * cbb.dot(b, c).real + cbb.dot(b, cbb.matvec(ry, b)).real


def channel(rng: random.Random) -> list[list[complex]]:
    """H[n][k] for 9 symbols, from AR(1) taps with stationary start."""
    taps = [cbb.cn(rng, p) for p in POWERS]
    out = []
    for n in range(9):
        if n:
            taps = [A * h + cbb.cn(rng, (1 - A * A) * p) for h, p in zip(taps, POWERS)]
        out.append([sum(h * cmath.exp(-2j * math.pi * l * k / N) for l, h in enumerate(taps)) for k in range(N)])
    return out


def test_closed_form_mse_matches_simulation() -> None:
    # 300 channel realizations, seed 1, 6 nearest pilots per target, average over all 144 positions.
    rng = random.Random(1)
    plan = []
    for t in TARGETS:
        idx = nearest(t, PILOTS, 6)
        w, m = wiener_weights(t, [PILOTS[i] for i in idx], corr, SIGMA2)
        plan.append((t, idx, w, m))
    predicted = sum(m for *_, m in plan) / len(plan)
    acc = 0.0
    trials = 300
    for _ in range(trials):
        h = channel(rng)
        y = [h[n][k] + cbb.cn(rng, SIGMA2) for n, k in PILOTS]
        for (n, k), idx, w, _ in plan:
            acc += abs(h[n][k] - sum(wi.conjugate() * y[i] for wi, i in zip(w, idx))) ** 2
    assert 0.9 < acc / (trials * len(plan)) / predicted < 1.1


def test_estimate_uses_the_same_weights() -> None:
    rng = random.Random(2)
    y = [cbb.cn(rng, 1.0) for _ in PILOTS]
    targets = [(2, 5), (6, 14), (4, 3)]
    got = estimate(targets, PILOTS, y, corr, SIGMA2, 6)
    for t, g in zip(targets, got):
        idx = nearest(t, PILOTS, 6)
        w, _ = wiener_weights(t, [PILOTS[i] for i in idx], corr, SIGMA2)
        assert abs(g - sum(wi.conjugate() * y[i] for wi, i in zip(w, idx))) < 1e-12


def test_no_other_weights_do_better() -> None:
    # Brute force: random changes of the weights, and bilinear interpolation of the 4 corner pilots,
    # never give a smaller closed-form MSE than the Wiener weights on the same pilots.
    rng = random.Random(3)
    for t in ((1, 1), (2, 4), (5, 7), (7, 13)):
        n0, k0 = 4 * (t[0] // 4), 3 * (t[1] // 3)
        corners = [(n0, k0), (n0, k0 + 3), (n0 + 4, k0), (n0 + 4, k0 + 3)]
        w, m = wiener_weights(t, corners, corr, SIGMA2)
        assert abs(mse_of(w, t, corners) - m) < 1e-12
        u, v = (t[0] - n0) / 4, (t[1] - k0) / 3
        bilinear = [(1 - u) * (1 - v), (1 - u) * v, u * (1 - v), u * v]
        assert mse_of(bilinear, t, corners) > m
        for _ in range(50):
            b = [wi + cbb.cn(rng, 0.01) for wi in w]
            assert mse_of(b, t, corners) >= m - 1e-12


def test_more_pilots_never_raise_the_mse() -> None:
    for t in ((1, 1), (3, 8), (6, 14)):
        ms = [wiener_weights(t, [PILOTS[i] for i in nearest(t, PILOTS, c)], corr, SIGMA2)[1] for c in (2, 4, 6, 9, 18)]
        assert all(a >= b - 1e-12 for a, b in zip(ms, ms[1:]))


def test_a_clean_pilot_is_returned_as_it_is() -> None:
    rng = random.Random(4)
    y = [cbb.cn(rng, 1.0) for _ in PILOTS]
    i = PILOTS.index((4, 9))
    got = estimate([(4, 9)], PILOTS, y, corr, 1e-12, 6)[0]
    assert abs(got - y[i]) < 1e-6
    _, m = wiener_weights((4, 9), [PILOTS[i]], corr, 1e-12)
    assert m < 1e-9

History

Wiener filtering for pilot-symbol-assisted channel estimation was first used for single-carrier systems, where the pilots are spread in time only. Peter Hoeher, Stefan Kaiser and Patrick Robertson, at the German Aerospace Center, applied it in two dimensions to OFDM in 1997, with pilots spread over time and frequency and a filter that uses both correlations. Edfors and coauthors gave low-rank versions of the LMMSE estimator, and later standards such as DVB-T and LTE adopted scattered pilot grids that suit this kind of interpolation.

References

  1. 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 (the pilot grid in time and frequency, the two-dimensional Wiener filter and its mean squared error)
  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 (the LMMSE channel estimator in frequency and its low-rank approximations)
  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 (pilot arrangements and simpler interpolators, for comparison)

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