Algorithmcore
LMMSE channel estimation
Also called linear MMSE channel estimation, MMSE channel estimator.
Estimates the channel taps from pilots by the linear filter with the least mean squared error, h = (R_h X^H X + N0 I)^(-1) R_h X^H y, using the channel covariance and the noise level.
- Solves
- Channel estimation
- Time
- O(m L^2 + L^3) worst
- Space
- O(L^2) extra
- Where
- L = the number of channel taps; m = the number of pilot observations
- Model
- Real RAM
- Properties
- deterministicneeds channel statisticsoptimal among linear estimatorsoptimal for gaussian channelsnot unbiased
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Andrey Kolmogorov, Norbert Wiener, 1941
LMMSE channel estimation finds the taps of a channel from pilots with the linear filter that has the smallest mean squared error on average over the channels. It is the least squares channel estimator with prior knowledge added: the receiver knows the covariance of the taps and the noise level . For the model , with the pilot matrix and noise , the estimate is . It is the Wiener filter of the pilot model. Its error is never larger than that of LS, and the gain is largest at low SNR and when has a few strong directions. For Gaussian channels it is also the best estimator of any kind. The estimate is biased toward the prior mean, zero here. Two-dimensional Wiener pilot interpolation applies the same filter across the time and frequency grid of OFDM, DFT-based channel estimation is a cheaper estimator that uses only the channel length, and the MMSE linear equalizer uses the same formula to estimate the data symbols instead of the channel.
In plain words
Least squares fits the taps to the received pilots and trusts the data alone. But the receiver often knows more: how strong each tap is on average, and how much noise there is. LMMSE uses this. When a tap is weak on average or the noise is strong, it trusts the data less and pulls that estimate toward zero. When a tap is strong and the noise is weak, it gives almost the least squares answer. The pull is chosen so that the average squared error is as small as any linear rule can make it. The price is that the receiver must know the statistics, and that each single estimate is a little too small on average.
The problem
The input is a block of known pilots , the samples , the number of taps , the covariance of the taps, and . The model is one sample per symbol, , with independent of each other and of . As for LS, the algorithm uses the samples , which depend on the pilots only, so with . The taps have mean zero; for a nonzero mean see the variants. The output is an estimate , where the matrix minimizes the mean squared error , averaged over the channel and the noise. The SNR is , where is the average energy of a pilot.
The algorithm
LMMSE-CHANNEL-ESTIMATE(x, y, L, R_h, N0)- 1
X ← the m × L pilot matrix, X[i][l] = x[i + L - 1 - l] - 2
v ← (y[L - 1], .., y[N_p - 1]) ▷ the samples that see pilots only - 3
G ← Xᴴ X ; b ← Xᴴ v - 4
A ← R_h G + N0 I - 5
c ← R_h b - 6
return ĥ ← A⁻¹ c ▷ an L × L solve
Lines L1 and L2 are the same as in the LS estimator. Line L3 forms the matrix and the vector of the normal equations. Lines L4 to L6 compute . This form solves an system instead of inverting the matrix , and it does not need , so a tap known to be zero, with a zero row in , is allowed and is estimated as exactly zero. is not Hermitian, so line L6 uses Gaussian elimination. If , and do not change, the receiver computes once, and each estimate is .
Example
Use the pilots of the LS example, with , so , and the same samples , which give and the LS estimate . Let the taps be independent with , and let , an SNR of 2, or 3 dB.
| step | value |
|---|---|
| L4: | |
| L5: | |
| L6: |
Because and are diagonal, each tap is the LS value times a shrink factor , with the variance of tap : for the strong tap and for the weak one. The error covariance is , so the mean squared error is , against for LS. The table gives both errors for other noise levels.
| SNR in dB | LS error | LMMSE error | |
|---|---|---|---|
| 1 | 0 | 0.5 | 0.30159 |
| 0.5 | 3.01 | 0.25 | 0.18503 |
| 0.1 | 10 | 0.05 | 0.04646 |
| 0.01 | 20 | 0.005 | 0.00496 |
At high SNR the two are almost equal. With no data at all, the best guess is , with error .
Correctness
Claim. Among all linear estimators , the matrix gives the smallest mean squared error, and it is the only one that does. Lines L4 to L6 compute . The error covariance is , and its trace is at most the LS error .
Key step. The orthogonality principle: the error is uncorrelated with every sample of . Any other then has the error with positive definite. The identity moves between the two forms. LS is one of the linear estimators, so LMMSE is at least as good. For Gaussian and , the error is independent of , which makes the conditional mean. The full proof is in the proofs folder.
Proof: The LMMSE channel estimate minimizes the mean squared error over all linear estimators, and its two forms and its error covariance agreefull
Write for the pilot matrix of line L1 and for the samples of line L2. The model is
where has mean zero and covariance , which is Hermitian and positive semidefinite, and has mean zero and covariance with , and is uncorrelated with . Let and
is Hermitian and positive definite, because . We also need .
Lemma 1 (the error of a linear estimator). For any matrix , the estimate has the mean squared error
Proof. , and , because is Hermitian.
Theorem 1 (the best linear estimator). Let . Then
for every . So is the unique linear estimator with the smallest mean squared error, and the error is uncorrelated with (the orthogonality principle).
Proof. Put in Lemma 1. Since , the cross terms are and its conjugate, so
The last two terms cancel. is positive definite, so over the rows of , with equality if and only if . Finally, .
Lemma 2 (the form of lines L3 to L6). is invertible, and . So line L6 returns .
Proof. Let be an eigenvalue of with eigenvector . Then when , and , which shows because both quadratic forms are real and nonnegative and if . So every eigenvalue of is at least , and is invertible. Next,
Multiply on the left by and on the right by : .
This form needs an solve instead of an inverse, and it does not need , so a singular is allowed. A zero row of gives a zero row of , and so the estimate of a tap that is known to be zero is exactly zero.
Theorem 2 (the error covariance). The error has mean zero and covariance
which equals when is invertible. The mean squared error is .
Proof. . By the orthogonality of Theorem 1, , so . With Lemma 2,
If is invertible, .
Corollary 1 (LMMSE is at least as good as LS). If is invertible, , the error of the LS estimate.
Proof. The LS estimate is a linear estimator . It is unbiased for every fixed , with error covariance , so its mean squared error averaged over is also . By Theorem 1 this is at least .
Corollary 2 (the limits). If and are invertible, then , the LS estimator, as . As , and the estimate falls back to the prior mean.
Proof. is continuous in near because is invertible, and at it is . For large , .
Theorem 3 (Gaussian channel and noise). If and are jointly Gaussian and independent, then , so the LMMSE estimate has the smallest mean squared error among all estimators, linear or not.
Proof. The pair is a linear function of the Gaussian vector , so it is jointly Gaussian. By Theorem 1, and are uncorrelated, and uncorrelated jointly Gaussian vectors are independent. So , and . The conditional mean minimizes the mean squared error over all functions of .
Remark (nonzero mean). If , apply the result to and : , with the same error covariance.
Remark (the cost). Lines L1 and L2 copy numbers. Line L3 costs multiplications, line L4 costs , line L5 costs and the solve of line L6 costs . The total is per pilot block. If , and do not change, is computed once, and each estimate costs multiplications, the same as LS.
Complexity
Line L3 costs complex multiplications, line L4 costs , line L5 , and the solve of line L6 . The total is per pilot block in the real RAM, with extra space. The other form, with the inverse, costs , which is worse when there are many pilots. When , and are fixed, is computed once and each estimate costs multiplications, the same as LS. In OFDM with subcarriers, the full LMMSE matrix is , and a low-rank approximation keeps only the strong eigenvectors of the channel covariance.
Properties
- Least mean squared error among linear estimators. No other linear function of the pilots does better on average over the channel distribution.
- Optimal for Gaussian channels. For Rayleigh fading taps and Gaussian noise, , the best estimator of any kind.
- Biased. For a fixed channel, in general: the estimate is pulled toward zero. The error is small on average over the channels, not for each channel.
- At least as good as LS. . The gain is large at low SNR and for channels whose covariance has a few strong eigenvalues, and it vanishes as , where the estimate tends to LS.
- Error covariance. when is invertible: the information from the prior adds to the information from the pilots.
- Sensitive to the model. A wrong or gives a larger error than the formula. In practice, a covariance for a longer delay spread than the true one loses less than a covariance for a shorter one, which suppresses real taps.
Variants and improvements
- Nonzero mean. For a channel with a known mean , such as Rician fading, use .
- Diagonal approximation. With independent taps and orthogonal pilots, , and the estimate is the LS estimate times one shrink factor per tap, , as in the example.
- OFDM frequency and time interpolation. Two-dimensional Wiener pilot interpolation estimates the channel at every subcarrier and symbol from the pilots of a grid, with the correlation from the delay spread and the Doppler spread. Separable filters, one in frequency and one in time, cut the cost.
- Low-rank LMMSE. Keep the largest eigenvalues of only. The cost per estimate falls from to with little loss. The frequency correlation of a channel with taps at multiples of the sample time has rank at most , so loses nothing.
- Tracking. If the channel changes over time with a known model, the Kalman filter, as in Kalman channel tracking, gives the LMMSE estimate from all pilots so far, updated recursively.
- Regularized LS. If only and the tap power are known, gives , which is ridge regression with the parameter .
When to use it
Use LMMSE when the receiver knows or can estimate the channel covariance and the noise level, and when the SNR is low or the pilots are few, so that LS is noisy. Typical cases are OFDM receivers with a known power delay profile, and pilot interpolation in time with a known Doppler spread. Use LS when the statistics are unknown or change fast, or at high SNR, where both give nearly the same error.
Pitfalls
- A wrong noise level. If is too small, the estimate is close to LS and keeps its noise. If is too large, the estimate shrinks the taps too much and is biased. Measure , for example from guard subcarriers or from the residual of the LS fit.
- A covariance from the wrong channel. comes from the power delay profile. A profile that is shorter than the true one sets the late taps to almost zero and loses their energy. When in doubt, use a profile that is too long, not too short.
- The inverse of . The form fails for a singular , which is common in OFDM, where the covariance of a channel with taps has rank . Lines L4 to L6 do not need the inverse.
- The cost of the large form. inverts an matrix. For many pilots, use the form of lines L4 to L6.
- Expecting an unbiased estimate. For one channel, the LMMSE estimate is too small on average. A detector that uses it with the error covariance works as designed; one that treats it as exact loses a little.
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)
lmmse_channel_estimation.py 73 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lmmse-channel-estimation/. The authors are listed in prov/5PBE09.jsonl.
"""Linear MMSE estimation of the taps of an FIR channel from known pilots.
The model is v = X h + w, where X is the m by L pilot matrix with
X[i][l] = x[i + L - 1 - l], v holds the samples y[L-1], ..., y[Np-1], the
taps h have mean zero and covariance R_h, and w ~ CN(0, N0 I) is independent
of h. The LMMSE estimate is
h_hat = R_h X^H (X R_h X^H + N0 I)^(-1) v = (R_h X^H X + N0 I)^(-1) R_h X^H v.
The second form solves an L by L system and needs no inverse of R_h, so a
singular R_h (a tap that is known to be zero) is allowed. The error
covariance is C_e = N0 (R_h X^H X + N0 I)^(-1) R_h.
"""
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
if taps < 1 or m < 1:
raise ValueError("need at least L pilots for L taps")
return [[complex(x[i + taps - 1 - l]) for l in range(taps)] for i in range(m)]
def _system(x: list[complex], taps: int, r_h: list[list[complex]], n0: float):
if len(r_h) != taps or any(len(r) != taps for r in r_h):
raise ValueError("R_h must be L by L")
if n0 <= 0:
raise ValueError("N0 must be positive")
xm = training_matrix(x, taps)
xh = cbb.herm(xm)
g = cbb.matmul(xh, xm)
a = cbb.add(cbb.matmul(r_h, g), cbb.scale(n0, cbb.eye(taps)))
return xm, xh, a
def lmmse_estimate(x: list[complex], y: list[complex], taps: int, r_h: list[list[complex]], n0: float) -> list[complex]:
"""The LMMSE estimate of L = taps zero-mean taps with covariance r_h, from pilots x and samples y[0..Np-1]."""
if len(y) != len(x):
raise ValueError("need one received sample per pilot")
if len(r_h) != taps or any(len(r) != taps for r in r_h):
raise ValueError("R_h must be L by L")
if n0 <= 0:
raise ValueError("N0 must be positive")
xm = training_matrix(x, taps) # @line L1
v = [complex(s) for s in y[taps - 1 :]] # @line L2
xh = cbb.herm(xm)
g, b = cbb.matmul(xh, xm), cbb.matvec(xh, v) # @line L3
a = cbb.add(cbb.matmul(r_h, g), cbb.scale(n0, cbb.eye(taps))) # @line L4
c = cbb.matvec(r_h, b) # @line L5
return cbb.solve(a, c) # @line L6
def lmmse_matrix(x: list[complex], taps: int, r_h: list[list[complex]], n0: float) -> list[list[complex]]:
"""The L by m matrix W = (R_h X^H X + N0 I)^(-1) R_h X^H, so that h_hat = W v."""
_, xh, a = _system(x, taps, r_h, n0)
return cbb.solve(a, cbb.matmul(r_h, xh))
def error_covariance(x: list[complex], taps: int, r_h: list[list[complex]], n0: float) -> list[list[complex]]:
"""C_e = E[(h_hat - h)(h_hat - h)^H] = N0 (R_h X^H X + N0 I)^(-1) R_h."""
_, _, a = _system(x, taps, r_h, n0)
return cbb.scale(n0, cbb.solve(a, r_h))
def lmmse_mse(x: list[complex], taps: int, r_h: list[list[complex]], n0: float) -> float:
"""The mean squared error E||h_hat - h||^2 = tr(C_e)."""
c = error_covariance(x, taps, r_h, n0)
return sum(c[i][i].real for i in range(taps))
test_lmmse_channel_estimation.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lmmse-channel-estimation/. The authors are listed in prov/5PBE09.jsonl.
import random
import pytest
import cbb
from lmmse_channel_estimation import error_covariance, lmmse_estimate, lmmse_matrix, lmmse_mse, training_matrix
def close(a, b, tol=1e-9):
if a and isinstance(a[0], list):
return len(a) == len(b) and all(close(r, s, tol) for r, s in zip(a, b))
return len(a) == len(b) and all(abs(p - q) <= tol for p, q in zip(a, b))
def trace(a):
return sum(a[i][i] for i in range(len(a))).real
def random_covariance(rng, n, rank=None):
"""R = C C^H for a random n by rank matrix C, so R is Hermitian, positive semidefinite."""
c = [[cbb.cn(rng, 1.0) for _ in range(rank or n)] for _ in range(n)]
return cbb.matmul(c, cbb.herm(c))
def textbook_matrix(xm, r_h, n0):
"""The other form W = R_h X^H (X R_h X^H + N0 I)^(-1), with an m by m inverse."""
xh = cbb.herm(xm)
k = cbb.add(cbb.matmul(cbb.matmul(xm, r_h), xh), cbb.scale(n0, cbb.eye(len(xm))))
return cbb.matmul(cbb.matmul(r_h, xh), cbb.inv(k))
def linear_mse(w, xm, r_h, n0):
"""E||W v - h||^2 for v = X h + w: tr(W K W^H) - 2 Re tr(W X R_h) + tr(R_h), K = X R_h X^H + N0 I."""
k = cbb.add(cbb.matmul(cbb.matmul(xm, r_h), cbb.herm(xm)), cbb.scale(n0, cbb.eye(len(xm))))
t1 = trace(cbb.matmul(cbb.matmul(w, k), cbb.herm(w)))
t2 = trace(cbb.matmul(cbb.matmul(w, xm), r_h))
return t1 - 2 * t2 + trace(r_h)
def test_example_on_the_page() -> None:
x = [1, 1, -1, 1, 1]
r_h = [[0.8, 0], [0, 0.2]]
y = [1.3, 1.6, -0.7, 0.55, 1.6] # the LS page example; y[0] is not used
assert close(lmmse_estimate(x, y, 2, r_h, 0.5), [3.2 / 3.7 * 1.1125, 0.8 / 1.3 * 0.4875])
assert close(lmmse_estimate(x, y, 2, r_h, 0.5), [0.9621621621621622, 0.3])
c = error_covariance(x, 2, r_h, 0.5)
assert close(c, [[0.4 / 3.7, 0], [0, 0.1 / 1.3]])
assert abs(lmmse_mse(x, 2, r_h, 0.5) - 0.18503118503118504) < 1e-12
assert lmmse_mse(x, 2, r_h, 0.5) < 0.5 / 2 # the LS error N0 tr((X^H X)^(-1)) = 0.25
def test_the_two_forms_agree() -> None:
rng = random.Random(5201)
for _ in range(60):
taps = rng.randint(1, 4)
x = [cbb.cn(rng, 1.0) for _ in range(taps + rng.randint(0, 6))]
r_h = random_covariance(rng, taps, rng.randint(1, taps)) # may be singular
n0 = rng.uniform(0.05, 2.0)
xm = training_matrix(x, taps)
assert close(lmmse_matrix(x, taps, r_h, n0), textbook_matrix(xm, r_h, n0), 1e-8)
y = [cbb.cn(rng, 1.0) for _ in x]
assert close(lmmse_estimate(x, y, taps, r_h, n0), cbb.matvec(lmmse_matrix(x, taps, r_h, n0), y[taps - 1 :]), 1e-9)
def test_orthogonality_and_minimum_over_all_linear_estimators() -> None:
rng = random.Random(5202)
for _ in range(60):
taps = rng.randint(1, 4)
x = [cbb.cn(rng, 1.0) for _ in range(taps + rng.randint(0, 5))]
r_h = random_covariance(rng, taps)
n0 = rng.uniform(0.05, 2.0)
xm = training_matrix(x, taps)
w = lmmse_matrix(x, taps, r_h, n0)
# orthogonality: E[(W v - h) v^H] = W K - R_h X^H = 0
k = cbb.add(cbb.matmul(cbb.matmul(xm, r_h), cbb.herm(xm)), cbb.scale(n0, cbb.eye(len(xm))))
assert close(cbb.matmul(w, k), cbb.matmul(r_h, cbb.herm(xm)), 1e-8)
best = linear_mse(w, xm, r_h, n0)
assert abs(best - lmmse_mse(x, taps, r_h, n0)) < 1e-9
for _ in range(5):
other = [[a + cbb.cn(rng, 0.05) for a in row] for row in w]
assert linear_mse(other, xm, r_h, n0) >= best - 1e-12
rand_w = [[cbb.cn(rng, 1.0) for _ in range(len(xm))] for _ in range(taps)]
assert linear_mse(rand_w, xm, r_h, n0) >= best
def test_monte_carlo_mse_matches_the_closed_form() -> None:
rng = random.Random(5203)
taps, n0, runs = 3, 0.3, 4000
x = [complex(rng.choice((-1, 1)), rng.choice((-1, 1))) / 2**0.5 for _ in range(8)]
pdp = [0.6, 0.3, 0.1] # exponential-like power delay profile with correlated taps
r_h = [[0.5 ** abs(i - k) * (pdp[i] * pdp[k]) ** 0.5 for k in range(taps)] for i in range(taps)]
chol = cbb.cholesky(r_h)
xm = training_matrix(x, taps)
w = lmmse_matrix(x, taps, r_h, n0)
sq, mean = 0.0, [0j] * taps
for _ in range(runs):
h = cbb.matvec(chol, [cbb.cn(rng, 1.0) for _ in range(taps)])
v = cbb.awgn(rng, cbb.matvec(xm, h), n0)
e = cbb.sub(cbb.matvec(w, v), h)
sq += cbb.norm2(e) / runs
mean = [a + b / runs for a, b in zip(mean, e)]
want = lmmse_mse(x, taps, r_h, n0)
assert abs(sq - want) < 0.08 * want # 4000 runs, seed 5203
assert max(abs(a) for a in mean) < 0.03
def test_lmmse_beats_ls_and_tends_to_ls() -> None:
rng = random.Random(5204)
for _ in range(60):
taps = rng.randint(1, 4)
x = [cbb.cn(rng, 1.0) for _ in range(2 * taps - 1 + rng.randint(1, 5))]
r_h = random_covariance(rng, taps)
n0 = rng.uniform(0.05, 2.0)
xm = training_matrix(x, taps)
g = cbb.matmul(cbb.herm(xm), xm)
ls_mse = n0 * trace(cbb.inv(g))
assert lmmse_mse(x, taps, r_h, n0) <= ls_mse + 1e-12
y = [cbb.cn(rng, 1.0) for _ in x]
ls = cbb.solve(g, cbb.matvec(cbb.herm(xm), y[taps - 1 :]))
assert close(lmmse_estimate(x, y, taps, r_h, 1e-10), ls, 1e-6)
def test_noiseless_data_and_a_known_zero_tap() -> None:
x = [1, 1, -1, 1, 1, -1, -1]
h = [0.9 - 0.2j, 0, 0.3j]
y = cbb.conv(x, h)[: len(x)]
r_h = [[1, 0, 0], [0, 0, 0], [0, 0, 0.5]] # singular: the middle tap is known to be zero
got = lmmse_estimate(x, y, 3, r_h, 1e-12)
assert close(got, h, 1e-9)
assert got[1] == 0
def test_errors() -> None:
with pytest.raises(ValueError):
lmmse_estimate([1, 1], [1, 1], 2, [[1, 0], [0, 1]], 0.0)
with pytest.raises(ValueError):
lmmse_estimate([1, 1], [1, 1], 2, [[1]], 0.1)
with pytest.raises(ValueError):
lmmse_estimate([1], [1], 2, [[1, 0], [0, 1]], 0.1)
History
Andrey Kolmogorov in 1941, for discrete time, and Norbert Wiener in a classified report of 1942, published in 1949, derived the linear estimator of a stationary process with the least mean squared error. The matrix form for a finite set of observations, with the orthogonality principle, became standard in estimation theory. In wireless receivers, LMMSE channel estimation became common with OFDM in the 1990s, where the correlation of the channel across subcarriers is known from the delay spread. Biguesh and Gershman in 2006 compared the LS and LMMSE estimators for training-based MIMO systems and gave the training signals that minimize the error of each.
References
- Steven M. Kay, Fundamentals of Statistical Signal Processing, Volume I: Estimation Theory, Prentice Hall, 1993, Chapter 12 (linear Bayesian estimators and the orthogonality principle) 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 LMMSE estimator from training, its mean squared error against the LS estimator, and the training that minimizes it
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 5PBE09 Edit this page History Report an error Markdown