lib_jsl_dsp/discrete/spectral/
chirpz.rs1use std::f64::consts::PI;
20
21use num_complex::Complex;
22
23use crate::{
24 ffts::{
25 Fft,
26 fft_engine_trait::{FftEngine1D, FftDirection, FftOrdering, FftScaleFactor},
27 },
28 prelude::{C1D, ErrorsJSL, IsAnalytic},
29};
30
31fn complex_powf(base: Complex<f64>, exponent: f64) -> Result<Complex<f64>, ErrorsJSL> {
32 if !base.re.is_finite() || !base.im.is_finite() {
33 return Err(ErrorsJSL::InvalidInputRange(
34 "complex parameter values must be finite",
35 ));
36 }
37 if base == Complex::new(0.0, 0.0) {
38 return Err(ErrorsJSL::InvalidInputRange(
39 "complex contour parameters must be non-zero",
40 ));
41 }
42 Ok((base.ln() * exponent).exp())
43}
44
45pub fn chirpz<T: IsAnalytic>(
63 data_in: &[T],
64 m: Option<usize>,
65 w: Option<Complex<f64>>,
66 a: Option<Complex<f64>>,
67) -> Result<C1D, ErrorsJSL> {
68 if data_in.is_empty() {
69 return Err(ErrorsJSL::InvalidInputRange("data_in must be non-empty"));
70 }
71
72 let n = data_in.len();
73 let m = m.unwrap_or(n);
74 if m == 0 {
75 return Err(ErrorsJSL::InvalidInputRange("m must be > 0"));
76 }
77
78 let a = a.unwrap_or(Complex::new(1.0, 0.0));
79 if a == Complex::new(0.0, 0.0) {
80 return Err(ErrorsJSL::InvalidInputRange("a must be non-zero"));
81 }
82
83 let w = w.unwrap_or_else(|| {
84 let theta = -2.0 * PI / m as f64;
85 Complex::new(theta.cos(), theta.sin())
86 });
87 if w == Complex::new(0.0, 0.0) {
88 return Err(ErrorsJSL::InvalidInputRange("w must be non-zero"));
89 }
90
91 let g_len = m + n - 1;
93 let conv_len = n + g_len - 1;
94 let fft_len = conv_len.next_power_of_two();
95
96 let mut y = vec![Complex::new(0.0, 0.0); fft_len];
97 for idx in 0..n {
98 let idxf = idx as f64;
99 let a_term = complex_powf(a, -idxf)?;
100 let w_term = complex_powf(w, 0.5 * idxf * idxf)?;
101 y[idx] = data_in[idx].to_complex() * a_term * w_term;
102 }
103
104 let mut v = vec![Complex::new(0.0, 0.0); fft_len];
105 for q in (-(n as isize) + 1)..=(m as isize - 1) {
106 let qf = q as f64;
107 v[(q + (n as isize - 1)) as usize] = complex_powf(w, -0.5 * qf * qf)?;
108 }
109 let mut fft = Fft::new();
112 fft.plan(
113 fft_len,
114 FftScaleFactor::None,
115 FftDirection::Forward,
116 FftOrdering::Standard,
117 )?;
118 let mut ifft = Fft::new();
119 ifft.plan(
120 fft_len,
121 FftScaleFactor::N,
122 FftDirection::Inverse,
123 FftOrdering::Standard,
124 )?;
125
126 let y_fft = fft.execute(&y)?;
127 let v_fft = fft.execute(&v)?;
128 let prod = y_fft
129 .iter()
130 .zip(v_fft.iter())
131 .map(|(a, b)| *a * *b)
132 .collect::<Vec<_>>();
133 let conv = ifft.execute(&prod)?;
134
135 let mut out = Vec::with_capacity(m);
136 for k in 0..m {
137 let kf = k as f64;
138 let w_term = complex_powf(w, 0.5 * kf * kf)?;
139 out.push(conv[k + n - 1] * w_term);
140 }
141
142 Ok(C1D::from_vec(out))
143}
144
145#[cfg(test)]
146mod tests {
147 use super::*;
148
149 fn direct_chirpz<T: IsAnalytic>(
150 data_in: &[T],
151 m: usize,
152 w: Complex<f64>,
153 a: Complex<f64>,
154 ) -> Vec<Complex<f64>> {
155 let mut out = Vec::with_capacity(m);
156 for k in 0..m {
157 let mut acc = Complex::new(0.0, 0.0);
158 for (n, x) in data_in.iter().enumerate() {
159 let term = complex_powf(a, -(n as f64)).unwrap()
160 * complex_powf(w, (n * k) as f64).unwrap();
161 acc += x.to_complex() * term;
162 }
163 out.push(acc);
164 }
165 out
166 }
167
168 fn assert_close(actual: Complex<f64>, expected: Complex<f64>, tol: f64) {
169 assert!(
170 (actual - expected).norm() < tol,
171 "actual={actual}, expected={expected}, tol={tol}"
172 );
173 }
174
175 #[test]
176 fn test_chirpz_matches_direct_dft_default_settings() {
177 let x = [1.0, -0.5, 0.25, 2.0, -1.0];
178 let actual = chirpz(&x, None, None, None).unwrap();
179 let m = x.len();
180 let theta = -2.0 * PI / m as f64;
181 let w = Complex::new(theta.cos(), theta.sin());
182 let expected = direct_chirpz(&x, m, w, Complex::new(1.0, 0.0));
183
184 assert_eq!(actual.len(), expected.len());
185 for (a, e) in actual.iter().zip(expected.iter()) {
186 assert_close(*a, *e, 1e-9);
187 }
188 }
189
190 #[test]
191 fn test_chirpz_matches_direct_custom_spiral() {
192 let x = [
193 Complex::new(1.0, 0.5),
194 Complex::new(-0.25, 1.0),
195 Complex::new(0.75, -0.5),
196 Complex::new(0.1, 0.2),
197 ];
198 let m = 6;
199 let radius = 0.93_f64;
200 let angle = -0.37_f64;
201 let w = Complex::new(radius * angle.cos(), radius * angle.sin());
202 let a = Complex::new(0.85, 0.15);
203
204 let actual = chirpz(&x, Some(m), Some(w), Some(a)).unwrap();
205 let expected = direct_chirpz(&x, m, w, a);
206
207 assert_eq!(actual.len(), m);
208 for (a, e) in actual.iter().zip(expected.iter()) {
209 assert_close(*a, *e, 1e-8);
210 }
211 }
212
213 #[test]
214 fn test_chirpz_rejects_empty_input() {
215 let err = chirpz::<f64>(&[], None, None, None).unwrap_err();
216 assert!(matches!(err, ErrorsJSL::InvalidInputRange(_)));
217 }
218}