Algorithm Search⌘K

Algorithmcore

MMSE linear equalizer

Also called MMSE equalizer, linear MMSE equalizer.

The FIR filter that minimizes the mean squared error between its output and the delayed symbols. It solves (Es H H^H + N0 I) f = Es H e, trades residual ISI for less noise, and is biased.

Time
O(N^2 (N + L) + K N) worst
Space
O(N (N + L)) extra
Where
K = the number of symbols; L = the number of channel taps; N = the number of equalizer taps
Properties
biaseddeterministiclinearminimizes mse over linear filtersneeds noise level
Origin
Allen Gersho, 1969

The MMSE linear equalizer is the FIR filter that makes its output as close as possible, in mean squared error, to the transmitted symbol a few samples back. A channel hh of LL taps smears each symbol into its neighbors, and white noise of power N0N_0 is added. The zero-forcing equalizer inverts the channel and ignores the noise, so it amplifies the noise wherever the channel is weak. The MMSE equalizer minimizes the sum of the residual intersymbol interference and the noise. Its NN taps solve one Hermitian linear system, the finite-length Wiener filter: (EsHHH+N0I)f=EsHeΔ(E_s H H^H + N_0 I) f = E_s H e_\Delta, with c=fˉc = \bar f. At high SNR it tends to a ZF design, and at low SNR to a matched filter. The same formula with a channel matrix in place of a convolution is the MMSE MIMO detector, the MMSE multiuser detector for CDMA, and, at the transmitter, regularized ZF precoding. The LMMSE channel estimator solves the same kind of equation for the channel instead of the symbols.

In plain words

The channel adds echoes of each symbol to the next samples, and it adds noise. A linear equalizer is a short filter that combines a few received samples with fixed weights to recover one symbol. The zero-forcing choice of weights cancels the echoes completely, but if the channel is weak at some frequency, it boosts the noise there by a large factor. The MMSE choice asks a different question: which weights make the output closest to the symbol on average, counting echoes and noise together? The answer leaves a little echo in place and boosts the noise much less. It needs the channel and the noise level. The output is a little smaller than the symbol on average, so a QAM slicer must scale it first.

The problem

The input is the channel h=(h0,…,hL−1)h = (h_0, \ldots, h_{L-1}), known or estimated, the noise power N0N_0, the symbol energy EsE_s, the number of taps NN and the decision delay Δ\Delta, with 0≤Δ≤N+L−20 \le \Delta \le N + L - 2. The received samples are y[n]=∑lhl x[n−l]+w[n]y[n] = \sum_l h_l\, x[n-l] + w[n] at one sample per symbol, with independent symbols of mean zero and energy EsE_s, and w[n]∼CN(0,N0)w[n] \sim \mathcal{CN}(0, N_0). The equalizer output is z[n]=∑i=0N−1ci y[n−i]z[n] = \sum_{i=0}^{N-1} c_i\, y[n-i]. The output is the tap vector cc that minimizes J=E∣z[n]−x[n−Δ]∣2J = E|z[n] - x[n - \Delta]|^2, and the minimum JJ.

Stack the last NN samples in u=(y[n],…,y[n−N+1])Tu = (y[n], \ldots, y[n-N+1])^T. Then u=Hs+vu = H s + v, where s=(x[n],…,x[n−N−L+2])Ts = (x[n], \ldots, x[n-N-L+2])^T and HH is the N×(N+L−1)N \times (N + L - 1) convolution matrix with Hij=hj−iH_{ij} = h_{j-i}. With f=cˉf = \bar c, the output is z[n]=fHuz[n] = f^H u, a linear estimate of the entry Δ\Delta of ss.

The algorithm

  1. MMSE-EQUALIZER(h, N, Δ, N0, Es)
  2. 1H[i][j] ← h[j - i] for 0 ≤ i < N, 0 ≤ j < N + L - 1 ▷ h[t] = 0 outside 0 .. L - 1
  3. 2R ← Es H Hᴴ + N0 I ▷ the covariance of u
  4. 3r ← Es H e_Δ ▷ column Δ of H, times Es
  5. 4f ← R⁻¹ r ▷ Gaussian elimination or Cholesky
  6. 5c ← conj(f) ▷ the taps, z[n] = Σ c[i] y[n - i]
  7. 6J ← Es - rᴴ f ▷ the minimum mean squared error
  8. 7return c, J

Line L1 builds the convolution matrix. Line L2 is the covariance of the received vector: EsHHHE_s H H^H from the symbols and N0IN_0 I from the noise. Line L3 is the cross-correlation between the received vector and the wanted symbol x[n−Δ]x[n - \Delta]. Line L4 solves the Wiener-Hopf equations Rf=rR f = r. RR is Hermitian positive definite, so a Cholesky factorization works. Line L6 gives the error without a simulation. The delay is a design choice: the implementation also tries every Δ\Delta and keeps the one with the smallest JJ.

