Algorithm Search⌘K

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.

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
Properties
deterministicneeds channel statisticsoptimal among linear estimatorsoptimal for gaussian channelsnot unbiased
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 Rh=E[hhH]R_h = E[h h^H] of the taps and the noise level N0N_0. For the model y=Xh+wy = X h + w, with the pilot matrix XX and noise w∼CN(0,N0I)w \sim \mathcal{CN}(0, N_0 I), the estimate is h^=RhXH(XRhXH+N0I)−1y=(RhXHX+N0I)−1RhXHy\hat h = R_h X^H (X R_h X^H + N_0 I)^{-1} y = (R_h X^H X + N_0 I)^{-1} R_h X^H y. 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 RhR_h 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 NpN_p known pilots x[0],…,x[Np−1]x[0], \ldots, x[N_p - 1], the samples y[0],…,y[Np−1]y[0], \ldots, y[N_p - 1], the number of taps LL, the L×LL \times L covariance RhR_h of the taps, and N0N_0. The model is one sample per symbol, 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 w[k]∼CN(0,N0)w[k] \sim \mathcal{CN}(0, N_0) independent of each other and of hh. As for LS, the algorithm uses the m=Np−L+1m = N_p - L + 1 samples v=(y[L−1],…,y[Np−1])v = (y[L-1], \ldots, y[N_p-1]), which depend on the pilots only, so v=Xh+wv = X h + w with Xil=x[i+L−1−l]X_{il} = x[i + L - 1 - l]. The taps have mean zero; for a nonzero mean see the variants. The output is an estimate h^=Wv\hat h = W v, where the L×mL \times m matrix WW minimizes the mean squared error E∥Wv−h∥2E\|W v - h\|^2, averaged over the channel and the noise. The SNR is Es/N0E_s/N_0, where EsE_s is the average energy of a pilot.

The algorithm

  1. LMMSE-CHANNEL-ESTIMATE(x, y, L, R_h, N0)
  2. 1X ← the m × L pilot matrix, X[i][l] = x[i + L - 1 - l]
  3. 2v ← (y[L - 1], .., y[N_p - 1]) ▷ the samples that see pilots only
  4. 3G ← Xᴴ X ; b ← Xᴴ v
  5. 4A ← R_h G + N0 I
  6. 5c ← R_h b
  7. 6return ĥ ← 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 (RhG+N0I)−1RhXHv(R_h G + N_0 I)^{-1} R_h X^H v. This form solves an L×LL \times L system instead of inverting the m×mm \times m matrix XRhXH+N0IX R_h X^H + N_0 I, and it does not need Rh−1R_h^{-1}, so a tap known to be zero, with a zero row in RhR_h, is allowed and is estimated as exactly zero. AA is not Hermitian, so line L6 uses Gaussian elimination. If XX, RhR_h and N0N_0 do not change, the receiver computes W=A−1RhXHW = A^{-1} R_h X^H once, and each estimate is h^=Wv\hat h = W v.

Example

Use the pilots of the LS example, x=(1,1,−1,1,1)x = (1, 1, -1, 1, 1) with L=2L = 2, so G=XTX=4IG = X^T X = 4I, and the same samples v=(1.6,−0.7,0.55,1.6)v = (1.6, -0.7, 0.55, 1.6), which give b=XTv=(4.45,1.95)b = X^T v = (4.45, 1.95) and the LS estimate (1.1125,0.4875)(1.1125, 0.4875). Let the taps be independent with Rh=diag⁡(0.8,0.2)R_h = \operatorname{diag}(0.8, 0.2), and let N0=0.5N_0 = 0.5, an SNR of 2, or 3 dB.

step value
L4: A=RhG+N0IA = R_h G + N_0 I diag⁡(3.7, 1.3)\operatorname{diag}(3.7,\ 1.3)
L5: c=Rhbc = R_h b (3.56, 0.39)(3.56,\ 0.39)
L6: h^=A−1c\hat h = A^{-1} c (0.96216, 0.3)(0.96216,\ 0.3)

Because RhR_h and GG are diagonal, each tap is the LS value times a shrink factor σl2⋅4/(σl2⋅4+N0)\sigma_l^2 \cdot 4 / (\sigma_l^2 \cdot 4 + N_0), with σl2\sigma_l^2 the variance of tap ll: 3.2/3.7=0.864863.2/3.7 = 0.86486 for the strong tap and 0.8/1.3=0.615380.8/1.3 = 0.61538 for the weak one. The error covariance N0A−1RhN_0 A^{-1} R_h is diag⁡(0.10811,0.07692)\operatorname{diag}(0.10811, 0.07692), so the mean squared error is 0.185030.18503, against N0/2=0.25N_0/2 = 0.25 for LS. The table gives both errors for other noise levels.

