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
//! FFT Plan Caching Module
//!
//! This module provides a caching mechanism for FFT plans to improve performance
//! when performing repeated transforms of the same size.

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

// ========================================
// RUSTFFT BACKEND
// ========================================

#[cfg(feature = "rustfft-backend")]
use rustfft::FftPlanner;

/// Cache key for storing FFT plans
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
struct PlanKey {
    size: usize,
    forward: bool,
    // Future: Add backend identifier when we support multiple backends
}

/// Cached FFT plan with metadata (rustfft backend)
#[cfg(feature = "rustfft-backend")]
#[derive(Clone)]
struct CachedPlan {
    plan: Arc<dyn rustfft::Fft<f64>>,
    last_used: Instant,
    usage_count: usize,
}

/// Cached FFT plan with metadata (OxiFFT backend)
#[cfg(all(feature = "oxifft", not(feature = "rustfft-backend")))]
#[derive(Clone)]
struct CachedPlan {
    // For OxiFFT, we don't store the plan here since it's managed globally
    // This struct just tracks metadata for statistics
    size: usize,
    forward: bool,
    last_used: Instant,
    usage_count: usize,
}

/// FFT Plan Cache with configurable size limits and TTL
pub struct PlanCache {
    cache: Arc<Mutex<HashMap<PlanKey, CachedPlan>>>,
    max_entries: usize,
    max_age: Duration,
    enabled: Arc<Mutex<bool>>,
    hit_count: Arc<Mutex<u64>>,
    miss_count: Arc<Mutex<u64>>,
}

impl PlanCache {
    /// Create a new plan cache with default settings
    pub fn new() -> Self {
        Self {
            cache: Arc::new(Mutex::new(HashMap::new())),
            max_entries: 128,
            max_age: Duration::from_secs(3600), // 1 hour
            enabled: Arc::new(Mutex::new(true)),
            hit_count: Arc::new(Mutex::new(0)),
            miss_count: Arc::new(Mutex::new(0)),
        }
    }

    /// Create a new plan cache with custom settings
    pub fn with_config(max_entries: usize, max_age: Duration) -> Self {
        Self {
            cache: Arc::new(Mutex::new(HashMap::new())),
            max_entries,
            max_age,
            enabled: Arc::new(Mutex::new(true)),
            hit_count: Arc::new(Mutex::new(0)),
            miss_count: Arc::new(Mutex::new(0)),
        }
    }

    /// Enable or disable the cache
    pub fn set_enabled(&self, enabled: bool) {
        *self.enabled.lock().expect("Operation failed") = enabled;
    }

    /// Check if the cache is enabled
    pub fn is_enabled(&self) -> bool {
        *self.enabled.lock().expect("Operation failed")
    }

    /// Clear all cached plans
    pub fn clear(&self) {
        if let Ok(mut cache) = self.cache.lock() {
            cache.clear();
        }
    }

    /// Get statistics about cache usage
    pub fn get_stats(&self) -> CacheStats {
        let hit_count = *self.hit_count.lock().expect("Operation failed");
        let miss_count = *self.miss_count.lock().expect("Operation failed");
        let total_requests = hit_count + miss_count;
        let hit_rate = if total_requests > 0 {
            hit_count as f64 / total_requests as f64
        } else {
            0.0
        };

        let size = self.cache.lock().map(|c| c.len()).unwrap_or(0);

        CacheStats {
            hit_count,
            miss_count,
            hit_rate,
            size,
            max_size: self.max_entries,
        }
    }

