Algorithm Search⌘K

Algorithmintro

Zero-forcing equalizer

Also called ZF equalizer.

A linear FIR filter that inverts the channel, so that the combined response is a unit pulse and the intersymbol interference is zero. The price is noise enhancement, large near spectral nulls.

Time
O(N^3 + K N) worst
Space
O(N^2) extra
Where
K = the number of symbols; N = the number of equalizer taps
Properties
deterministicenhances noiselinearnot needs noise levelremoves isi in its window
Origin
Robert W. Lucky, 1965

The zero-forcing (ZF) equalizer is a linear filter that undoes the intersymbol interference of a channel by inverting it. A channel with taps hh smears each symbol over LL samples. The ZF equalizer is an FIR filter cc of NN taps, chosen so that the combined response g=c∗hg = c * h is 1 at the decision delay Δ\Delta and 0 at the N−1N - 1 indices around it. With an infinite filter it is C(z)=1/H(z)C(z) = 1/H(z) and removes all interference, so the equalized channel meets the Nyquist ISI criterion. The price is noise enhancement: white noise of power N0N_0 leaves the filter with power N0∥c∥2N_0 \|c\|^2, which is very large when the channel has a deep spectral null. The MMSE linear equalizer adds N0N_0 to the same design and trades a little interference for much less noise, and the decision feedback equalizer cancels the past interference with decisions instead of inverting it. The same inverse appears in three other places: the ZF MIMO detector inverts a channel matrix across antennas, ZF precoding inverts it at the transmitter, and the decorrelating detector inverts the correlation of CDMA users. Frequency-domain equalization computes a ZF or MMSE equalizer per DFT bin.

In plain words

The channel adds an echo of each symbol to the next few samples, so the symbols overlap. The ZF equalizer is a second filter that cancels these echoes. Its taps are chosen so that, after the channel and the equalizer, each symbol arrives alone, with no part of its neighbors. A finite filter can do this exactly only at a few positions, so it forces the echoes to zero at the positions closest to the symbol, and a small residue remains further away. The equalizer does not look at the noise. Where the channel is weak at some frequency, the equalizer must amplify that frequency to restore the signal, and it amplifies the noise there too. On a good channel this costs little. On a channel with a deep fade in its spectrum, the noise can become much larger than the signal.

The problem

The input is the channel h=(h0,…,hL−1)h = (h_0, \ldots, h_{L-1}), known or estimated, the number of equalizer 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 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]=∑kgk x[n−k]+ν[n]z[n] = \sum_{i=0}^{N-1} c_i\, y[n - i] = \sum_k g_k\, x[n-k] + \nu[n], where g=c∗hg = c * h has N+L−1N + L - 1 terms and ν\nu is the filtered noise. The output is the tap vector cc such that gΔ=1g_\Delta = 1 and gk=0g_k = 0 at the other N−1N - 1 indices of a window of NN consecutive indices around Δ\Delta. The receiver then decides x[n−Δ]x[n - \Delta] from z[n]z[n] with a slicer, as in the minimum distance detector.

The algorithm

  1. ZF-EQUALIZER(h, N, Δ)
  2. 1s ← min(max(Δ - ⌊(N - 1)/2⌋, 0), L - 1) ▷ the first index of the window
  3. 2A[k][i] ← h[s + k - i] for 0 ≤ k, i < N ▷ h[t] = 0 outside 0 .. L - 1
  4. 3e ← (0, .., 0) with e[Δ - s] ← 1
  5. 4c ← A⁻¹ e ▷ Gaussian elimination
  6. 5return c

Line L1 places the window of NN forced indices around Δ\Delta, as close to centered as the length N+L−1N + L - 1 of gg allows. Line L2 builds the N×NN \times N part of the convolution matrix that maps cc to gs,…,gs+N−1g_s, \ldots, g_{s+N-1}; it is a Toeplitz matrix, constant along each diagonal. Line L3 is the target: a unit pulse at the delay. Line L4 solves for the taps. If AA is singular, the channel cannot be forced to zero on this window, and the implementation reports an error. Then the receiver filters the samples with cc and reads the output with the delay Δ\Delta.