N0N_0 SNR in dB LS error N0/2N_0/2 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 h^=0\hat h = 0, with error tr⁡(Rh)=1\operatorname{tr}(R_h) = 1.

Correctness

Claim. Among all linear estimators WvW v, the matrix W∗=RhXH(XRhXH+N0I)−1W_\ast = R_h X^H (X R_h X^H + N_0 I)^{-1} gives the smallest mean squared error, and it is the only one that does. Lines L4 to L6 compute W∗vW_\ast v. The error covariance is Ce=N0(RhXHX+N0I)−1RhC_e = N_0 (R_h X^H X + N_0 I)^{-1} R_h, and its trace is at most the LS error N0tr⁡((XHX)−1)N_0 \operatorname{tr}((X^H X)^{-1}).

Key step. The orthogonality principle: the error W∗v−hW_\ast v - h is uncorrelated with every sample of vv. Any other W=W∗+DW = W_\ast + D then has the error J(W∗)+tr⁡(DKDH)J(W_\ast) + \operatorname{tr}(D K D^H) with K=XRhXH+N0IK = X R_h X^H + N_0 I positive definite. The identity (RhG+N0I)RhXH=RhXHK(R_h G + N_0 I) R_h X^H = R_h X^H K moves between the two forms. LS is one of the linear estimators, so LMMSE is at least as good. For Gaussian hh and ww, the error is independent of vv, which makes W∗vW_\ast v 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 XX for the m×Lm \times L pilot matrix of line L1 and vv for the samples of line L2. The model is

v=Xh+w,(1)v = X h + w, \tag{1}

where hh has mean zero and covariance R=Rh=E[hhH]R = R_h = E[h h^H], which is Hermitian and positive semidefinite, and ww has mean zero and covariance N0IN_0 I with N0>0N_0 > 0, and is uncorrelated with hh. Let G=XHXG = X^H X and

K=E[vvH]=XRXH+N0I.K = E[v v^H] = X R X^H + N_0 I.

KK is Hermitian and positive definite, because zHKz=(XHz)HR(XHz)+N0∥z∥2≥N0∥z∥2z^H K z = (X^H z)^H R (X^H z) + N_0 \|z\|^2 \ge N_0 \|z\|^2. We also need E[hvH]=E[h(Xh+w)H]=RXHE[h v^H] = E[h (X h + w)^H] = R X^H.

Lemma 1 (the error of a linear estimator). For any L×mL \times m matrix WW, the estimate WvW v has the mean squared error

J(W)=E∥Wv−h∥2=tr⁡(WKWH)−2Re⁡tr⁡(WXR)+tr⁡(R).J(W) = E\|W v - h\|^2 = \operatorname{tr}(W K W^H) - 2 \operatorname{Re} \operatorname{tr}(W X R) + \operatorname{tr}(R).

Proof. E∥Wv−h∥2=tr⁡E[(Wv−h)(Wv−h)H]=tr⁡(WKWH−WXR−RXHWH+R)E\|W v - h\|^2 = \operatorname{tr} E[(W v - h)(W v - h)^H] = \operatorname{tr}(W K W^H - W X R - R X^H W^H + R), and tr⁡(RXHWH)=tr⁡(WXR)‾\operatorname{tr}(R X^H W^H) = \overline{\operatorname{tr}(W X R)}, because RR is Hermitian. □\square

Theorem 1 (the best linear estimator). Let W∗=RXHK−1W_\ast = R X^H K^{-1}. Then

J(W)=J(W∗)+tr⁡((W−W∗)K(W−W∗)H)J(W) = J(W_\ast) + \operatorname{tr}\big((W - W_\ast) K (W - W_\ast)^H\big)

for every WW. So W∗W_\ast is the unique linear estimator with the smallest mean squared error, and the error W∗v−hW_\ast v - h is uncorrelated with vv (the orthogonality principle).

Proof. Put D=W−W∗D = W - W_\ast in Lemma 1. Since W∗K=RXHW_\ast K = R X^H, the cross terms are tr⁡(DKW∗H)=tr⁡(DXR)\operatorname{tr}(D K W_\ast^H) = \operatorname{tr}(D X R) and its conjugate, so

J(W)=J(W∗)+tr⁡(DKDH)+2Re⁡tr⁡(DXR)−2Re⁡tr⁡(DXR).J(W) = J(W_\ast) + \operatorname{tr}(D K D^H) + 2 \operatorname{Re} \operatorname{tr}(D X R) - 2 \operatorname{Re} \operatorname{tr}(D X R).

The last two terms cancel. KK is positive definite, so tr⁡(DKDH)=∑idiHKdi≥0\operatorname{tr}(D K D^H) = \sum_i d_i^H K d_i \ge 0 over the rows diHd_i^H of DD, with equality if and only if D=0D = 0. Finally, E[(W∗v−h)vH]=W∗K−RXH=0E[(W_\ast v - h) v^H] = W_\ast K - R X^H = 0. □\square

