Algorithm Search⌘K

Algorithmintro

Least squares channel estimation

Also called LS channel estimator.

Estimates the taps of an FIR channel from known pilots as h = (X^H X)^(-1) X^H y. It needs no channel statistics, is unbiased, and its error is N0 tr((X^H X)^(-1)).

Time
O(m L^2) worst
Space
O(L^2) extra
Where
L = the number of channel taps; m = the number of pilot observations
Properties
deterministicefficient in gaussian noisenot needs channel statisticsunbiased
Origin
Adrien Marie Legendre, Carl Friedrich Gauss, 1805

Least squares (LS) channel estimation finds the taps of a channel from pilots, symbols that the receiver knows in advance. The channel is an FIR filter h=(h0,…,hL−1)h = (h_0, \ldots, h_{L-1}), and the received samples are y=Xh+wy = X h + w, where the matrix XX holds the pilots and w∼CN(0,N0I)w \sim \mathcal{CN}(0, N_0 I) is the noise. The LS estimate h^=(XHX)−1XHy\hat h = (X^H X)^{-1} X^H y is the tap vector that makes ∥y−Xh∥2\|y - X h\|^2 smallest; it is the least squares problem solved with the pseudoinverse of XX. It uses no knowledge of the channel statistics. It is unbiased, its mean squared error is N0tr⁡((XHX)−1)N_0 \operatorname{tr}((X^H X)^{-1}), and in Gaussian noise this error is equal to the Cramer-Rao bound. LMMSE channel estimation adds the channel covariance and the noise level and gets a smaller error, mostly at low SNR. Pilot symbol assisted modulation decides where the pilots go in time, sparse channel estimation uses fewer pilots when only a few taps are not zero, and comb-pilot channel estimation is the OFDM form, where LS becomes one division per pilot subcarrier.

In plain words

The transmitter sends a short block of symbols that the receiver already knows. The channel smears each symbol over the next few samples, as an echo does. So each received sample is a sum of a few known symbols, each multiplied by an unknown channel tap, plus noise. There are more samples than taps. The receiver then picks the taps that explain the samples best: the taps for which the sum of the squared differences between the samples and the samples they predict is smallest. This is the same fit as a straight line through noisy points. The receiver needs nothing more than the pilots. The estimate is correct on average, and it is better when the pilots have more energy and when they excite all the taps equally.

The problem

The input is a block of NpN_p known pilots x[0],…,x[Np−1]x[0], \ldots, x[N_p - 1], the NpN_p samples y[0],…,y[Np−1]y[0], \ldots, y[N_p - 1] that the receiver gets while they arrive, and the number of taps LL. The model is one sample per symbol, after the matched filter:

y[k]=∑l=0L−1hl x[k−l]+w[k],y[k] = \sum_{l=0}^{L-1} h_l\, x[k - l] + w[k],

with complex taps hlh_l and noise w[k]∼CN(0,N0)w[k] \sim \mathcal{CN}(0, N_0), independent from sample to sample, so that E∣w[k]∣2=N0E|w[k]|^2 = N_0. The first L−1L - 1 samples also hold symbols sent before the pilots, which the receiver does not know. So the algorithm uses only the m=Np−L+1m = N_p - L + 1 samples y[L−1],…,y[Np−1]y[L-1], \ldots, y[N_p - 1]. In matrix form they are v=Xh+wv = X h + w, where XX is the m×Lm \times L matrix with Xil=x[i+L−1−l]X_{il} = x[i + L - 1 - l], constant along each diagonal. The output is an estimate h^\hat h of the LL taps. LS asks for the h^\hat h that minimizes ∥v−Xh^∥2\|v - X \hat h\|^2. This needs XX to have full column rank, and so m≥Lm \ge L, that is Np≥2L−1N_p \ge 2L - 1.

The algorithm

  1. LS-CHANNEL-ESTIMATE(x, y, L)
  2. 1m ← N_p - L + 1 ▷ N_p pilots in x
  3. 2X[i][l] ← x[i + L - 1 - l] for 0 ≤ i < m, 0 ≤ l < L
  4. 3v ← (y[L - 1], .., y[N_p - 1]) ▷ the samples that see pilots only
  5. 4G ← Xᴴ X ▷ L × L, Hermitian
  6. 5b ← Xᴴ v
  7. 6return ĥ ← G⁻¹ b ▷ by Cholesky, G = C Cᴴ

