scirs2-fft 0.4.1

Fast Fourier Transform module for SciRS2 (scirs2-fft)
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
/*!
 * Parallel FFT algorithms implementations
 *
 * This module provides implementations of parallel Fast Fourier Transform (FFT)
 * algorithms for multi-threaded execution on multi-core CPUs.
 */

use crate::error::FFTResult;
use crate::fft::algorithms::{parse_norm_mode, NormMode};
#[cfg(feature = "oxifft")]
use crate::oxifft_plan_cache;
#[cfg(feature = "oxifft")]
use oxifft::{Complex as OxiComplex, Direction};
#[cfg(feature = "rustfft-backend")]
use rustfft::{num_complex::Complex as RustComplex, FftPlanner};
use scirs2_core::ndarray::{Array2, Axis};
use scirs2_core::numeric::Complex64;
use scirs2_core::numeric::NumCast;

use scirs2_core::parallel_ops::*;

/// Compute a 2D FFT using parallel processing for rows and columns
///
/// # Arguments
///
/// * `input` - Input 2D array
/// * `shape` - Shape of the output (optional)
/// * `axes` - Axes along which to compute the FFT (optional)
/// * `norm` - Normalization mode (optional)
/// * `workers` - Number of worker threads to use (optional)
///
/// # Returns
///
/// A 2D array of complex values representing the parallel FFT result
///
/// # Examples
///
/// ```
/// use scirs2_fft::fft2_parallel;
/// use scirs2_core::ndarray::{array, Array2};
///
/// // Create a simple 2x2 array
/// let input = array![[1.0, 2.0], [3.0, 4.0]];
///
/// // Compute the 2D FFT in parallel
/// let result = fft2_parallel(&input, None, None, None, None).expect("valid input");
///
/// // The DC component should be the sum of all elements
/// assert!((result[[0, 0]].re - 10.0).abs() < 1e-10);
/// ```
#[cfg(feature = "parallel")]
#[allow(clippy::too_many_arguments)]
#[allow(dead_code)]
pub fn fft2_parallel<T>(
    input: &Array2<T>,
    shape: Option<(usize, usize)>,
    axes: Option<(i32, i32)>,
    norm: Option<&str>,
    workers: Option<usize>,
) -> FFTResult<Array2<Complex64>>
where
    T: NumCast + Copy + std::fmt::Debug + 'static,
{
    // Get input array shape
    let inputshape = input.shape();

    // Determine output shape
    let outputshape = shape.unwrap_or((inputshape[0], inputshape[1]));

    // Determine axes to perform FFT on
    let axes = axes.unwrap_or((0, 1));

    // Validate axes
    if axes.0 < 0 || axes.0 > 1 || axes.1 < 0 || axes.1 > 1 || axes.0 == axes.1 {
        return Err(crate::FFTError::ValueError(
            "Invalid axes for 2D FFT".to_string(),
        ));
    }

    // Parse normalization mode
    let norm_mode = parse_norm_mode(norm, false);

    // Number of workers for parallel computation
    #[cfg(feature = "parallel")]
    let num_workers = workers.unwrap_or_else(|| num_threads().min(8));

    // Convert input array to complex numbers
    let mut complex_input = Array2::<Complex64>::zeros((inputshape[0], inputshape[1]));
    for i in 0..inputshape[0] {
        for j in 0..inputshape[1] {
            let val = input[[i, j]];

            // Try to convert to Complex64
            if let Some(c) = crate::fft::utility::try_as_complex(val) {
                complex_input[[i, j]] = c;
            } else {
                // Not a complex number, try to convert to f64 and make into a complex with zero imaginary part
                let real = NumCast::from(val).ok_or_else(|| {
                    crate::FFTError::ValueError(format!("Could not convert {val:?} to f64"))
                })?;
                complex_input[[i, j]] = Complex64::new(real, 0.0);
            }
        }
    }

    // Pad or truncate to match output shape if necessary
    let mut padded_input = if inputshape != [outputshape.0, outputshape.1] {
        let mut padded = Array2::<Complex64>::zeros((outputshape.0, outputshape.1));
        let copy_rows = std::cmp::min(inputshape[0], outputshape.0);
        let copy_cols = std::cmp::min(inputshape[1], outputshape.1);

        for i in 0..copy_rows {
            for j in 0..copy_cols {
                padded[[i, j]] = complex_input[[i, j]];
            }
        }
        padded
    } else {
        complex_input
    };

    // Perform FFT using the available backend
    #[cfg(feature = "oxifft")]
    {
        // Perform FFT along each row in parallel
        if num_workers > 1 {
            padded_input
                .axis_iter_mut(Axis(0))
                .into_par_iter()
                .for_each(|mut row| {
                    // Convert to OxiFFT compatible format
                    let input_oxi: Vec<OxiComplex<f64>> =
                        row.iter().map(|&c| OxiComplex::new(c.re, c.im)).collect();
                    let mut output: Vec<OxiComplex<f64>> = vec![OxiComplex::zero(); outputshape.1];

                    // Perform FFT
                    if let Err(_e) =
                        oxifft_plan_cache::execute_c2c(&input_oxi, &mut output, Direction::Forward)
                    {
                        // Error handling in parallel context - just skip this row
                        return;
                    }

                    // Update row with FFT result
                    for (i, val) in output.iter().enumerate() {
                        row[i] = Complex64::new(val.re, val.im);
                    }
                });
        } else {
            // Fall back to sequential processing if only one worker
            for mut row in padded_input.rows_mut() {
                let input_oxi: Vec<OxiComplex<f64>> =
                    row.iter().map(|&c| OxiComplex::new(c.re, c.im)).collect();
                let mut output: Vec<OxiComplex<f64>> = vec![OxiComplex::zero(); outputshape.1];

                oxifft_plan_cache::execute_c2c(&input_oxi, &mut output, Direction::Forward)?;

                for (i, val) in output.iter().enumerate() {
                    row[i] = Complex64::new(val.re, val.im);
                }
            }
        }

        // Perform FFT along each column in parallel
        if num_workers > 1 {
            padded_input
                .axis_iter_mut(Axis(1))
                .into_par_iter()
                .for_each(|mut col| {
                    // Convert to OxiFFT compatible format
                    let input_oxi: Vec<OxiComplex<f64>> =
                        col.iter().map(|&c| OxiComplex::new(c.re, c.im)).collect();
                    let mut output: Vec<OxiComplex<f64>> = vec![OxiComplex::zero(); outputshape.0];

                    // Perform FFT
                    if let Err(_e) =
                        oxifft_plan_cache::execute_c2c(&input_oxi, &mut output, Direction::Forward)
                    {
                        // Error handling in parallel context - just skip this column
                        return;
                    }

                    // Update column with FFT result
                    for (i, val) in output.iter().enumerate() {
                        col[i] = Complex64::new(val.re, val.im);
                    }
                });
        } else {
            // Fall back to sequential processing if only one worker
            for mut col in padded_input.columns_mut() {
                let input_oxi: Vec<OxiComplex<f64>> =
                    col.iter().map(|&c| OxiComplex::new(c.re, c.im)).collect();
                let mut output: Vec<OxiComplex<f64>> = vec![OxiComplex::zero(); outputshape.0];

                oxifft_plan_cache::execute_c2c(&input_oxi, &mut output, Direction::Forward)?;

                for (i, val) in output.iter().enumerate() {
                    col[i] = Complex64::new(val.re, val.im);
                }
            }
        }
    }

    #[cfg(not(feature = "oxifft"))]
    {
        #[cfg(feature = "rustfft-backend")]
        {
            // Create FFT planner
            let mut planner = FftPlanner::new();

            // Perform FFT along each row in parallel
            let row_fft = planner.plan_fft_forward(outputshape.1);

            if num_workers > 1 {
                padded_input
                    .axis_iter_mut(Axis(0))
                    .into_par_iter()
                    .for_each(|mut row| {
                        // Convert to rustfft compatible format
                        let mut buffer: Vec<RustComplex<f64>> =
                            row.iter().map(|&c| RustComplex::new(c.re, c.im)).collect();

                        // Perform FFT
                        row_fft.process(&mut buffer);

                        // Update row with FFT result
                        for (i, val) in buffer.iter().enumerate() {
                            row[i] = Complex64::new(val.re, val.im);
                        }
                    });
            } else {
                // Fall back to sequential processing if only one worker
                for mut row in padded_input.rows_mut() {
                    let mut buffer: Vec<RustComplex<f64>> =
                        row.iter().map(|&c| RustComplex::new(c.re, c.im)).collect();

                    row_fft.process(&mut buffer);

                    for (i, val) in buffer.iter().enumerate() {
                        row[i] = Complex64::new(val.re, val.im);
                    }
                }
            }

            // Perform FFT along each column in parallel
            let col_fft = planner.plan_fft_forward(outputshape.0);

            if num_workers > 1 {
                padded_input
                    .axis_iter_mut(Axis(1))
                    .into_par_iter()
                    .for_each(|mut col| {
                        // Convert to rustfft compatible format
                        let mut buffer: Vec<RustComplex<f64>> =
                            col.iter().map(|&c| RustComplex::new(c.re, c.im)).collect();

                        // Perform FFT
                        col_fft.process(&mut buffer);

                        // Update column with FFT result
                        for (i, val) in buffer.iter().enumerate() {
                            col[i] = Complex64::new(val.re, val.im);
                        }
                    });
            } else {
                // Fall back to sequential processing if only one worker
                for mut col in padded_input.columns_mut() {
                    let mut buffer: Vec<RustComplex<f64>> =
                        col.iter().map(|&c| RustComplex::new(c.re, c.im)).collect();

                    col_fft.process(&mut buffer);

                    for (i, val) in buffer.iter().enumerate() {
                        col[i] = Complex64::new(val.re, val.im);
                    }
                }
            }
        }

        #[cfg(not(feature = "rustfft-backend"))]
        {
            return Err(crate::FFTError::ComputationError(
                "No FFT backend available. Enable either 'oxifft' or 'rustfft-backend' feature."
                    .to_string(),
            ));
        }
    }

    // Apply normalization if needed
    if norm_mode != NormMode::None {
        let total_elements = outputshape.0 * outputshape.1;
        let scale = match norm_mode {
            NormMode::Backward => 1.0 / (total_elements as f64),
            NormMode::Ortho => 1.0 / (total_elements as f64).sqrt(),
            NormMode::Forward => 1.0 / (total_elements as f64),
            NormMode::None => 1.0, // Should not happen due to earlier check
        };

        padded_input.mapv_inplace(|x| x * scale);
    }

    Ok(padded_input)
}

