oxifft 0.2.0

Pure Rust implementation of FFTW - the Fastest Fourier Transform in the West
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
//! wasm-bindgen bindings for JavaScript interop.

#[cfg(not(feature = "std"))]
extern crate alloc;

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

use crate::api::{Direction, Flags, Plan};
use crate::kernel::Complex;

#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;

/// WebAssembly FFT wrapper for JavaScript.
///
/// Provides a plan-based interface for repeated FFT operations.
///
/// # Example (JavaScript)
///
/// ```javascript
/// import { WasmFft } from 'oxifft';
///
/// const fft = new WasmFft(256);
/// const real = new Float64Array([1, 2, 3, ...]);
/// const imag = new Float64Array([0, 0, 0, ...]);
/// const result = fft.forward(real, imag);
/// ```
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub struct WasmFft {
    /// Size of the transform.
    size: usize,
    /// Forward FFT plan.
    forward_plan: Option<Plan<f64>>,
    /// Inverse FFT plan.
    inverse_plan: Option<Plan<f64>>,
}

#[cfg_attr(feature = "wasm", wasm_bindgen)]
impl WasmFft {
    /// Create a new WASM FFT wrapper.
    ///
    /// # Arguments
    ///
    /// * `size` - Transform size
    #[cfg_attr(feature = "wasm", wasm_bindgen(constructor))]
    pub fn new(size: usize) -> Self {
        let forward_plan = Plan::dft_1d(size, Direction::Forward, Flags::ESTIMATE);
        let inverse_plan = Plan::dft_1d(size, Direction::Backward, Flags::ESTIMATE);

        Self {
            size,
            forward_plan,
            inverse_plan,
        }
    }

    /// Get the transform size.
    #[cfg_attr(feature = "wasm", wasm_bindgen(getter))]
    pub fn size(&self) -> usize {
        self.size
    }

    /// Execute forward FFT.
    ///
    /// # Arguments
    ///
    /// * `real` - Real part of input (length must equal size)
    /// * `imag` - Imaginary part of input (length must equal size)
    ///
    /// # Returns
    ///
    /// Interleaved output: [re0, im0, re1, im1, ...]
    pub fn forward(&self, real: &[f64], imag: &[f64]) -> Vec<f64> {
        if real.len() != self.size || imag.len() != self.size {
            return Vec::new();
        }

        let plan = match &self.forward_plan {
            Some(p) => p,
            None => return Vec::new(),
        };

        // Create complex input
        let input: Vec<Complex<f64>> = real
            .iter()
            .zip(imag.iter())
            .map(|(&r, &i)| Complex::new(r, i))
            .collect();

        let mut output = vec![Complex::<f64>::zero(); self.size];
        plan.execute(&input, &mut output);

        // Return interleaved result
        let mut result = Vec::with_capacity(self.size * 2);
        for c in output {
            result.push(c.re);
            result.push(c.im);
        }
        result
    }

    /// Execute inverse FFT.
    ///
    /// # Arguments
    ///
    /// * `real` - Real part of input (length must equal size)
    /// * `imag` - Imaginary part of input (length must equal size)
    ///
    /// # Returns
    ///
    /// Interleaved output: [re0, im0, re1, im1, ...]
    pub fn inverse(&self, real: &[f64], imag: &[f64]) -> Vec<f64> {
        if real.len() != self.size || imag.len() != self.size {
            return Vec::new();
        }

        let plan = match &self.inverse_plan {
            Some(p) => p,
            None => return Vec::new(),
        };

        // Create complex input
        let input: Vec<Complex<f64>> = real
            .iter()
            .zip(imag.iter())
            .map(|(&r, &i)| Complex::new(r, i))
            .collect();

        let mut output = vec![Complex::<f64>::zero(); self.size];
        plan.execute(&input, &mut output);

        // Normalize by size for proper inverse
        let scale = 1.0 / (self.size as f64);
        let mut result = Vec::with_capacity(self.size * 2);
        for c in output {
            result.push(c.re * scale);
            result.push(c.im * scale);
        }
        result
    }

    /// Execute forward FFT with interleaved input.
    ///
    /// # Arguments
    ///
    /// * `interleaved` - Interleaved complex input [re0, im0, re1, im1, ...]
    ///
    /// # Returns
    ///
    /// Interleaved output.
    pub fn forward_interleaved(&self, interleaved: &[f64]) -> Vec<f64> {
        if interleaved.len() != self.size * 2 {
            return Vec::new();
        }

        let plan = match &self.forward_plan {
            Some(p) => p,
            None => return Vec::new(),
        };

        // Create complex input from interleaved data
        let input: Vec<Complex<f64>> = interleaved
            .chunks_exact(2)
            .map(|c| Complex::new(c[0], c[1]))
            .collect();

        let mut output = vec![Complex::<f64>::zero(); self.size];
        plan.execute(&input, &mut output);

        // Return interleaved result
        let mut result = Vec::with_capacity(self.size * 2);
        for c in output {
            result.push(c.re);
            result.push(c.im);
        }
        result
    }