Lines L1 and L2 build the pilot matrix. Each row is a window of LL pilots, newest first, so row ii times hh is the noiseless sample y[i+L−1]y[i + L - 1]. Line L3 drops the first L−1L - 1 samples, which also depend on unknown symbols sent before the pilots. Lines L4 and L5 form the normal equations Gh^=bG \hat h = b, and line L6 solves them. GG is Hermitian and positive definite when XX has full column rank, so the Cholesky decomposition applies; it costs half as much as a general solver and fails exactly when the pilots do not excite every tap. For a fixed pilot block, the receiver computes P=G−1XHP = G^{-1} X^H once, and each later estimate is the product h^=Pv\hat h = P v.

Example

Take L=2L = 2 and the pilots x=(1,1,−1,1,1)x = (1, 1, -1, 1, 1), so Np=5N_p = 5 and m=4m = 4. Line L2 gives the rows (x[1],x[0])=(1,1)(x[1], x[0]) = (1, 1), (−1,1)(-1, 1), (1,−1)(1, -1) and (1,1)(1, 1). Then XTX=4IX^T X = 4 I: the two columns are orthogonal and have the same energy. The channel is h=(1,0.5)h = (1, 0.5), so the noiseless samples of line L3 are Xh=(1.5,−0.5,0.5,1.5)X h = (1.5, -0.5, 0.5, 1.5).

Let the noise on these four samples be (0.1,−0.2,0.05,0.1)(0.1, -0.2, 0.05, 0.1), so v=(1.6,−0.7,0.55,1.6)v = (1.6, -0.7, 0.55, 1.6).

step value
L4: G=XTXG = X^T X 4I4 I
L5: b=XTvb = X^T v (1.6+0.7+0.55+1.6, 1.6−0.7−0.55+1.6)=(4.45, 1.95)(1.6 + 0.7 + 0.55 + 1.6,\ 1.6 - 0.7 - 0.55 + 1.6) = (4.45,\ 1.95)
L6: h^=G−1b\hat h = G^{-1} b (1.1125, 0.4875)(1.1125,\ 0.4875)

The error is (0.1125,−0.0125)(0.1125, -0.0125). Because G=4IG = 4I, each tap estimate is the true tap plus the average of four noise samples with signs, so its variance is N0/4N_0/4, and the mean squared error is N0tr⁡(G−1)=N0/2N_0 \operatorname{tr}(G^{-1}) = N_0/2. With no noise, line L6 returns (1,0.5)(1, 0.5) exactly.

Correctness

Claim. If XX has full column rank, line L6 returns the unique minimizer of ∥v−Xg∥2\|v - X g\|^2. Under the model, E[h^]=hE[\hat h] = h and the error covariance is N0(XHX)−1N_0 (X^H X)^{-1}. For pilots of a fixed total energy T=tr⁡(XHX)T = \operatorname{tr}(X^H X), the mean squared error is at least L2N0/TL^2 N_0 / T, with equality if and only if XHX=(T/L)IX^H X = (T/L) I.

Key step. The residual r=v−Xh^r = v - X \hat h is orthogonal to every column of XX, since XHr=b−Gh^=0X^H r = b - G \hat h = 0. So for any other g=h^+dg = \hat h + d, ∥v−Xg∥2=∥r∥2+∥Xd∥2\|v - X g\|^2 = \|r\|^2 + \|X d\|^2, and the second term is positive unless d=0d = 0. The error is h^−h=G−1XHw\hat h - h = G^{-1} X^H w, a linear function of zero-mean noise, which gives the bias and the covariance. The bound on the trace follows from the Cauchy-Schwarz inequality on the eigenvalues of GG. The full proof is in the proofs folder.

Proof: The LS channel estimate minimizes the residual, is unbiased, has error covariance N0 (X^H X)^(-1), and orthogonal training minimizes its errorfull

Write XX for the m×Lm \times L pilot matrix of line L2, with Xil=x[i+L−1−l]X_{il} = x[i + L - 1 - l] and m=Np−L+1m = N_p - L + 1, and v=(y[L−1],…,y[Np−1])v = (y[L-1], \ldots, y[N_p - 1]) for the samples of line L3. Each of these samples depends on pilots only, so the model is

v=Xh+w,w∼CN(0,N0I).(1)v = X h + w, \qquad w \sim \mathcal{CN}(0, N_0 I). \tag{1}