Example

Take h=(1,0.5)h = (1, 0.5), Es=1E_s = 1, N0=0.1N_0 = 0.1 (an SNR of 10 dB), and N=5N = 5 taps. The minimum error JJ for each delay is:

Δ\Delta 0 1 2 3 4 5
JJ 0.11404 0.11197 0.11547 0.13606 0.24147 0.77851

The best delay is Δ=1\Delta = 1. Its taps and the combined response g=c∗hg = c * h are:

index 0 1 2 3 4 5
taps cc 0.05090 0.86258 -0.37987 0.16306 -0.06039
combined gg 0.05090 0.88803 0.05142 -0.02687 0.02114 -0.03020

The interference is not zero, and the cursor g1=0.88803g_1 = 0.88803 is less than 1. This is the bias: gΔ=1−J/Esg_\Delta = 1 - J/E_s. The noise gain is ∥c∥2=0.921\|c\|^2 = 0.921, against 1.332 for the ZF equalizer. The error splits into Es∥g−eΔ∥2+N0∥c∥2=0.01985+0.09212=0.11197E_s \|g - e_\Delta\|^2 + N_0 \|c\|^2 = 0.01985 + 0.09212 = 0.11197. The 5-tap ZF equalizer with delay 0 has the error 0.031252+0.1×1.33203=0.134180.03125^2 + 0.1 \times 1.33203 = 0.13418. After the scaling by 1/gΔ1/g_\Delta, the SINR is Es/J−1=7.93E_s/J - 1 = 7.93, or 8.99 dB. A long equalizer reaches J∞=N0/(1.25+N0)2−1=0.11026J_\infty = N_0 / \sqrt{(1.25 + N_0)^2 - 1} = 0.11026; 15 taps already give 0.110264.

On the channel B of Proakis, h=(0.407,0.815,0.407)h = (0.407, 0.815, 0.407), with N=31N = 31 and N0=0.01N_0 = 0.01 (20 dB), the best delay is 16 and J=0.1795J = 0.1795, an unbiased SINR of 6.60 dB. The best ZF equalizer of the same length has the error 26.7, because of its noise gain of 2641.

Correctness

Claim. The taps of line L5 are the unique minimizer of JJ over all NN-tap filters, and line L6 is the minimum. The minimum is also J=N0Es[(EsHHH+N0I)−1]ΔΔJ = N_0 E_s [(E_s H^H H + N_0 I)^{-1}]_{\Delta\Delta}, and the output satisfies E[z[n]∣x[n−Δ]]=(1−J/Es) x[n−Δ]E[z[n] \mid x[n-\Delta]] = (1 - J/E_s)\, x[n-\Delta].

Key step. For any taps, J(f)=fHRf−2 Re(fHr)+EsJ(f) = f^H R f - 2\,\mathrm{Re}(f^H r) + E_s. Completing the square gives J(f)=Es−rHR−1r+(f−R−1r)HR(f−R−1r)J(f) = E_s - r^H R^{-1} r + (f - R^{-1} r)^H R (f - R^{-1} r), and RR is positive definite because HH has full row rank. The closed form follows from the push-through identity HH(EsHHH+N0I)−1=(EsHHH+N0I)−1HHH^H (E_s H H^H + N_0 I)^{-1} = (E_s H^H H + N_0 I)^{-1} H^H. The full proof, with the bias, the unbiased SINR and the limits in N0N_0, is in the proofs folder.

Proof: The MMSE linear equalizer solves the Wiener-Hopf equations, its error is N0 Es times a diagonal entry of an inverse, and its output is biased by 1 - J/Esfull

The channel taps are h0,…,hL−1h_0, \ldots, h_{L-1}, not all zero. The received samples are y[n]=∑lhl x[n−l]+w[n]y[n] = \sum_l h_l\, x[n-l] + w[n], where the symbols x[n]x[n] are independent with mean zero and E∣x[n]∣2=EsE|x[n]|^2 = E_s, and the noise samples w[n]∼CN(0,N0)w[n] \sim \mathcal{CN}(0, N_0) are independent of each other and of the symbols. The equalizer has the taps c0,…,cN−1c_0, \ldots, c_{N-1}, its output is z[n]=∑i=0N−1ci y[n−i]z[n] = \sum_{i=0}^{N-1} c_i\, y[n-i], and z[n]z[n] estimates x[n−Δ]x[n - \Delta] for a delay 0≤Δ≤N+L−20 \le \Delta \le N + L - 2.

