scirs2-fft 0.4.2

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
use plotly::{
    common::{Mode, Title},
    Layout, Plot, Scatter,
};
use scirs2_core::random::rngs::StdRng;
use scirs2_core::random::SeedableRng;
use scirs2_core::random::{Distribution, Normal};
use scirs2_fft::{
    sparse_fft::{SparseFFTAlgorithm, SparseFFTResult, WindowFunction},
    sparse_fft_gpu::GPUBackend,
    sparse_fft_gpu_cuda::{cuda_sparse_fft, get_cuda_devices},
    sparse_fft_gpu_memory::{init_global_memory_manager, is_cuda_available, AllocationStrategy},
};
use std::f64::consts::PI;
use std::time::Instant;

/// Create a sparse signal with known frequencies in the spectrum
#[allow(dead_code)]
fn create_sparse_signal(n: usize, frequencies: &[(usize, f64)], noise_level: f64) -> Vec<f64> {
    // Create deterministic RNG for reproducible results
    let mut rng = StdRng::seed_from_u64(42);
    let normal = Normal::new(0.0, noise_level).expect("Operation failed");

    let mut signal = vec![0.0; n];

    // Add sinusoidal components
    for (i, sample) in signal.iter_mut().enumerate().take(n) {
        let t = 2.0 * PI * (i as f64) / (n as f64);
        for &(freq, amp) in frequencies {
            *sample += amp * (freq as f64 * t).sin();
        }
    }

    // Add noise
    if noise_level > 0.0 {
        for sample in &mut signal {
            *sample += normal.sample(&mut rng);
        }
    }

    signal
}

/// Calculate relative error between identified frequencies and ground truth
#[allow(dead_code)]
fn calculate_frequency_error(result: &SparseFFTResult, truefrequencies: &[(usize, f64)]) -> f64 {
    let mut min_error_sum = 0.0;
    let mut found_count = 0;

    // For each true frequency, find the closest detected frequency
    for &(true_freq, _true_amp) in truefrequencies {
        let mut min_error = f64::MAX;

        // Find the closest detected frequency
        for &detected_freq in result.indices.iter() {
            let error =
                (detected_freq as f64 - true_freq as f64).abs() / (true_freq as f64).max(1.0);
            if error < min_error {
                min_error = error;
                if min_error < 0.05 {
                    // Consider it found if within 5% error
                    found_count += 1;
                }
            }
        }

        min_error_sum += min_error;
    }

    // Return average error
    if found_count > 0 {
        min_error_sum / found_count as f64
    } else {
        1.0 // All _frequencies missed
    }
}

/// Run a benchmark of all algorithms on signals with different characteristics
#[allow(dead_code)]
fn run_algorithm_benchmarks() {
    // Print header
    println!(
        "\n{:<15} {:<15} {:<15} {:<15} {:<15} {:<15}",
        "Signal Type", "Size", "Sublinear", "CompressedSensing", "Iterative", "FrequencyPruning"
    );
    println!("{:-<80}", "");

    // List of signal sizes to test
    let signalsizes = [1024, 8 * 1024, 64 * 1024, 256 * 1024];

    // List of noise levels to test
    let noise_levels = [0.0, 0.05, 0.2, 0.5];

    // Initialize GPU if available
    if is_cuda_available() {
        let _ = init_global_memory_manager(
            GPUBackend::CUDA,
            0, // First device
            AllocationStrategy::CacheBySize,
            1024 * 1024 * 1024, // 1 GB limit
        );
    }

    // List of algorithms to benchmark
    let algorithms = [
        SparseFFTAlgorithm::Sublinear,
        SparseFFTAlgorithm::CompressedSensing,
        SparseFFTAlgorithm::Iterative,
        SparseFFTAlgorithm::FrequencyPruning,
    ];

    // Test over different signal sizes
    for &size in &signalsizes {
        // Create frequency components (scaled by signal size)
        let frequencies = vec![
            (size / 100, 1.0),
            (size / 40, 0.5),
            (size / 20, 0.25),
            (size / 10, 0.15),
            (size / 5, 0.1),
        ];

        // Test clean signal
        let clean_signal = create_sparse_signal(size, &frequencies, 0.0);
        let mut clean_times = Vec::new();

        for &algorithm in &algorithms {
            let start = Instant::now();
            let _ = cuda_sparse_fft(
                &clean_signal,
                10, // Sparsity parameter
                0,  // Device ID
                Some(algorithm),
                Some(WindowFunction::Hann),
            )
            .expect("Operation failed");
            let elapsed = start.elapsed().as_millis();
            clean_times.push(elapsed);
        }

        println!(
            "{:<15} {:<15} {:<15} {:<15} {:<15} {:<15}",
            "Clean", size, clean_times[0], clean_times[1], clean_times[2], clean_times[3]
        );

        // Test different noise levels
        for &noise in &noise_levels {
            if noise > 0.0 {
                let noisy_signal = create_sparse_signal(size, &frequencies, noise);
                let mut noisy_times = Vec::new();

                for &algorithm in &algorithms {
                    let start = Instant::now();
                    let _ = cuda_sparse_fft(
                        &noisy_signal,
                        10, // Sparsity parameter
                        0,  // Device ID
                        Some(algorithm),
                        Some(WindowFunction::Hann),
                    )
                    .expect("Operation failed");
                    let elapsed = start.elapsed().as_millis();
                    noisy_times.push(elapsed);
                }

                println!(
                    "{:<15} {:<15} {:<15} {:<15} {:<15} {:<15}",
                    format!("Noise {:.2}", noise),
                    size,
                    noisy_times[0],
                    noisy_times[1],
                    noisy_times[2],
                    noisy_times[3]
                );
            }
        }
    }
}