Let G=XHXG = X^H X (line L4) and b=XHvb = X^H v (line L5). We work in exact complex arithmetic.

Lemma 1 (when the estimate exists). GG is Hermitian and positive semidefinite. It is positive definite if and only if XX has full column rank LL. This needs m≥Lm \ge L, that is Np≥2L−1N_p \ge 2L - 1.

Proof. GH=XHX=GG^H = X^H X = G, and zHGz=∥Xz∥2≥0z^H G z = \|X z\|^2 \ge 0 for every zz, with equality if and only if Xz=0X z = 0. So GG is positive definite if and only if Xz=0X z = 0 only for z=0z = 0, which is full column rank. An m×Lm \times L matrix has rank at most mm, so full column rank needs m≥Lm \ge L. □\square

When GG is positive definite, the Cholesky factor of line L6 exists and h^=G−1b=(XHX)−1XHv\hat h = G^{-1} b = (X^H X)^{-1} X^H v. If GG is singular, the implementation raises an error.

Theorem 1 (least squares). h^\hat h is the unique minimizer of ∥v−Xg∥2\|v - X g\|^2 over g∈CLg \in \mathbb{C}^L.

Proof. For any gg, write g=h^+dg = \hat h + d. Then v−Xg=r−Xdv - X g = r - X d with r=v−Xh^r = v - X \hat h. By line L6, XHr=b−Gh^=0X^H r = b - G \hat h = 0, so the cross terms (Xd)Hr=dHXHr(X d)^H r = d^H X^H r and rHXdr^H X d are zero, and

∥v−Xg∥2=∥r∥2+∥Xd∥2≥∥r∥2.\|v - X g\|^2 = \|r\|^2 + \|X d\|^2 \ge \|r\|^2.

Equality holds if and only if Xd=0X d = 0, and by Lemma 1 this means d=0d = 0. □\square

Theorem 2 (bias and error covariance). Under (1), E[h^]=hE[\hat h] = h and E[(h^−h)(h^−h)H]=N0(XHX)−1E[(\hat h - h)(\hat h - h)^H] = N_0 (X^H X)^{-1}. So the mean squared error is

E∥h^−h∥2=N0tr⁡((XHX)−1).E\|\hat h - h\|^2 = N_0 \operatorname{tr}\big((X^H X)^{-1}\big).

Proof. Put (1) into h^=G−1XHv\hat h = G^{-1} X^H v: h^=G−1XHXh+G−1XHw=h+G−1XHw\hat h = G^{-1} X^H X h + G^{-1} X^H w = h + G^{-1} X^H w. The error is e=G−1XHwe = G^{-1} X^H w, a linear function of ww, so E[e]=0E[e] = 0 and

E[eeH]=G−1XHE[wwH]XG−1=N0 G−1G G−1=N0 G−1,E[e e^H] = G^{-1} X^H E[w w^H] X G^{-1} = N_0\, G^{-1} G\, G^{-1} = N_0\, G^{-1},

because GG and G−1G^{-1} are Hermitian. The mean squared error is the trace of this matrix. □\square

In the linear Gaussian model (1), this covariance is equal to the Cramer-Rao bound for unbiased estimators of hh, so no unbiased estimator does better. Kay proves this for the linear model in Chapter 4 and for complex data in Chapter 15. With a prior on hh, a biased estimator can do better; that is the LMMSE estimator.

Theorem 3 (the best training). Let T=tr⁡(XHX)>0T = \operatorname{tr}(X^H X) > 0, the total energy of the pilot rows. Then

tr⁡((XHX)−1)≥L2T,\operatorname{tr}\big((X^H X)^{-1}\big) \ge \frac{L^2}{T},

with equality if and only if XHX=(T/L) IX^H X = (T/L)\, I.

Proof. GG is Hermitian and positive definite, so it has eigenvalues λ1,…,λL>0\lambda_1, \ldots, \lambda_L > 0 with ∑iλi=T\sum_i \lambda_i = T, and G−1G^{-1} has eigenvalues 1/λi1/\lambda_i. By the Cauchy-Schwarz inequality on the vectors (λi)(\sqrt{\lambda_i}) and (1/λi)(1/\sqrt{\lambda_i}),

L2=(∑iλi⋅1λi)2≤(∑iλi)(∑i1λi)=T tr⁡(G−1).L^2 = \Big(\sum_i \sqrt{\lambda_i} \cdot \frac{1}{\sqrt{\lambda_i}}\Big)^2 \le \Big(\sum_i \lambda_i\Big)\Big(\sum_i \frac{1}{\lambda_i}\Big) = T\, \operatorname{tr}(G^{-1}).

