Skip to main content

lib_jsl_dsp/discrete/digital_communications/
decision_feedback_equalizer.rs

1//! Decision feedback equalizer (DFE).
2//!
3//! A channel with memory smears each symbol over its neighbours (inter-symbol interference).
4//! A plain linear equalizer fights this by inverting the channel, which amplifies noise where the
5//! channel is weak. The DFE has two parts:
6//!
7//! - a **feed-forward** filter over recent received samples, which handles *pre-cursor* ISI and
8//!   shapes the signal;
9//! - a **feedback** filter over the receiver's own *past decisions*, which subtracts the
10//!   *post-cursor* ISI exactly. Because it works from clean, already-decided symbols rather than
11//!   noisy samples, it cancels interference without enhancing noise.
12//!
13//! The output before the slicer is `y[n] = Σ w_ff[k] x[n-k] + Σ w_fb[k] d[n-1-k]`, where
14//! `e = d − y` is the error against the target symbol. The target is a known training symbol, or
15//! (once converged) the slicer's own decision, which is *decision-directed* operation. For a
16//! causal channel `h = [1, h₁, h₂, …]` the feedback taps converge to `−h₁, −h₂, …`.
17//!
18//! Two adaptation algorithms are offered:
19//!
20//! - **NLMS** (`w ← w + μ e conj(u) / (ε + ‖u‖²)`): cheap (`O(M)` per symbol) and robust, but its
21//!   convergence along weakly excited directions is slow, and ISI makes the regressor strongly
22//!   correlated, so it can need thousands of symbols.
23//! - **RLS** (recursive least squares with forgetting factor `λ`): `O(M²)` per symbol but converges
24//!   in a few multiples of `M` symbols regardless of the channel, which is why it is the usual
25//!   choice for training.
26//!
27//! Error propagation (a wrong decision corrupting the next few outputs) is the DFE's known weakness
28//! and is why training first, at a good signal-to-noise ratio, matters.
29//!
30//! See the book entry [Channels and equalisation](https://jwkunz.github.io/lib_jsl/book/comms/equalisation.html#the-decision-feedback-equalizer).
31
32use super::constellations::Constellation;
33use crate::discrete::stream_operator::{StreamOperator, StreamOperatorManagement};
34use lib_jsl_core::ErrorsJSL;
35use num_complex::Complex;
36
37/// How the equalizer adapts its weights.
38#[derive(Clone, Debug)]
39enum Adaptation {
40    Nlms { step_size: f64 },
41    Rls { forgetting: f64, p: Vec<Vec<Complex<f64>>> },
42}
43
44/// An adaptive decision feedback equalizer for complex symbols.
45#[derive(Clone, Debug)]
46pub struct DecisionFeedbackEqualizer {
47    constellation: Constellation,
48    main_tap: usize,
49    forward_len: usize,
50    adaptation: Adaptation,
51    /// Weights: the feed-forward taps followed by the feedback taps.
52    weights: Vec<Complex<f64>>,
53    /// Regressor: recent received samples then recent decisions, each newest first.
54    regressor: Vec<Complex<f64>>,
55}
56
57const REGULARIZATION: f64 = 1e-6;
58/// Initial inverse-correlation scale for RLS (large = trust the data quickly).
59const RLS_INITIAL_P: f64 = 100.0;
60
61impl DecisionFeedbackEqualizer {
62    /// An NLMS equalizer with `forward_taps >= 1` and `feedback_taps >= 0` taps, step size
63    /// `0 < step_size < 2` (0.01 to 0.2 is typical), deciding on `constellation`. The feed-forward
64    /// main tap starts at index 0, so the output at time `n` estimates the symbol that arrived
65    /// with sample `n`.
66    pub fn new(constellation: Constellation, forward_taps: usize, feedback_taps: usize, step_size: f64) -> Result<Self, ErrorsJSL> {
67        Self::with_main_tap(constellation, forward_taps, feedback_taps, step_size, 0)
68    }
69
70    /// Like [`new`](Self::new) but with the feed-forward main tap initialised at `main_tap`, so
71    /// that `main_tap` samples of pre-cursor ISI can be handled; the output then estimates the
72    /// symbol that arrived `main_tap` samples earlier.
73    pub fn with_main_tap(constellation: Constellation, forward_taps: usize, feedback_taps: usize, step_size: f64, main_tap: usize) -> Result<Self, ErrorsJSL> {
74        if !(step_size > 0.0 && step_size < 2.0) {
75            return Err(ErrorsJSL::InvalidInputRange("NLMS step size must be in (0, 2)"));
76        }
77        Self::build(constellation, forward_taps, feedback_taps, main_tap, Adaptation::Nlms { step_size })
78    }
79
80    /// An RLS equalizer with forgetting factor `0.9 <= forgetting <= 1` (0.995 to 0.9995 is
81    /// typical; 1 weights all history equally). Converges in a few multiples of the total tap count.
82    pub fn new_rls(constellation: Constellation, forward_taps: usize, feedback_taps: usize, forgetting: f64) -> Result<Self, ErrorsJSL> {
83        Self::with_main_tap_rls(constellation, forward_taps, feedback_taps, forgetting, 0)
84    }
85
86    /// Like [`new_rls`](Self::new_rls) with the feed-forward main tap at `main_tap`.
87    pub fn with_main_tap_rls(constellation: Constellation, forward_taps: usize, feedback_taps: usize, forgetting: f64, main_tap: usize) -> Result<Self, ErrorsJSL> {
88        if !(0.9..=1.0).contains(&forgetting) {
89            return Err(ErrorsJSL::InvalidInputRange("RLS forgetting factor must be in [0.9, 1]"));
90        }
91        let m = forward_taps + feedback_taps;
92        let mut p = vec![vec![Complex::new(0.0, 0.0); m]; m];
93        for (i, row) in p.iter_mut().enumerate() {
94            row[i] = Complex::new(RLS_INITIAL_P, 0.0);
95        }
96        Self::build(constellation, forward_taps, feedback_taps, main_tap, Adaptation::Rls { forgetting, p })
97    }
98
99    fn build(constellation: Constellation, forward_taps: usize, feedback_taps: usize, main_tap: usize, adaptation: Adaptation) -> Result<Self, ErrorsJSL> {
100        if forward_taps == 0 || main_tap >= forward_taps {
101            return Err(ErrorsJSL::InvalidInputRange("Need at least one feed-forward tap and main_tap < forward_taps"));
102        }
103        let total = forward_taps + feedback_taps;
104        let mut weights = vec![Complex::new(0.0, 0.0); total];
105        weights[main_tap] = Complex::new(1.0, 0.0);
106        Ok(DecisionFeedbackEqualizer { constellation, main_tap, forward_len: forward_taps, adaptation, weights, regressor: vec![Complex::new(0.0, 0.0); total] })
107    }
108
109    pub fn forward_taps(&self) -> &[Complex<f64>] {
110        &self.weights[..self.forward_len]
111    }
112
113    /// The feedback taps; for a causal channel they converge to minus the post-cursor ISI.
114    pub fn feedback_taps(&self) -> &[Complex<f64>] {
115        &self.weights[self.forward_len..]
116    }
117
118    /// The main tap index (the equalizer's decision delay in samples).
119    pub fn main_tap(&self) -> usize {
120        self.main_tap
121    }
122
123    /// Processes one received sample. With `Some(target)` the equalizer trains on that symbol;
124    /// with `None` it uses its own decision. Returns `(equalized sample, decision)`.
125    pub fn equalize_sample(&mut self, x: Complex<f64>, target: Option<Complex<f64>>) -> (Complex<f64>, Complex<f64>) {
126        // ANCHOR: dfe
127        let fl = self.forward_len;
128        // Shift the received-sample part of the regressor and insert the new sample.
129        self.regressor[..fl].rotate_right(1);
130        self.regressor[0] = x;
131        let y: Complex<f64> = self.weights.iter().zip(&self.regressor).map(|(w, u)| w * u).sum();
132        let decision = self.constellation.slice(y);
133        let desired = target.unwrap_or(decision);
134        let error = desired - y;
135        match &mut self.adaptation {
136            Adaptation::Nlms { step_size } => {
137                let power: f64 = self.regressor.iter().map(|v| v.norm_sqr()).sum();
138                let gain = *step_size / (REGULARIZATION + power);
139                for (w, u) in self.weights.iter_mut().zip(&self.regressor) {
140                    *w += error * u.conj() * gain;
141                }
142            }
143            Adaptation::Rls { forgetting, p } => {
144                let m = self.weights.len();
145                // pq = P conj(u); denominator = lambda + u^T P conj(u).
146                let q: Vec<Complex<f64>> = self.regressor.iter().map(|u| u.conj()).collect();
147                let pq: Vec<Complex<f64>> = (0..m).map(|i| (0..m).map(|j| p[i][j] * q[j]).sum()).collect();
148                let denom = *forgetting + self.regressor.iter().zip(&pq).map(|(u, v)| u * v).sum::<Complex<f64>>();
149                let k: Vec<Complex<f64>> = pq.iter().map(|v| v / denom).collect();
150                for (w, ki) in self.weights.iter_mut().zip(&k) {
151                    *w += ki * error;
152                }
153                // P <- (P - k u^T P) / lambda, where u^T P is the row vector with entries sum_i u_i P[i][j].
154                let utp: Vec<Complex<f64>> = (0..m).map(|j| (0..m).map(|i| self.regressor[i] * p[i][j]).sum()).collect();
155                for i in 0..m {
156                    for j in 0..m {
157                        p[i][j] = (p[i][j] - k[i] * utp[j]) / *forgetting;
158                    }
159                }
160            }
161        }
162        // Shift the decision part of the regressor, feeding back the target while training.
163        if self.regressor.len() > fl {
164            self.regressor[fl..].rotate_right(1);
165            self.regressor[fl] = desired;
166        }
167        (y, decision)
168        // ANCHOR_END: dfe
169    }
170
171    /// Trains on known symbols: `targets[i]` is the desired output for `received[i]` (when the
172    /// main tap is nonzero, shift the targets by that delay). Returns the squared error of each
173    /// step so convergence can be inspected.
174    pub fn train(&mut self, received: &[Complex<f64>], targets: &[Complex<f64>]) -> Result<Vec<f64>, ErrorsJSL> {
175        if received.len() != targets.len() {
176            return Err(ErrorsJSL::IncompatibleArraySizes((received.len(), targets.len())));
177        }
178        Ok(received
179            .iter()
180            .zip(targets)
181            .map(|(&x, &t)| {
182                let (y, _) = self.equalize_sample(x, Some(t));
183                (t - y).norm_sqr()
184            })
185            .collect())
186    }
187}
188
189impl StreamOperatorManagement for DecisionFeedbackEqualizer {
190    /// Clears the delay lines and restarts the weights (a fresh equalizer).
191    fn reset(&mut self) -> Result<(), ErrorsJSL> {
192        self.regressor.iter_mut().for_each(|v| *v = Complex::new(0.0, 0.0));
193        self.weights.iter_mut().for_each(|v| *v = Complex::new(0.0, 0.0));
194        self.weights[self.main_tap] = Complex::new(1.0, 0.0);
195        if let Adaptation::Rls { p, .. } = &mut self.adaptation {
196            for (i, row) in p.iter_mut().enumerate() {
197                row.iter_mut().for_each(|v| *v = Complex::new(0.0, 0.0));
198                row[i] = Complex::new(RLS_INITIAL_P, 0.0);
199            }
200        }
201        Ok(())
202    }
203
204    fn finalize(&mut self) -> Result<(), ErrorsJSL> {
205        Ok(())
206    }
207}
208
209/// Decision-directed streaming: each input sample yields the equalized (pre-slicer) sample.
210impl StreamOperator<Complex<f64>, Complex<f64>> for DecisionFeedbackEqualizer {
211    fn process(&mut self, data_in: &[Complex<f64>]) -> Result<Option<Vec<Complex<f64>>>, ErrorsJSL> {
212        if data_in.is_empty() {
213            return Ok(None);
214        }
215        Ok(Some(data_in.iter().map(|&x| self.equalize_sample(x, None).0).collect()))
216    }
217
218    fn flush(&mut self) -> Result<Option<Vec<Complex<f64>>>, ErrorsJSL> {
219        Ok(None)
220    }
221}
222
223/// Builds an equalizer, trains it on the first `training.len()` symbols of `received` against the
224/// known `training` symbols, then equalizes the rest decision-directed. Returns the equalized
225/// samples for the whole record.
226pub fn decision_feedback_equalizer(
227    received: &[Complex<f64>],
228    training: &[Complex<f64>],
229    constellation: Constellation,
230    forward_taps: usize,
231    feedback_taps: usize,
232    step_size: f64,
233) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
234    if training.len() > received.len() {
235        return Err(ErrorsJSL::IncompatibleArraySizes((training.len(), received.len())));
236    }
237    let mut eq = DecisionFeedbackEqualizer::new(constellation, forward_taps, feedback_taps, step_size)?;
238    let mut out = Vec::with_capacity(received.len());
239    for (i, &x) in received.iter().enumerate() {
240        out.push(eq.equalize_sample(x, training.get(i).copied()).0);
241    }
242    Ok(out)
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    fn lcg(seed: &mut u64) -> f64 {
250        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
251        ((*seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5
252    }
253
254    fn gauss(seed: &mut u64) -> f64 {
255        (0..12).map(|_| lcg(seed)).sum::<f64>()
256    }
257
258    fn symbols(c: &Constellation, n: usize, seed: &mut u64) -> Vec<Complex<f64>> {
259        (0..n).map(|_| c.points()[((lcg(seed) + 0.5) * c.size() as f64) as usize % c.size()]).collect()
260    }
261
262    fn through_channel(x: &[Complex<f64>], h: &[Complex<f64>], noise: f64, seed: &mut u64) -> Vec<Complex<f64>> {
263        (0..x.len())
264            .map(|n| {
265                let s: Complex<f64> = h.iter().enumerate().filter(|(k, _)| *k <= n).map(|(k, c)| c * x[n - k]).sum();
266                s + Complex::new(gauss(seed), gauss(seed)) * noise
267            })
268            .collect()
269    }
270
271    fn errors(c: &Constellation, y: &[Complex<f64>], want: &[Complex<f64>]) -> usize {
272        y.iter().zip(want).filter(|(a, b)| c.slice(**a) != **b).count()
273    }
274
275    #[test]
276    fn cancels_post_cursor_isi_and_learns_the_negated_channel_taps() {
277        let c = Constellation::qpsk();
278        let mut seed = 3;
279        let h = [Complex::new(1.0, 0.0), Complex::new(0.5, 0.2), Complex::new(-0.3, 0.1)];
280        let tx = symbols(&c, 10_000, &mut seed);
281        let rx = through_channel(&tx, &h, 0.02, &mut seed);
282        // The uncompensated channel makes many errors.
283        assert!(errors(&c, &rx[3000..], &tx[3000..]) > 100);
284
285        let mut eq = DecisionFeedbackEqualizer::new_rls(c.clone(), 3, 2, 0.9995).unwrap();
286        let mse = eq.train(&rx[..3000], &tx[..3000]).unwrap();
287        let early: f64 = mse[..20].iter().sum::<f64>() / 20.0;
288        let late: f64 = mse[2900..].iter().sum::<f64>() / 100.0;
289        assert!(late < early * 0.05 && late < 2e-3, "MSE {early} -> {late}");
290        // Feedback taps converge to minus the post-cursors; the first forward tap to ~1.
291        let fb = eq.feedback_taps();
292        assert!((fb[0] + h[1]).norm() < 0.02 && (fb[1] + h[2]).norm() < 0.02, "{fb:?}");
293        assert!((eq.forward_taps()[0] - Complex::new(1.0, 0.0)).norm() < 0.02, "{:?}", eq.forward_taps());
294        // Now decision-directed on the rest: no symbol errors.
295        let y = eq.process(&rx[3000..]).unwrap().unwrap();
296        assert_eq!(errors(&c, &y, &tx[3000..]), 0);
297    }
298
299    #[test]
300    fn rls_converges_where_nlms_is_still_crawling() {
301        // The ISI makes the regressor ill-conditioned (eigenvalue spread in the hundreds), so NLMS
302        // learns the weakly excited directions very slowly; RLS is unaffected.
303        let c = Constellation::qpsk();
304        let mut seed = 31;
305        let h = [Complex::new(1.0, 0.0), Complex::new(0.5, 0.2), Complex::new(-0.3, 0.1)];
306        let tx = symbols(&c, 1500, &mut seed);
307        let rx = through_channel(&tx, &h, 0.01, &mut seed);
308        let tap_error = |eq: &DecisionFeedbackEqualizer| (eq.feedback_taps()[0] + h[1]).norm() + (eq.feedback_taps()[1] + h[2]).norm();
309        let mut rls = DecisionFeedbackEqualizer::new_rls(c.clone(), 3, 2, 0.999).unwrap();
310        let mut nlms = DecisionFeedbackEqualizer::new(c, 3, 2, 0.05).unwrap();
311        rls.train(&rx, &tx).unwrap();
312        nlms.train(&rx, &tx).unwrap();
313        assert!(tap_error(&rls) < 0.02, "RLS tap error {}", tap_error(&rls));
314        assert!(tap_error(&nlms) > 5.0 * tap_error(&rls), "NLMS {} vs RLS {}", tap_error(&nlms), tap_error(&rls));
315    }
316
317    #[test]
318    fn nlms_still_equalizes_adequately_for_decision_making() {
319        let c = Constellation::qpsk();
320        let mut seed = 17;
321        let h = [Complex::new(1.0, 0.0), Complex::new(0.5, 0.2), Complex::new(-0.3, 0.1)];
322        let tx = symbols(&c, 12_000, &mut seed);
323        let rx = through_channel(&tx, &h, 0.02, &mut seed);
324        let mut eq = DecisionFeedbackEqualizer::new(c.clone(), 3, 2, 0.1).unwrap();
325        let mse = eq.train(&rx[..6000], &tx[..6000]).unwrap();
326        let early: f64 = mse[..100].iter().sum::<f64>() / 100.0;
327        let late: f64 = mse[5900..].iter().sum::<f64>() / 100.0;
328        assert!(late < early * 0.05, "MSE {early} -> {late}");
329        let y = eq.process(&rx[6000..]).unwrap().unwrap();
330        assert_eq!(errors(&c, &y, &tx[6000..]), 0);
331    }
332
333    #[test]
334    fn handles_pre_cursor_isi_with_a_delayed_main_tap() {
335        let c = Constellation::qpsk();
336        let mut seed = 5;
337        // Precursor 0.35, main 1.0, post-cursors 0.4 and -0.2.
338        let h = [Complex::new(0.35, 0.0), Complex::new(1.0, 0.0), Complex::new(0.4, 0.0), Complex::new(-0.2, 0.0)];
339        let tx = symbols(&c, 9000, &mut seed);
340        let rx = through_channel(&tx, &h, 0.02, &mut seed);
341        let delay = 1; // the main path is the second tap, so the output lags the input by 1
342        let mut eq = DecisionFeedbackEqualizer::with_main_tap_rls(c.clone(), 5, 2, 0.999, delay).unwrap();
343        // The output at step n estimates the symbol sent at n - delay.
344        let targets: Vec<Complex<f64>> = (0..2000).map(|n| if n >= delay { tx[n - delay] } else { Complex::new(0.0, 0.0) }).collect();
345        eq.train(&rx[..2000], &targets[..2000]).unwrap();
346        let y = eq.process(&rx[2000..]).unwrap().unwrap();
347        let want: Vec<Complex<f64>> = (2000..9000).map(|n| tx[n - delay]).collect();
348        assert_eq!(errors(&c, &y, &want), 0);
349        assert_eq!(eq.main_tap(), 1);
350    }
351
352    #[test]
353    fn works_with_a_qam_constellation_and_the_one_shot_helper() {
354        let c = Constellation::qam(16).unwrap();
355        let mut seed = 9;
356        let h = [Complex::new(1.0, 0.0), Complex::new(0.25, -0.1)];
357        let tx = symbols(&c, 10_000, &mut seed);
358        let rx = through_channel(&tx, &h, 0.01, &mut seed);
359        let y = decision_feedback_equalizer(&rx, &tx[..3000], c.clone(), 3, 3, 0.1).unwrap();
360        assert_eq!(y.len(), rx.len());
361        assert_eq!(errors(&c, &y[6000..], &tx[6000..]), 0);
362        assert!(decision_feedback_equalizer(&rx[..10], &tx[..20], c, 3, 3, 0.03).is_err());
363    }
364
365    #[test]
366    fn without_isi_the_equalizer_leaves_the_signal_alone() {
367        let c = Constellation::bpsk();
368        let mut seed = 2;
369        let tx = symbols(&c, 500, &mut seed);
370        let mut eq = DecisionFeedbackEqualizer::new(c.clone(), 2, 2, 0.1).unwrap();
371        let y = eq.process(&tx).unwrap().unwrap();
372        assert!(y.iter().zip(&tx).all(|(a, b)| (a - b).norm() < 1e-9));
373        assert!(eq.feedback_taps().iter().all(|w| w.norm() < 1e-9));
374    }
375
376    #[test]
377    fn reset_restores_the_initial_weights_and_streaming_is_chunk_independent() {
378        let c = Constellation::qpsk();
379        let mut seed = 12;
380        let h = [Complex::new(1.0, 0.0), Complex::new(0.4, 0.0)];
381        let tx = symbols(&c, 800, &mut seed);
382        let rx = through_channel(&tx, &h, 0.01, &mut seed);
383        let make = || DecisionFeedbackEqualizer::new(c.clone(), 3, 2, 0.05).unwrap();
384        let whole = make().process(&rx).unwrap().unwrap();
385        let mut eq = make();
386        let mut parts = Vec::new();
387        for ch in rx.chunks(33) {
388            parts.extend(eq.process(ch).unwrap().unwrap());
389        }
390        assert!(whole.iter().zip(&parts).all(|(a, b)| (a - b).norm() < 1e-12));
391        StreamOperatorManagement::reset(&mut eq).unwrap();
392        assert!(eq.feedback_taps().iter().all(|w| w.norm() == 0.0));
393        assert_eq!(eq.forward_taps()[0], Complex::new(1.0, 0.0));
394        assert!(eq.process(&[]).unwrap().is_none() && eq.flush().unwrap().is_none());
395    }
396
397    #[test]
398    fn invalid_parameters() {
399        let c = Constellation::bpsk();
400        assert!(DecisionFeedbackEqualizer::new(c.clone(), 0, 2, 0.1).is_err());
401        assert!(DecisionFeedbackEqualizer::new(c.clone(), 3, 2, 0.0).is_err());
402        assert!(DecisionFeedbackEqualizer::new(c.clone(), 3, 2, 2.0).is_err());
403        assert!(DecisionFeedbackEqualizer::with_main_tap(c.clone(), 3, 2, 0.1, 3).is_err());
404        assert!(DecisionFeedbackEqualizer::new_rls(c.clone(), 3, 2, 0.5).is_err());
405        assert!(DecisionFeedbackEqualizer::new_rls(c.clone(), 3, 2, 1.1).is_err());
406        assert!(DecisionFeedbackEqualizer::new_rls(c.clone(), 0, 2, 0.99).is_err());
407        let mut eq = DecisionFeedbackEqualizer::new(c, 3, 0, 0.1).unwrap();
408        assert!(eq.train(&[Complex::new(1.0, 0.0)], &[]).is_err());
409        assert!(eq.feedback_taps().is_empty());
410    }
411}