Skip to main content

lib_jsl_dsp/discrete/resampling/
cic.rs

1//! Cascaded integrator-comb (CIC) decimators and interpolators (Hogenauer).
2//!
3//! A CIC filter is `N` cascaded moving sums of length `R·M` built from `N` integrators and `N`
4//! combs (differential delay `M`) with the rate change between them, so it needs no multipliers:
5//! `H(z) = ((1 − z^{−RM}) / (1 − z^{−1}))^N`, magnitude `|sin(πRMf) / sin(πf)|^N` and DC gain
6//! `(RM)^N`. Integer (two's complement) arithmetic is required: the integrators overflow by
7//! design, and the wrap-around cancels exactly in the combs as long as the output itself fits.
8//!
9//! See the book entry [Resampling: polyphase, half-band and CIC filters](https://jwkunz.github.io/lib_jsl/book/spectral/resampling.html#cic-filters).
10
11use lib_jsl_core::ErrorsJSL;
12use std::collections::VecDeque;
13
14fn check(rate: usize, stages: usize, delay: usize) -> Result<(), ErrorsJSL> {
15    if rate == 0 || stages == 0 || delay == 0 {
16        return Err(ErrorsJSL::InvalidInputRange("Rate, stage count and differential delay must be positive."));
17    }
18    Ok(())
19}
20
21/// A comb `y[n] = x[n] − x[n − M]` with wrapping arithmetic.
22#[derive(Debug, Clone)]
23struct Comb {
24    history: VecDeque<i64>,
25}
26
27impl Comb {
28    fn new(delay: usize) -> Self {
29        Comb { history: VecDeque::from(vec![0; delay]) }
30    }
31    fn step(&mut self, x: i64) -> i64 {
32        let old = self.history.pop_front().expect("delay >= 1");
33        self.history.push_back(x);
34        x.wrapping_sub(old)
35    }
36}
37
38/// A CIC decimator by `R`: integrators at the input rate, then combs at the output rate.
39#[derive(Debug, Clone)]
40pub struct CicDecimator {
41    rate: usize,
42    integrators: Vec<i64>,
43    combs: Vec<Comb>,
44    phase: usize,
45    gain: f64,
46}
47
48impl CicDecimator {
49    pub fn new(rate: usize, stages: usize, differential_delay: usize) -> Result<Self, ErrorsJSL> {
50        check(rate, stages, differential_delay)?;
51        Ok(CicDecimator {
52            rate,
53            integrators: vec![0; stages],
54            combs: (0..stages).map(|_| Comb::new(differential_delay)).collect(),
55            phase: 0,
56            gain: ((rate * differential_delay) as f64).powi(stages as i32),
57        })
58    }
59
60    /// The DC gain `(RM)^N`; divide the output by it (or shift by `N·log₂(RM)` bits) to normalise.
61    pub fn gain(&self) -> f64 {
62        self.gain
63    }
64
65    /// Consumes input samples and returns the decimated outputs produced (one per `R` inputs).
66    // ANCHOR: cic
67    pub fn process(&mut self, x: &[i64]) -> Vec<i64> {
68        let mut out = Vec::with_capacity(x.len() / self.rate + 1);
69        for &v in x {
70            let mut acc = v;
71            for integrator in self.integrators.iter_mut() {
72                *integrator = integrator.wrapping_add(acc);
73                acc = *integrator;
74            }
75            self.phase += 1;
76            if self.phase == self.rate {
77                self.phase = 0;
78                out.push(self.combs.iter_mut().fold(acc, |a, comb| comb.step(a)));
79            }
80        }
81        out
82    }
83    // ANCHOR_END: cic
84}
85
86/// A CIC interpolator by `R`: combs at the input rate, zero-stuffing, integrators at the output
87/// rate.
88#[derive(Debug, Clone)]
89pub struct CicInterpolator {
90    rate: usize,
91    integrators: Vec<i64>,
92    combs: Vec<Comb>,
93    gain: f64,
94}
95
96impl CicInterpolator {
97    pub fn new(rate: usize, stages: usize, differential_delay: usize) -> Result<Self, ErrorsJSL> {
98        check(rate, stages, differential_delay)?;
99        Ok(CicInterpolator {
100            rate,
101            integrators: vec![0; stages],
102            combs: (0..stages).map(|_| Comb::new(differential_delay)).collect(),
103            gain: ((rate * differential_delay) as f64).powi(stages as i32) / rate as f64,
104        })
105    }
106
107    /// The DC gain `(RM)^N / R` of the interpolated output.
108    pub fn gain(&self) -> f64 {
109        self.gain
110    }
111
112    /// Returns `R` output samples per input sample.
113    pub fn process(&mut self, x: &[i64]) -> Vec<i64> {
114        let mut out = Vec::with_capacity(x.len() * self.rate);
115        for &v in x {
116            let combed = self.combs.iter_mut().fold(v, |a, comb| comb.step(a));
117            for k in 0..self.rate {
118                let mut acc = if k == 0 { combed } else { 0 };
119                for integrator in self.integrators.iter_mut() {
120                    *integrator = integrator.wrapping_add(acc);
121                    acc = *integrator;
122                }
123                out.push(acc);
124            }
125        }
126        out
127    }
128}
129
130/// The magnitude response of a CIC decimator at frequency `f` in cycles per *input* sample,
131/// normalised to unit DC gain: `|sin(πRMf) / (RM sin(πf))|^N`.
132pub fn cic_magnitude_response(rate: usize, stages: usize, differential_delay: usize, f: f64) -> f64 {
133    let rm = (rate * differential_delay) as f64;
134    let s = (std::f64::consts::PI * f).sin();
135    if s.abs() < 1e-15 {
136        return 1.0;
137    }
138    ((std::f64::consts::PI * rm * f).sin() / (rm * s)).abs().powi(stages as i32)
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    /// N boxcars of length L (exact integer convolution).
146    fn boxcars(x: &[i64], length: usize, stages: usize) -> Vec<i64> {
147        let mut y = x.to_vec();
148        for _ in 0..stages {
149            y = (0..y.len()).map(|n| (0..length).filter(|&k| k <= n).map(|k| y[n - k]).sum()).collect();
150        }
151        y
152    }
153
154    fn signal(n: usize) -> Vec<i64> {
155        (0..n).map(|i| ((i as i64 * 7919) % 2001) - 1000).collect()
156    }
157
158    #[test]
159    fn decimator_equals_cascaded_moving_sums_then_downsampling() {
160        for (r, n, m) in [(4, 3, 1), (8, 4, 2), (5, 1, 1)] {
161            let x = signal(400);
162            let mut cic = CicDecimator::new(r, n, m).unwrap();
163            let y = cic.process(&x);
164            let reference: Vec<i64> = boxcars(&x, r * m, n).into_iter().skip(r - 1).step_by(r).collect();
165            assert_eq!(y, reference, "R={r} N={n} M={m}");
166        }
167    }
168
169    #[test]
170    fn interpolator_equals_zero_stuffing_then_moving_sums() {
171        let (r, n, m) = (4, 3, 1);
172        let x = signal(60);
173        let y = CicInterpolator::new(r, n, m).unwrap().process(&x);
174        let stuffed: Vec<i64> = x.iter().flat_map(|&v| std::iter::once(v).chain(std::iter::repeat_n(0, r - 1))).collect();
175        assert_eq!(y, boxcars(&stuffed, r * m, n));
176    }
177
178    #[test]
179    fn integrator_wrap_around_cancels_and_response_has_nulls() {
180        // DC input of 2³⁰ with gain 256⁴ = 2³²: the integrators overflow i64 many times over, yet
181        // every settled output is exactly 2⁶².
182        let mut cic = CicDecimator::new(256, 4, 1).unwrap();
183        let y = cic.process(&vec![1i64 << 30; 256 * 40]);
184        assert!(y[4..].iter().all(|&v| v == 1i64 << 62), "{:?}", &y[..6]);
185        assert_eq!(cic.gain(), 2f64.powi(32));
186        // Nulls at multiples of the output rate, unit gain at DC, sinc-like droop at the band edge.
187        assert!(cic_magnitude_response(8, 3, 1, 1.0 / 8.0) < 1e-12);
188        assert_eq!(cic_magnitude_response(8, 3, 1, 0.0), 1.0);
189        let droop = cic_magnitude_response(8, 3, 1, 1.0 / 32.0);
190        assert!(droop > 0.6 && droop < 0.75, "{droop}");
191        assert!(CicDecimator::new(0, 1, 1).is_err() && CicInterpolator::new(2, 0, 1).is_err());
192    }
193}