Let u=(y[n],y[n−1],…,y[n−N+1])Tu = (y[n], y[n-1], \ldots, y[n-N+1])^T and s=(x[n],x[n−1],…,x[n−N−L+2])Ts = (x[n], x[n-1], \ldots, x[n-N-L+2])^T. Since y[n−i]=∑jhj−i x[n−j]+w[n−i]y[n-i] = \sum_j h_{j-i}\, x[n-j] + w[n-i], we have u=Hs+vu = H s + v with Hij=hj−iH_{ij} = h_{j-i} (line L1), an N×(N+L−1)N \times (N+L-1) matrix, and vv the noise vector. Then E[ssH]=EsIE[s s^H] = E_s I, E[vvH]=N0IE[v v^H] = N_0 I and E[svH]=0E[s v^H] = 0. Write f=cˉf = \bar c, so that z[n]=fHuz[n] = f^H u, and g=HTcg = H^T c, which is the combined response g=c∗hg = c * h because gj=∑icihj−ig_j = \sum_i c_i h_{j-i}.

Lemma 1 (the error of any taps). For every cc,

J(c)=E∣z[n]−x[n−Δ]∣2=Es∥g−eΔ∥2+N0∥c∥2.J(c) = E|z[n] - x[n-\Delta]|^2 = E_s \|g - e_\Delta\|^2 + N_0 \|c\|^2 .

Proof. z[n]−x[n−Δ]=∑j(gj−[j=Δ]) x[n−j]+∑ici w[n−i]z[n] - x[n - \Delta] = \sum_j (g_j - [j = \Delta])\, x[n-j] + \sum_i c_i\, w[n-i]. All terms are independent with mean zero, so the variances add: EsE_s times ∣gj−[j=Δ]∣2|g_j - [j = \Delta]|^2 for each symbol and N0∣ci∣2N_0 |c_i|^2 for each noise sample. □\square

Lemma 2 (R is positive definite). R=E[uuH]=EsHHH+N0IR = E[u u^H] = E_s H H^H + N_0 I is Hermitian and positive definite when N0>0N_0 > 0, and also when N0=0N_0 = 0.

Proof. The formula follows from u=Hs+vu = Hs + v and the moments above. For a vector a≠0a \ne 0, aHRa=Es∥HHa∥2+N0∥a∥2a^H R a = E_s \|H^H a\|^2 + N_0 \|a\|^2. If N0>0N_0 > 0, this is positive. If N0=0N_0 = 0, we need HHa≠0H^H a \ne 0, that is, HH has full row rank. Let pp be the first index with hp≠0h_p \ne 0. Row ii of HH is zero in the columns j<i+pj < i + p and has hp≠0h_p \ne 0 in column i+pi + p. These leading entries are in different columns and move to the right from row to row, so the rows are linearly independent. □\square

Theorem 1 (the Wiener solution). Let r=E[u x[n−Δ]‾]=EsHeΔr = E[u\, \overline{x[n-\Delta]}] = E_s H e_\Delta (lines L2 and L3). The taps c=fˉc = \bar f with Rf=rR f = r (lines L4 and L5) are the unique minimizer of JJ, and the minimum is J=Es−rHfJ = E_s - r^H f (line L6).

Proof. Expand J=E∣fHu−x[n−Δ]∣2=fHRf−fHr−rHf+EsJ = E|f^H u - x[n-\Delta]|^2 = f^H R f - f^H r - r^H f + E_s. Let f0=R−1rf_0 = R^{-1} r, which exists by Lemma 2. Completing the square gives

J(f)=Es−rHf0+(f−f0)HR(f−f0).J(f) = E_s - r^H f_0 + (f - f_0)^H R (f - f_0).

The last term is positive for f≠f0f \ne f_0, because RR is positive definite. So f0f_0 is the unique minimizer and J(f0)=Es−rHf0J(f_0) = E_s - r^H f_0, which is real because rHR−1rr^H R^{-1} r is a Hermitian form. □\square

The minimizer satisfies the orthogonality principle: the error e=fHu−x[n−Δ]e = f^H u - x[n - \Delta] has E[u eˉ]=Rf−r=0E[u\, \bar e] = R f - r = 0, so the error is uncorrelated with every input sample of the filter.

Theorem 2 (the closed form of J). If N0>0N_0 > 0, then

J=N0Es[(EsHHH+N0I)−1]ΔΔ.J = N_0 E_s \left[ (E_s H^H H + N_0 I)^{-1} \right]_{\Delta\Delta}.

Proof. The push-through identity HH(EsHHH+N0I)=(EsHHH+N0I)HHH^H (E_s H H^H + N_0 I) = (E_s H^H H + N_0 I) H^H gives HHR−1=M−1HHH^H R^{-1} = M^{-1} H^H with M=EsHHH+N0IM = E_s H^H H + N_0 I, which is positive definite. Then

J=Es−Es2 eΔTHHR−1HeΔ=Es eΔTM−1(M−EsHHH) eΔ=N0Es eΔTM−1eΔ.□J = E_s - E_s^2\, e_\Delta^T H^H R^{-1} H e_\Delta = E_s\, e_\Delta^T M^{-1} (M - E_s H^H H)\, e_\Delta = N_0 E_s\, e_\Delta^T M^{-1} e_\Delta. \qquad \square