Lemma 2 (the form of lines L3 to L6). A=RG+N0IA = R G + N_0 I is invertible, and W∗=A−1RXHW_\ast = A^{-1} R X^H. So line L6 returns h^=A−1RXHv=W∗v\hat h = A^{-1} R X^H v = W_\ast v.

Proof. Let μ\mu be an eigenvalue of RGR G with eigenvector z≠0z \ne 0. Then Gz≠0G z \ne 0 when μ≠0\mu \ne 0, and (Gz)HRGz=μ zHGz(G z)^H R G z = \mu\, z^H G z, which shows μ≥0\mu \ge 0 because both quadratic forms are real and nonnegative and zHGz>0z^H G z > 0 if Gz≠0G z \ne 0. So every eigenvalue of AA is at least N0>0N_0 > 0, and AA is invertible. Next,

ARXH=RXHXRXH+N0RXH=RXH(XRXH+N0I)=RXHK.A R X^H = R X^H X R X^H + N_0 R X^H = R X^H (X R X^H + N_0 I) = R X^H K.

Multiply on the left by A−1A^{-1} and on the right by K−1K^{-1}: RXHK−1=A−1RXHR X^H K^{-1} = A^{-1} R X^H. □\square

This form needs an L×LL \times L solve instead of an m×mm \times m inverse, and it does not need R−1R^{-1}, so a singular RR is allowed. A zero row of RR gives a zero row of RXHR X^H, and so the estimate of a tap that is known to be zero is exactly zero.

Theorem 2 (the error covariance). The error e=h^−he = \hat h - h has mean zero and covariance

Ce=N0(RG+N0I)−1R,C_e = N_0 (R G + N_0 I)^{-1} R,

which equals (R−1+G/N0)−1(R^{-1} + G/N_0)^{-1} when RR is invertible. The mean squared error is tr⁡(Ce)\operatorname{tr}(C_e).

Proof. E[e]=W∗XE[h]+W∗E[w]−E[h]=0E[e] = W_\ast X E[h] + W_\ast E[w] - E[h] = 0. By the orthogonality of Theorem 1, E[evH]=0E[e v^H] = 0, so Ce=E[e(W∗v−h)H]=−E[ehH]=R−W∗XRC_e = E[e (W_\ast v - h)^H] = -E[e h^H] = R - W_\ast X R. With Lemma 2,

Ce=R−A−1RGR=A−1(AR−RGR)=A−1(RGR+N0R−RGR)=N0A−1R.C_e = R - A^{-1} R G R = A^{-1}(A R - R G R) = A^{-1} (R G R + N_0 R - R G R) = N_0 A^{-1} R.

If RR is invertible, N0A−1R=N0(R−1A)−1=N0(G+N0R−1)−1=(R−1+G/N0)−1N_0 A^{-1} R = N_0 (R^{-1} A)^{-1} = N_0 (G + N_0 R^{-1})^{-1} = (R^{-1} + G/N_0)^{-1}. □\square

Corollary 1 (LMMSE is at least as good as LS). If GG is invertible, tr⁡(Ce)≤N0tr⁡(G−1)\operatorname{tr}(C_e) \le N_0 \operatorname{tr}(G^{-1}), the error of the LS estimate.

Proof. The LS estimate G−1XHvG^{-1} X^H v is a linear estimator WLSvW_{LS} v. It is unbiased for every fixed hh, with error covariance N0G−1N_0 G^{-1}, so its mean squared error averaged over hh is also N0tr⁡(G−1)N_0 \operatorname{tr}(G^{-1}). By Theorem 1 this is at least J(W∗)=tr⁡(Ce)J(W_\ast) = \operatorname{tr}(C_e). □\square

Corollary 2 (the limits). If RR and GG are invertible, then W∗→G−1XHW_\ast \to G^{-1} X^H, the LS estimator, as N0→0N_0 \to 0. As N0→∞N_0 \to \infty, W∗→0W_\ast \to 0 and the estimate falls back to the prior mean.

Proof. W∗=(RG+N0I)−1RXHW_\ast = (R G + N_0 I)^{-1} R X^H is continuous in N0N_0 near 00 because RGR G is invertible, and at N0=0N_0 = 0 it is (RG)−1RXH=G−1XH(R G)^{-1} R X^H = G^{-1} X^H. For large N0N_0, W∗=N0−1(RG/N0+I)−1RXH→0W_\ast = N_0^{-1} (R G / N_0 + I)^{-1} R X^H \to 0. □\square

Theorem 3 (Gaussian channel and noise). If hh and ww are jointly Gaussian and independent, then h^=E[h∣v]\hat h = E[h \mid v], so the LMMSE estimate has the smallest mean squared error among all estimators, linear or not.

