Algorithm Search⌘K

Algorithmcore

Viterbi equalizer

Also called MLSE equalizer.

Finds the maximum likelihood symbol sequence over an ISI channel by the Viterbi algorithm on a trellis of channel states.

Time
O(N M^L) worst
Space
O(N M^(L-1)) extra
Where
L = the number of channel taps; M = the alphabet size; N = the number of symbols
Properties
deterministicexact mlneeds channel
Origin
G. David Forney Jr., 1972

The Viterbi equalizer finds the most likely transmitted sequence on a channel with intersymbol interference. The channel output at time kk depends on the current symbol and on the last L−1L-1 symbols, so these L−1L-1 symbols are a state. A sequence of symbols is a path through a trellis with ML−1M^{L-1} states per time step, and the squared distance between the received samples and the noiseless output is a sum of branch metrics along the path. The Viterbi algorithm finds the path with the smallest sum. With white Gaussian noise this path is the maximum likelihood sequence. The input is usually the output of a whitened matched filter, which gives a causal channel with white noise. This page gives the ISI trellis and its metric; the search itself is the one on the Viterbi algorithm page.

In plain words

Each received sample is a mix of the current symbol and a few earlier ones. A detector that looks at one sample at a time treats the earlier symbols as noise. The Viterbi equalizer does not. It keeps, for every possible group of recent symbols, the best guess of the whole past that ends in that group. When a new sample arrives, it extends each guess by each possible new symbol, scores how well the result explains the sample, and keeps only the best extension into each group. At the end it reads back the best guess. The number of groups grows quickly with the length of the channel, which limits the method to short channels and small alphabets.

The problem

The input is a known channel f=(f0,…,fL−1)f = (f_0, \ldots, f_{L-1}), an alphabet A\mathcal{A} of MM points, the L−1L-1 known symbols before the block, and the samples yk=∑l=0L−1flxk−l+nky_k = \sum_{l=0}^{L-1} f_l x_{k-l} + n_k for k=0,…,N−1k = 0, \ldots, N-1, with nkn_k white CN(0,N0)\mathcal{CN}(0, N_0). The output is the sequence x^∈AN\hat x \in \mathcal{A}^N that minimizes

J(x)=∑k=0N−1∣yk−∑l=0L−1flxk−l∣2,J(x) = \sum_{k=0}^{N-1} \Big| y_k - \sum_{l=0}^{L-1} f_l x_{k-l} \Big|^2 ,

which is the maximum likelihood sequence. If the transmitter ends the block with L−1L-1 known tail symbols, the receiver adds their L−1L-1 samples to yy and forces the tail in the trellis.

The algorithm

The state at time kk is sk=(xk−1,…,xk−L+1)s_k = (x_{k-1}, \ldots, x_{k-L+1}). A symbol aa moves sks_k to sk+1=(a,xk−1,…,xk−L+2)s_{k+1} = (a, x_{k-1}, \ldots, x_{k-L+2}), and the branch metric is λk(s,a)=∣yk−f0a−∑l≥1flsl∣2\lambda_k(s, a) = |y_k - f_0 a - \sum_{l \ge 1} f_l s_l|^2.

  1. VITERBI-EQUALIZER(y, f, A, pre, tail)
  2. 1S ← the M^(L-1) states; before x[0] the past symbols come from pre
  3. 2metric[s] ← 0 for the start state, ∞ for the others
  4. 3for k ← 0 to K - 1
  5. 4for each state s with metric[s] < ∞ and each symbol a allowed at k ▷ only the tail symbol after x[n-1]
  6. 5λ ← |y[k] - f[0] a - Σ_{l≥1} f[l] x[k-l](s)|²
  7. 6if metric[s] + λ < new[next(s, a)] then keep it and set ptr[k][next(s, a)] ← (s, a)
  8. 7s ← the state with the smallest metric
  9. 8follow ptr from s back to k = 0 and read the symbols
  10. 9return the first n symbols

Line L1 fixes the trellis. Line L2 starts from the known past. Lines L4 to L6 are the add-compare-select step: each state keeps the one path into it with the smallest metric, its survivor. Line L5 is the only part that depends on the channel. For k≥L−1k \ge L-1 the noiseless output depends only on (s,a)(s, a), so the implementation computes the MLM^L values once. Lines L7 and L8 are the traceback. With a known tail, one state remains at the end and line L7 has no choice.