Equality holds if and only if the two vectors are parallel, that is all λi\lambda_i are equal to T/LT/L. A Hermitian matrix with all eigenvalues equal to cc is cIc I. □\square

So for a fixed pilot energy, the mean squared error is at least L2N0/TL^2 N_0 / T, and pilots with XHX=(T/L)IX^H X = (T/L) I reach it. The page example has XTX=4IX^T X = 4I, T=8T = 8 and L=2L = 2, so its error is N0⋅2/4=N0/2=L2N0/TN_0 \cdot 2/4 = N_0/2 = L^2 N_0/T.

Remark (the cost). Lines L2 and L3 copy mL+mm L + m numbers. Line L4 forms the L×LL \times L matrix GG with mL2m L^2 multiplications; it is Hermitian, so half of them suffice. Line L5 costs mLm L, and the Cholesky solve of line L6 costs O(L3)O(L^3). With m≥Lm \ge L, the total is O(mL2)O(m L^2). When the same pilots are used again, P=G−1XHP = G^{-1} X^H is computed once, and each new estimate h^=Pv\hat h = P v costs mLm L multiplications.

Complexity

Lines L2 and L3 copy O(mL)O(m L) numbers. Line L4 costs mL2m L^2 complex multiplications, or about half of that with the Hermitian symmetry, line L5 costs mLm L, and the Cholesky solve of line L6 costs O(L3)O(L^3). Since m≥Lm \ge L, the total is O(mL2)O(m L^2) per pilot block in the real RAM, with O(L2)O(L^2) extra space for GG. When the pilots are the same in every block, P=(XHX)−1XHP = (X^H X)^{-1} X^H is computed once, and each estimate costs mLm L complex multiplications. With orthogonal pilots, GG is a multiple of II, and h^\hat h is XHvX^H v times a constant.

Properties

  • Unbiased, with no prior. E[h^]=hE[\hat h] = h for every channel. The estimator needs neither N0N_0 nor the channel statistics, so it works when these are unknown or change.
  • Efficient in Gaussian noise. In the linear Gaussian model, N0(XHX)−1N_0 (X^H X)^{-1} is equal to the Cramer-Rao bound. No unbiased estimator has a smaller error. A biased estimator with a prior on hh, such as LMMSE, can do better.
  • Error and pilot energy. The mean squared error N0tr⁡((XHX)−1)N_0 \operatorname{tr}((X^H X)^{-1}) falls in proportion to 1/(pilot energy)1/(\text{pilot energy}) and grows with LL. For orthogonal pilots it is L2N0/TL^2 N_0 / T, or LN0/(mEp)L N_0 / (m E_p) when each pilot has energy EpE_p.
  • Orthogonal training is best. Among pilot blocks of the same energy, those with XHXX^H X a multiple of II give the smallest error. A block of mm symbols with zero periodic autocorrelation at every lag other than 0, such as a Zadoff-Chu sequence, has this property when its last L−1L - 1 symbols are also sent first, as a cyclic prefix. The example above is the block (1,−1,1,1)(1, -1, 1, 1) with the prefix 11.
  • Error grows with the number of taps. Each extra tap adds about N0/(mEp)N_0 / (m E_p) to the error. An LL chosen too large adds noise; an LL chosen too small leaves a model error. Sparse channel estimation tries to estimate only the taps that are not zero.
  • Linear and exact. The estimate is a fixed linear function of vv, and with no noise it is the true hh.

Variants and improvements

  • Weighted LS. For colored noise with covariance CC, use h^=(XHC−1X)−1XHC−1v\hat h = (X^H C^{-1} X)^{-1} X^H C^{-1} v, the best linear unbiased estimator.
  • LMMSE estimation. With the channel covariance RhR_h and N0N_0 known, LMMSE channel estimation shrinks the LS estimate toward the prior mean and gets a smaller mean squared error.
  • OFDM and the cyclic prefix. With a cyclic prefix, XX is circulant and the DFT makes it diagonal. LS then becomes one complex division per pilot subcarrier, H^k=Yk/Xk\hat H_k = Y_k / X_k; see comb-pilot channel estimation. DFT-based channel estimation then removes the noise outside the first LL taps.
  • MIMO training. For ntn_t transmit antennas, XX has ntLn_t L columns and each antenna needs its own pilots. Orthogonal pilots across the antennas are again best. In multicell systems, reused pilots cause pilot contamination.
  • Recursive LS. When pilots or decisions arrive one by one, the RLS algorithm updates the same solution in O(L2)O(L^2) per sample, with a forgetting factor that tracks a slowly changing channel.
  • Sparse estimation. When most taps are zero, sparse channel estimation fits only a few taps and needs fewer pilots than 2L−12L - 1.