Theorem 3 (the bias and the unbiased SINR). With the MMSE taps, E[z[n]∣x[n−Δ]]=(1−J/Es) x[n−Δ]E[z[n] \mid x[n-\Delta]] = (1 - J/E_s)\, x[n-\Delta]. The rest of the output, z[n]−gΔx[n−Δ]z[n] - g_\Delta x[n-\Delta], is uncorrelated with x[n−Δ]x[n-\Delta] and has variance J(1−J/Es)J (1 - J/E_s). So, if J<EsJ < E_s, the scaled output z[n]/(1−J/Es)z[n] / (1 - J/E_s) is unbiased, and its signal to interference plus noise ratio is Es/J−1E_s / J - 1.

Proof. z[n]=gΔx[n−Δ]+qz[n] = g_\Delta x[n-\Delta] + q, where q=∑j≠Δgjx[n−j]+∑iciw[n−i]q = \sum_{j \ne \Delta} g_j x[n-j] + \sum_i c_i w[n-i] is independent of x[n−Δ]x[n-\Delta] and has mean zero. So E[z∣x[n−Δ]]=gΔx[n−Δ]E[z \mid x[n-\Delta]] = g_\Delta x[n-\Delta]. Now gΔ=eΔTHTc=fHHeΔ=fHr/Esg_\Delta = e_\Delta^T H^T c = f^H H e_\Delta = f^H r / E_s. Since fHr=rHf‾f^H r = \overline{r^H f} and rHf=Es−Jr^H f = E_s - J is real, gΔ=1−J/Esg_\Delta = 1 - J/E_s, a real number in [0,1][0, 1]. By Lemma 1 split into the Δ\Delta term and the rest, J=Es∣1−gΔ∣2+E∣q∣2=J2/Es+E∣q∣2J = E_s |1 - g_\Delta|^2 + E|q|^2 = J^2/E_s + E|q|^2, so E∣q∣2=J(1−J/Es)E|q|^2 = J(1 - J/E_s). The ratio of signal power to the power of qq is gΔ2Es/E∣q∣2=(Es−J)/Jg_\Delta^2 E_s / E|q|^2 = (E_s - J)/J. □\square

So the MMSE equalizer shrinks the wanted symbol by the factor 1−J/Es1 - J/E_s. For PSK and for BPSK decisions by sign this does not matter, but for QAM with several amplitude levels the slicer must divide by this factor first.

Corollary 1 (the limits in N0). As N0→0N_0 \to 0, the taps tend to c=(HHH)−1HeΔ‾c = \overline{(H H^H)^{-1} H e_\Delta}, the least-squares fit that minimizes ∥HTc−eΔ∥2=∥g−eΔ∥2\|H^T c - e_\Delta\|^2 = \|g - e_\Delta\|^2. As N0→∞N_0 \to \infty, N0f→EsHeΔN_0 f \to E_s H e_\Delta, the time-reversed and conjugated channel, a matched filter for the symbol at the delay.

Proof. f=(EsHHH+N0I)−1EsHeΔf = (E_s H H^H + N_0 I)^{-1} E_s H e_\Delta is continuous in N0≥0N_0 \ge 0 by Lemma 2, and at N0=0N_0 = 0 it is (HHH)−1HeΔ(H H^H)^{-1} H e_\Delta. The normal equations of min⁡c∥HTc−eΔ∥2\min_c \|H^T c - e_\Delta\|^2 are HˉHTc=HˉeΔ\bar H H^T c = \bar H e_\Delta, whose conjugate is HHHcˉ=HeΔH H^H \bar c = H e_\Delta, the same system. For the second limit, N0f=(I+(Es/N0)HHH)−1EsHeΔ→EsHeΔN_0 f = (I + (E_s/N_0) H H^H)^{-1} E_s H e_\Delta \to E_s H e_\Delta. □\square

Corollary 2 (MMSE against ZF). The ZF equalizer with the same NN and Δ\Delta has the error J(cZF)=Es∥gZF−eΔ∥2+N0∥cZF∥2≥JJ(c_{ZF}) = E_s \|g_{ZF} - e_\Delta\|^2 + N_0 \|c_{ZF}\|^2 \ge J, by Lemma 1 and Theorem 1. On a channel with a near spectral null, ∥cZF∥2\|c_{ZF}\|^2 is large, and the gap is large.

Remark (the infinite-length error, cited). As N→∞N \to \infty with a suitable delay, JJ decreases to

J∞=12π∫−ππEsN0Es∣H(ejω)∣2+N0 dω,J_\infty = \frac{1}{2\pi} \int_{-\pi}^{\pi} \frac{E_s N_0}{E_s |H(e^{j\omega})|^2 + N_0}\, d\omega ,