Example

Take f=(1,0.5)f = (1, 0.5), BPSK with A={+1,−1}\mathcal{A} = \{+1, -1\}, and the known symbol x−1=+1x_{-1} = +1. The state is the last symbol, so there are 2 states. The transmitted block is x=(+1,−1,−1,+1)x = (+1, -1, -1, +1), the noiseless outputs are (1.5,−0.5,−1.5,0.5)(1.5, -0.5, -1.5, 0.5), and the noise gives y=(1.4,0.1,−1.2,0.6)y = (1.4, 0.1, -1.2, 0.6). Each cell shows the survivor metric of the state and the state it came from:

kk yky_k state +1+1 state −1-1
0 1.4 0.01 from +1+1 3.61 from +1+1
1 0.1 1.97 from +1+1 0.37 from +1+1
2 -1.2 3.26 from −1-1 0.46 from −1-1
3 0.6 0.47 from −1-1 4.47 from +1+1

At k=2k = 2, the state +1+1 compares 1.97+(−1.2−1.5)21.97 + (-1.2 - 1.5)^2 with 0.37+(−1.2−1+0.5)20.37 + (-1.2 - 1 + 0.5)^2, that is 9.26 with 3.26, and keeps the path from −1-1. At the end, the state +1+1 has the smallest metric, 0.47. The traceback reads +1,−1,−1,+1+1, -1, -1, +1 backward through the "from" column, so x^=(+1,−1,−1,+1)\hat x = (+1, -1, -1, +1), which is correct. A slicer on yy decides x1=+1x_1 = +1, because y1=0.1>0y_1 = 0.1 > 0. Both survivors at k=1k = 1 come from the state +1+1 at k=0k = 0, so the two paths merge there and x0=+1x_0 = +1 is final after one step. In a stream, the receiver outputs a symbol when all survivors agree on it.

On f=(1,0.5)f = (1, 0.5) at N0=0.4N_0 = 0.4, a run of 60000 BPSK symbols with seed 7505 gave 572 errors, a rate of 0.00953. The matched filter bound Q(2∥f∥2/N0)Q(\sqrt{2\|f\|^2/N_0}) is 0.00621. For this channel, the minimum squared distance between two output sequences is dmin⁡2=5=4∥f∥2d_{\min}^2 = 5 = 4\|f\|^2, the same as for a single isolated symbol, so the ISI costs nothing at high SNR. On the channel B of Proakis, f=(0.407,0.815,0.407)f = (0.407, 0.815, 0.407), a search over error events up to length 16 gives dmin⁡2=2.6569d_{\min}^2 = 2.6569 against 4∥f∥2=3.98214\|f\|^2 = 3.9821, a loss of 1.76 dB. On the channel C of Proakis, f=(0.227,0.460,0.688,0.460,0.227)f = (0.227, 0.460, 0.688, 0.460, 0.227), the same search gives dmin⁡2=1.2624d_{\min}^2 = 1.2624 against 3.9984, a loss of 5.01 dB. A linear equalizer loses much more on both channels, because their zeros are near the unit circle.

Correctness

Claim. The returned sequence minimizes JJ over AN\mathcal{A}^N with the known pre and tail symbols, so it is a maximum likelihood sequence when the noise is white and Gaussian.

Key step. The noiseless output at time kk depends only on the state and the new symbol, so JJ is a sum of branch metrics along a trellis path. Two paths that reach the same state at time kk have the same future branch metrics, so only the better one can be part of the best full path. By induction on kk, each survivor is the best path into its state, and the best final survivor is the best path overall. The proofs folder has the details and the high-SNR bounds Q(dmin⁡2/(2N0))Q(\sqrt{d_{\min}^2/(2N_0)}) and Q(2∥f∥2/N0)Q(\sqrt{2\|f\|^2/N_0}).

Proof: The Viterbi equalizer returns the maximum likelihood sequence on a channel with white Gaussian noisefull