When to use it

Use LS when the receiver has a block of known pilots and does not know the channel statistics or the noise level, or when these change too fast to estimate. It is the first estimator to try and the reference for the others. At high SNR it is close to LMMSE. At low SNR, or with many taps and few pilots, use LMMSE if the channel covariance is known, and a sparse estimator if the channel has few strong paths.

Pitfalls

  • Too few pilots. With Np<2L−1N_p < 2L - 1, or with pilots that do not excite every tap (for example all pilots equal, which makes the columns of XX the same), XHXX^H X is singular. Line L6 must detect this and not return a result.
  • Using the first samples. The samples y[0],…,y[L−2]y[0], \ldots, y[L-2] also depend on the unknown data before the pilots. Putting them in line L3 with zeros for the unknown symbols adds a bias.
  • Solving the normal equations in bad cases. The condition number of XHXX^H X is the square of that of XX. For badly conditioned pilots, a QR decomposition of XX is more accurate than lines L4 to L6. With good pilots, XHXX^H X is close to a multiple of II, and this does not matter.
  • Too many taps. Each tap that the channel does not have still adds noise to the estimate. Choose LL from the delay spread, not larger.
  • Conjugates. In complex arithmetic the normal equations need XHX^H, not XTX^T. With XTX^T, the estimate is wrong for every complex pilot.

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)
least_squares_channel_estimation.py 76 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/least-squares-channel-estimation/. The authors are listed in prov/JGTN3A.jsonl.

"""Least squares (LS) estimation of the taps of an FIR channel from known pilots.

The model is y[k] = sum_{l=0}^{L-1} h[l] x[k-l] + w[k] at one sample per
symbol, with complex taps h and noise w ~ CN(0, N0). The transmitter sends
Np known pilots x[0], ..., x[Np-1]. The receiver uses only the m = Np - L + 1
samples y[L-1], ..., y[Np-1], which depend on pilots alone. In matrix form
v = X h + w with X[i][l] = x[i + L - 1 - l], and the LS estimate is
h_hat = (X^H X)^(-1) X^H v. Its error covariance is N0 (X^H X)^(-1), so its
mean squared error is N0 tr((X^H X)^(-1)).
"""

import cbb


def training_matrix(x: list[complex], taps: int) -> list[list[complex]]:
    """The m by L pilot matrix X with X[i][l] = x[i + L - 1 - l], m = len(x) - L + 1."""
    m = len(x) - taps + 1  # @line L1
    if taps < 1 or m < taps:
        raise ValueError("need at least 2L - 1 pilots for L taps")
    return [[complex(x[i + taps - 1 - l]) for l in range(taps)] for i in range(m)]  # @line L2


def _chol_solve(g: list[list[complex]], b: list[complex]) -> list[complex]:
    """Solve g z = b for a Hermitian positive definite g, by Cholesky g = C C^H."""
    try:
        c = cbb.cholesky(g)
    except ValueError:
        raise ValueError("X^H X is singular: the pilots do not excite every tap") from None
    n = len(g)
    u = [0j] * n
    for i in range(n):  # forward substitution, C u = b
        u[i] = (b[i] - sum(c[i][k] * u[k] for k in range(i))) / c[i][i]
    z = [0j] * n
    for i in range(n - 1, -1, -1):  # back substitution, C^H z = u
        z[i] = (u[i] - sum(c[k][i].conjugate() * z[k] for k in range(i + 1, n))) / c[i][i].conjugate()
    return z


def ls_estimate(x: list[complex], y: list[complex], taps: int) -> list[complex]:
    """The LS estimate of L = taps channel taps from Np pilots x and the Np samples y[0..Np-1]."""
    if len(y) != len(x):
        raise ValueError("need one received sample per pilot")
    xm = training_matrix(x, taps)  # @line L1
    v = [complex(s) for s in y[taps - 1 :]]  # @line L3
    xh = cbb.herm(xm)
    g = cbb.matmul(xh, xm)  # @line L4
    b = cbb.matvec(xh, v)  # @line L5
    return _chol_solve(g, b)  # @line L6