/// Analyze algorithm accuracy on signals with increasing noise levels
#[allow(dead_code)]
fn analyze_algorithm_accuracy() {
    println!("\nAnalyzing algorithm accuracy with increasing noise levels:");

    // Signal parameters
    let n = 16 * 1024;
    let frequencies = vec![(30, 1.0), (100, 0.5), (300, 0.25), (700, 0.1), (1500, 0.05)];

    // List of noise levels to test
    let noise_levels = [0.0, 0.01, 0.05, 0.1, 0.2, 0.5, 1.0];

    // Create plots
    let mut accuracy_plot = Plot::new();
    let mut time_plot = Plot::new();

    // Test each algorithm
    let algorithms = [
        SparseFFTAlgorithm::Sublinear,
        SparseFFTAlgorithm::CompressedSensing,
        SparseFFTAlgorithm::Iterative,
        SparseFFTAlgorithm::FrequencyPruning,
    ];

    // Set up result arrays
    let mut algorithm_errors = vec![Vec::new(); algorithms.len()];
    let mut algorithm_times = vec![Vec::new(); algorithms.len()];

    // Print header
    println!(
        "\n{:<15} {:<20} {:<20} {:<15}",
        "Noise Level", "Algorithm", "Frequency Error (%)", "Time (ms)"
    );
    println!("{:-<75}", "");

    // Test over different noise levels
    for &noise in &noise_levels {
        // Create signal with this noise level
        let signal = create_sparse_signal(n, &frequencies, noise);

        // Test each algorithm
        for (i, &algorithm) in algorithms.iter().enumerate() {
            // Run the algorithm
            let start = Instant::now();
            let result = cuda_sparse_fft(
                &signal,
                10, // Sparsity parameter (more than actual to ensure we find all)
                0,  // Device ID
                Some(algorithm),
                Some(WindowFunction::Hann),
            )
            .expect("Operation failed");
            let elapsed = start.elapsed().as_millis();

            // Calculate error
            let error = calculate_frequency_error(&result, &frequencies);
            let error_percent = error * 100.0;

            // Store results
            algorithm_errors[i].push(error_percent);
            algorithm_times[i].push(elapsed as f64);

            // Print results
            println!(
                "{:<15.3} {:<20} {:<20.2} {:<15}",
                noise,
                format!("{:?}", algorithm),
                error_percent,
                elapsed
            );
        }
    }

    // Add traces to plots
    for (i, &algorithm) in algorithms.iter().enumerate() {
        // Accuracy plot
        let error_trace = Scatter::new(
            noise_levels
                .iter()
                .map(|&n| format!("{n:.2}"))
                .collect::<Vec<_>>(),
            algorithm_errors[i].clone(),
        )
        .name(format!("{algorithm:?}"))
        .mode(Mode::LinesMarkers);

        accuracy_plot.add_trace(error_trace);

        // Time plot
        let time_trace = Scatter::new(
            noise_levels
                .iter()
                .map(|&n| format!("{n:.2}"))
                .collect::<Vec<_>>(),
            algorithm_times[i].clone(),
        )
        .name(format!("{algorithm:?}"))
        .mode(Mode::LinesMarkers);

        time_plot.add_trace(time_trace);
    }

    // Set layouts
    accuracy_plot.set_layout(
        Layout::new()
            .title(Title::with_text("<b>Algorithm Accuracy vs Noise Level</b>"))
            .x_axis(plotly::layout::Axis::new().title(Title::with_text("Noise Level (σ)")))
            .y_axis(
                plotly::layout::Axis::new()
                    .title(Title::with_text("Frequency Error (%)"))
                    .range(vec![0.0, 30.0]),
            ),
    );

    time_plot.set_layout(
        Layout::new()
            .title(Title::with_text(
                "<b>Algorithm Execution Time vs Noise Level</b>",
            ))
            .x_axis(plotly::layout::Axis::new().title(Title::with_text("Noise Level (σ)")))
            .y_axis(
                plotly::layout::Axis::new()
                    .title(Title::with_text("Execution Time (ms)"))
                    .type_(plotly::layout::AxisType::Log),
            ),
    );

    // Save plots
    accuracy_plot.write_html("sparse_fft_algorithm_accuracy.html");
    time_plot.write_html("sparse_fft_algorithm_timing.html");

    println!(
        "\nPlots saved as sparse_fft_algorithm_accuracy.html and sparse_fft_algorithm_timing.html"
    );
}