The channel taps are f0,…,fL−1f_0, \ldots, f_{L-1} and the alphabet A\mathcal{A} has MM points. The known symbols x−L+1,…,x−1x_{-L+1}, \ldots, x_{-1} come from pre, the unknown symbols are x0,…,xn−1x_0, \ldots, x_{n-1}, and the known symbols xn,…,xK−1x_n, \ldots, x_{K-1} come from tail. The received samples are yk=∑l=0L−1flxk−l+nky_k = \sum_{l=0}^{L-1} f_l x_{k-l} + n_k for k=0,…,K−1k = 0, \ldots, K-1, with nkn_k i.i.d. CN(0,N0)\mathcal{CN}(0, N_0). Write y^k(x)=∑lflxk−l\hat y_k(x) = \sum_l f_l x_{k-l} and

J(x)=∑k=0K−1∣yk−y^k(x)∣2.J(x) = \sum_{k=0}^{K-1} |y_k - \hat y_k(x)|^2 .

Lemma 1 (the metric). The likelihood is p(y∣x)=(πN0)−Kexp⁡(−J(x)/N0)p(y \mid x) = (\pi N_0)^{-K} \exp(-J(x)/N_0). So a sequence maximizes the likelihood over An\mathcal{A}^n if and only if it minimizes JJ.

Proof. Given xx, the samples yky_k are independent with yk∼CN(y^k(x),N0)y_k \sim \mathcal{CN}(\hat y_k(x), N_0). Multiply the densities. The exponential is strictly decreasing in JJ. □\square

Lemma 2 (the state). Let the state at time kk be sk=(xk−1,…,xk−L+1)s_k = (x_{k-1}, \ldots, x_{k-L+1}). Then y^k(x)\hat y_k(x) depends only on sks_k and xkx_k, and sk+1s_{k+1} is a function of sks_k and xkx_k. For k<L−1k < L - 1, the entries of sks_k with negative index are the known pre symbols.

Proof. y^k\hat y_k uses xk,…,xk−L+1x_k, \ldots, x_{k-L+1}, which are xkx_k and the entries of sks_k. The next state drops xk−L+1x_{k-L+1} and puts xkx_k in front. In the code, the state integer holds only the entries with index at least 0, and out reads the others from pre (line L5). So two partial sequences with the same last L−1L - 1 symbols give the same branch metrics at every later time. □\square

So J(x)=∑kλk(sk,xk)J(x) = \sum_k \lambda_k(s_k, x_k) with the branch metric λk(s,a)=∣yk−y^k∣2\lambda_k(s, a) = |y_k - \hat y_k|^2. Each sequence xx is a path through the trellis with ML−1M^{L-1} states per time, and JJ is the sum of the branch metrics along the path.

Lemma 3 (the survivors). After step kk of the loop at line L3, metric[s] is the minimum of ∑t≤kλt\sum_{t \le k} \lambda_t over all paths of length k+1k+1 that are allowed (they use the tail symbol at times t≥nt \ge n) and end in state ss, or ∞\infty if there is no such path. Following the pointers from ss gives a path that reaches this minimum.

Proof. By induction on kk. Before the loop there is one path of length 0, and it has metric 0 (line L2). The state label 0 is a placeholder: for k<L−1k < L-1, line L5 reads the past symbols from pre, and the entries of the state that the code uses at time kk are only those with index k−t≥0k - t \ge 0. Assume the claim after step k−1k - 1. A path of length k+1k+1 that ends in tt is a path of length kk that ends in some ss with next(s,a)=t\mathrm{next}(s, a) = t, followed by the branch aa. Its metric is the metric of the prefix plus λk(s,a)\lambda_k(s, a), and λk(s,a)\lambda_k(s, a) does not depend on the prefix by Lemma 2. So the best path into tt has the best prefix into its own ss, which gives the minimum over ss and aa of metric[s] +λk(s,a)+ \lambda_k(s, a). Lines L4 to L6 compute exactly this minimum and store the argument in the pointer. At times k≥nk \ge n, line L4 tries only the tail symbol, which is the set of allowed branches. □\square

Theorem 1 (maximum likelihood). viterbi_equalize returns a sequence x^∈An\hat x \in \mathcal{A}^n with J(x^)=min⁡x∈AnJ(x)J(\hat x) = \min_{x \in \mathcal{A}^n} J(x), with the pre and tail symbols fixed. So x^\hat x is a maximum likelihood sequence.

Proof. By Lemma 3 with k=K−1k = K - 1, the minimum of metric over all states (line L7) is the minimum of JJ over all allowed paths, and the traceback at line L8 returns a path that reaches it. The allowed paths are exactly the sequences x∈Anx \in \mathcal{A}^n followed by the tail. Line L9 drops the tail. Lemma 1 ends the proof. □\square