Example

Take h=(1,0.5)h = (1, 0.5), N=5N = 5 and Δ=0\Delta = 0. Line L1 gives s=min⁡(max⁡(0−2,0),1)=0s = \min(\max(0 - 2, 0), 1) = 0. So AA is lower triangular, with 1 on the diagonal and 0.5 below it, and line L4 is a forward substitution: c0=1c_0 = 1 and ck=−0.5 ck−1c_k = -0.5\, c_{k-1}.

index 0 1 2 3 4 5
taps cc 1 -0.5 0.25 -0.125 0.0625
combined g=c∗hg = c * h 1 0 0 0 0 0.03125

The interference is zero on the window 0,…,40, \ldots, 4, and g5=0.55=0.03125g_5 = 0.5^5 = 0.03125 remains outside it. The noise gain is ∥c∥2=1.33203\|c\|^2 = 1.33203, or 1.245 dB. As NN grows, it tends to 12π∫−ππ∣H(ejω)∣−2dω=1/(1−0.52)=4/3\frac{1}{2\pi}\int_{-\pi}^{\pi} |H(e^{j\omega})|^{-2} d\omega = 1/(1 - 0.5^2) = 4/3, or 1.249 dB. For h=(1,0.9)h = (1, 0.9), whose spectrum falls to 0.10.1 at half the symbol rate, the limit is 1/0.19=5.261/0.19 = 5.26, or 7.21 dB.

The delay matters. For the channel h=(0.5,1)h = (0.5, 1), whose zero lies outside the unit circle, N=5N = 5 gives the noise gain 1364 with Δ=0\Delta = 0 and 1.31 with Δ=3\Delta = 3. The causal inverse of such a channel grows, and a delay lets the filter approximate the decaying anticausal inverse instead.

The channel B of Proakis, h=(0.407,0.815,0.407)h = (0.407, 0.815, 0.407), has H(ejπ)=0.407−0.815+0.407=−0.001H(e^{j\pi}) = 0.407 - 0.815 + 0.407 = -0.001, an almost exact null. The best delay with N=31N = 31 taps gives the noise gain 2641, or 34.2 dB, and the infinite-length value is 0.815/(0.8152−0.8142)3/2=123960.815/(0.815^2 - 0.814^2)^{3/2} = 12396, or 40.9 dB. A ZF equalizer is useless on this channel.

Correctness

Claim. If AA is invertible, the taps of line L4 give gΔ=1g_\Delta = 1 and gk=0g_k = 0 for the other N−1N - 1 indices of the window, and they are the only taps that do so. The output is then x[n−Δ]x[n - \Delta] plus the residual interference from the L−1L - 1 indices outside the window, plus noise of variance N0∥c∥2N_0 \|c\|^2.

Key step. Row kk of AcA c is ∑ihs+k−i ci=gs+k\sum_i h_{s+k-i}\, c_i = g_{s+k}, so Ac=eA c = e is exactly the forcing condition on the window. For Δ=0\Delta = 0, AA is lower triangular, and the taps are the first NN coefficients of the power series of 1/H(z)1/H(z). For a minimum-phase channel, Parseval's theorem then gives the limit of the noise gain. The full proof is in the proofs folder. Lucky's optimality result is cited there, not proved.

Proof: The ZF equalizer forces the combined response to a unit pulse on its window, and its noise gain tends to the integral of 1/|H|^2full

The channel taps are h0,…,hL−1h_0, \ldots, h_{L-1}, with ht=0h_t = 0 for t<0t < 0 and t≥Lt \ge L. The equalizer has the taps c0,…,cN−1c_0, \ldots, c_{N-1}, and the received samples are y[n]=∑lhl x[n−l]+w[n]y[n] = \sum_l h_l\, x[n - l] + w[n] with w[n]∼CN(0,N0)w[n] \sim \mathcal{CN}(0, N_0) independent. The equalizer output is

z[n]=∑i=0N−1ci y[n−i]=∑kgk x[n−k]+∑ici w[n−i],gk=∑i=0N−1ci hk−i,(1)z[n] = \sum_{i=0}^{N-1} c_i\, y[n - i] = \sum_k g_k\, x[n - k] + \sum_i c_i\, w[n - i], \qquad g_k = \sum_{i=0}^{N-1} c_i\, h_{k - i}, \tag{1}