    /// Get or create an FFT plan for the given size and direction (rustfft backend)
    #[cfg(feature = "rustfft-backend")]
    pub fn get_or_create_plan(
        &self,
        size: usize,
        forward: bool,
        planner: &mut FftPlanner<f64>,
    ) -> Arc<dyn rustfft::Fft<f64>> {
        if !*self.enabled.lock().expect("Operation failed") {
            return if forward {
                planner.plan_fft_forward(size)
            } else {
                planner.plan_fft_inverse(size)
            };
        }

        let key = PlanKey { size, forward };

        // Try to get from cache first
        if let Ok(mut cache) = self.cache.lock() {
            if let Some(cached) = cache.get_mut(&key) {
                // Check if the plan is still valid (not too old)
                if cached.last_used.elapsed() <= self.max_age {
                    cached.last_used = Instant::now();
                    cached.usage_count += 1;
                    *self.hit_count.lock().expect("Operation failed") += 1;
                    return cached.plan.clone();
                } else {
                    // Remove stale entry
                    cache.remove(&key);
                }
            }
        }

        // Cache miss - create new plan
        *self.miss_count.lock().expect("Operation failed") += 1;

        let plan: Arc<dyn rustfft::Fft<f64>> = if forward {
            planner.plan_fft_forward(size)
        } else {
            planner.plan_fft_inverse(size)
        };

        // Store in cache if enabled
        if let Ok(mut cache) = self.cache.lock() {
            // Clean up old entries if we're at capacity
            if cache.len() >= self.max_entries {
                self.evict_old_entries(&mut cache);
            }

            cache.insert(
                key,
                CachedPlan {
                    plan: plan.clone(),
                    last_used: Instant::now(),
                    usage_count: 1,
                },
            );
        }

        plan
    }

    /// Get or create an FFT plan for the given size and direction (OxiFFT backend)
    ///
    /// Note: OxiFFT plans are managed globally via oxifft_plan_cache.
    /// This method provides a compatible API but delegates to the global cache.
    #[cfg(all(feature = "oxifft", not(feature = "rustfft-backend")))]
    pub fn track_plan_usage(&self, size: usize, forward: bool) {
        if !*self.enabled.lock().expect("Operation failed") {
            return;
        }

        let key = PlanKey { size, forward };

        // Try to get from cache first
        if let Ok(mut cache) = self.cache.lock() {
            if let Some(cached) = cache.get_mut(&key) {
                // Check if the plan is still valid (not too old)
                if cached.last_used.elapsed() <= self.max_age {
                    cached.last_used = Instant::now();
                    cached.usage_count += 1;
                    *self.hit_count.lock().expect("Operation failed") += 1;
                    return;
                } else {
                    // Remove stale entry
                    cache.remove(&key);
                }
            }
        }

        // Cache miss - track new plan
        *self.miss_count.lock().expect("Operation failed") += 1;

        // Store metadata in cache if enabled
        if let Ok(mut cache) = self.cache.lock() {
            // Clean up old entries if we're at capacity
            if cache.len() >= self.max_entries {
                self.evict_old_entries(&mut cache);
            }

            cache.insert(
                key,
                CachedPlan {
                    size,
                    forward,
                    last_used: Instant::now(),
                    usage_count: 1,
                },
            );
        }
    }

    /// Evict old entries from the cache (LRU-style)
    fn evict_old_entries(&self, cache: &mut HashMap<PlanKey, CachedPlan>) {
        // Remove entries older than max_age
        cache.retain(|_, v| v.last_used.elapsed() <= self.max_age);

        // If still over capacity, remove least recently used
        while cache.len() >= self.max_entries {
            if let Some((key_to_remove_, _)) = cache
                .iter()
                .min_by_key(|(_, v)| (v.last_used, v.usage_count))
                .map(|(k, v)| (k.clone(), v.clone()))
            {
                cache.remove(&key_to_remove_);
            } else {
                break;
            }
        }
    }

    /// Pre-populate cache with common sizes (rustfft backend)
    #[cfg(feature = "rustfft-backend")]
    pub fn precompute_common_sizes(&self, sizes: &[usize], planner: &mut FftPlanner<f64>) {
        for &size in sizes {
            // Pre-compute both forward and inverse plans
            self.get_or_create_plan(size, true, planner);
            self.get_or_create_plan(size, false, planner);
        }
    }

    /// Pre-populate cache with common sizes (OxiFFT backend)
    ///
    /// Note: With OxiFFT, plans are created lazily and cached globally.
    /// This method just tracks the sizes for statistics.
    #[cfg(all(feature = "oxifft", not(feature = "rustfft-backend")))]
    pub fn precompute_common_sizes(&self, sizes: &[usize]) {
        for &size in sizes {
            // Track both forward and inverse plans
            self.track_plan_usage(size, true);
            self.track_plan_usage(size, false);
        }
    }
}

impl Default for PlanCache {
    fn default() -> Self {
        Self::new()
    }
}

/// Statistics about cache usage
#[derive(Debug, Clone)]
pub struct CacheStats {
    pub hit_count: u64,
    pub miss_count: u64,
    pub hit_rate: f64,
    pub size: usize,
    pub max_size: usize,
}