/// Analyze the performance of different algorithms with increasing signal size
#[allow(dead_code)]
fn analyze_scaling_behavior() {
    println!("\nAnalyzing algorithm scaling behavior with increasing signal size:");

    // Signal sizes to test
    let sizes = [
        1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576,
    ];

    // Create plots
    let mut scaling_plot = Plot::new();

    // Test each algorithm
    let algorithms = [
        SparseFFTAlgorithm::Sublinear,
        SparseFFTAlgorithm::CompressedSensing,
        SparseFFTAlgorithm::Iterative,
        SparseFFTAlgorithm::FrequencyPruning,
    ];

    // Set up result arrays
    let mut algorithm_times = vec![Vec::new(); algorithms.len()];

    // Print header
    println!(
        "\n{:<15} {:<20} {:<15}",
        "Signal Size", "Algorithm", "Time (ms)"
    );
    println!("{:-<55}", "");

    // Test over different signal sizes
    for &size in &sizes {
        // Create frequency components (scaled by signal size)
        let frequencies = vec![
            (size / 100, 1.0),
            (size / 40, 0.5),
            (size / 20, 0.25),
            (size / 10, 0.15),
            (size / 5, 0.1),
        ];

        // Create signal
        let signal = create_sparse_signal(size, &frequencies, 0.05); // Light noise

        // Test each algorithm
        for (i, &algorithm) in algorithms.iter().enumerate() {
            // Run the algorithm
            let start = Instant::now();
            let _ = cuda_sparse_fft(
                &signal,
                10, // Sparsity parameter
                0,  // Device ID
                Some(algorithm),
                Some(WindowFunction::Hann),
            )
            .expect("Operation failed");
            let elapsed = start.elapsed().as_millis();

            // Store results
            algorithm_times[i].push(elapsed as f64);

            // Print results
            println!(
                "{:<15} {:<20} {:<15}",
                size,
                format!("{:?}", algorithm),
                elapsed
            );
        }
    }

    // Add traces to plot
    for (i, &algorithm) in algorithms.iter().enumerate() {
        // Scaling plot
        let time_trace = Scatter::new(
            sizes.iter().map(|&s| format!("{s}")).collect::<Vec<_>>(),
            algorithm_times[i].clone(),
        )
        .name(format!("{algorithm:?}"))
        .mode(Mode::LinesMarkers);

        scaling_plot.add_trace(time_trace);
    }

    // Set layout
    scaling_plot.set_layout(
        Layout::new()
            .title(Title::with_text(
                "<b>Algorithm Scaling with Signal Size</b>",
            ))
            .x_axis(
                plotly::layout::Axis::new()
                    .title(Title::with_text("Signal Size (samples)"))
                    .type_(plotly::layout::AxisType::Log),
            )
            .y_axis(
                plotly::layout::Axis::new()
                    .title(Title::with_text("Execution Time (ms)"))
                    .type_(plotly::layout::AxisType::Log),
            ),
    );

    // Save plot
    scaling_plot.write_html("sparse_fft_algorithm_scaling.html");

    println!("\nPlot saved as sparse_fft_algorithm_scaling.html");
}

#[allow(dead_code)]
fn main() {
    println!("GPU-Accelerated Sparse FFT Algorithm Comparison");
    println!("===============================================");

    // Check CUDA availability
    if is_cuda_available() {
        let devices = get_cuda_devices().expect("Operation failed");
        println!("\nCUDA is available with {} device(s):", devices.len());

        for (idx, device) in devices.iter().enumerate() {
            println!("  - Device {} (initialized: {})", idx, device.initialized);
        }

        // Initialize GPU memory manager
        let _ = init_global_memory_manager(
            GPUBackend::CUDA,
            0, // First device
            AllocationStrategy::CacheBySize,
            1024 * 1024 * 1024, // 1 GB limit
        );

        // Run benchmarks
        run_algorithm_benchmarks();

        // Analyze accuracy
        analyze_algorithm_accuracy();

        // Analyze scaling behavior
        analyze_scaling_behavior();

        println!("\nAnalysis completed successfully!");
    } else {
        println!("\nCUDA is not available. This example requires GPU acceleration.");
    }
}