If two paths tie, the code keeps the first one it finds. The brute force in the tests may keep another one, so the tests compare the metrics too.

Theorem 2 (the cost). The loop runs KK times. Each step visits ML−1M^{L-1} states and MM branches per state, and each branch metric costs O(1)O(1) for k≥L−1k \ge L - 1, because the code computes the MLM^L outputs y^\hat y for each state and symbol once before the loop, in O(LML)O(L M^L). They do not depend on kk for k≥L−1k \ge L - 1. The first L−1L - 1 steps cost O(L)O(L) per branch. So the time is O(KML+L2ML)O(K M^L + L^2 M^L), which is O(KML)O(K M^L) when K≥L2K \ge L^2. The pointers need O(KML−1)O(K M^{L-1}) space.

Proof. Count the operations in lines L3 to L6. The traceback costs O(K)O(K). □\square

Theorem 3 (the high SNR error rate). For BPSK with A={+1,−1}\mathcal{A} = \{+1, -1\}, define dmin⁡2=min⁡∥f∗e∥2d_{\min}^2 = \min \|f * e\|^2 over error sequences e∈{−2,0,2}me \in \{-2, 0, 2\}^m with e0≠0e_0 \ne 0. Then dmin⁡2≤4∥f∥2d_{\min}^2 \le 4 \|f\|^2. If the block is longer than the event that reaches dmin⁡d_{\min}, the probability that the output sequence is wrong is at least c Q(dmin⁡2/(2N0))c\,Q\big(\sqrt{d_{\min}^2/(2 N_0)}\big) for a constant c>0c > 0. The probability of an error on a given symbol is at least Q(2∥f∥2/N0)Q\big(\sqrt{2\|f\|^2/N_0}\big).

Proof. The single error e=(2)e = (2) gives ∥f∗e∥2=4∥f∥2\|f * e\|^2 = 4\|f\|^2, so the minimum is at most this. For the first bound, take the event ee that reaches dmin⁡d_{\min}, placed inside the block, and the transmitted data for which x+ex + e is in the alphabet. This data has probability c=2−w(e)c = 2^{-w(e)}, where w(e)w(e) is the number of nonzero entries. With u=f∗eu = f * e, J(x+e)<J(x)J(x + e) < J(x) holds if and only if ∥n−u∥2<∥n∥2\|n - u\|^2 < \|n\|^2, that is Re⟨n,u⟩/∥u∥>∥u∥/2\mathrm{Re}\langle n, u\rangle / \|u\| > \|u\|/2. The left side is real Gaussian with variance N0/2N_0/2, so this happens with probability Q(dmin⁡/(2N0/2))Q(d_{\min}/(2\sqrt{N_0/2})), and then the ML output is not xx. For the second bound, give the detector all other symbols for free. Then deciding xkx_k is a binary test between two points at the distance 2∥f∥2\|f\| and the best error probability is Q(∥f∥/N0/2)Q(\|f\|/\sqrt{N_0/2}). No detector beats the genie. □\square

The union bound over all error events gives an upper bound of the same form ∑ew(e)2−w(e)Q(∥f∗e∥/2N0)\sum_e w(e) 2^{-w(e)} Q(\|f * e\|/\sqrt{2 N_0}), which the first term dominates at high SNR. The function min_distance_bpsk computes dmin⁡2d_{\min}^2 by a depth-first search over ee: it adds the energy of the outputs that one more entry fixes, prunes a branch once its partial energy reaches the best value found, and closes an event by adding the energy of the last L−1L - 1 outputs.

Complexity

Each step visits ML−1M^{L-1} states with MM branches, so NN symbols cost O(NML)O(N M^L) time once the MLM^L noiseless outputs are tabulated, in the word RAM with the metrics as numbers of fixed precision. The pointers take O(NML−1)O(N M^{L-1}) space. A stream receiver keeps only the last DD steps of pointers, with a decision delay DD of about 5 times the channel memory, and needs O(DML−1)O(D M^{L-1}) space. The cost is exponential in the channel memory: 8-PSK on 5 taps needs 84=40968^4 = 4096 states, and 64-QAM on 3 taps needs 4096 states as well. A linear or decision feedback equalizer costs O(NL)O(N L).