/// Non-parallel fallback implementation of fft2_parallel for when the parallel feature is disabled
#[cfg(not(feature = "parallel"))]
#[allow(dead_code)]
pub fn fft2_parallel<T>(
    input: &Array2<T>,
    shape: Option<(usize, usize)>,
    _axes: Option<(i32, i32)>,
    _norm: Option<&str>,
    _workers: Option<usize>,
) -> FFTResult<Array2<Complex64>>
where
    T: NumCast + Copy + std::fmt::Debug + 'static,
{
    // When parallel feature is disabled, just use the standard fft2 implementation
    crate::fft::algorithms::fft2(input, shape, None, None)
}

/// Compute the inverse 2D FFT using parallel processing
///
/// # Arguments
///
/// * `input` - Input 2D array of complex values
/// * `shape` - Shape of the output (optional)
/// * `axes` - Axes along which to compute the FFT (optional)
/// * `norm` - Normalization mode (optional)
/// * `workers` - Number of worker threads to use (optional)
///
/// # Returns
///
/// A 2D array of complex values representing the inverse FFT result
#[cfg(feature = "parallel")]
#[allow(clippy::too_many_arguments)]
#[allow(dead_code)]
pub fn ifft2_parallel<T>(
    input: &Array2<T>,
    shape: Option<(usize, usize)>,
    axes: Option<(i32, i32)>,
    norm: Option<&str>,
    workers: Option<usize>,
) -> FFTResult<Array2<Complex64>>
where
    T: NumCast + Copy + std::fmt::Debug + 'static,
{
    // Get input array shape
    let inputshape = input.shape();

    // Determine output shape
    let outputshape = shape.unwrap_or((inputshape[0], inputshape[1]));

    // Determine axes to perform FFT on
    let axes = axes.unwrap_or((0, 1));

    // Validate axes
    if axes.0 < 0 || axes.0 > 1 || axes.1 < 0 || axes.1 > 1 || axes.0 == axes.1 {
        return Err(crate::FFTError::ValueError(
            "Invalid axes for 2D IFFT".to_string(),
        ));
    }

    // Parse normalization mode (default is "backward" for inverse FFT)
    let norm_mode = parse_norm_mode(norm, true);

    // Number of workers for parallel computation
    #[cfg(feature = "parallel")]
    let num_workers = workers.unwrap_or_else(|| num_threads().min(8));

    // Convert input to complex and copy to output shape
    let mut complex_input = Array2::<Complex64>::zeros((inputshape[0], inputshape[1]));
    for i in 0..inputshape[0] {
        for j in 0..inputshape[1] {
            let val = input[[i, j]];

            // Try to convert to Complex64
            if let Some(c) = crate::fft::utility::try_as_complex(val) {
                complex_input[[i, j]] = c;
            } else {
                // Not a complex number, try to convert to f64 and make into a complex with zero imaginary part
                let real = NumCast::from(val).ok_or_else(|| {
                    crate::FFTError::ValueError(format!("Could not convert {val:?} to f64"))
                })?;
                complex_input[[i, j]] = Complex64::new(real, 0.0);
            }
        }
    }

    // Pad or truncate to match output shape if necessary
    let mut padded_input = if inputshape != [outputshape.0, outputshape.1] {
        let mut padded = Array2::<Complex64>::zeros((outputshape.0, outputshape.1));
        let copy_rows = std::cmp::min(inputshape[0], outputshape.0);
        let copy_cols = std::cmp::min(inputshape[1], outputshape.1);

        for i in 0..copy_rows {
            for j in 0..copy_cols {
                padded[[i, j]] = complex_input[[i, j]];
            }
        }
        padded
    } else {
        complex_input
    };

    // Perform inverse FFT using the available backend
    #[cfg(feature = "oxifft")]
    {
        // Perform inverse FFT along each row in parallel
        if num_workers > 1 {
            padded_input
                .axis_iter_mut(Axis(0))
                .into_par_iter()
                .for_each(|mut row| {
                    // Convert to OxiFFT compatible format
                    let input_oxi: Vec<OxiComplex<f64>> =
                        row.iter().map(|&c| OxiComplex::new(c.re, c.im)).collect();
                    let mut output: Vec<OxiComplex<f64>> = vec![OxiComplex::zero(); outputshape.1];

                    // Perform inverse FFT
                    if let Err(_e) =
                        oxifft_plan_cache::execute_c2c(&input_oxi, &mut output, Direction::Backward)
                    {
                        // Error handling in parallel context - just skip this row
                        return;
                    }

                    // Update row with IFFT result
                    for (i, val) in output.iter().enumerate() {
                        row[i] = Complex64::new(val.re, val.im);
                    }
                });
        } else {
            // Fall back to sequential processing if only one worker
            for mut row in padded_input.rows_mut() {
                let input_oxi: Vec<OxiComplex<f64>> =
                    row.iter().map(|&c| OxiComplex::new(c.re, c.im)).collect();
                let mut output: Vec<OxiComplex<f64>> = vec![OxiComplex::zero(); outputshape.1];

                oxifft_plan_cache::execute_c2c(&input_oxi, &mut output, Direction::Backward)?;

                for (i, val) in output.iter().enumerate() {
                    row[i] = Complex64::new(val.re, val.im);
                }
            }
        }

        // Perform inverse FFT along each column in parallel
        if num_workers > 1 {
            padded_input
                .axis_iter_mut(Axis(1))
                .into_par_iter()
                .for_each(|mut col| {
                    // Convert to OxiFFT compatible format
                    let input_oxi: Vec<OxiComplex<f64>> =
                        col.iter().map(|&c| OxiComplex::new(c.re, c.im)).collect();
                    let mut output: Vec<OxiComplex<f64>> = vec![OxiComplex::zero(); outputshape.0];

                    // Perform inverse FFT
                    if let Err(_e) =
                        oxifft_plan_cache::execute_c2c(&input_oxi, &mut output, Direction::Backward)
                    {
                        // Error handling in parallel context - just skip this column
                        return;
                    }

                    // Update column with IFFT result
                    for (i, val) in output.iter().enumerate() {
                        col[i] = Complex64::new(val.re, val.im);
                    }
                });
        } else {
            // Fall back to sequential processing if only one worker
            for mut col in padded_input.columns_mut() {
                let input_oxi: Vec<OxiComplex<f64>> =
                    col.iter().map(|&c| OxiComplex::new(c.re, c.im)).collect();
                let mut output: Vec<OxiComplex<f64>> = vec![OxiComplex::zero(); outputshape.0];

                oxifft_plan_cache::execute_c2c(&input_oxi, &mut output, Direction::Backward)?;

                for (i, val) in output.iter().enumerate() {
                    col[i] = Complex64::new(val.re, val.im);
                }
            }
        }
    }

    #[cfg(not(feature = "oxifft"))]
    {
        #[cfg(feature = "rustfft-backend")]
        {
            // Create FFT planner
            let mut planner = FftPlanner::new();

            // Perform inverse FFT along each row in parallel
            let row_ifft = planner.plan_fft_inverse(outputshape.1);

            if num_workers > 1 {
                padded_input
                    .axis_iter_mut(Axis(0))
                    .into_par_iter()
                    .for_each(|mut row| {
                        // Convert to rustfft compatible format
                        let mut buffer: Vec<RustComplex<f64>> =
                            row.iter().map(|&c| RustComplex::new(c.re, c.im)).collect();

                        // Perform inverse FFT
                        row_ifft.process(&mut buffer);

                        // Update row with IFFT result
                        for (i, val) in buffer.iter().enumerate() {
                            row[i] = Complex64::new(val.re, val.im);
                        }
                    });
            } else {
                // Fall back to sequential processing if only one worker
                for mut row in padded_input.rows_mut() {
                    let mut buffer: Vec<RustComplex<f64>> =
                        row.iter().map(|&c| RustComplex::new(c.re, c.im)).collect();

                    row_ifft.process(&mut buffer);

                    for (i, val) in buffer.iter().enumerate() {
                        row[i] = Complex64::new(val.re, val.im);
                    }
                }
            }

            // Perform inverse FFT along each column in parallel
            let col_ifft = planner.plan_fft_inverse(outputshape.0);

            if num_workers > 1 {
                padded_input
                    .axis_iter_mut(Axis(1))
                    .into_par_iter()
                    .for_each(|mut col| {
                        // Convert to rustfft compatible format
                        let mut buffer: Vec<RustComplex<f64>> =
                            col.iter().map(|&c| RustComplex::new(c.re, c.im)).collect();

                        // Perform inverse FFT
                        col_ifft.process(&mut buffer);

                        // Update column with IFFT result
                        for (i, val) in buffer.iter().enumerate() {
                            col[i] = Complex64::new(val.re, val.im);
                        }
                    });
            } else {
                // Fall back to sequential processing if only one worker
                for mut col in padded_input.columns_mut() {
                    let mut buffer: Vec<RustComplex<f64>> =
                        col.iter().map(|&c| RustComplex::new(c.re, c.im)).collect();

                    col_ifft.process(&mut buffer);

                    for (i, val) in buffer.iter().enumerate() {
                        col[i] = Complex64::new(val.re, val.im);
                    }
                }
            }
        }

        #[cfg(not(feature = "rustfft-backend"))]
        {
            return Err(crate::FFTError::ComputationError(
                "No FFT backend available. Enable either 'oxifft' or 'rustfft-backend' feature."
                    .to_string(),
            ));
        }
    }

    // Apply appropriate normalization
    let total_elements = outputshape.0 * outputshape.1;
    let scale = match norm_mode {
        NormMode::Backward => 1.0 / (total_elements as f64),
        NormMode::Ortho => 1.0 / (total_elements as f64).sqrt(),
        NormMode::Forward => 1.0, // No additional normalization for forward mode in IFFT
        NormMode::None => 1.0,    // No normalization
    };

    if scale != 1.0 {
        padded_input.mapv_inplace(|x| x * scale);
    }

    Ok(padded_input)
}

/// Non-parallel fallback implementation of ifft2_parallel for when the parallel feature is disabled
#[cfg(not(feature = "parallel"))]
#[allow(dead_code)]
pub fn ifft2_parallel<T>(
    input: &Array2<T>,
    shape: Option<(usize, usize)>,
    _axes: Option<(i32, i32)>,
    _norm: Option<&str>,
    _workers: Option<usize>,
) -> FFTResult<Array2<Complex64>>
where
    T: NumCast + Copy + std::fmt::Debug + 'static,
{
    // When parallel feature is disabled, just use the standard ifft2 implementation
    crate::fft::algorithms::ifft2(input, shape, None, None)
}