so g=c∗hg = c * h is the combined response, with N+L−1N + L - 1 terms g0,…,gN+L−2g_0, \ldots, g_{N+L-2}. Let Δ\Delta be the decision delay, with 0≤Δ≤N+L−20 \le \Delta \le N + L - 2, and let ss be the value of line L1.

Lemma 1 (the window is valid). 0≤s≤L−10 \le s \le L - 1, the window s,…,s+N−1s, \ldots, s + N - 1 lies in 0,…,N+L−20, \ldots, N + L - 2, and it contains Δ\Delta.

Proof. Line L1 clamps ss to [0,L−1][0, L-1], so s+N−1≤N+L−2s + N - 1 \le N + L - 2. Let u=Δ−⌊(N−1)/2⌋u = \Delta - \lfloor (N-1)/2 \rfloor. If 0≤u≤L−10 \le u \le L - 1, then s=us = u and s≤Δ≤s+N−1s \le \Delta \le s + N - 1, because 0≤⌊(N−1)/2⌋≤N−10 \le \lfloor (N-1)/2 \rfloor \le N - 1. If u<0u < 0, then s=0≤Δs = 0 \le \Delta and Δ<⌊(N−1)/2⌋≤N−1\Delta < \lfloor (N-1)/2 \rfloor \le N - 1. If u>L−1u > L - 1, then s=L−1<Δs = L - 1 < \Delta and Δ≤N+L−2=s+N−1\Delta \le N + L - 2 = s + N - 1. □\square

Theorem 1 (zero forcing). If the matrix AA of line L2 is invertible, the taps cc of line L4 give gΔ=1g_\Delta = 1 and gk=0g_k = 0 for every other kk in the window s,…,s+N−1s, \ldots, s + N - 1. They are the only NN taps that do so.

Proof. By (1), gs+k=∑ihs+k−i ci=(Ac)kg_{s + k} = \sum_i h_{s + k - i}\, c_i = (A c)_k for 0≤k<N0 \le k < N. Line L4 makes Ac=eA c = e, where ee has a single 1 at index Δ−s\Delta - s, which is in 0,…,N−10, \ldots, N-1 by Lemma 1. So gs+k=1g_{s+k} = 1 for s+k=Δs + k = \Delta and 00 for the other kk. Any c′c' with the same forcing satisfies Ac′=eA c' = e, and so c′=A−1e=cc' = A^{-1} e = c. □\square

So the output is z[n]=x[n−Δ]+∑k∉Wgk x[n−k]+ν[n]z[n] = x[n - \Delta] + \sum_{k \notin W} g_k\, x[n-k] + \nu[n], where WW is the window, the middle sum is the residual ISI from the L−1L - 1 indices outside the window, and ν[n]=∑iciw[n−i]\nu[n] = \sum_i c_i w[n-i] is the filtered noise.

Lemma 2 (noise enhancement). ν[n]\nu[n] has mean zero and variance N0∥c∥2N_0 \|c\|^2.

Proof. The samples w[n−i]w[n - i] for i=0,…,N−1i = 0, \ldots, N-1 are independent with mean zero and variance N0N_0, so E∣ν[n]∣2=∑i∣ci∣2E∣w[n−i]∣2=N0∥c∥2E|\nu[n]|^2 = \sum_i |c_i|^2 E|w[n-i]|^2 = N_0 \|c\|^2. □\square

Lemma 3 (when the system is solvable, delay 0). If s=0s = 0, then AA is lower triangular with h0h_0 on its diagonal, so it is invertible if and only if h0≠0h_0 \ne 0. For Δ=0\Delta = 0 the taps are the first NN coefficients of the power series of 1/H(z)1/H(z), where H(z)=∑lhlz−lH(z) = \sum_l h_l z^{-l}:

c0=1h0,ck=−1h0∑l=1min⁡(k,L−1)hl ck−l(1≤k<N).c_0 = \frac{1}{h_0}, \qquad c_k = -\frac{1}{h_0} \sum_{l=1}^{\min(k, L-1)} h_l\, c_{k-l} \quad (1 \le k < N).

