Skip to main content

lib_jsl_dsp/discrete/spectral/
freqz.rs

1//! Frequency-response utility similar to `scipy.signal.freqz`.
2//!
3//! This implementation computes the complex frequency response of a digital
4//! filter described by numerator coefficients `b` and denominator coefficients
5//! `a`:
6//!
7//! `H(e^{jw}) = (b[0] + b[1] e^{-jw} + ... + b[M] e^{-jwM}) /`
8//! `            (a[0] + a[1] e^{-jw} + ... + a[N] e^{-jwN})`
9//!
10//! The public API follows the most commonly used parts of SciPy's `freqz`:
11//! - integer `worN` for an automatically generated grid
12//! - explicit frequency arrays
13//! - `whole`
14//! - `fs`
15//! - `include_nyquist`
16//!
17//! Unlike the current SciPy `whole=True` behavior, this implementation returns
18//! the full-circle frequency axis in ascending order from `-fs/2` to values
19//! just below `fs/2`. This keeps the frequency axis sorted from lowest to
20//! highest while still covering the whole unit circle.
21//!
22//! See the book entry [Digital IIR design by the bilinear transform](https://jwkunz.github.io/lib_jsl/book/filters/iir-design.html#evaluating-the-response).
23
24use std::f64::consts::PI;
25
26use ndarray::Array1;
27use num_complex::Complex;
28
29use lib_jsl_core::{C1D, ErrorsJSL, IsAnalytic, R1D};
30
31#[derive(Clone, Debug, PartialEq)]
32#[non_exhaustive]
33pub struct FreqzResult {
34    /// Frequency axis in the same units as `fs`.
35    pub w: R1D,
36    /// Complex frequency response evaluated at each frequency in `w`.
37    pub h: C1D,
38}
39
40#[derive(Clone, Debug, PartialEq)]
41pub enum FreqzWorN {
42    /// Generate a uniform frequency grid with the given number of points.
43    NumPoints(usize),
44    /// Evaluate at the explicitly provided frequencies, expressed in the same
45    /// units as `fs`.
46    Frequencies(Vec<f64>),
47}
48
49fn validate_fs(fs: f64) -> Result<(), ErrorsJSL> {
50    if !fs.is_finite() || fs <= 0.0 {
51        return Err(ErrorsJSL::InvalidInputRange("fs must be finite and > 0"));
52    }
53    Ok(())
54}
55
56fn validate_coefficients<T: IsAnalytic>(b: &[T], a: &[T]) -> Result<(), ErrorsJSL> {
57    if b.is_empty() {
58        return Err(ErrorsJSL::InvalidInputRange(
59            "numerator coefficients must be non-empty",
60        ));
61    }
62    if a.is_empty() {
63        return Err(ErrorsJSL::InvalidInputRange(
64            "denominator coefficients must be non-empty",
65        ));
66    }
67    Ok(())
68}
69
70fn build_frequency_grid(
71    wor_n: Option<FreqzWorN>,
72    whole: bool,
73    fs: f64,
74    include_nyquist: bool,
75) -> Result<R1D, ErrorsJSL> {
76    match wor_n.unwrap_or(FreqzWorN::NumPoints(512)) {
77        FreqzWorN::NumPoints(n) => {
78            if n == 0 {
79                return Err(ErrorsJSL::InvalidInputRange("worN must be > 0"));
80            }
81
82            let values = if whole {
83                let step = fs / n as f64;
84                (0..n)
85                    .map(|k| -0.5 * fs + k as f64 * step)
86                    .collect::<Vec<_>>()
87            } else if n == 1 {
88                vec![0.0]
89            } else {
90                let stop = 0.5 * fs;
91                let denom = if include_nyquist {
92                    (n - 1) as f64
93                } else {
94                    n as f64
95                };
96                (0..n)
97                    .map(|k| stop * k as f64 / denom)
98                    .collect::<Vec<_>>()
99            };
100
101            Ok(Array1::from_vec(values))
102        }
103        FreqzWorN::Frequencies(w) => {
104            if w.is_empty() {
105                return Err(ErrorsJSL::InvalidInputRange(
106                    "frequency array must be non-empty",
107                ));
108            }
109            if w.iter().any(|x| !x.is_finite()) {
110                return Err(ErrorsJSL::InvalidInputRange(
111                    "frequency array values must be finite",
112                ));
113            }
114            Ok(Array1::from_vec(w))
115        }
116    }
117}
118
119fn eval_response_at<T: IsAnalytic>(b: &[T], a: &[T], omega: f64) -> Result<Complex<f64>, ErrorsJSL> {
120    let z_inv = Complex::from_polar(1.0, -omega);
121
122    let mut zk = Complex::new(1.0, 0.0);
123    let mut num = Complex::new(0.0, 0.0);
124    for coeff in b {
125        num += coeff.to_complex() * zk;
126        zk *= z_inv;
127    }
128
129    zk = Complex::new(1.0, 0.0);
130    let mut den = Complex::new(0.0, 0.0);
131    for coeff in a {
132        den += coeff.to_complex() * zk;
133        zk *= z_inv;
134    }
135
136    if den.norm_sqr() <= 1e-24 {
137        return Err(ErrorsJSL::RuntimeError(
138            "frequency response undefined because denominator is zero",
139        ));
140    }
141
142    Ok(num / den)
143}
144
145/// Compute the frequency response of a digital filter.
146///
147/// Arguments:
148/// - `b`: numerator coefficients
149/// - `a`: optional denominator coefficients; defaults to `[1]` when omitted
150/// - `wor_n`: optional frequency-grid specification; defaults to 512 points
151/// - `whole`: optional; defaults to `false`. When `true` and `wor_n` is an
152///   integer, evaluate the whole unit circle and return the axis in ascending
153///   order on `[-fs/2, fs/2)`
154/// - `fs`: sampling frequency used for the returned axis units; defaults to
155///   `2*pi`, matching SciPy's radians/sample convention
156/// - `include_nyquist`: optional; defaults to `true`. Only used for
157///   non-`whole` integer grids
158///
159/// Notes:
160/// - If `wor_n` is `FreqzWorN::Frequencies`, the explicit frequencies are used
161///   as-is and `whole` is ignored, matching SciPy's behavior.
162/// - This implementation does not include SciPy's plotting callback.
163pub fn freqz<T: IsAnalytic>(
164    b: &[T],
165    a: Option<&[T]>,
166    wor_n: Option<FreqzWorN>,
167    whole: Option<bool>,
168    fs: Option<f64>,
169    include_nyquist: Option<bool>,
170) -> Result<FreqzResult, ErrorsJSL> {
171    let default_a = [T::one()];
172    let a = a.unwrap_or(&default_a);
173    let whole = whole.unwrap_or(false);
174    let fs = fs.unwrap_or(2.0 * PI);
175    let include_nyquist = include_nyquist.unwrap_or(true);
176
177    validate_fs(fs)?;
178    validate_coefficients(b, a)?;
179
180    let w = build_frequency_grid(wor_n, whole, fs, include_nyquist)?;
181    let mut h = Vec::with_capacity(w.len());
182    for &freq in &w {
183        let omega = (2.0 * PI / fs) * freq;
184        h.push(eval_response_at(b, a, omega)?);
185    }
186
187    Ok(FreqzResult {
188        w,
189        h: Array1::from_vec(h),
190    })
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    fn assert_close_complex(a: Complex<f64>, b: Complex<f64>, tol: f64) {
198        assert!(
199            (a - b).norm() < tol,
200            "left={a}, right={b}, tol={tol}"
201        );
202    }
203
204    #[test]
205    fn test_freqz_identity_filter_is_flat() {
206        let result = freqz(&[1.0], None, Some(FreqzWorN::NumPoints(8)), None, None, None)
207            .unwrap();
208
209        assert_eq!(result.w.len(), 8);
210        assert_eq!(result.h.len(), 8);
211        for &h in &result.h {
212            assert_close_complex(h, Complex::new(1.0, 0.0), 1e-12);
213        }
214    }
215
216    #[test]
217    fn test_freqz_include_nyquist_hits_pi_for_default_fs() {
218        let result = freqz(&[1.0], None, Some(FreqzWorN::NumPoints(5)), None, None, None)
219            .unwrap();
220
221        assert!((result.w[0] - 0.0).abs() < 1e-12);
222        assert!((result.w[result.w.len() - 1] - PI).abs() < 1e-12);
223    }
224
225    #[test]
226    fn test_freqz_whole_returns_sorted_axis() {
227        let fs = 20.0;
228        let result = freqz(
229            &[1.0, -1.0],
230            None,
231            Some(FreqzWorN::NumPoints(8)),
232            Some(true),
233            Some(fs),
234            None,
235        )
236        .unwrap();
237
238        let expected = vec![-10.0, -7.5, -5.0, -2.5, 0.0, 2.5, 5.0, 7.5];
239        assert_eq!(result.w.to_vec(), expected);
240        for pair in result.w.iter().zip(result.w.iter().skip(1)) {
241            assert!(pair.0 < pair.1);
242        }
243    }
244
245    #[test]
246    fn test_freqz_whole_reorders_response_with_sorted_axis() {
247        let result = freqz(
248            &[1.0, 1.0],
249            None,
250            Some(FreqzWorN::NumPoints(4)),
251            Some(true),
252            None,
253            None,
254        )
255        .unwrap();
256
257        assert_eq!(result.w.to_vec(), vec![-PI, -PI / 2.0, 0.0, PI / 2.0]);
258        assert_close_complex(result.h[0], Complex::new(0.0, 0.0), 1e-12);
259        assert_close_complex(result.h[1], Complex::new(1.0, 1.0), 1e-12);
260        assert_close_complex(result.h[2], Complex::new(2.0, 0.0), 1e-12);
261        assert_close_complex(result.h[3], Complex::new(1.0, -1.0), 1e-12);
262    }
263
264    #[test]
265    fn test_freqz_explicit_frequency_array() {
266        let freqs = vec![0.0, PI / 2.0, PI];
267        let result = freqz(
268            &[1.0],
269            Some(&[1.0, -0.5]),
270            Some(FreqzWorN::Frequencies(freqs.clone())),
271            Some(true),
272            None,
273            None,
274        )
275        .unwrap();
276
277        assert_eq!(result.w.to_vec(), freqs);
278        assert_close_complex(result.h[0], Complex::new(2.0, 0.0), 1e-12);
279        assert_close_complex(result.h[1], Complex::new(0.8, -0.4), 1e-12);
280        assert_close_complex(result.h[2], Complex::new(2.0 / 3.0, 0.0), 1e-12);
281    }
282}