impl std::fmt::Display for CacheStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Cache Stats: {} hits, {} misses ({:.1}% hit rate), {}/{} entries",
            self.hit_count,
            self.miss_count,
            self.hit_rate * 100.0,
            self.size,
            self.max_size
        )
    }
}

/// Global plan cache instance
static GLOBAL_PLAN_CACHE: std::sync::OnceLock<PlanCache> = std::sync::OnceLock::new();

/// Get the global plan cache instance
#[allow(dead_code)]
pub fn get_global_cache() -> &'static PlanCache {
    GLOBAL_PLAN_CACHE.get_or_init(PlanCache::new)
}

/// Initialize the global plan cache with custom settings
#[allow(dead_code)]
pub fn init_global_cache(max_entries: usize, max_age: Duration) -> Result<(), &'static str> {
    GLOBAL_PLAN_CACHE
        .set(PlanCache::with_config(max_entries, max_age))
        .map_err(|_| "Global plan cache already initialized")
}

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

    #[cfg(feature = "rustfft-backend")]
    #[test]
    fn test_plan_cache_basic_rustfft() {
        let cache = PlanCache::new();
        let mut planner = FftPlanner::new();

        // Get the same plan twice
        let _plan1 = cache.get_or_create_plan(128, true, &mut planner);
        let _plan2 = cache.get_or_create_plan(128, true, &mut planner);

        // Second request should be a cache hit
        let stats = cache.get_stats();
        assert_eq!(stats.hit_count, 1);
        assert_eq!(stats.miss_count, 1);
    }

    #[cfg(feature = "rustfft-backend")]
    #[test]
    fn test_cache_eviction_rustfft() {
        let cache = PlanCache::with_config(2, Duration::from_secs(3600));
        let mut planner = FftPlanner::new();

        // Fill cache with 2 entries
        cache.get_or_create_plan(64, true, &mut planner);
        cache.get_or_create_plan(128, true, &mut planner);

        // Add a third entry, which should evict the oldest
        cache.get_or_create_plan(256, true, &mut planner);

        let stats = cache.get_stats();
        assert_eq!(stats.size, 2);
    }

    #[cfg(feature = "rustfft-backend")]
    #[test]
    fn test_cache_disabled_rustfft() {
        let cache = PlanCache::new();
        cache.set_enabled(false);

        let mut planner = FftPlanner::new();

        // Get the same plan twice with cache disabled
        cache.get_or_create_plan(128, true, &mut planner);
        cache.get_or_create_plan(128, true, &mut planner);

        // Both should be misses
        let stats = cache.get_stats();
        assert_eq!(stats.hit_count, 0);
        assert_eq!(stats.miss_count, 0); // No tracking when disabled
    }

    #[cfg(all(feature = "oxifft", not(feature = "rustfft-backend")))]
    #[test]
    fn test_plan_cache_basic_oxifft() {
        let cache = PlanCache::new();

        // Track the same plan twice
        cache.track_plan_usage(128, true);
        cache.track_plan_usage(128, true);

        // Second request should be a cache hit
        let stats = cache.get_stats();
        assert_eq!(stats.hit_count, 1);
        assert_eq!(stats.miss_count, 1);
    }

    #[cfg(all(feature = "oxifft", not(feature = "rustfft-backend")))]
    #[test]
    fn test_cache_eviction_oxifft() {
        let cache = PlanCache::with_config(2, Duration::from_secs(3600));

        // Fill cache with 2 entries
        cache.track_plan_usage(64, true);
        cache.track_plan_usage(128, true);

        // Add a third entry, which should evict the oldest
        cache.track_plan_usage(256, true);

        let stats = cache.get_stats();
        assert_eq!(stats.size, 2);
    }

    #[cfg(all(feature = "oxifft", not(feature = "rustfft-backend")))]
    #[test]
    fn test_cache_disabled_oxifft() {
        let cache = PlanCache::new();
        cache.set_enabled(false);

        // Track the same plan twice with cache disabled
        cache.track_plan_usage(128, true);
        cache.track_plan_usage(128, true);

        // Both should be misses
        let stats = cache.get_stats();
        assert_eq!(stats.hit_count, 0);
        assert_eq!(stats.miss_count, 0); // No tracking when disabled
    }
}