Proof. With s=0s = 0, Aki=hk−iA_{ki} = h_{k-i} is zero for i>ki > k and h0h_0 for i=ki = k. Its determinant is h0Nh_0^N. Row kk of Ac=eA c = e reads ∑l=0min⁡(k,L−1)hlck−l=[k=0]\sum_{l=0}^{\min(k, L-1)} h_l c_{k-l} = [k = 0], which is the stated recursion. The same recursion defines the coefficients dkd_k of D(z)=∑kdkz−k=1/H(z)D(z) = \sum_k d_k z^{-k} = 1/H(z), since H(z)D(z)=1H(z) D(z) = 1 means ∑lhldk−l=[k=0]\sum_l h_l d_{k-l} = [k = 0] for all k≥0k \ge 0. So ck=dkc_k = d_k for k<Nk < N. □\square

For h=(1,a)h = (1, a), this gives ck=(−a)kc_k = (-a)^k, the combined response g=(1,0,…,0,−(−a)N)g = (1, 0, \ldots, 0, -(-a)^N), and ∥c∥2=(1−∣a∣2N)/(1−∣a∣2)\|c\|^2 = (1 - |a|^{2N})/(1 - |a|^2).

Theorem 2 (the limit of the noise gain). Let Δ=0\Delta = 0 and let all zeros of H(z)H(z) lie strictly inside the unit circle, with h0≠0h_0 \ne 0 (a minimum-phase channel). Then, as N→∞N \to \infty, the residual ISI tends to 0 and

∥c∥2→12π∫−ππdω∣H(ejω)∣2.\|c\|^2 \to \frac{1}{2\pi} \int_{-\pi}^{\pi} \frac{d\omega}{|H(e^{j\omega})|^2}.

Proof. H(z)=h0∏r=1L−1(1−ζrz−1)H(z) = h_0 \prod_{r=1}^{L-1} (1 - \zeta_r z^{-1}) with all ∣ζr∣<1|\zeta_r| < 1. Each factor 1/(1−ζrz−1)=∑kζrkz−k1/(1 - \zeta_r z^{-1}) = \sum_k \zeta_r^k z^{-k} has absolutely summable coefficients, and so does their product D(z)=1/H(z)D(z) = 1/H(z), with ∣dk∣≤Cρk|d_k| \le C \rho^k for some CC and any ρ\rho with max⁡r∣ζr∣<ρ<1\max_r |\zeta_r| < \rho < 1. By Lemma 3, ck=dkc_k = d_k for k<Nk < N, so ∥c∥2=∑k<N∣dk∣2→∑k∣dk∣2\|c\|^2 = \sum_{k<N} |d_k|^2 \to \sum_k |d_k|^2. On the unit circle, D(ejω)=∑kdke−jωk=1/H(ejω)D(e^{j\omega}) = \sum_k d_k e^{-j \omega k} = 1/H(e^{j\omega}), and Parseval's theorem gives ∑k∣dk∣2=12π∫−ππ∣D(ejω)∣2dω\sum_k |d_k|^2 = \frac{1}{2\pi}\int_{-\pi}^{\pi} |D(e^{j\omega})|^2 d\omega. The residual ISI is gk=∑i<Ndihk−ig_k = \sum_{i < N} d_i h_{k-i} for N≤k≤N+L−2N \le k \le N + L - 2, and ∣gk∣≤∑l∣hl∣ CρN−L+1→0|g_k| \le \sum_l |h_l|\, C \rho^{N - L + 1} \to 0. □\square

For other channels the same limit holds with a delay that grows with NN: the zeros outside the unit circle need an anticausal inverse, which a delayed FIR filter approximates. If H(ejω)H(e^{j\omega}) has a zero on the unit circle, the integral diverges, and so does the noise gain of the ZF equalizer as NN grows.