Properties

  • Exact. It is the maximum likelihood sequence detector, so it minimizes the probability of a sequence error, not of a symbol error. The BCJR algorithm on the same trellis gives the symbol-wise MAP decisions and soft outputs.
  • Error events. At high SNR, errors come in short events, and the rate is close to c Q(dmin⁡2/(2N0))c\,Q(\sqrt{d_{\min}^2/(2N_0)}). The minimum distance dmin⁡d_{\min} is at most the matched filter bound distance 2∥f∥2\|f\|, and often equal to it.
  • No noise enhancement. Unlike linear equalizers, it never inverts the channel, so spectral nulls do not amplify the noise. They only reduce dmin⁡d_{\min}.
  • Needs white noise. The Euclidean metric is the log-likelihood only for white noise. With colored noise, whiten first, or use the Ungerboeck metric on the matched filter output.
  • Needs the channel. The receiver must know ff. A wrong estimate gives a wrong metric for every branch. Per-survivor processing tracks the channel inside the trellis.

Variants and improvements

  • Ungerboeck receiver. Works on the matched filter output with a modified branch metric, so it needs no whitening filter. See Ungerboeck MLSE receiver.
  • Reduced states. Reduced-state sequence estimation keeps only a few recent symbols or only subsets of the alphabet in the state, and cancels the rest of the ISI with decisions from each survivor. DDFSE with a memory of μ<L−1\mu < L-1 symbols uses MμM^\mu states instead of ML−1M^{L-1}.
  • Soft outputs. The soft-output Viterbi algorithm and the BCJR algorithm give reliabilities for a decoder, which is the start of turbo equalization.
  • Adaptive. Per-survivor processing updates a channel estimate or a phase estimate along each survivor.
  • Partial response. On a channel designed to have a short known response, such as duobinary f=(1,1)f = (1, 1) in partial-response signaling, the trellis is small and fixed. Magnetic recording uses this.

When to use it

Use it when the channel memory and the alphabet are small enough that ML−1M^{L-1} states are affordable, the channel is known or well estimated, and the best detection matters: GSM receivers with binary symbols and a few taps, partial-response read channels, short optical and wireline links. For long channels or large constellations, use a DFE, RSSE, or a block transmission with frequency-domain equalization.

Pitfalls

  • Colored noise. Running the Euclidean metric on matched filter samples, or on samples with colored noise, is no longer maximum likelihood. Use the WMF output or the Ungerboeck metric.
  • Maximum-phase channels. The full Viterbi equalizer does not care about the phase of the channel, but a short decision delay does: if the energy comes late, the survivors merge late. The WMF gives the minimum-phase channel.
  • The start state. The trellis must start from the known past, or from all states with metric 0 if the past is unknown. Starting from a wrong known state adds errors at the start of each block.
  • Metric overflow. Metrics grow without bound in a stream. Subtract the minimum metric at each step, or use modular arithmetic on fixed-point metrics.
  • States grow quickly. ML−1M^{L-1} looks small for BPSK, but 16-QAM on 4 taps already needs 4096 states.

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.

viterbi_equalizer.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/viterbi-equalizer/. The authors are listed in prov/8TQVP4.jsonl.

"""The Viterbi equalizer: maximum likelihood sequence detection on an ISI channel.

The model is Forney's: y[k] = sum_{l=0}^{L-1} f[l] x[k-l] + n[k] with white
Gaussian noise, for example the output of a whitened matched filter. The state
at time k is the last L-1 symbols (x[k-1], ..., x[k-L+1]), so there are
M^(L-1) states and M branches leave each state. The branch metric is
|y[k] - sum_l f[l] x[k-l]|^2. The search over the trellis is the Viterbi
algorithm; this file only builds the ISI trellis and its metric.

A state is an integer s = i1 + M i2 + ... + M^(L-2) i_{L-1}, where i_t is the
alphabet index of x[k-t]. The symbol with index i0 moves s to
i0 + M (s mod M^(L-2)).
"""

import itertools


def _next_state(s: int, i0: int, m: int, mem: int) -> int:
    if mem == 0:
        return 0
    return i0 + m * (s % (m ** (mem - 1)))


def _state_of(symbols: list[int], m: int) -> int:
    """The state for the indices (i1, i2, ...) of the most recent symbols first."""
    s = 0
    for t, i in enumerate(symbols):
        s += i * m ** t
    return s