the error of the unconstrained Wiener filter C(ejω)=EsH(ejω)‾/(Es∣H(ejω)∣2+N0)C(e^{j\omega}) = E_s \overline{H(e^{j\omega})} / (E_s |H(e^{j\omega})|^2 + N_0); see Proakis and Salehi, Section 9.4-2. For h=(1,a)h = (1, a) and Es=1E_s = 1, ∣H∣2=1+a2+2acos⁡ω|H|^2 = 1 + a^2 + 2a \cos\omega, and the integral 12π∫dω/(A+Bcos⁡ω)=(A2−B2)−1/2\frac{1}{2\pi}\int d\omega / (A + B\cos\omega) = (A^2 - B^2)^{-1/2} gives J∞=N0/(1+a2+N0)2−4a2J_\infty = N_0 / \sqrt{(1 + a^2 + N_0)^2 - 4a^2}. The tests check the finite JJ against this value.

Remark (the cost). Line L2 forms RR from HH in O(N2(N+L))O(N^2 (N + L)) operations, line L4 solves the system in O(N3)O(N^3), and line L6 costs O(N)O(N), once per channel and delay. Trying all N+L−1N + L - 1 delays costs N+L−1N + L - 1 solves, or one inverse of MM by Theorem 2, whose diagonal gives every JJ at once.

Complexity

Line L2 costs O(N2(N+L))O(N^2 (N + L)) operations, line L4 costs O(N3)O(N^3), and lines L3, L5 and L6 cost O(N)O(N), once per channel and delay. RR is a Hermitian Toeplitz matrix, so a Levinson recursion, as in the Levinson-Durbin recursion, solves it in O(N2)O(N^2). Filtering costs NN complex multiplications per symbol, so KK symbols cost O(N2(N+L)+KN)O(N^2 (N + L) + K N) in the real RAM, with O(N(N+L))O(N (N + L)) extra space for HH and RR. To try every delay, one inverse of EsHHH+N0IE_s H^H H + N_0 I gives all N+L−1N + L - 1 values of JJ on its diagonal.

Properties

  • Optimal among linear filters. No other NN-tap linear equalizer has a smaller mean squared error. It does not minimize the symbol error rate in general.
  • Orthogonality. The error z[n]−x[n−Δ]z[n] - x[n-\Delta] is uncorrelated with every sample y[n−i]y[n-i] in the filter.
  • Biased. The output is (1−J/Es) x[n−Δ](1 - J/E_s)\, x[n-\Delta] plus an uncorrelated term of variance J(1−J/Es)J(1 - J/E_s). The unbiased SINR is Es/J−1E_s/J - 1, which is 1 less than the biased ratio Es/JE_s/J.
  • Between ZF and the matched filter. As N0→0N_0 \to 0, the taps tend to the least squares ZF design, which minimizes ∥c∗h−eΔ∥2\|c * h - e_\Delta\|^2. As N0→∞N_0 \to \infty, they tend to EsHeΔ‾/N0E_s \overline{H e_\Delta}/N_0, a matched filter.
  • Infinite length. As NN grows, JJ tends to 12π∫−ππEsN0/(Es∣H(ejω)∣2+N0) dω\frac{1}{2\pi}\int_{-\pi}^{\pi} E_s N_0 / (E_s |H(e^{j\omega})|^2 + N_0)\, d\omega. This stays finite even if HH has a spectral null, unlike the noise gain of the ZF equalizer.
  • Needs the noise level. A wrong N0N_0 gives a filter between the MMSE and the ZF designs (too small) or too close to the matched filter (too large).

Variants and improvements

When to use it

Use the MMSE linear equalizer when the channel and the noise level are known or estimated, and a linear filter is cheap enough. It is better than ZF at every SNR, and much better on channels with deep spectral nulls. For a channel with a null in its band, a DFE or a Viterbi equalizer does better again. For long channels in a block system, the frequency-domain form is cheaper.

Pitfalls

  • Forgetting the bias. For QAM with 16 or more points, slice z[n]/(1−J/Es)z[n] / (1 - J/E_s), not z[n]z[n]. Otherwise the outer points fall short of their decision regions. For PSK and BPSK the bias does not change the decisions.
  • The conjugate. The Wiener solution is for z=fHuz = f^H u. A filter written as z[n]=∑ciy[n−i]z[n] = \sum c_i y[n-i] uses c=fˉc = \bar f. For a real channel the two agree, so a bug can hide until the first complex channel.
  • The wrong delay. The error depends on Δ\Delta by a large factor: for h=(1,0.5)h = (1, 0.5) and N=5N = 5, from 0.112 to 0.779. A delay near the middle of N+L−1N + L - 1 is a safe start, and a search over all delays is cheap.
  • Treating JJ as the noise variance. The residual is not Gaussian, because part of it is ISI from a finite alphabet. The Gaussian formula with the unbiased SINR is an approximation; the tests compare the BER with an exact sum over the ISI patterns.
  • An estimated channel. The design uses h^\hat h and N^0\hat N_0. Channel errors act like extra noise, so a slightly larger N0N_0 makes the equalizer more robust.

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)
mmse_linear_equalizer.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mmse-linear-equalizer/. The authors are listed in prov/4T3X0R.jsonl.

