Skip to main content

lib_jsl_dsp/continuous/spectral/
freqs.rs

1//! Analog frequency-response utility similar to `scipy.signal.freqs`.
2//!
3//! This evaluates the transfer function of a continuous-time linear filter:
4//!
5//! `H(jw) = (b[0] (jw)^M + b[1] (jw)^(M-1) + ... + b[M]) /`
6//! `        (a[0] (jw)^N + a[1] (jw)^(N-1) + ... + a[N])`
7//!
8//! Plotting support from SciPy is intentionally omitted here.
9//!
10//! See the book entry [Analogue prototypes: Butterworth, Chebyshev, elliptic and Bessel](https://jwkunz.github.io/lib_jsl/book/filters/analog-prototypes.html).
11
12use ndarray::Array1;
13use num_complex::Complex;
14
15use crate::{
16    number_theory::polynomial::{polynomial_eval, polynomial_roots},
17    prelude::{C1D, ErrorsJSL, IsAnalytic, R1D},
18};
19
20#[derive(Clone, Debug, PartialEq)]
21#[non_exhaustive]
22pub struct FreqsResult {
23    /// Angular frequency axis in rad/s.
24    pub w: R1D,
25    /// Complex analog frequency response evaluated at each frequency in `w`.
26    pub h: C1D,
27}
28
29#[derive(Clone, Debug, PartialEq)]
30pub enum FreqsWorN {
31    /// Automatically generate a frequency grid with the requested number of points.
32    NumPoints(usize),
33    /// Evaluate at the explicitly provided angular frequencies in rad/s.
34    Frequencies(Vec<f64>),
35}
36
37fn validate_coefficients<T: IsAnalytic>(b: &[T], a: &[T]) -> Result<(), ErrorsJSL> {
38    if b.is_empty() {
39        return Err(ErrorsJSL::InvalidInputRange(
40            "numerator coefficients must be non-empty",
41        ));
42    }
43    if a.is_empty() {
44        return Err(ErrorsJSL::InvalidInputRange(
45            "denominator coefficients must be non-empty",
46        ));
47    }
48    Ok(())
49}
50
51fn logspace(start_exp: f64, stop_exp: f64, n: usize) -> Vec<f64> {
52    if n == 0 {
53        return vec![];
54    }
55    if n == 1 {
56        return vec![10.0_f64.powf(start_exp)];
57    }
58    (0..n)
59        .map(|k| {
60            let t = k as f64 / (n - 1) as f64;
61            10.0_f64.powf(start_exp + t * (stop_exp - start_exp))
62        })
63        .collect()
64}
65
66fn auto_frequency_grid<T: IsAnalytic>(b: &[T], a: &[T], n: usize) -> Result<R1D, ErrorsJSL> {
67    if n == 0 {
68        return Err(ErrorsJSL::InvalidInputRange("worN must be > 0"));
69    }
70
71    let mut scales = Vec::new();
72    for root in polynomial_roots(b)?.iter().copied().chain(polynomial_roots(a)?.iter().copied()) {
73        let mag = root.norm();
74        if mag.is_finite() && mag > 0.0 {
75            scales.push(mag);
76        }
77    }
78
79    let (w_min, w_max) = if scales.is_empty() {
80        (0.1, 10.0)
81    } else {
82        let min_scale = scales
83            .iter()
84            .copied()
85            .fold(f64::INFINITY, |acc, x| acc.min(x));
86        let max_scale = scales
87            .iter()
88            .copied()
89            .fold(0.0_f64, |acc, x| acc.max(x));
90        let low = (min_scale / 10.0).max(1e-3);
91        let high = (max_scale * 10.0).max(low * 10.0);
92        (low, high)
93    };
94
95    Ok(Array1::from_vec(logspace(w_min.log10(), w_max.log10(), n)))
96}
97
98fn build_frequency_grid<T: IsAnalytic>(
99    b: &[T],
100    a: &[T],
101    wor_n: Option<FreqsWorN>,
102) -> Result<R1D, ErrorsJSL> {
103    match wor_n.unwrap_or(FreqsWorN::NumPoints(200)) {
104        FreqsWorN::NumPoints(n) => auto_frequency_grid(b, a, n),
105        FreqsWorN::Frequencies(w) => {
106            if w.is_empty() {
107                return Err(ErrorsJSL::InvalidInputRange(
108                    "frequency array must be non-empty",
109                ));
110            }
111            if w.iter().any(|x| !x.is_finite() || *x < 0.0) {
112                return Err(ErrorsJSL::InvalidInputRange(
113                    "frequency array values must be finite and >= 0",
114                ));
115            }
116            Ok(Array1::from_vec(w))
117        }
118    }
119}
120
121/// Compute the analog frequency response of a continuous-time filter.
122///
123/// Arguments:
124/// - `b`: numerator polynomial coefficients in descending powers of `s`
125/// - `a`: denominator polynomial coefficients in descending powers of `s`
126/// - `wor_n`: optional frequency-grid specification. `None` defaults to 200
127///   automatically chosen frequencies near pole/zero magnitudes.
128pub fn freqs<T: IsAnalytic>(
129    b: &[T],
130    a: &[T],
131    wor_n: Option<FreqsWorN>,
132) -> Result<FreqsResult, ErrorsJSL> {
133    validate_coefficients(b, a)?;
134    let w = build_frequency_grid(b, a, wor_n)?;
135
136    let mut h = Vec::with_capacity(w.len());
137    for &omega in &w {
138        let s = Complex::new(0.0, omega);
139        let numerator = polynomial_eval(b, s);
140        let denominator = polynomial_eval(a, s);
141        if denominator.norm_sqr() <= 1e-24 {
142            return Err(ErrorsJSL::RuntimeError(
143                "frequency response undefined because denominator is zero",
144            ));
145        }
146        h.push(numerator / denominator);
147    }
148
149    Ok(FreqsResult {
150        w,
151        h: Array1::from_vec(h),
152    })
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    fn assert_close_complex(a: Complex<f64>, b: Complex<f64>, tol: f64) {
160        assert!((a - b).norm() < tol, "left={a}, right={b}, tol={tol}");
161    }
162
163    #[test]
164    fn test_freqs_identity_is_flat() {
165        let result = freqs(&[1.0], &[1.0], None).unwrap();
166        assert_eq!(result.w.len(), 200);
167        assert_eq!(result.h.len(), 200);
168        for pair in result.w.iter().zip(result.w.iter().skip(1)) {
169            assert!(pair.0 < pair.1);
170        }
171        for &h in &result.h {
172            assert_close_complex(h, Complex::new(1.0, 0.0), 1e-12);
173        }
174    }
175
176    #[test]
177    fn test_freqs_matches_simple_rc_lowpass() {
178        let result = freqs(
179            &[1.0],
180            &[1.0, 1.0],
181            Some(FreqsWorN::Frequencies(vec![0.0, 1.0])),
182        )
183        .unwrap();
184
185        assert_eq!(result.w.to_vec(), vec![0.0, 1.0]);
186        assert_close_complex(result.h[0], Complex::new(1.0, 0.0), 1e-12);
187        assert_close_complex(result.h[1], Complex::new(0.5, -0.5), 1e-12);
188    }
189
190    #[test]
191    fn test_freqs_num_points_uses_requested_length() {
192        let result = freqs(&[1.0], &[1.0, 1.0], Some(FreqsWorN::NumPoints(17))).unwrap();
193        assert_eq!(result.w.len(), 17);
194        assert_eq!(result.h.len(), 17);
195    }
196
197    #[test]
198    fn test_freqs_rejects_negative_explicit_frequency() {
199        let err = freqs(&[1.0], &[1.0], Some(FreqsWorN::Frequencies(vec![-1.0]))).unwrap_err();
200        assert!(matches!(err, ErrorsJSL::InvalidInputRange(_)));
201    }
202}