Proof. The pair (e,v)(e, v) is a linear function of the Gaussian vector (h,w)(h, w), so it is jointly Gaussian. By Theorem 1, ee and vv are uncorrelated, and uncorrelated jointly Gaussian vectors are independent. So E[e∣v]=E[e]=0E[e \mid v] = E[e] = 0, and E[h∣v]=E[W∗v−e∣v]=W∗vE[h \mid v] = E[W_\ast v - e \mid v] = W_\ast v. The conditional mean minimizes the mean squared error over all functions of vv. □\square

Remark (nonzero mean). If E[h]=hˉE[h] = \bar h, apply the result to h−hˉh - \bar h and v−Xhˉv - X \bar h: h^=hˉ+W∗(v−Xhˉ)\hat h = \bar h + W_\ast (v - X \bar h), with the same error covariance.

Remark (the cost). Lines L1 and L2 copy O(mL)O(m L) numbers. Line L3 costs mL2+mLm L^2 + m L multiplications, line L4 costs L3L^3, line L5 costs L2L^2 and the solve of line L6 costs O(L3)O(L^3). The total is O(mL2+L3)O(m L^2 + L^3) per pilot block. If XX, RR and N0N_0 do not change, W∗W_\ast is computed once, and each estimate costs mLm L multiplications, the same as LS.

Complexity

Line L3 costs mL2+mLm L^2 + m L complex multiplications, line L4 costs L3L^3, line L5 L2L^2, and the solve of line L6 O(L3)O(L^3). The total is O(mL2+L3)O(m L^2 + L^3) per pilot block in the real RAM, with O(L2)O(L^2) extra space. The other form, with the m×mm \times m inverse, costs O(m3)O(m^3), which is worse when there are many pilots. When XX, RhR_h and N0N_0 are fixed, WW is computed once and each estimate costs mLm L multiplications, the same as LS. In OFDM with NN subcarriers, the full LMMSE matrix is N×NN \times N, 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, h^=E[h∣v]\hat h = E[h \mid v], the best estimator of any kind.
  • Biased. For a fixed channel, E[h^∣h]=W∗Xh≠hE[\hat h \mid h] = W_\ast X h \ne h 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. tr⁡(Ce)≤N0tr⁡((XHX)−1)\operatorname{tr}(C_e) \le N_0 \operatorname{tr}((X^H X)^{-1}). The gain is large at low SNR and for channels whose covariance has a few strong eigenvalues, and it vanishes as N0→0N_0 \to 0, where the estimate tends to LS.
  • Error covariance. Ce=(Rh−1+XHX/N0)−1C_e = (R_h^{-1} + X^H X / N_0)^{-1} when RhR_h is invertible: the information from the prior adds to the information from the pilots.
  • Sensitive to the model. A wrong RhR_h or N0N_0 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 hˉ\bar h, such as Rician fading, use h^=hˉ+W∗(v−Xhˉ)\hat h = \bar h + W_\ast (v - X \bar h).
  • Diagonal approximation. With independent taps and orthogonal pilots, XHX=mEsIX^H X = m E_s I, and the estimate is the LS estimate times one shrink factor per tap, σl2mEs/(σl2mEs+N0)\sigma_l^2 m E_s / (\sigma_l^2 m E_s + N_0), 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 rr largest eigenvalues of RhR_h only. The cost per estimate falls from O(N2)O(N^2) to O(Nr)O(N r) with little loss. The N×NN \times N frequency correlation of a channel with LL taps at multiples of the sample time has rank at most LL, so r=Lr = L 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 N0N_0 and the tap power σ2\sigma^2 are known, Rh=σ2IR_h = \sigma^2 I gives (XHX+(N0/σ2)I)−1XHv(X^H X + (N_0/\sigma^2) I)^{-1} X^H v, which is ridge regression with the parameter N0/σ2N_0/\sigma^2.

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 N0N_0 is too small, the estimate is close to LS and keeps its noise. If N0N_0 is too large, the estimate shrinks the taps too much and is biased. Measure N0N_0, for example from guard subcarriers or from the residual of the LS fit.
  • A covariance from the wrong channel. RhR_h 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 RhR_h. The form (Rh−1+G/N0)−1Gh^LS/N0(R_h^{-1} + G/N_0)^{-1} G \hat h_{LS} / N_0 fails for a singular RhR_h, which is common in OFDM, where the N×NN \times N covariance of a channel with L<NL < N taps has rank LL. Lines L4 to L6 do not need the inverse.
  • The cost of the large form. RhXH(XRhXH+N0I)−1R_h X^H (X R_h X^H + N_0 I)^{-1} inverts an m×mm \times m matrix. For many pilots, use the L×LL \times L 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 CeC_e 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.

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)
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

  1. 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)
  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 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.

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