Remark (Lucky's theorem, cited). Let pp be the index of the largest tap and define the initial distortion D0=∑l≠p∣hl∣/∣hp∣D_0 = \sum_{l \ne p} |h_l| / |h_p|. For odd NN and the delay Δ=p+(N−1)/2\Delta = p + (N-1)/2, which puts the cursor under the center tap, the window of line L1 is centered on Δ\Delta. Lucky proved that if D0<1D_0 < 1, this ZF equalizer minimizes the peak distortion ∑k≠Δ∣gk∣/∣gΔ∣\sum_{k \ne \Delta} |g_k| / |g_\Delta| over all equalizers with NN taps. The proof uses the convexity of the peak distortion in cc; see Lucky 1965 and Proakis and Salehi, Section 9.4-1. The tests check this optimality on random channels by perturbation, but this file does not prove it.

Remark (the cost). Line L2 builds N2N^2 entries, and the Gaussian elimination of line L4 costs O(N3)O(N^3), once per channel. Filtering costs NN complex multiplications per symbol.

Complexity

Line L2 fills N2N^2 entries and the Gaussian elimination of line L4 costs O(N3)O(N^3) operations, once per channel. A solver for Toeplitz systems brings this to O(N2)O(N^2). Filtering costs NN complex multiplications per symbol, so KK symbols cost O(N3+KN)O(N^3 + K N) in the real RAM, with O(N2)O(N^2) extra space for AA. For long channels, a ZF equalizer in the frequency domain with a cyclic prefix costs O(log⁡N)O(\log N) per symbol with the fast Fourier transform.

Properties

  • Interference removed, noise ignored. The design uses only hh, not N0N_0. It removes the interference on its window for any noise level.
  • Noise enhancement. The output noise variance is N0∥c∥2N_0 \|c\|^2. For a long filter, ∥c∥2\|c\|^2 approaches 12π∫∣H(ejω)∣−2dω\frac{1}{2\pi}\int |H(e^{j\omega})|^{-2} d\omega, the average of the inverse power gain, which is dominated by the weakest frequencies. So the output SNR is Es/(N0∥c∥2)E_s / (N_0 \|c\|^2), where SNR means Es/N0E_s/N_0 per complex symbol.
  • Spectral nulls. If H(ejω)=0H(e^{j\omega}) = 0 at some frequency, the integral diverges, and the noise gain grows without limit as NN grows.
  • Peak distortion. Lucky's theorem: if the initial distortion D0=∑l≠p∣hl∣/∣hp∣D_0 = \sum_{l \ne p} |h_l| / |h_p|, with hph_p the largest tap, is less than 1, the ZF equalizer with the cursor under its center tap minimizes the peak distortion ∑k≠Δ∣gk∣/∣gΔ∣\sum_{k \ne \Delta} |g_k| / |g_\Delta| over all NN-tap equalizers. If D0≥1D_0 \ge 1, it may not.
  • Limit of the MMSE equalizer. As N0→0N_0 \to 0, the MMSE linear equalizer tends to the ZF equalizer.
  • Exact recovery without noise. When the residual interference is small enough that the eye is open, the slicer recovers every symbol exactly.

Variants and improvements

  • Least squares ZF. Instead of forcing NN indices, minimize ∑k≠Δ∣gk∣2\sum_{k \ne \Delta} |g_k|^2 over all N+L−1N + L - 1 indices with gΔ=1g_\Delta = 1. This is the MMSE equalizer with N0=0N_0 = 0.
  • Adaptive ZF. The adaptive ZF algorithm adjusts the taps from the correlation of the error e[n]=z[n]−x^[n−Δ]e[n] = z[n] - \hat x[n - \Delta] with the decided symbols, ci←ci−μ e[n] x^[n−Δ−i]‾c_i \leftarrow c_i - \mu\, e[n]\, \overline{\hat x[n - \Delta - i]} in one common form, without an estimate of hh; see adaptive equalization.
  • Fractionally spaced ZF. With two samples per symbol, an FIR ZF equalizer of finite length can remove the interference exactly, because the two phases of the channel rarely share a zero; see the fractionally spaced equalizer.
  • ZF decision feedback. A ZF-DFE cancels the postcursor interference with past decisions, so the linear part only has to make the channel causal and monic. Its noise gain is smaller than that of the linear ZF.
  • Frequency-domain ZF. With a cyclic prefix, the channel is diagonal in the DFT domain, and the ZF equalizer is one division 1/Hk1/H_k per bin; see frequency-domain equalization and OFDM.

When to use it

Use a ZF equalizer when the channel has no deep spectral nulls and the SNR is high, so that the noise enhancement is small. It is simple, it does not need N0N_0, and it is a reference for other equalizers. Use the MMSE linear equalizer at moderate SNR or on channels with deep fades, and a DFE or a Viterbi equalizer when the channel has a null in its band.

Pitfalls

  • A channel with a spectral null. On a channel such as Proakis B, the ZF equalizer amplifies the noise by more than 30 dB. Check ∥c∥2\|c\|^2, or the minimum of ∣H(ejω)∣|H(e^{j\omega})|, before using it.
  • The wrong delay. For a channel that is not minimum phase, delay 0 gives a filter whose taps grow, with a huge noise gain. Try every delay and keep the one with the smallest noise gain and residual interference, or use a delay near the middle of N+L−1N + L - 1.
  • Too short a filter. A short equalizer leaves interference outside its window. For h=(1,a)h = (1, a) and delay 0, the residue is ∣a∣N|a|^N; for ∣a∣|a| near 1 it decays slowly.
  • An estimated channel. The ZF equalizer inverts the estimate, not the true channel. Errors in h^\hat h near a weak frequency are amplified, just as the noise is.
  • Treating the output noise as white. The noise ν[n]\nu[n] has variance N0∥c∥2N_0 \|c\|^2, but it is correlated from symbol to symbol. A sequence detector after the ZF equalizer must take this into account, or use a whitened model instead.

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)
zero_forcing_equalizer.py 59 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zero-forcing-equalizer/. The authors are listed in prov/2260NZ.jsonl.

