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)).
- Solves
- Channel estimation
- Time
- O(m L^2) worst
- Space
- O(L^2) extra
- Where
- L = the number of channel taps; m = the number of pilot observations
- Model
- Real RAM
- Properties
- deterministicefficient in gaussian noisenot needs channel statisticsunbiased
- Evidence
- Proof sketchCode in 1 languages
- 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 , and the received samples are , where the matrix holds the pilots and is the noise. The LS estimate is the tap vector that makes smallest; it is the least squares problem solved with the pseudoinverse of . It uses no knowledge of the channel statistics. It is unbiased, its mean squared error is , 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 known pilots , the samples that the receiver gets while they arrive, and the number of taps . The model is one sample per symbol, after the matched filter:
with complex taps and noise , independent from sample to sample, so that . The first samples also hold symbols sent before the pilots, which the receiver does not know. So the algorithm uses only the samples . In matrix form they are , where is the matrix with , constant along each diagonal. The output is an estimate of the taps. LS asks for the that minimizes . This needs to have full column rank, and so , that is .
The algorithm
LS-CHANNEL-ESTIMATE(x, y, L)- 1
m ← N_p - L + 1 ▷ N_p pilots in x - 2
X[i][l] ← x[i + L - 1 - l] for 0 ≤ i < m, 0 ≤ l < L - 3
v ← (y[L - 1], .., y[N_p - 1]) ▷ the samples that see pilots only - 4
G ← Xᴴ X ▷ L × L, Hermitian - 5
b ← Xᴴ v - 6
return ĥ ← G⁻¹ b ▷ by Cholesky, G = C Cᴴ
Lines L1 and L2 build the pilot matrix. Each row is a window of pilots, newest first, so row times is the noiseless sample . Line L3 drops the first samples, which also depend on unknown symbols sent before the pilots. Lines L4 and L5 form the normal equations , and line L6 solves them. is Hermitian and positive definite when 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 once, and each later estimate is the product .
Example
Take and the pilots , so and . Line L2 gives the rows , , and . Then : the two columns are orthogonal and have the same energy. The channel is , so the noiseless samples of line L3 are .
Let the noise on these four samples be , so .
| step | value |
|---|---|
| L4: | |
| L5: | |
| L6: |
The error is . Because , each tap estimate is the true tap plus the average of four noise samples with signs, so its variance is , and the mean squared error is . With no noise, line L6 returns exactly.
Correctness
Claim. If has full column rank, line L6 returns the unique minimizer of . Under the model, and the error covariance is . For pilots of a fixed total energy , the mean squared error is at least , with equality if and only if .
Key step. The residual is orthogonal to every column of , since . So for any other , , and the second term is positive unless . The error is , 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 . 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 for the pilot matrix of line L2, with and , and for the samples of line L3. Each of these samples depends on pilots only, so the model is
Let (line L4) and (line L5). We work in exact complex arithmetic.
Lemma 1 (when the estimate exists). is Hermitian and positive semidefinite. It is positive definite if and only if has full column rank . This needs , that is .
Proof. , and for every , with equality if and only if . So is positive definite if and only if only for , which is full column rank. An matrix has rank at most , so full column rank needs .
When is positive definite, the Cholesky factor of line L6 exists and . If is singular, the implementation raises an error.
Theorem 1 (least squares). is the unique minimizer of over .
Proof. For any , write . Then with . By line L6, , so the cross terms and are zero, and
Equality holds if and only if , and by Lemma 1 this means .
Theorem 2 (bias and error covariance). Under (1), and . So the mean squared error is
Proof. Put (1) into : . The error is , a linear function of , so and
because and are Hermitian. The mean squared error is the trace of this matrix.
In the linear Gaussian model (1), this covariance is equal to the Cramer-Rao bound for unbiased estimators of , 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 , a biased estimator can do better; that is the LMMSE estimator.
Theorem 3 (the best training). Let , the total energy of the pilot rows. Then
with equality if and only if .
Proof. is Hermitian and positive definite, so it has eigenvalues with , and has eigenvalues . By the Cauchy-Schwarz inequality on the vectors and ,
Equality holds if and only if the two vectors are parallel, that is all are equal to . A Hermitian matrix with all eigenvalues equal to is .
So for a fixed pilot energy, the mean squared error is at least , and pilots with reach it. The page example has , and , so its error is .
Remark (the cost). Lines L2 and L3 copy numbers. Line L4 forms the matrix with multiplications; it is Hermitian, so half of them suffice. Line L5 costs , and the Cholesky solve of line L6 costs . With , the total is . When the same pilots are used again, is computed once, and each new estimate costs multiplications.
Complexity
Lines L2 and L3 copy numbers. Line L4 costs complex multiplications, or about half of that with the Hermitian symmetry, line L5 costs , and the Cholesky solve of line L6 costs . Since , the total is per pilot block in the real RAM, with extra space for . When the pilots are the same in every block, is computed once, and each estimate costs complex multiplications. With orthogonal pilots, is a multiple of , and is times a constant.
Properties
- Unbiased, with no prior. for every channel. The estimator needs neither nor the channel statistics, so it works when these are unknown or change.
- Efficient in Gaussian noise. In the linear Gaussian model, is equal to the Cramer-Rao bound. No unbiased estimator has a smaller error. A biased estimator with a prior on , such as LMMSE, can do better.
- Error and pilot energy. The mean squared error falls in proportion to and grows with . For orthogonal pilots it is , or when each pilot has energy .
- Orthogonal training is best. Among pilot blocks of the same energy, those with a multiple of give the smallest error. A block of symbols with zero periodic autocorrelation at every lag other than 0, such as a Zadoff-Chu sequence, has this property when its last symbols are also sent first, as a cyclic prefix. The example above is the block with the prefix .
- Error grows with the number of taps. Each extra tap adds about to the error. An chosen too large adds noise; an 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 , and with no noise it is the true .
Variants and improvements
- Weighted LS. For colored noise with covariance , use , the best linear unbiased estimator.
- LMMSE estimation. With the channel covariance and 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, is circulant and the DFT makes it diagonal. LS then becomes one complex division per pilot subcarrier, ; see comb-pilot channel estimation. DFT-based channel estimation then removes the noise outside the first taps.
- MIMO training. For transmit antennas, has 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 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 .
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 , or with pilots that do not excite every tap (for example all pilots equal, which makes the columns of the same), is singular. Line L6 must detect this and not return a result.
- Using the first samples. The samples 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 is the square of that of . For badly conditioned pilots, a QR decomposition of is more accurate than lines L4 to L6. With good pilots, is close to a multiple of , and this does not matter.
- Too many taps. Each tap that the channel does not have still adds noise to the estimate. Choose from the delay spread, not larger.
- Conjugates. In complex arithmetic the normal equations need , not . With , 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.
# 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag JGTN3A Edit this page History Report an error Markdown