def ls_matrix(x: list[complex], taps: int) -> list[list[complex]]:
    """The L by m matrix P = (X^H X)^(-1) X^H. For fixed pilots, h_hat = P v costs O(m L)."""
    xm = training_matrix(x, taps)
    xh = cbb.herm(xm)
    g = cbb.matmul(xh, xm)
    cols = [_chol_solve(g, col) for col in (list(c) for c in zip(*xh))]
    return [list(r) for r in zip(*cols)]


def ls_mse(x: list[complex], taps: int, n0: float) -> float:
    """The mean squared error E||h_hat - h||^2 = N0 tr((X^H X)^(-1)) of the LS estimate."""
    xm = training_matrix(x, taps)
    g = cbb.matmul(cbb.herm(xm), xm)
    inv_g = [_chol_solve(g, col) for col in cbb.eye(taps)]
    return n0 * sum(inv_g[i][i].real for i in range(taps))


def received(x: list[complex], h: list[complex], noise: list[complex] | None = None) -> list[complex]:
    """y[k] = sum_l h[l] x[k-l] + w[k] for k = 0..len(x)-1, with x[k] = 0 for k < 0."""
    y = cbb.conv(x, h)[: len(x)]
    if noise is not None:
        y = [a + b for a, b in zip(y, noise)]
    return y
test_least_squares_channel_estimation.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/least-squares-channel-estimation/. The authors are listed in prov/JGTN3A.jsonl.

import random

import pytest

import cbb
from least_squares_channel_estimation import ls_estimate, ls_matrix, ls_mse, received, training_matrix


def close(a, b, tol=1e-9):
    return all(abs(p - q) <= tol for p, q in zip(a, b)) and len(a) == len(b)


def qpsk(rng):
    return complex(rng.choice((-1, 1)), rng.choice((-1, 1))) / 2**0.5


def qr_least_squares(xm, v):
    """An independent oracle: modified Gram-Schmidt X = Q R, then R h = Q^H v by back substitution."""
    m, n = len(xm), len(xm[0])
    cols = [[xm[i][k] for i in range(m)] for k in range(n)]
    q, r = [], [[0j] * n for _ in range(n)]
    for k in range(n):
        a = list(cols[k])
        for i, qi in enumerate(q):
            r[i][k] = cbb.dot(qi, a)
            a = [p - r[i][k] * s for p, s in zip(a, qi)]
        r[k][k] = cbb.norm2(a) ** 0.5
        q.append([p / r[k][k] for p in a])
    z = [cbb.dot(qi, v) for qi in q]
    h = [0j] * n
    for i in range(n - 1, -1, -1):
        h[i] = (z[i] - sum(r[i][k] * h[k] for k in range(i + 1, n))) / r[i][i]
    return h


def test_example_on_the_page() -> None:
    x = [1, 1, -1, 1, 1]
    assert training_matrix(x, 2) == [[1, 1], [-1, 1], [1, -1], [1, 1]]
    y = received(x, [1, 0.5])
    assert close(y[1:], [1.5, -0.5, 0.5, 1.5])
    noise = [0.3, 0.1, -0.2, 0.05, 0.1]  # the first sample is not used
    h = ls_estimate(x, received(x, [1, 0.5], noise), 2)
    assert close(h, [1.1125, 0.4875])
    assert abs(ls_mse(x, 2, 1.0) - 0.5) < 1e-12  # N0 tr((X^H X)^(-1)) with X^H X = 4 I


def test_noiseless_recovery_is_exact() -> None:
    rng = random.Random(4101)
    for _ in range(200):  # random QPSK pilots, CN(0, 1) taps, no noise
        taps = rng.randint(1, 5)
        x = [qpsk(rng) for _ in range(2 * taps + 3 + rng.randint(0, 6))]
        h = [cbb.cn(rng, 1.0) for _ in range(taps)]
        try:
            got = ls_estimate(x, received(x, h), taps)
        except ValueError:
            continue  # a rare singular X^H X for the shortest pilot blocks
        assert close(got, h, 1e-12)