"""The finite-length zero-forcing (ZF) linear equalizer of Lucky.

The channel is y[k] = sum_{l=0}^{L-1} h[l] x[k-l] + w[k] at one sample per
symbol. The equalizer is an FIR filter c of N taps, and the combined
response is g = c * h, of length N + L - 1. For a chosen decision delay D,
the ZF equalizer forces g[D] = 1 and g[k] = 0 at the other N - 1 indices of a
window of N consecutive indices that contains D. This is an N by N linear
system A c = e with A[k][i] = h[s + k - i]. The output noise is N0 ||c||^2.
"""

import cbb


def forcing_window(taps: int, n: int, delay: int) -> int:
    """The first index s of the window s..s+N-1 of the combined response, centered on the delay if possible."""
    if taps < 1 or n < 1 or not 0 <= delay <= n + taps - 2:
        raise ValueError("need L >= 1, N >= 1 and 0 <= delay <= N + L - 2")
    return min(max(delay - (n - 1) // 2, 0), taps - 1)


def zf_equalizer(h: list[complex], n: int, delay: int) -> list[complex]:
    """The N taps c that make the combined response c * h equal to 1 at the delay and 0 at N - 1 indices around it."""
    taps = len(h)
    s = forcing_window(taps, n, delay)  # @line L1
    hh = lambda t: complex(h[t]) if 0 <= t < taps else 0j
    a = [[hh(s + k - i) for i in range(n)] for k in range(n)]  # @line L2
    e = [0j] * n
    e[delay - s] = 1 + 0j  # @line L3
    try:
        c = cbb.solve(a, e)  # @line L4
    except ValueError:
        raise ValueError("the forcing system is singular for this channel, length and delay") from None
    return c  # @line L5


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]


def combined_response(c: list[complex], h: list[complex]) -> list[complex]:
    """g = c * h, the response from the symbols to the equalizer output."""
    return cbb.conv(c, h)


def peak_distortion(g: list[complex], delay: int) -> float:
    """Lucky's peak distortion: the sum of |g[k]| over k != delay, divided by |g[delay]|."""
    return sum(abs(v) for k, v in enumerate(g) if k != delay) / abs(g[delay])


def noise_gain(c: list[complex]) -> float:
    """||c||^2: white noise of variance N0 at the input has variance N0 ||c||^2 at the output."""
    return cbb.norm2(c)
test_zero_forcing_equalizer.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zero-forcing-equalizer/. The authors are listed in prov/2260NZ.jsonl.

import math
import random

import pytest

import cbb
from zero_forcing_equalizer import (
    combined_response,
    equalize,
    forcing_window,
    noise_gain,
    peak_distortion,
    zf_equalizer,
)

PROAKIS_B = [0.407, 0.815, 0.407]


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


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


def slice_qpsk(z):
    return complex(1 if z.real >= 0 else -1, 1 if z.imag >= 0 else -1) / math.sqrt(2)


def test_example_on_the_page() -> None:
    c = zf_equalizer([1, 0.5], 5, 0)
    assert close(c, [1, -0.5, 0.25, -0.125, 0.0625])
    g = combined_response(c, [1, 0.5])
    assert close(g, [1, 0, 0, 0, 0, 0.03125])
    assert abs(peak_distortion(g, 0) - 0.03125) < 1e-12
    assert abs(noise_gain(c) - 1.33203125) < 1e-12
    # the delay 2 centers the window: g = (0, 0, 1, 0, 0, 0.125)
    assert close(combined_response(zf_equalizer([1, 0.5], 5, 2), [1, 0.5]), [0, 0, 1, 0, 0, 0.125])


def test_noise_gain_closed_form_for_two_taps() -> None:
    # for h = (1, a) and delay 0, c[k] = (-a)^k, so ||c||^2 = (1 - |a|^(2N)) / (1 - |a|^2)
    for a in (0.5, 0.9, -0.3 + 0.4j):
        for n in (1, 4, 9, 30):
            want = (1 - abs(a) ** (2 * n)) / (1 - abs(a) ** 2)
            assert abs(noise_gain(zf_equalizer([1, a], n, 0)) - want) < 1e-9 * want


def test_forcing_conditions_hold_on_random_channels() -> None:
    rng = random.Random(6101)
    done = 0
    while done < 200:
        taps, n = rng.randint(1, 5), rng.randint(1, 9)
        h = [cbb.cn(rng, 1.0) for _ in range(taps)]
        delay = rng.randint(0, n + taps - 2)
        c = zf_equalizer(h, n, delay)
        g = combined_response(c, h)
        s = forcing_window(taps, n, delay)
        if noise_gain(c) > 1e6:
            continue  # nearly singular: the forcing still holds, but not to 1e-9
        want = [1 if k == delay else 0 for k in range(s, s + n)]
        assert close(g[s : s + n], want, 1e-9)
        done += 1


def test_noiseless_data_are_recovered_exactly() -> None:
    rng = random.Random(6102)
    for h, n, delay in (([1, 0.5], 5, 0), ([0.5, 1], 7, 6), (PROAKIS_B, 31, 16), ([0.8, -0.4j, 0.2], 11, 1)):
        x = [qpsk(rng) for _ in range(400)]
        y = cbb.conv(x, h)
        c = zf_equalizer(h, n, delay)
        assert peak_distortion(combined_response(c, h), delay) < 1  # the eye is open
        z = equalize(c, y, delay, len(x))
        assert [slice_qpsk(v) for v in z] == x


def test_output_noise_variance_is_n0_times_noise_gain() -> None:
    rng = random.Random(6103)
    c = zf_equalizer([1, 0.9], 9, 0)
    n0, runs = 0.2, 6000
    acc = 0.0
    for _ in range(runs):
        w = [cbb.cn(rng, n0) for _ in range(len(c))]
        acc += abs(sum(ci * wi for ci, wi in zip(c, reversed(w)))) ** 2 / runs
    want = n0 * noise_gain(c)
    assert abs(acc - want) < 0.06 * want  # 6000 runs, seed 6103


def test_bpsk_error_rate_after_zf_matches_the_formula() -> None:
    # h = (1, 0.5) with N = 15: the residual ISI is 0.5^15, so the output is x + Gaussian noise
    rng = random.Random(6104)
    h, n, n0, count = [1, 0.5], 15, 0.277, 20000
    c = zf_equalizer(h, n, 0)
    x = [rng.choice((-1.0, 1.0)) for _ in range(count)]
    y = cbb.awgn(rng, cbb.conv(x, h), n0)
    z = equalize(c, y, 0, count)
    errors = sum((v.real >= 0) != (s > 0) for v, s in zip(z, x))
    p = cbb.qfunc(math.sqrt(2 / (n0 * noise_gain(c))))  # real noise variance N0 ||c||^2 / 2, Es = 1
    lo, hi = cbb.wilson(errors, count)  # z = 3.29, about 200 errors expected
    assert lo <= p <= hi


def test_lucky_peak_distortion_is_minimal_when_the_eye_is_open() -> None:
    rng = random.Random(6105)
    done = 0
    while done < 60:
        taps, k = rng.randint(2, 4), rng.randint(1, 3)
        n = 2 * k + 1
        h = [rng.uniform(-1, 1) for _ in range(taps)]
        p = max(range(taps), key=lambda i: abs(h[i]))
        if sum(abs(v) for v in h) / abs(h[p]) - 1 >= 1:
            continue  # Lucky's theorem needs an initial distortion D0 < 1
        delay = p + k  # the cursor of h under the center tap of c
        c = zf_equalizer(h, n, delay)
        best = peak_distortion(combined_response(c, h), delay)
        for scale in (1e-1, 1e-2, 1e-4):
            for _ in range(20):
                d = [rng.uniform(-1, 1) for _ in range(n)]
                gd = combined_response(d, h)[delay]
                d = [a - gd * b for a, b in zip(d, c)]  # keep g[delay] = 1
                other = [a + scale * b for a, b in zip(c, d)]
                assert peak_distortion(combined_response(other, h), delay) >= best - 1e-12
        done += 1


def test_delay_matters_for_a_maximum_phase_channel() -> None:
    gains = [noise_gain(zf_equalizer([0.5, 1], 5, d)) for d in range(6)]
    assert abs(gains[0] - 1364) < 1e-9 and abs(gains[5] - 1.33203125) < 1e-9
    assert min(range(6), key=lambda d: gains[d]) == 3


def test_proakis_channel_b_has_a_huge_noise_gain() -> None:
    assert abs(PROAKIS_B[0] - PROAKIS_B[1] + PROAKIS_B[2] + 0.001) < 1e-12  # H at half the symbol rate
    best = min(noise_gain(zf_equalizer(PROAKIS_B, 31, d)) for d in range(32))
    assert 2000 < best < 3000
    a, b = 0.815, 0.814  # |H(w)| = |0.815 + 0.814 cos w|; the infinite-length gain is a / (a^2 - b^2)^(3/2)
    assert 12390 < a / (a * a - b * b) ** 1.5 < 12400


def test_errors() -> None:
    with pytest.raises(ValueError):
        zf_equalizer([0, 1], 3, 0)  # h[0] = 0 makes the triangular system singular
    with pytest.raises(ValueError):
        zf_equalizer([1, 0.5], 3, 4)  # the delay must be at most N + L - 2 = 3
    with pytest.raises(ValueError):
        zf_equalizer([], 3, 0)

History

Robert Lucky built the first automatic equalizers for data transmission over telephone lines at Bell Labs in the mid 1960s. His 1965 paper defined the peak distortion, the worst-case sum of the interference, and showed that when the eye is open before equalization, the equalizer that forces the interference to zero at the taps around the cursor minimizes it. The mean-square error criterion, which leads to the MMSE equalizer, followed in the late 1960s and soon replaced peak distortion in most designs, because it takes the noise into account and allows the LMS algorithm.

References

  1. R. W. Lucky, Automatic equalization for digital communication, Bell System Technical Journal 44(4), 1965, pages 547 to 588, the peak distortion criterion, the zero-forcing tap settings and their optimality when the initial distortion is less than 1
  2. John G. Proakis and Masoud Salehi, Digital Communications, fifth edition, McGraw-Hill, 2008, Section 9.4-1 (the peak distortion criterion and the zero-forcing equalizer)
  3. John R. Barry, Edward A. Lee and David G. Messerschmitt, Digital Communication, third edition, Kluwer Academic Publishers, 2004, Chapter 8 (equalization)

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