def viterbi_equalize(y: list[complex], f: list[complex], alphabet: list[complex], pre: list[complex] | None = None, tail: list[complex] | None = None) -> list[complex]:
    """The maximum likelihood sequence for y on the channel f.

    pre holds the L-1 known symbols before x[0], oldest first (zeros if absent).
    tail holds known symbols after the unknown ones; y covers the unknown symbols
    and then the tail. Returns the decisions on the len(y) - len(tail) unknown
    symbols.
    """
    m, mem = len(alphabet), len(f) - 1
    pre = list(pre) if pre is not None else [0j] * mem
    tail = list(tail) if tail is not None else []
    if len(pre) != mem:
        raise ValueError("pre must hold L-1 symbols")
    n = len(y) - len(tail)
    if n < 0:
        raise ValueError("y is shorter than the tail")
    index = {complex(a): i for i, a in enumerate(alphabet)}
    for v in tail:
        if complex(v) not in index:
            raise ValueError("tail symbols must be in the alphabet")
    states = m ** mem  # @line L1

    def out(s: int, i0: int, k: int) -> complex:
        # the noiseless output at time k for state s and new symbol i0; before x[0] the known pre symbols
        acc = f[0] * alphabet[i0]
        for t in range(1, mem + 1):
            if k - t >= 0:
                acc += f[t] * alphabet[(s // m ** (t - 1)) % m]
            else:
                acc += f[t] * pre[mem + (k - t)]
        return acc

    # for k >= L-1 the output depends only on (s, i0), so it is computed once: O(L M^L)
    steady = [[out(s, i0, mem) for i0 in range(m)] for s in range(states)]
    inf = float("inf")
    metric = [inf] * states
    metric[0] = 0.0  # @line L2
    back: list[list[tuple[int, int]]] = []
    for k in range(len(y)):  # @line L3
        new = [inf] * states
        ptr = [(-1, -1)] * states
        choices = range(m) if k < n else [index[complex(tail[k - n])]]
        for s in range(states):
            if metric[s] == inf:
                continue
            for i0 in choices:  # @line L4
                d = abs(y[k] - (steady[s][i0] if k >= mem else out(s, i0, k))) ** 2  # @line L5
                t = _next_state(s, i0, m, mem)
                cand = metric[s] + d
                if cand < new[t]:  # @line L6
                    new[t] = cand
                    ptr[t] = (s, i0)
        metric = new
        back.append(ptr)
    s = min(range(states), key=lambda q: metric[q])  # @line L7
    path = []
    for k in range(len(y) - 1, -1, -1):  # @line L8
        prev, i0 = back[k][s]
        path.append(alphabet[i0])
        s = prev
    path.reverse()
    return path[:n]  # @line L9


def sequence_metric(y: list[complex], f: list[complex], x: list[complex], pre: list[complex] | None = None) -> float:
    """sum_k |y[k] - sum_l f[l] x[k-l]|^2 over k = 0..len(y)-1, with x[k] for k < 0 from pre."""
    mem = len(f) - 1
    pre = list(pre) if pre is not None else [0j] * mem
    full = pre + list(x)
    total = 0.0
    for k in range(len(y)):
        acc = sum(f[l] * full[mem + k - l] for l in range(len(f)))
        total += abs(y[k] - acc) ** 2
    return total


def brute_force(y: list[complex], f: list[complex], alphabet: list[complex], pre: list[complex] | None = None, tail: list[complex] | None = None) -> list[complex]:
    """The ML sequence by trying all M^n sequences (for tests)."""
    tail = list(tail) if tail is not None else []
    n = len(y) - len(tail)
    best, arg = float("inf"), None
    for cand in itertools.product(alphabet, repeat=n):
        v = sequence_metric(y, f, list(cand) + tail, pre)
        if v < best:
            best, arg = v, list(cand)
    return arg


def min_distance_bpsk(f: list[float], max_len: int = 12) -> float:
    """The minimum squared distance between two BPSK (+-1) sequences through f.

    It is the minimum of ||f * e||^2 over error sequences e with e[0] != 0 and
    entries in {-2, 0, 2}, searched up to length max_len with pruning.
    """
    best = 4 * sum(abs(v) ** 2 for v in f)  # a single error: the matched filter bound
    mem = len(f) - 1

    def grow(e: list[int], acc: float) -> None:
        nonlocal best
        if acc >= best:
            return
        # close the event: the outputs after the last error symbol
        tail = 0.0
        for k in range(len(e), len(e) + mem):
            tail += abs(sum(f[l] * e[k - l] for l in range(len(f)) if 0 <= k - l < len(e))) ** 2
        if e[-1] != 0 and acc + tail < best:
            best = acc + tail
        if len(e) >= max_len:
            return
        for v in (-2, 0, 2):
            e2 = e + [v]
            k = len(e2) - 1
            out = sum(f[l] * e2[k - l] for l in range(len(f)) if k - l >= 0)
            grow(e2, acc + abs(out) ** 2)

    grow([2], abs(f[0] * 2) ** 2)
    return best
test_viterbi_equalizer.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/viterbi-equalizer/. The authors are listed in prov/8TQVP4.jsonl.

import itertools
import math
import random

import pytest

from viterbi_equalizer import brute_force, min_distance_bpsk, sequence_metric, viterbi_equalize


def cn(rng, var):
    s = math.sqrt(var / 2)
    return complex(rng.gauss(0, s), rng.gauss(0, s))


def channel_out(f, x, pre):
    mem = len(f) - 1
    full = list(pre) + list(x)
    return [sum(f[l] * full[mem + k - l] for l in range(len(f))) for k in range(len(x))]


def qfunc(x):
    return 0.5 * math.erfc(x / math.sqrt(2))


def wilson(k, n, z=3.29):
    p = k / n
    den = 1 + z * z / n
    mid = (p + z * z / (2 * n)) / den
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / den
    return mid - half, mid + half


def test_example_on_the_page() -> None:
    y = [1.4, 0.1, -1.2, 0.6]
    d = viterbi_equalize(y, [1, 0.5], [1, -1], pre=[1])
    assert d == [1, -1, -1, 1]
    assert abs(sequence_metric(y, [1, 0.5], d, pre=[1]) - 0.47) < 1e-12
    # the symbol-by-symbol slicer on y gets x[1] wrong
    assert [1 if v > 0 else -1 for v in y] == [1, 1, -1, 1]


def test_equals_brute_force_bpsk_with_and_without_tail() -> None:
    rng = random.Random(7501)
    for trial in range(16):
        taps = rng.randint(1, 4)
        f = [rng.gauss(0, 1) for _ in range(taps)]
        pre = [rng.choice((-1, 1)) for _ in range(taps - 1)]
        n = 10
        tail = [rng.choice((-1, 1)) for _ in range(taps - 1)] if trial % 2 else []
        x = [rng.choice((-1, 1)) for _ in range(n)]
        y = [v + rng.gauss(0, 0.8) for v in channel_out(f, x + tail, pre)]
        v = viterbi_equalize(y, f, [1, -1], pre=pre, tail=tail)
        b = brute_force(y, f, [1, -1], pre=pre, tail=tail)
        assert len(v) == n
        assert abs(sequence_metric(y, f, v + tail, pre) - sequence_metric(y, f, b + tail, pre)) < 1e-9
        assert v == b


def test_equals_brute_force_complex_qpsk() -> None:
    rng = random.Random(7502)
    qpsk = [complex(a, b) for a in (-1, 1) for b in (-1, 1)]
    for _ in range(10):
        taps = rng.randint(2, 3)
        f = [cn(rng, 1.0) for _ in range(taps)]
        pre = [rng.choice(qpsk) for _ in range(taps - 1)]
        x = [rng.choice(qpsk) for _ in range(5)]
        y = [v + cn(rng, 1.0) for v in channel_out(f, x, pre)]
        v = viterbi_equalize(y, f, qpsk, pre=pre)
        b = brute_force(y, f, qpsk, pre=pre)
        assert abs(sequence_metric(y, f, v, pre) - sequence_metric(y, f, b, pre)) < 1e-9
        assert v == b


def test_equals_brute_force_4pam() -> None:
    rng = random.Random(7503)
    pam = [3, 1, -1, -3]
    for _ in range(4):
        f = [1.0, rng.uniform(-0.9, 0.9)]
        x = [rng.choice(pam) for _ in range(6)]
        y = [v + rng.gauss(0, 0.7) for v in channel_out(f, x, [3])]
        assert viterbi_equalize(y, f, pam, pre=[3]) == brute_force(y, f, pam, pre=[3])


def test_noiseless_recovery_on_known_channels() -> None:
    rng = random.Random(7504)
    for f in ([1, 0.5], [0.407, 0.815, 0.407], [0.227, 0.460, 0.688, 0.460, 0.227]):
        x = [rng.choice((-1, 1)) for _ in range(300)]
        pre = [1] * (len(f) - 1)
        assert viterbi_equalize(channel_out(f, x, pre), f, [1, -1], pre=pre) == x


def test_minimum_distance_against_short_error_sequences() -> None:
    assert abs(min_distance_bpsk([1, 0.5]) - 5.0) < 1e-12
    for f in ([1, 0.5], [0.407, 0.815, 0.407], [1, -0.9, 0.3]):
        best = float("inf")
        for n in range(1, 9):
            for e in itertools.product((-2, 0, 2), repeat=n):
                if e[0] == 0:
                    continue
                full = [sum(f[l] * e[k - l] for l in range(len(f)) if 0 <= k - l < n) for k in range(n + len(f) - 1)]
                best = min(best, sum(v * v for v in full))
        assert abs(min_distance_bpsk(f) - best) < 1e-12
    # the channel B of Proakis: d_min^2 = 2.6569 against the matched filter bound 4 ||f||^2 = 3.9821
    assert abs(min_distance_bpsk([0.407, 0.815, 0.407]) - 2.656904) < 1e-9


def test_bit_error_rate_is_between_the_matched_filter_bound_and_twice_it() -> None:
    # f = (1, 0.5) has d_min^2 = 4 ||f||^2, so at high SNR the BER is close to Q(sqrt(2 ||f||^2 / N0))
    rng = random.Random(7505)
    f, n0 = [1, 0.5], 0.4
    sigma = math.sqrt(n0 / 2)  # real BPSK: only the real part of CN(0, N0) noise matters
    errors = total = 0
    while total < 60000:
        x = [rng.choice((-1, 1)) for _ in range(200)]
        y = [v + rng.gauss(0, sigma) for v in channel_out(f, x, [1])]
        d = viterbi_equalize(y, f, [1, -1], pre=[1])
        errors += sum(a != b for a, b in zip(d, x))
        total += len(x)
    assert errors >= 100
    lo, hi = wilson(errors, total)
    mfb = qfunc(math.sqrt(2 * 1.25 / n0))
    assert lo >= mfb
    assert hi <= 2 * mfb


def test_input_checks() -> None:
    with pytest.raises(ValueError):
        viterbi_equalize([1, 2], [1, 0.5], [1, -1], pre=[])
    with pytest.raises(ValueError):
        viterbi_equalize([1], [1, 0.5], [1, -1], tail=[1, 1])
    with pytest.raises(ValueError):
        viterbi_equalize([1, 2], [1, 0.5], [1, -1], tail=[3])

History

Viterbi published the algorithm in 1967 to decode convolutional codes. In 1972, Forney showed that the ISI channel is a finite-state machine like a convolutional encoder, that the whitened matched filter gives a discrete-time model with white noise, and that the Viterbi algorithm on this model is the maximum likelihood sequence estimator. He also gave the error event analysis with dmin⁡d_{\min} and showed that for many channels the loss against the matched filter bound is small. In 1974, Ungerboeck gave the same detector on the matched filter output without the whitening filter. Later work reduced the number of states: reduced-state sequence estimation and DDFSE in the late 1980s, and per-survivor processing in the 1990s added channel tracking.

References

  1. G. David Forney, Jr., Maximum-likelihood sequence estimation of digital sequences in the presence of intersymbol interference, IEEE Transactions on Information Theory 18(3), 1972, pages 363 to 378, the discrete-time white-noise model, the ISI trellis with M^(L-1) states and the error event analysis
  2. Andrew J. Viterbi, Error bounds for convolutional codes and an asymptotically optimum decoding algorithm, IEEE Transactions on Information Theory 13(2), 1967, pages 260 to 269, the decoding algorithm
  3. John G. Proakis and Masoud Salehi, Digital Communications, fifth edition, McGraw-Hill, 2008, Section 9.3 (maximum likelihood sequence estimation for the discrete-time white noise model, and its performance)

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