Skip to main content

lib_jsl_dsp/discrete/resampling/
half_band.rs

1//! Half-band filters and factor-of-two decimation and interpolation.
2//!
3//! A half-band low-pass has its cutoff at a quarter of the sample rate and a response symmetric
4//! about it, `H(f) + H(½ − f) = 1`. Its impulse response is then zero at every even offset from
5//! the centre except the centre itself (`½`), so nearly half the taps vanish, and a decimator
6//! or interpolator by two needs only about `N/4` multiplies per output.
7//!
8//! See the book entry [Resampling: polyphase, half-band and CIC filters](https://jwkunz.github.io/lib_jsl/book/spectral/resampling.html#half-band-filters).
9
10use crate::discrete::windows::kaiser::kaiser;
11use lib_jsl_core::ErrorsJSL;
12use std::f64::consts::PI;
13
14/// A half-band low-pass of `num_taps = 4k + 3` taps by the Kaiser-windowed sinc
15/// `h[n] = ½ sinc(n/2) w[n]` (centred). Larger `beta` gives more stopband attenuation and a wider
16/// transition (β ≈ 0.1102 (A − 8.7) for an attenuation of A dB).
17pub fn halfband_lowpass(num_taps: usize, beta: f64) -> Result<Vec<f64>, ErrorsJSL> {
18    if num_taps < 3 || num_taps % 4 != 3 {
19        return Err(ErrorsJSL::InvalidInputRange("A half-band filter needs 4k + 3 taps."));
20    }
21    let window = kaiser(num_taps, beta, true);
22    let centre = (num_taps / 2) as isize;
23    Ok((0..num_taps)
24        .map(|i| {
25            let n = i as isize - centre;
26            let value = if n == 0 {
27                0.5
28            } else if n % 2 == 0 {
29                0.0
30            } else {
31                (PI * n as f64 / 2.0).sin() / (PI * n as f64)
32            };
33            value * window[i]
34        })
35        .collect())
36}
37
38/// Streaming decimation by two with a half-band filter: computes only every other output and
39/// skips the zero taps.
40#[derive(Debug, Clone)]
41pub struct HalfBandDecimator {
42    /// The non-zero odd-offset taps (offsets −c+1, −c+3, …).
43    odd_taps: Vec<(usize, f64)>,
44    centre: usize,
45    centre_tap: f64,
46    history: Vec<f64>,
47    parity: bool,
48}
49
50impl HalfBandDecimator {
51    pub fn new(taps: &[f64]) -> Result<Self, ErrorsJSL> {
52        if taps.len() < 3 || taps.len() % 4 != 3 {
53            return Err(ErrorsJSL::InvalidInputRange("A half-band filter needs 4k + 3 taps."));
54        }
55        let centre = taps.len() / 2;
56        let odd_taps = taps.iter().enumerate().filter(|&(i, _)| (i as isize - centre as isize) % 2 != 0).map(|(i, &t)| (i, t)).collect();
57        Ok(HalfBandDecimator { odd_taps, centre, centre_tap: taps[centre], history: vec![0.0; taps.len()], parity: false })
58    }
59
60    /// Consumes input samples and returns one output per two inputs (`y[m] = (h ∗ x)[2m + 1]`,
61    /// i.e. the full-rate filter output at odd indices).
62    pub fn process(&mut self, x: &[f64]) -> Vec<f64> {
63        let mut out = Vec::with_capacity(x.len() / 2 + 1);
64        for &v in x {
65            self.history.rotate_right(1);
66            self.history[0] = v;
67            self.parity = !self.parity;
68            if !self.parity {
69                // history[k] = x[n − k]; the full-rate output is Σ h[k] x[n − k].
70                let mut y = self.centre_tap * self.history[self.centre];
71                for &(k, t) in &self.odd_taps {
72                    y += t * self.history[k];
73                }
74                out.push(y);
75            }
76        }
77        out
78    }
79}
80
81/// Streaming interpolation by two with a half-band filter (gain two to preserve the level):
82/// the even phase is the delayed input times `2·h_c`, the odd phase uses only the odd taps.
83#[derive(Debug, Clone)]
84pub struct HalfBandInterpolator {
85    taps: Vec<f64>,
86    history: Vec<f64>,
87}
88
89impl HalfBandInterpolator {
90    pub fn new(taps: &[f64]) -> Result<Self, ErrorsJSL> {
91        if taps.len() < 3 || taps.len() % 4 != 3 {
92            return Err(ErrorsJSL::InvalidInputRange("A half-band filter needs 4k + 3 taps."));
93        }
94        Ok(HalfBandInterpolator { taps: taps.to_vec(), history: vec![0.0; taps.len() / 2 + 1] })
95    }
96
97    /// Returns two outputs per input: the full-rate filtered, zero-stuffed signal times two.
98    pub fn process(&mut self, x: &[f64]) -> Vec<f64> {
99        let mut out = Vec::with_capacity(2 * x.len());
100        for &v in x {
101            self.history.rotate_right(1);
102            self.history[0] = v;
103            // Zero-stuffed u[2j] = x[j]; output at 2j uses taps with even index, at 2j+1 odd ones.
104            for phase in 0..2 {
105                let mut y = 0.0;
106                // Output 2j + phase sees x[j − (k − phase)/2] through every tap k ≡ phase (mod 2).
107                for (k, &t) in self.taps.iter().enumerate().skip(phase).step_by(2) {
108                    if t != 0.0 {
109                        y += t * self.history[(k - phase) / 2];
110                    }
111                }
112                out.push(2.0 * y);
113            }
114        }
115        out
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    fn response(h: &[f64], f: f64) -> f64 {
124        let (re, im) = h.iter().enumerate().fold((0.0, 0.0), |(r, i), (n, &t)| (r + t * (2.0 * PI * f * n as f64).cos(), i - t * (2.0 * PI * f * n as f64).sin()));
125        (re * re + im * im).sqrt()
126    }
127
128    fn convolve(x: &[f64], h: &[f64]) -> Vec<f64> {
129        (0..x.len()).map(|n| (0..h.len()).filter(|&k| k <= n).map(|k| h[k] * x[n - k]).sum()).collect()
130    }
131
132    #[test]
133    fn design_has_the_half_band_structure() {
134        let h = halfband_lowpass(31, 8.0).unwrap();
135        let c = h.len() / 2;
136        assert_eq!(h[c], 0.5);
137        assert!((0..h.len()).filter(|&i| i != c && (i as isize - c as isize) % 2 == 0).all(|i| h[i] == 0.0));
138        assert!((response(&h, 0.25) - 0.5).abs() < 1e-12);
139        for f in [0.02, 0.1, 0.17] {
140            assert!((response(&h, f) + response(&h, 0.5 - f) - 1.0).abs() < 1e-3, "f={f}");
141        }
142        assert!(response(&h, 0.4) < 1e-3 && (response(&h, 0.05) - 1.0).abs() < 1e-3);
143        assert!(halfband_lowpass(29, 8.0).is_err());
144    }
145
146    #[test]
147    fn decimator_and_interpolator_match_full_rate_filtering() {
148        let h = halfband_lowpass(23, 7.0).unwrap();
149        let x: Vec<f64> = (0..300).map(|i| (0.05 * i as f64).sin() + 0.3 * ((i * 13) % 7) as f64).collect();
150        let full = convolve(&x, &h);
151        let mut decimator = HalfBandDecimator::new(&h).unwrap();
152        let mut y = decimator.process(&x[..101]);
153        y.extend(decimator.process(&x[101..]));
154        let reference: Vec<f64> = full.iter().skip(1).step_by(2).copied().collect();
155        assert_eq!(y.len(), reference.len());
156        assert!(y.iter().zip(&reference).all(|(a, b)| (a - b).abs() < 1e-12));
157        let up = HalfBandInterpolator::new(&h).unwrap().process(&x[..50]);
158        let stuffed: Vec<f64> = x[..50].iter().flat_map(|&v| [v, 0.0]).collect();
159        let reference: Vec<f64> = convolve(&stuffed, &h).iter().map(|v| 2.0 * v).collect();
160        assert!(up.iter().zip(&reference).all(|(a, b)| (a - b).abs() < 1e-12));
161        assert!(HalfBandDecimator::new(&h[..5]).is_err());
162    }
163}