def test_against_an_independent_qr_solver_and_the_normal_equations() -> None:
    rng = random.Random(4102)
    for _ in range(150):
        taps = rng.randint(1, 4)
        x = [cbb.cn(rng, 1.0) for _ in range(taps + rng.randint(taps, 12))]
        y = [cbb.cn(rng, 2.0) for _ in x]  # any data, not only data of the model
        got = ls_estimate(x, y, taps)
        xm, v = training_matrix(x, taps), y[taps - 1 :]
        assert close(got, qr_least_squares(xm, v), 1e-8)
        resid = cbb.sub(v, cbb.matvec(xm, got))
        assert close(cbb.matvec(cbb.herm(xm), resid), [0j] * taps, 1e-8)  # X^H (v - X h) = 0
        best = cbb.norm2(resid)
        for _ in range(5):  # every other tap vector leaves a larger residual
            other = [a + cbb.cn(rng, 0.01) for a in got]
            assert cbb.norm2(cbb.sub(v, cbb.matvec(xm, other))) >= best - 1e-12
        p = ls_matrix(x, taps)
        assert close(cbb.matvec(p, v), got, 1e-8)


def test_unbiased_and_mse_matches_the_formula() -> None:
    rng = random.Random(4103)
    x = [qpsk(rng) for _ in range(12)]
    h = [0.9 + 0.1j, -0.4 + 0.3j, 0.2j]
    n0, runs = 0.2, 3000
    p, taps = ls_matrix(x, 3), 3
    clean = received(x, h)[taps - 1 :]
    mean, sq = [0j] * taps, 0.0
    for _ in range(runs):
        v = cbb.awgn(rng, clean, n0)
        e = cbb.sub(cbb.matvec(p, v), h)
        mean = [a + b / runs for a, b in zip(mean, e)]
        sq += cbb.norm2(e) / runs
    want = ls_mse(x, taps, n0)
    assert max(abs(a) for a in mean) < 0.03
    assert abs(sq - want) < 0.1 * want  # the sample mean of a scaled chi-square, 3000 runs


def test_orthogonal_training_is_optimal() -> None:
    # tr((X^H X)^(-1)) >= L^2 / tr(X^H X), with equality when X^H X is a multiple of I
    rng = random.Random(4104)
    for _ in range(200):
        taps = rng.randint(1, 4)
        x = [qpsk(rng) for _ in range(2 * taps - 1 + rng.randint(0, 8))]
        xm = training_matrix(x, taps)
        g = cbb.matmul(cbb.herm(xm), xm)
        trace = sum(g[i][i].real for i in range(taps))
        try:
            mse = ls_mse(x, taps, 1.0)
        except ValueError:
            continue
        assert mse >= taps * taps / trace - 1e-9
    assert abs(ls_mse([1, 1, -1, 1, 1], 2, 1.0) - 4 / 8) < 1e-12  # the example reaches the bound


def test_errors() -> None:
    with pytest.raises(ValueError):
        ls_estimate([1, 1], [1, 1], 2)  # Np = 2 < 2L - 1
    with pytest.raises(ValueError):
        ls_estimate([0, 0, 0, 0], [1, 1, 1, 1], 2)  # the pilots excite nothing
    with pytest.raises(ValueError):
        ls_estimate([1, 1, 1], [1, 1], 2)

History

Adrien-Marie Legendre published the method of least squares in 1805, and Carl Friedrich Gauss published his account, with a probabilistic justification, in 1809. In digital communications, receivers used known training symbols from the start of adaptive equalization in the 1960s, and LS gave the estimate of the channel from such a block in one step instead of by slow adaptation. GSM, for example, places a training sequence of 26 bits in the middle of each normal burst. The theory of the estimator itself, with its error and its optimal pilots, belongs to the linear model of estimation theory, as in the book by Kay. Biguesh and Gershman in 2006 compared the LS and LMMSE estimators for MIMO training and showed that orthogonal training minimizes the LS error.

References

  1. Steven M. Kay, Fundamentals of Statistical Signal Processing, Volume I: Estimation Theory, Prentice Hall, 1993, Chapter 4 (the linear model and its efficient estimator), Chapter 8 (least squares) and Chapter 15 (complex data and parameters)
  2. M. Biguesh and A. B. Gershman, Training-based MIMO channel estimation: a study of estimator tradeoffs and optimal training signals, IEEE Transactions on Signal Processing 54(3), 2006, pages 884 to 893, the LS estimator, its mean squared error, and the result that orthogonal training minimizes that error for a fixed training energy

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
  • at least three sources
  • a scene preset for the example