    /// Execute inverse FFT with interleaved input.
    ///
    /// # Arguments
    ///
    /// * `interleaved` - Interleaved complex input [re0, im0, re1, im1, ...]
    ///
    /// # Returns
    ///
    /// Interleaved output (normalized).
    pub fn inverse_interleaved(&self, interleaved: &[f64]) -> Vec<f64> {
        if interleaved.len() != self.size * 2 {
            return Vec::new();
        }

        let plan = match &self.inverse_plan {
            Some(p) => p,
            None => return Vec::new(),
        };

        let input: Vec<Complex<f64>> = interleaved
            .chunks_exact(2)
            .map(|c| Complex::new(c[0], c[1]))
            .collect();

        let mut output = vec![Complex::<f64>::zero(); self.size];
        plan.execute(&input, &mut output);

        let scale = 1.0 / (self.size as f64);
        let mut result = Vec::with_capacity(self.size * 2);
        for c in output {
            result.push(c.re * scale);
            result.push(c.im * scale);
        }
        result
    }
}

/// One-shot forward FFT (f64).
///
/// # Arguments
///
/// * `real` - Real part of input
/// * `imag` - Imaginary part of input
///
/// # Returns
///
/// Interleaved output: [re0, im0, re1, im1, ...]
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn fft_f64(real: &[f64], imag: &[f64]) -> Vec<f64> {
    if real.len() != imag.len() || real.is_empty() {
        return Vec::new();
    }

    let n = real.len();
    let plan = match Plan::dft_1d(n, Direction::Forward, Flags::ESTIMATE) {
        Some(p) => p,
        None => return Vec::new(),
    };

    let input: Vec<Complex<f64>> = real
        .iter()
        .zip(imag.iter())
        .map(|(&r, &i)| Complex::new(r, i))
        .collect();

    let mut output = vec![Complex::<f64>::zero(); n];
    plan.execute(&input, &mut output);

    let mut result = Vec::with_capacity(n * 2);
    for c in output {
        result.push(c.re);
        result.push(c.im);
    }
    result
}

/// One-shot inverse FFT (f64).
///
/// # Arguments
///
/// * `real` - Real part of input
/// * `imag` - Imaginary part of input
///
/// # Returns
///
/// Interleaved output: [re0, im0, re1, im1, ...] (normalized)
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn ifft_f64(real: &[f64], imag: &[f64]) -> Vec<f64> {
    if real.len() != imag.len() || real.is_empty() {
        return Vec::new();
    }

    let n = real.len();
    let plan = match Plan::dft_1d(n, Direction::Backward, Flags::ESTIMATE) {
        Some(p) => p,
        None => return Vec::new(),
    };

    let input: Vec<Complex<f64>> = real
        .iter()
        .zip(imag.iter())
        .map(|(&r, &i)| Complex::new(r, i))
        .collect();

    let mut output = vec![Complex::<f64>::zero(); n];
    plan.execute(&input, &mut output);

    let scale = 1.0 / (n as f64);
    let mut result = Vec::with_capacity(n * 2);
    for c in output {
        result.push(c.re * scale);
        result.push(c.im * scale);
    }
    result
}

/// One-shot forward FFT (f32).
///
/// # Arguments
///
/// * `real` - Real part of input
/// * `imag` - Imaginary part of input
///
/// # Returns
///
/// Interleaved output: [re0, im0, re1, im1, ...]
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn fft_f32(real: &[f32], imag: &[f32]) -> Vec<f32> {
    if real.len() != imag.len() || real.is_empty() {
        return Vec::new();
    }

    let n = real.len();
    let plan = match Plan::dft_1d(n, Direction::Forward, Flags::ESTIMATE) {
        Some(p) => p,
        None => return Vec::new(),
    };

    let input: Vec<Complex<f32>> = real
        .iter()
        .zip(imag.iter())
        .map(|(&r, &i)| Complex::new(r, i))
        .collect();

    let mut output = vec![Complex::<f32>::zero(); n];
    plan.execute(&input, &mut output);

    let mut result = Vec::with_capacity(n * 2);
    for c in output {
        result.push(c.re);
        result.push(c.im);
    }
    result
}

/// One-shot inverse FFT (f32).
///
/// # Arguments
///
/// * `real` - Real part of input
/// * `imag` - Imaginary part of input
///
/// # Returns
///
/// Interleaved output: [re0, im0, re1, im1, ...] (normalized)
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn ifft_f32(real: &[f32], imag: &[f32]) -> Vec<f32> {
    if real.len() != imag.len() || real.is_empty() {
        return Vec::new();
    }

    let n = real.len();
    let plan = match Plan::dft_1d(n, Direction::Backward, Flags::ESTIMATE) {
        Some(p) => p,
        None => return Vec::new(),
    };

    let input: Vec<Complex<f32>> = real
        .iter()
        .zip(imag.iter())
        .map(|(&r, &i)| Complex::new(r, i))
        .collect();

    let mut output = vec![Complex::<f32>::zero(); n];
    plan.execute(&input, &mut output);

    let scale = 1.0 / (n as f32);
    let mut result = Vec::with_capacity(n * 2);
    for c in output {
        result.push(c.re * scale);
        result.push(c.im * scale);
    }
    result
}