"""The finite-length MMSE linear equalizer.

The channel is y[k] = sum_{l=0}^{L-1} h[l] x[k-l] + w[k] at one sample per
symbol. The symbols are independent with mean zero and E|x|^2 = Es, and the
noise is CN(0, N0), independent of the symbols. The equalizer is an FIR filter
c of N taps with output z[k] = sum_i c[i] y[k-i], and z[k] estimates
x[k - D] for a decision delay D. The regressor u = (y[k], ..., y[k-N+1]) is
u = H s + w with H[i][j] = h[j-i] (an N by N + L - 1 matrix) and
s = (x[k], ..., x[k-N-L+2]). With f = conj(c), so that z = f^H u, the
Wiener-Hopf equations are R f = r with R = Es H H^H + N0 I and r = Es H e_D.
The minimum mean squared error is J = Es - r^H f.
"""

import cbb


def channel_matrix(h: list[complex], n: int) -> list[list[complex]]:
    """The N by N + L - 1 matrix H with H[i][j] = h[j - i], so that u = H s + w."""
    taps = len(h)
    if taps < 1 or n < 1:
        raise ValueError("need L >= 1 and N >= 1")
    return [[complex(h[j - i]) if 0 <= j - i < taps else 0j for j in range(n + taps - 1)] for i in range(n)]


def mmse_equalizer(h: list[complex], n: int, delay: int, n0: float, es: float = 1.0) -> tuple[list[complex], float]:
    """The N taps c that minimize E|z[k] - x[k - delay]|^2, and that minimum J."""
    if n0 < 0 or es <= 0:
        raise ValueError("need N0 >= 0 and Es > 0")
    if not 0 <= delay <= n + len(h) - 2:
        raise ValueError("need 0 <= delay <= N + L - 2")
    hm = channel_matrix(h, n)  # @line L1
    m = len(hm[0])
    big_r = [[es * sum(hm[i][t] * hm[k][t].conjugate() for t in range(m)) + (n0 if i == k else 0) for k in range(n)] for i in range(n)]  # @line L2
    r = [es * hm[i][delay] for i in range(n)]  # @line L3
    try:
        f = cbb.solve(big_r, r)  # @line L4
    except ValueError:
        raise ValueError("R is singular: N0 = 0 and H does not have full row rank") from None
    c = [v.conjugate() for v in f]  # @line L5
    j = es - cbb.dot(r, f).real  # @line L6
    return c, j  # @line L7


def best_delay(h: list[complex], n: int, n0: float, es: float = 1.0) -> tuple[int, list[complex], float]:
    """The decision delay with the smallest MMSE, found by trying all N + L - 1 delays."""
    best = None
    for d in range(n + len(h) - 1):
        c, j = mmse_equalizer(h, n, d, n0, es)
        if best is None or j < best[2]:
            best = (d, c, j)
    return best


def mse(c: list[complex], h: list[complex], delay: int, n0: float, es: float = 1.0) -> float:
    """E|z[k] - x[k - delay]|^2 for any taps c: Es ||c * h - e_delay||^2 + N0 ||c||^2."""
    g = cbb.conv(c, h)
    return es * sum(abs(v - (1 if k == delay else 0)) ** 2 for k, v in enumerate(g)) + n0 * cbb.norm2(c)


def bias(j: float, es: float = 1.0) -> float:
    """The gain of the MMSE output on the wanted symbol: E[z | x[k - delay]] = (1 - J / Es) x[k - delay]."""
    return 1.0 - j / es


def unbiased_sinr(j: float, es: float = 1.0) -> float:
    """The signal to interference plus noise ratio after the bias is removed: Es / J - 1."""
    return es / j - 1.0


def equalize(c: list[complex], y: list[complex], delay: int, count: int) -> list[complex]:
    """The equalizer output z = c * y, read at the delay: the estimates of x[0], ..., x[count - 1]."""
    z = cbb.conv(c, y)
    if len(z) < delay + count:
        z = z + [0j] * (delay + count - len(z))
    return z[delay : delay + count]
test_mmse_linear_equalizer.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mmse-linear-equalizer/. The authors are listed in prov/4T3X0R.jsonl.

import itertools
import math
import random

import pytest

import cbb
from mmse_linear_equalizer import (
    best_delay,
    bias,
    channel_matrix,
    equalize,
    mmse_equalizer,
    mse,
    unbiased_sinr,
)

PROAKIS_B = [0.407, 0.815, 0.407]


