oxifft 0.3.1

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
//! Frequency hashing utilities for sparse FFT.
//!
//! Implements hash functions used to map frequencies to buckets
//! in the FFAST algorithm.

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

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

/// Hash function for frequency bucketization.
#[derive(Debug, Clone, Copy)]
pub struct FrequencyHash {
    /// Number of buckets.
    num_buckets: usize,
    /// Signal length.
    n: usize,
    /// Permutation offset (random shift).
    offset: usize,
    /// Permutation scale (multiplicative).
    scale: usize,
}

impl FrequencyHash {
    /// Create a new frequency hash function.
    ///
    /// # Arguments
    ///
    /// * `num_buckets` - Number of buckets (B)
    /// * `n` - Signal length
    pub fn new(num_buckets: usize, n: usize) -> Self {
        Self {
            num_buckets,
            n,
            offset: 0,
            scale: 1,
        }
    }

    /// Create with random permutation parameters.
    ///
    /// # Arguments
    ///
    /// * `num_buckets` - Number of buckets
    /// * `n` - Signal length
    /// * `seed` - Random seed for permutation
    pub fn with_permutation(num_buckets: usize, n: usize, seed: u64) -> Self {
        // Simple pseudo-random permutation using linear congruential generator
        let offset = ((seed * 1103515245 + 12345) % (n as u64)) as usize;
        let scale = Self::find_coprime(n, seed);

        Self {
            num_buckets,
            n,
            offset,
            scale,
        }
    }

    /// Find a coprime for multiplicative permutation.
    fn find_coprime(n: usize, seed: u64) -> usize {
        // Start from a seed-based value and find nearest coprime
        let start = ((seed * 48271) % (n as u64)) as usize;
        let start = start.max(1);

        for candidate in start..n {
            if gcd(candidate, n) == 1 {
                return candidate;
            }
        }

        // Fallback
        1
    }

    /// Hash a frequency index to a bucket.
    #[inline]
    pub fn hash(&self, freq: usize) -> usize {
        // Apply permutation: (scale * freq + offset) mod n, then mod num_buckets
        let permuted = (self.scale.wrapping_mul(freq).wrapping_add(self.offset)) % self.n;
        permuted % self.num_buckets
    }

    /// Inverse hash: find candidate frequencies that map to a bucket.
    ///
    /// Returns all frequencies in [0, n) that hash to the given bucket.
    pub fn inverse_hash(&self, bucket: usize) -> Vec<usize> {
        let mut candidates = Vec::new();

        for freq in 0..self.n {
            if self.hash(freq) == bucket {
                candidates.push(freq);
            }
        }

        candidates
    }

    /// Get collision probability estimate.
    ///
    /// Returns expected number of collisions for k sparse frequencies.
    pub fn collision_probability(&self, k: usize) -> f64 {
        // Birthday paradox approximation
        let b = self.num_buckets as f64;
        let k_f = k as f64;

        // Expected collisions ≈ k^2 / (2B)
        (k_f * k_f) / (2.0 * b)
    }

    /// Number of buckets.
    pub fn num_buckets(&self) -> usize {
        self.num_buckets
    }

    /// Signal length.
    pub fn signal_length(&self) -> usize {
        self.n
    }
}

/// Multi-hash using Chinese Remainder Theorem.
///
/// Uses multiple coprime bucket counts to uniquely identify frequencies.
/// Kept for future algorithm enhancements.
#[derive(Debug, Clone)]
pub struct CrtHash {
    /// Individual hash functions with coprime bucket counts.
    hashes: Vec<FrequencyHash>,
    /// Product of all bucket counts.
    product: usize,
    /// Signal length.
    n: usize,
}

