1use std::f64::consts::PI;
24
25use lib_jsl_core::{C1D, ErrorsJSL, IsAnalytic};
26use num_complex::Complex;
27
28use crate::{
29 bluestein_fft::BluesteinFft,
30 fft_engine_trait::{FftEngine1D, FftDirection, FftOrdering, FftScaleFactor},
31};
32
33const ALPHA_TOL: f64 = 1e-12;
34
35fn approx_eq(a: f64, b: f64) -> bool {
36 (a - b).abs() <= ALPHA_TOL
37}
38
39fn unitary_fft(
40 engine: &mut BluesteinFft,
41 data: &[Complex<f64>],
42) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
43 engine.execute(data)
44}
45
46fn wrapped_center_coordinate(index: usize, size: usize) -> f64 {
47 if index < size / 2 {
48 index as f64
49 } else {
50 index as f64 - size as f64
51 }
52}
53
54pub struct FractionalFft {
56 size: usize,
57 chirp_argument: Vec<Complex<f64>>,
58 fft_engine: BluesteinFft,
59 ifft_engine: BluesteinFft,
60}
61
62impl FractionalFft {
63 pub fn new() -> Self {
64 Self {
65 size: 0,
66 chirp_argument: Vec::new(),
67 fft_engine: BluesteinFft::new(),
68 ifft_engine: BluesteinFft::new(),
69 }
70 }
71
72 pub fn plan(&mut self, size: usize) -> Result<(), ErrorsJSL> {
74 if size == 0 {
75 return Err(ErrorsJSL::InvalidInputRange("size must be > 0"));
76 }
77
78 self.size = size;
79 self.chirp_argument = (0..size)
80 .map(|k| {
81 let coord = wrapped_center_coordinate(k, size);
82 Complex::new(0.0, PI * coord * coord / size as f64)
83 })
84 .collect();
85
86 self.fft_engine.plan(
87 size,
88 FftScaleFactor::SqrtN,
89 FftDirection::Forward,
90 FftOrdering::Standard,
91 )?;
92 self.ifft_engine.plan(
93 size,
94 FftScaleFactor::SqrtN,
95 FftDirection::Inverse,
96 FftOrdering::Standard,
97 )?;
98 Ok(())
99 }
100
101 fn ensure_size(&mut self, size: usize) -> Result<(), ErrorsJSL> {
102 if self.size != size {
103 self.plan(size)?;
104 }
105 Ok(())
106 }
107
108 fn execute_quarter_turn_case(
109 &mut self,
110 data: &[Complex<f64>],
111 alpha_mod: f64,
112 ) -> Result<Option<Vec<Complex<f64>>>, ErrorsJSL> {
113 if approx_eq(alpha_mod, 0.0) || approx_eq(alpha_mod, 4.0) {
114 return Ok(Some(data.to_vec()));
115 }
116 if approx_eq(alpha_mod, 1.0) {
117 return Ok(Some(unitary_fft(&mut self.fft_engine, data)?));
118 }
119 if approx_eq(alpha_mod, 2.0) {
120 return Ok(Some(data.iter().rev().copied().collect()));
121 }
122 if approx_eq(alpha_mod, 3.0) {
123 return Ok(Some(unitary_fft(&mut self.ifft_engine, data)?));
124 }
125 Ok(None)
126 }
127
128 fn normalize_alpha(
129 &mut self,
130 mut data: Vec<Complex<f64>>,
131 alpha_mod: f64,
132 ) -> Result<(Vec<Complex<f64>>, f64), ErrorsJSL> {
133 if alpha_mod < 0.5 {
134 data = unitary_fft(&mut self.ifft_engine, &data)?;
135 Ok((data, alpha_mod + 1.0))
136 } else if alpha_mod < 1.5 {
137 Ok((data, alpha_mod))
138 } else if alpha_mod < 2.5 {
139 data = unitary_fft(&mut self.fft_engine, &data)?;
140 Ok((data, alpha_mod - 1.0))
141 } else if alpha_mod < 3.5 {
142 data.reverse();
143 Ok((data, alpha_mod - 2.0))
144 } else {
145 data = unitary_fft(&mut self.ifft_engine, &data)?;
146 Ok((data, alpha_mod - 3.0))
147 }
148 }
149
150 pub fn execute<T: IsAnalytic>(&mut self, input: &[T], alpha: f64) -> Result<C1D, ErrorsJSL> {
154 if input.is_empty() {
155 return Err(ErrorsJSL::InvalidInputRange("input must be non-empty"));
156 }
157 if !alpha.is_finite() {
158 return Err(ErrorsJSL::InvalidInputRange("alpha must be finite"));
159 }
160
161 self.ensure_size(input.len())?;
162 let data = input.iter().map(|x| x.to_complex()).collect::<Vec<_>>();
163 let alpha_mod = alpha.rem_euclid(4.0);
164
165 if let Some(result) = self.execute_quarter_turn_case(&data, alpha_mod)? {
166 return Ok(C1D::from_vec(result));
167 }
168
169 let (data, alpha_core) = self.normalize_alpha(data, alpha_mod)?;
170
171 let phi = alpha_core * PI / 2.0;
172 let cot_phi = 1.0 / phi.tan();
173 let sq_cot_phi = (1.0 + cot_phi * cot_phi).sqrt();
174 let scale =
175 Complex::new(1.0, -cot_phi).sqrt() / Complex::new((self.size as f64).sqrt(), 0.0);
176
177 let chirp1 = self
178 .chirp_argument
179 .iter()
180 .map(|arg| (*arg * (cot_phi - sq_cot_phi)).exp())
181 .collect::<Vec<_>>();
182 let chirp2 = self
183 .chirp_argument
184 .iter()
185 .map(|arg| (*arg * sq_cot_phi).exp())
186 .collect::<Vec<_>>();
187
188 let weighted = chirp1
189 .iter()
190 .zip(data.iter())
191 .map(|(c, x)| *c * *x)
192 .collect::<Vec<_>>();
193 let fft1 = unitary_fft(&mut self.fft_engine, &chirp2)?;
194 let fft2 = unitary_fft(&mut self.fft_engine, &weighted)?;
195 let product = fft1
196 .iter()
197 .zip(fft2.iter())
198 .map(|(a, b)| *a * *b)
199 .collect::<Vec<_>>();
200 let ifft = unitary_fft(&mut self.ifft_engine, &product)?;
201 let convolution_scale = (self.size as f64).sqrt();
205
206 Ok(C1D::from_vec(
207 chirp1
208 .iter()
209 .zip(ifft.iter())
210 .map(|(c, y)| scale * convolution_scale * *c * *y)
211 .collect(),
212 ))
213 }
214}
215
216impl Default for FractionalFft {
217 fn default() -> Self {
218 Self::new()
219 }
220}
221
222pub fn frft<T: IsAnalytic>(input: &[T], alpha: f64) -> Result<C1D, ErrorsJSL> {
224 let mut frft_engine = FractionalFft::new();
225 frft_engine.execute(input, alpha)
226}
227
228#[cfg(test)]
229mod tests {
230 use super::*;
231
232 fn assert_complex_close(actual: Complex<f64>, expected: Complex<f64>, tol: f64) {
233 assert!(
234 (actual - expected).norm() < tol,
235 "actual={actual}, expected={expected}, tol={tol}"
236 );
237 }
238
239 #[test]
240 fn test_frft_alpha_zero_is_identity() {
241 let x = [
242 Complex::new(1.0, 0.2),
243 Complex::new(-0.5, 1.0),
244 Complex::new(0.25, -0.75),
245 Complex::new(2.0, 0.0),
246 Complex::new(-1.5, 0.4),
247 ];
248 let y = frft(&x, 0.0).unwrap();
249 assert_eq!(y.len(), x.len());
250 for (actual, expected) in y.iter().zip(x.iter()) {
251 assert_complex_close(*actual, *expected, 1e-12);
252 }
253 }
254
255 #[test]
256 fn test_frft_alpha_one_matches_unitary_fft() {
257 let x = [
258 Complex::new(1.0, 0.0),
259 Complex::new(-0.5, 0.75),
260 Complex::new(0.25, -0.25),
261 Complex::new(2.0, 1.0),
262 Complex::new(-1.0, 0.5),
263 ];
264 let y = frft(&x, 1.0).unwrap();
265
266 let mut fft = BluesteinFft::new();
267 fft.plan(
268 x.len(),
269 FftScaleFactor::SqrtN,
270 FftDirection::Forward,
271 FftOrdering::Standard,
272 )
273 .unwrap();
274 let expected = fft.execute(&x).unwrap();
275
276 for (actual, expected) in y.iter().zip(expected.iter()) {
277 assert_complex_close(*actual, *expected, 1e-12);
278 }
279 }
280
281 #[test]
282 fn test_frft_alpha_two_is_reversal() {
283 let x = [1.0, -0.5, 0.25, 2.0, -1.25, 0.4];
284 let y = frft(&x, 2.0).unwrap();
285 let expected = x
286 .iter()
287 .rev()
288 .map(|&v| Complex::new(v, 0.0))
289 .collect::<Vec<_>>();
290 for (actual, expected) in y.iter().zip(expected.iter()) {
291 assert_complex_close(*actual, *expected, 1e-12);
292 }
293 }
294
295 #[test]
296 fn test_frft_is_periodic_mod_four() {
297 let x = [
298 Complex::new(1.0, 0.1),
299 Complex::new(-0.5, 0.75),
300 Complex::new(0.25, -0.25),
301 Complex::new(2.0, 1.0),
302 Complex::new(-1.0, 0.5),
303 Complex::new(0.3, -0.2),
304 ];
305 let alpha = 0.73;
306 let y0 = frft(&x, alpha).unwrap();
307 let y1 = frft(&x, alpha + 4.0).unwrap();
308
309 for (actual, expected) in y0.iter().zip(y1.iter()) {
310 assert_complex_close(*actual, *expected, 1e-6);
311 }
312 }
313
314 #[test]
315 fn intermediate_orders_preserve_energy_and_the_gaussian() {
316 let n = 256;
319 let s = (n as f64).sqrt();
320 let g: Vec<Complex<f64>> = (0..n)
321 .map(|k| {
322 let t = wrapped_center_coordinate(k, n) / s;
323 Complex::new((-PI * t * t).exp(), 0.0)
324 })
325 .collect();
326 let energy = |v: &[Complex<f64>]| v.iter().map(|z| z.norm_sqr()).sum::<f64>();
327 let mut f = FractionalFft::new();
328 for alpha in [0.1, 0.3, 0.5, 0.8, 1.4, 2.7] {
329 let y = f.execute(&g, alpha).unwrap();
330 assert!((energy(y.as_slice().unwrap()) / energy(&g) - 1.0).abs() < 0.01, "alpha = {alpha}");
331 let worst = y.iter().zip(&g).map(|(a, b)| (a.norm() - b.norm()).abs()).fold(0.0, f64::max);
332 assert!(worst < 0.1, "alpha = {alpha}: magnitude error {worst}");
333 }
334 }
335}