def qpsk(rng):
    return complex(rng.choice((-1, 1)), rng.choice((-1, 1))) / math.sqrt(2)


def zf_taps(h, n):
    # the delay 0 ZF taps: the first N terms of the power series of 1 / H(z)
    c = []
    for k in range(n):
        acc = (1 if k == 0 else 0) - sum(h[l] * c[k - l] for l in range(1, min(k, len(h) - 1) + 1))
        c.append(acc / h[0])
    return c


def test_example_on_the_page() -> None:
    want = [0.114043, 0.11197, 0.11547, 0.136058, 0.24147, 0.778511]
    for d, w in enumerate(want):
        assert abs(mmse_equalizer([1, 0.5], 5, d, 0.1)[1] - w) < 1e-6
    d, c, j = best_delay([1, 0.5], 5, 0.1)
    assert d == 1 and abs(j - 0.1119702) < 1e-7
    assert abs(bias(j) - 0.8880298) < 1e-7 and abs(cbb.db(unbiased_sinr(j)) - 8.993) < 1e-3
    assert abs(mse(zf_taps([1, 0.5], 5), [1, 0.5], 0, 0.1) - 0.1341796875) < 1e-12


def test_j_matches_the_closed_forms_on_random_channels() -> None:
    rng = random.Random(7101)
    for _ in range(60):
        taps, n = rng.randint(1, 4), rng.randint(1, 7)
        h = [cbb.cn(rng, 1.0) for _ in range(taps)]
        n0, es = rng.uniform(0.01, 1.0), rng.uniform(0.5, 2.0)
        d = rng.randint(0, n + taps - 2)
        c, j = mmse_equalizer(h, n, d, n0, es)
        assert abs(mse(c, h, d, n0, es) - j) < 1e-9
        # J = N0 Es [(Es H^H H + N0 I)^(-1)] at (d, d)
        hm = channel_matrix(h, n)
        m = len(hm[0])
        a = [[es * sum(hm[t][i].conjugate() * hm[t][k] for t in range(n)) + (n0 if i == k else 0) for k in range(m)] for i in range(m)]
        e = [1 if i == d else 0 for i in range(m)]
        assert abs(n0 * es * cbb.solve(a, e)[d].real - j) < 1e-9


def test_taps_are_the_minimum_against_perturbations() -> None:
    rng = random.Random(7102)
    for _ in range(40):
        taps, n = rng.randint(2, 4), rng.randint(2, 6)
        h = [cbb.cn(rng, 1.0) for _ in range(taps)]
        n0, d = rng.uniform(0.01, 0.5), rng.randint(0, n + taps - 2)
        c, j = mmse_equalizer(h, n, d, n0)
        for scale in (1.0, 1e-2, 1e-4):
            for _ in range(10):
                other = [v + scale * cbb.cn(rng, 1.0) for v in c]
                assert mse(other, h, d, n0) >= j - 1e-12


def test_monte_carlo_mse_and_bias() -> None:
    rng = random.Random(7103)
    h, n, n0, count = [1, 0.5], 5, 0.1, 20000
    d, c, j = best_delay(h, n, n0)
    x = [qpsk(rng) for _ in range(count)]
    y = cbb.awgn(rng, cbb.conv(x, h), n0)
    z = equalize(c, y, d, count)
    inner = range(n, count - n)  # skip the edges of the block
    got = sum(abs(z[k] - x[k]) ** 2 for k in inner) / len(inner)
    assert abs(got - j) < 0.05 * j  # 20000 symbols, seed 7103
    gain = sum(z[k] * x[k].conjugate() for k in inner) / len(inner)
    assert abs(gain - bias(j)) < 0.02


def test_limits_in_n0() -> None:
    h, n, d = [1, 0.5], 5, 0
    # N0 -> 0: the MMSE taps tend to the least-squares fit of c * h to the unit pulse
    c_small = mmse_equalizer(h, n, d, 1e-9)[0]
    hm = channel_matrix(h, n)  # g = H^T c, so minimize ||H^T c - e||^2
    m = len(hm[0])
    gram = [[sum(hm[i][t] * hm[k][t].conjugate() for t in range(m)) for k in range(n)] for i in range(n)]
    ls = [v.conjugate() for v in cbb.solve(gram, [hm[i][d] for i in range(n)])]
    assert max(abs(p - q) for p, q in zip(c_small, ls)) < 1e-6
    # N0 large: the taps tend to the matched filter conj(H e_d) / N0
    n0 = 1e6
    c_big = mmse_equalizer(h, n, 1, n0)[0]
    assert max(abs(c_big[i] * n0 - hm[i][1].conjugate()) for i in range(n)) < 1e-4
    # with no ISI the MMSE equalizer is a scalar Es / (Es + N0)
    c1, j1 = mmse_equalizer([1], 1, 0, 0.25)
    assert abs(c1[0] - 0.8) < 1e-12 and abs(j1 - 0.2) < 1e-12