impl CrtHash {
    /// Create a CRT-based multi-hash.
    ///
    /// # Arguments
    ///
    /// * `bucket_counts` - Array of coprime bucket counts
    /// * `n` - Signal length
    pub fn new(bucket_counts: &[usize], n: usize) -> Self {
        let hashes: Vec<_> = bucket_counts
            .iter()
            .map(|&b| FrequencyHash::new(b, n))
            .collect();

        let product: usize = bucket_counts.iter().product();

        Self { hashes, product, n }
    }

    /// Create from coprime factors.
    ///
    /// # Arguments
    ///
    /// * `factors` - Coprime factors for bucket counts
    /// * `n` - Signal length
    pub fn from_factors(factors: &[usize], n: usize) -> Self {
        Self::new(factors, n)
    }

    /// Hash a frequency to a tuple of bucket indices.
    pub fn hash(&self, freq: usize) -> Vec<usize> {
        self.hashes.iter().map(|h| h.hash(freq)).collect()
    }

    /// Recover frequency from bucket indices using CRT.
    ///
    /// # Arguments
    ///
    /// * `bucket_indices` - Tuple of bucket indices from each hash
    ///
    /// # Returns
    ///
    /// Recovered frequency if valid, None otherwise.
    pub fn recover_frequency(&self, bucket_indices: &[usize]) -> Option<usize> {
        if bucket_indices.len() != self.hashes.len() {
            return None;
        }

        // Apply CRT to solve:
        // x ≡ bucket_indices[i] (mod bucket_counts[i]) for all i

        let mut result = 0usize;

        for (i, &idx) in bucket_indices.iter().enumerate() {
            let ni = self.hashes[i].num_buckets();
            let mi = self.product / ni;

            // Find multiplicative inverse of mi mod ni
            if let Some(yi) = mod_inverse(mi % ni, ni) {
                result = result.wrapping_add(idx.wrapping_mul(mi).wrapping_mul(yi));
            } else {
                return None;
            }
        }

        let freq = result % self.product;
        if freq < self.n {
            Some(freq)
        } else {
            None
        }
    }

    /// Number of hash functions.
    pub fn num_hashes(&self) -> usize {
        self.hashes.len()
    }

    /// Get individual hash functions.
    pub fn hashes(&self) -> &[FrequencyHash] {
        &self.hashes
    }
}

/// Calculate GCD using Euclidean algorithm.
fn gcd(a: usize, b: usize) -> usize {
    if b == 0 {
        a
    } else {
        gcd(b, a % b)
    }
}

/// Calculate modular multiplicative inverse using extended Euclidean algorithm.
fn mod_inverse(a: usize, m: usize) -> Option<usize> {
    if m == 0 {
        return None;
    }

    let (gcd, x, _) = extended_gcd(a as i64, m as i64);

    if gcd != 1 {
        return None; // No inverse exists
    }

    // Make sure result is positive
    let inv = ((x % m as i64) + m as i64) % m as i64;
    Some(inv as usize)
}

/// Extended Euclidean algorithm.
///
/// Returns (gcd, x, y) such that a*x + b*y = gcd.
fn extended_gcd(a: i64, b: i64) -> (i64, i64, i64) {
    if a == 0 {
        (b, 0, 1)
    } else {
        let (gcd, x, y) = extended_gcd(b % a, a);
        (gcd, y - (b / a) * x, x)
    }
}