/// Real-to-complex FFT (f64).
///
/// # Arguments
///
/// * `input` - Real input signal
///
/// # Returns
///
/// Interleaved complex output (hermitian symmetric, n/2+1 complex values)
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub fn rfft_f64(input: &[f64]) -> Vec<f64> {
    if input.is_empty() {
        return Vec::new();
    }

    let n = input.len();

    // Convert to complex
    let complex_input: Vec<Complex<f64>> = input.iter().map(|&r| Complex::new(r, 0.0)).collect();

    let plan = match Plan::dft_1d(n, Direction::Forward, Flags::ESTIMATE) {
        Some(p) => p,
        None => return Vec::new(),
    };

    let mut output = vec![Complex::<f64>::zero(); n];
    plan.execute(&complex_input, &mut output);

    // Return only first n/2+1 due to hermitian symmetry
    let out_len = n / 2 + 1;
    let mut result = Vec::with_capacity(out_len * 2);
    for c in output.iter().take(out_len) {
        result.push(c.re);
        result.push(c.im);
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_wasm_fft_forward() {
        let fft = WasmFft::new(4);

        let real = [1.0, 1.0, 1.0, 1.0];
        let imag = [0.0, 0.0, 0.0, 0.0];

        let result = fft.forward(&real, &imag);

        // DC component should be 4
        assert!((result[0] - 4.0).abs() < 1e-10);
        assert!(result[1].abs() < 1e-10);

        // Other components should be 0
        assert!(result[2].abs() < 1e-10);
        assert!(result[3].abs() < 1e-10);
    }

    #[test]
    fn test_wasm_fft_inverse() {
        let fft = WasmFft::new(4);

        let real = [1.0, 2.0, 3.0, 4.0];
        let imag = [0.0, 0.0, 0.0, 0.0];

        // Forward then inverse should recover original
        let forward = fft.forward(&real, &imag);

        let fwd_real: Vec<f64> = forward.iter().step_by(2).copied().collect();
        let fwd_imag: Vec<f64> = forward.iter().skip(1).step_by(2).copied().collect();

        let inverse = fft.inverse(&fwd_real, &fwd_imag);

        for i in 0..4 {
            assert!((inverse[i * 2] - real[i]).abs() < 1e-10);
            assert!(inverse[i * 2 + 1].abs() < 1e-10);
        }
    }

    #[test]
    fn test_fft_f64_oneshot() {
        let real = [1.0, 0.0, 0.0, 0.0];
        let imag = [0.0, 0.0, 0.0, 0.0];

        let result = fft_f64(&real, &imag);

        // DFT of impulse is all ones
        for i in 0..4 {
            assert!((result[i * 2] - 1.0).abs() < 1e-10);
            assert!(result[i * 2 + 1].abs() < 1e-10);
        }
    }

    #[test]
    fn test_ifft_f64_oneshot() {
        let real = [4.0, 0.0, 0.0, 0.0];
        let imag = [0.0, 0.0, 0.0, 0.0];

        let result = ifft_f64(&real, &imag);

        // IDFT should recover uniform signal
        for i in 0..4 {
            assert!((result[i * 2] - 1.0).abs() < 1e-10);
            assert!(result[i * 2 + 1].abs() < 1e-10);
        }
    }

    #[test]
    fn test_fft_f32_oneshot() {
        let real = [1.0_f32, 1.0, 1.0, 1.0];
        let imag = [0.0_f32, 0.0, 0.0, 0.0];

        let result = fft_f32(&real, &imag);

        // DC should be 4
        assert!((result[0] - 4.0).abs() < 1e-5);
    }

    #[test]
    fn test_rfft_f64() {
        let input = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
        let result = rfft_f64(&input);

        // Impulse -> all ones (first n/2+1 = 5 complex values)
        assert_eq!(result.len(), 10); // 5 complex = 10 floats

        for chunk in result.chunks(2) {
            assert!((chunk[0] - 1.0).abs() < 1e-10);
            assert!(chunk[1].abs() < 1e-10);
        }
    }

    #[test]
    fn test_wasm_fft_interleaved() {
        let fft = WasmFft::new(4);

        // [1+0i, 1+0i, 1+0i, 1+0i]
        let interleaved = [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0];

        let result = fft.forward_interleaved(&interleaved);

        // DC component should be 4
        assert!((result[0] - 4.0).abs() < 1e-10);
    }
}