def test_long_equalizer_reaches_the_infinite_length_mse() -> None:
    # for h = (1, a), |H|^2 = 1 + a^2 + 2 a cos w, and J_inf = N0 / sqrt((1 + a^2 + N0)^2 - 4 a^2)
    for a, n0 in ((0.5, 0.1), (0.9, 0.05)):
        j_inf = n0 / math.sqrt((1 + a * a + n0) ** 2 - 4 * a * a)
        j5, j15 = best_delay([1, a], 5, n0)[2], best_delay([1, a], 15, n0)[2]
        j30 = mmse_equalizer([1, a], 30, 15, n0)[1]  # one delay in the middle is enough here
        assert j5 >= j15 >= j_inf - 1e-12 and j30 >= j_inf - 1e-12
        assert j30 - j_inf < 1e-3  # 1.7e-11 for a = 0.5 and 1.0e-4 for a = 0.9, whose zero is near the circle


def zf_window(h, n, d):
    # the ZF taps for delay d: force c * h = e_d on a window of N indices around d
    s = min(max(d - (n - 1) // 2, 0), len(h) - 1)
    a = [[complex(h[s + k - i]) if 0 <= s + k - i < len(h) else 0j for i in range(n)] for k in range(n)]
    return cbb.solve(a, [1 if s + k == d else 0 for k in range(n)])


def test_proakis_b_mmse_beats_zf_by_far() -> None:
    n0 = 0.01
    d, c, j = best_delay(PROAKIS_B, 31, n0)
    assert abs(j - 0.179469) < 1e-5
    zf = min(mse(zf_window(PROAKIS_B, 31, dd), PROAKIS_B, dd, n0) for dd in range(32))
    assert zf > 100 * j  # the best ZF equalizer has an MSE of about 26.7


def test_bpsk_error_rate_matches_exact_enumeration() -> None:
    rng = random.Random(7104)
    h, n, n0, count = PROAKIS_B, 11, 0.1, 5000
    d, c, j = best_delay(h, n, n0)
    g = [v.real for v in cbb.conv(c, h)]
    sigma = math.sqrt(n0 * cbb.norm2(c) / 2)  # real part of the filtered CN(0, N0) noise
    others = [g[k] for k in range(len(g)) if k != d]
    p = sum(cbb.qfunc((g[d] + sum(s * v for s, v in zip(signs, others))) / sigma) for signs in itertools.product((-1, 1), repeat=len(others)))
    p /= 2 ** len(others)  # about 0.059, so about 290 errors expected
    x = [rng.choice((-1.0, 1.0)) for _ in range(count)]
    y = cbb.awgn(rng, cbb.conv(x, h), n0)
    z = equalize(c, y, d, count)
    inner = range(n, count - n)
    errors = sum((z[k].real >= 0) != (x[k] > 0) for k in inner)
    lo, hi = cbb.wilson(errors, len(inner))  # z = 3.29
    assert lo <= p <= hi


def test_errors() -> None:
    with pytest.raises(ValueError):
        mmse_equalizer([1, 0.5], 3, 4, 0.1)  # the delay must be at most N + L - 2
    with pytest.raises(ValueError):
        mmse_equalizer([1, 0.5], 3, 0, -1.0)
    with pytest.raises(ValueError):
        mmse_equalizer([0, 0], 3, 0, 0.0)  # R = 0
    with pytest.raises(ValueError):
        channel_matrix([], 3)

History

Lucky's zero-forcing equalizers of 1965 minimized the peak distortion. In 1969, Gersho studied the mean-square error criterion for adaptive equalizers of highly dispersive channels; with it the optimal taps are the finite-length Wiener filter, and the LMS algorithm of Widrow and Hoff can find them. The mean-square error criterion takes the noise into account, and it replaced peak distortion in most later designs. Later work on the MMSE-DFE studied the bias and linked the unbiased SNR to capacity; see the MMSE-DFE canonical theorem.

References

  1. John G. Proakis and Masoud Salehi, Digital Communications, fifth edition, McGraw-Hill, 2008, Section 9.4-2 (the mean-square error criterion) and Section 9.4-3 (the performance of the MSE equalizer)
  2. John R. Barry, Edward A. Lee and David G. Messerschmitt, Digital Communication, third edition, Kluwer Academic Publishers, 2004, Chapter 8 (equalization)
  3. A. Gersho, Adaptive equalization of highly dispersive channels for data transmission, Bell System Technical Journal 48(1), 1969, pages 55 to 70, the mean-square error criterion for the equalizer taps
  4. Steven M. Kay, Fundamentals of Statistical Signal Processing, Volume I: Estimation Theory, Prentice Hall, 1993, Chapter 12 (linear Bayesian estimators and the Wiener filter)

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
  • a scene preset for the example