/// Generate coprime factors for CRT.
///
/// Returns a set of small coprime numbers whose product is at least target.
pub fn generate_coprime_factors(target: usize, max_factor: usize) -> Vec<usize> {
    let small_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47];

    let mut factors = Vec::new();
    let mut product = 1usize;

    for &p in &small_primes {
        if product >= target {
            break;
        }
        if p <= max_factor {
            factors.push(p);
            product *= p;
        }
    }

    factors
}

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

    #[test]
    fn test_frequency_hash() {
        let hash = FrequencyHash::new(16, 1024);

        // Simple modulo hash
        assert_eq!(hash.hash(0), 0);
        assert_eq!(hash.hash(16), 0);
        assert_eq!(hash.hash(17), 1);
    }

    #[test]
    fn test_hash_with_permutation() {
        let hash = FrequencyHash::with_permutation(16, 1024, 12345);

        // Should produce valid bucket indices
        for freq in 0..100 {
            let bucket = hash.hash(freq);
            assert!(bucket < 16);
        }
    }

    #[test]
    fn test_inverse_hash() {
        let hash = FrequencyHash::new(8, 64);

        let candidates = hash.inverse_hash(0);
        // Should include 0, 8, 16, 24, 32, 40, 48, 56
        assert!(candidates.contains(&0));
        assert!(candidates.contains(&8));
        assert!(candidates.contains(&16));
    }

    #[test]
    fn test_collision_probability() {
        let hash = FrequencyHash::new(100, 1000);

        let prob = hash.collision_probability(10);
        // k^2/(2B) = 100/200 = 0.5
        assert!((prob - 0.5).abs() < 0.01);
    }

    #[test]
    fn test_crt_hash() {
        let crt = CrtHash::new(&[3, 5, 7], 1024);

        // Test round-trip: hash and recover
        for freq in 0..100 {
            let buckets = crt.hash(freq);
            if let Some(recovered) = crt.recover_frequency(&buckets) {
                // Recovered frequency should match original mod product
                assert_eq!(recovered % 105, freq % 105);
            }
        }
    }

    #[test]
    fn test_gcd() {
        assert_eq!(gcd(12, 8), 4);
        assert_eq!(gcd(17, 13), 1);
        assert_eq!(gcd(100, 35), 5);
    }

    #[test]
    fn test_mod_inverse() {
        // 3 * 7 = 21 ≡ 1 (mod 10)
        assert_eq!(mod_inverse(3, 10), Some(7));

        // No inverse when gcd != 1
        assert_eq!(mod_inverse(4, 8), None);
    }

    #[test]
    fn test_generate_coprime_factors() {
        let factors = generate_coprime_factors(100, 50);
        assert!(factors.len() >= 2);

        // Product should be at least 100
        let product: usize = factors.iter().product();
        assert!(product >= 100);

        // All factors should be coprime
        for i in 0..factors.len() {
            for j in i + 1..factors.len() {
                assert_eq!(gcd(factors[i], factors[j]), 1);
            }
        }
    }

    #[test]
    fn test_frequency_hash_signal_length() {
        let hash = FrequencyHash::new(16, 1024);
        assert_eq!(hash.signal_length(), 1024);
    }

    #[test]
    fn test_frequency_hash_with_permutation_hash_range() {
        let hash = FrequencyHash::with_permutation(16, 1024, 42);
        for freq in 0..50 {
            let bucket = hash.hash(freq);
            assert!(bucket < 16, "hash({freq}) = {bucket} out of range [0, 16)");
        }
    }

    #[test]
    fn test_crt_hash_from_factors() {
        let crt = CrtHash::from_factors(&[3, 5, 7], 1024);
        assert_eq!(crt.num_hashes(), 3);
    }

    #[test]
    fn test_crt_hash_num_hashes_and_hashes() {
        let crt = CrtHash::new(&[3, 5], 256);
        assert_eq!(crt.num_hashes(), 2);
        let hash_fns = crt.hashes();
        assert_eq!(hash_fns.len(), 2);
        assert_eq!(hash_fns[0].num_buckets(), 3);
        assert_eq!(hash_fns[1].num_buckets(), 5);
    }

    #[test]
    fn test_extended_gcd_basic() {
        // Bezout identity: 3*x + 5*y = gcd(3,5)=1
        let (g, x, y) = extended_gcd(3, 5);
        assert_eq!(g, 1);
        assert_eq!(3 * x + 5 * y, g);
    }

    #[test]
    fn test_extended_gcd_non_coprime() {
        let (g, x, y) = extended_gcd(12, 8);
        assert_eq!(g, 4);
        assert_eq!(12 * x + 8 * y, g);
    }
}