veils 0.1.4

A high-performance Short-Time Fourier Transform (STFT) library with scipy.signal.ShortTimeFFT compatibility
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
// '''WARNING 100% AI generated file'''
use veils::StandaloneSTFT;

/// Create a Hann window of given length
fn hann_window(length: usize) -> Vec<f64> {
    (0..length)
        .map(|i| 0.5 * (1.0 - (2.0 * std::f64::consts::PI * i as f64 / (length - 1) as f64).cos()))
        .collect()
}

/// Test data structure for reproducible tests
#[derive(Debug)]
struct TestSignal {
    name: &'static str,
    data: Vec<f64>,
    expected_error: f64,
}

/// Generate the three standard test signals used for validation
fn generate_test_signals() -> Vec<TestSignal> {
    vec![
        // 1. Impulse signal - most critical test for STFT accuracy
        TestSignal {
            name: "impulse",
            data: {
                let mut impulse = vec![0.0; 64];
                impulse[32] = 1.0;
                impulse
            },
            expected_error: 0.0, // Should be perfect
        },
        // 2. Sine wave - tests harmonic content
        TestSignal {
            name: "sine_wave",
            data: (0..64)
                .map(|i| (2.0 * std::f64::consts::PI * 5.0 * i as f64 / 1000.0).sin())
                .collect(),
            expected_error: 1e-15, // Machine precision
        },
        // 3. Chirp signal - tests time-varying frequency content
        TestSignal {
            name: "chirp",
            data: {
                let t: Vec<f64> = (0..64).map(|i| i as f64 / 1000.0).collect();
                t.iter()
                    .map(|&t_val| (2.0 * std::f64::consts::PI * (5.0 + 10.0 * t_val) * t_val).sin())
                    .collect()
            },
            expected_error: 1e-15, // Machine precision
        },
    ]
}

#[test]
fn test_stft_creation() {
    let window = hann_window(16);
    let stft = StandaloneSTFT::new(
        window,
        4,      // hop length
        1000.0, // sampling rate
        Some("onesided"),
        None, // mfft
        None, // dual_win
        None, // phase_shift
    );

    assert!(stft.is_ok(), "STFT creation should succeed");

    let stft = stft.unwrap();
    assert_eq!(stft.hop(), 4);
    assert_eq!(stft.fs(), 1000.0);
    assert_eq!(stft.mfft(), 16);
}

#[test]
fn test_stft_invalid_parameters() {
    // Empty window should fail
    let result = StandaloneSTFT::new(vec![], 4, 1000.0, Some("onesided"), None, None, None);
    assert!(result.is_err());

    // Zero hop should fail
    let window = hann_window(16);
    let result = StandaloneSTFT::new(
        window,
        0, // invalid hop
        1000.0,
        Some("onesided"),
        None,
        None,
        None,
    );
    assert!(result.is_err());

    let window = hann_window(16);
    assert!(
        StandaloneSTFT::new(window.clone(), 4, 0.0, Some("onesided"), None, None, None).is_err()
    );
    assert!(StandaloneSTFT::new(
        window.clone(),
        4,
        1000.0,
        Some("onesided"),
        Some(15),
        None,
        None
    )
    .is_err());
    assert!(StandaloneSTFT::new(
        window.clone(),
        4,
        f64::NAN,
        Some("onesided"),
        None,
        None,
        None
    )
    .is_err());
    assert!(StandaloneSTFT::new(
        window.clone(),
        4,
        f64::INFINITY,
        Some("onesided"),
        None,
        None,
        None
    )
    .is_ok());
    assert!(StandaloneSTFT::new(
        window,
        4,
        1000.0,
        Some("onesided"),
        Some(16),
        None,
        Some(-16)
    )
    .is_err());
}

#[test]
fn test_fft_mode_parsing() {
    let window = hann_window(16);

    // Test all valid FFT modes
    let modes = ["twosided", "centered", "onesided", "onesided2X"];
    for mode in &modes {
        let stft = StandaloneSTFT::new(window.clone(), 4, 1000.0, Some(mode), None, None, None);
        assert!(stft.is_ok(), "Mode {} should be valid", mode);
    }

    // Test invalid mode
    let stft = StandaloneSTFT::new(window, 4, 1000.0, Some("invalid_mode"), None, None, None);
    assert!(stft.is_err());
}

#[test]
fn test_perfect_reconstruction_impulse() {
    let window = hann_window(16);
    let mut stft = StandaloneSTFT::new(
        window,
        4,      // hop length
        1000.0, // sampling rate
        Some("onesided"),
        None,
        None,
        None,
    )
    .unwrap();

    // Create impulse signal
    let mut signal = vec![0.0; 64];
    signal[32] = 1.0;

    // Forward STFT
    let stft_result = stft.stft(&signal, None, None, None).unwrap();

    // Inverse STFT (STFT already returns [freq][time] format)
    let reconstructed = stft.istft(&stft_result, None, None).unwrap();

    // Check perfect reconstruction
    let min_len = signal.len().min(reconstructed.len());
    let error: f64 = signal[..min_len]
        .iter()
        .zip(reconstructed[..min_len].iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0, f64::max);

    assert!(
        error < 1e-14,
        "Impulse reconstruction error {} should be < 1e-14",
        error
    );
}

#[test]
fn test_perfect_reconstruction_sine_wave() {
    let window = hann_window(16);
    let mut stft =
        StandaloneSTFT::new(window, 4, 1000.0, Some("onesided"), None, None, None).unwrap();

    // Create sine wave
    let signal: Vec<f64> = (0..64)
        .map(|i| (2.0 * std::f64::consts::PI * 5.0 * i as f64 / 1000.0).sin())
        .collect();

    // Forward STFT
    let stft_result = stft.stft(&signal, None, None, None).unwrap();

    // Inverse STFT (STFT already returns [freq][time] format)
    let reconstructed = stft.istft(&stft_result, None, None).unwrap();

    // Check reconstruction accuracy
    let min_len = signal.len().min(reconstructed.len());
    let error: f64 = signal[..min_len]
        .iter()
        .zip(reconstructed[..min_len].iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0, f64::max);

    assert!(
        error < 1e-15,
        "Sine wave reconstruction error {} should be < 1e-15",
        error
    );
}

#[test]
fn test_perfect_reconstruction_chirp() {
    let window = hann_window(16);
    let mut stft =
        StandaloneSTFT::new(window, 4, 1000.0, Some("onesided"), None, None, None).unwrap();

    // Create chirp signal
    let t: Vec<f64> = (0..64).map(|i| i as f64 / 1000.0).collect();
    let signal: Vec<f64> = t
        .iter()
        .map(|&t_val| (2.0 * std::f64::consts::PI * (5.0 + 10.0 * t_val) * t_val).sin())
        .collect();

    // Forward STFT
    let stft_result = stft.stft(&signal, None, None, None).unwrap();

    // Inverse STFT (STFT already returns [freq][time] format)
    let reconstructed = stft.istft(&stft_result, None, None).unwrap();

    // Check reconstruction accuracy
    let min_len = signal.len().min(reconstructed.len());
    let error: f64 = signal[..min_len]
        .iter()
        .zip(reconstructed[..min_len].iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0.0, f64::max);

    assert!(
        error < 1e-15,
        "Chirp reconstruction error {} should be < 1e-15",
        error
    );
}

/// Comprehensive test using all three standard test signals
#[test]
fn test_all_signals_perfect_reconstruction() {
    let test_signals = generate_test_signals();
    let window = hann_window(16);

    for test_signal in test_signals {
        println!("Testing signal: {}", test_signal.name);

        let mut stft = StandaloneSTFT::new(
            window.clone(),
            4,
            1000.0,
            Some("onesided"),
            None,
            None,
            None,
        )
        .unwrap();

        // Forward STFT
        let stft_result = stft.stft(&test_signal.data, None, None, None).unwrap();

        // Verify STFT dimensions
        assert!(!stft_result.is_empty(), "STFT result should not be empty");
        assert!(
            !stft_result[0].is_empty(),
            "STFT frequency bins should not be empty"
        );

        // Inverse STFT (STFT already returns [freq][time] format)
        let reconstructed = stft.istft(&stft_result, None, None).unwrap();

        // Check reconstruction accuracy
        let min_len = test_signal.data.len().min(reconstructed.len());
        let error: f64 = test_signal.data[..min_len]
            .iter()
            .zip(reconstructed[..min_len].iter())
            .map(|(a, b)| (a - b).abs())
            .fold(0.0, f64::max);

        println!("  Reconstruction error: {:.2e}", error);
        assert!(
            error <= test_signal.expected_error,
            "Signal {} reconstruction error {:.2e} exceeds expected {:.2e}",
            test_signal.name,
            error,
            test_signal.expected_error
        );
    }
}

#[test]
fn test_different_fft_modes() {
    let window = hann_window(16);
    let signal: Vec<f64> = (0..64)
        .map(|i| (2.0 * std::f64::consts::PI * 5.0 * i as f64 / 1000.0).sin())
        .collect();

    let modes = ["twosided", "centered", "onesided", "onesided2X"];

    for mode in &modes {
        println!("Testing FFT mode: {}", mode);

        let mut stft =
            StandaloneSTFT::new(window.clone(), 4, 1000.0, Some(mode), None, None, None).unwrap();

        // Forward STFT
        let stft_result = stft.stft(&signal, None, None, None).unwrap();

        // Verify dimensions based on mode (format: [freq_bins][time_slices])
        let expected_freq_bins = match *mode {
            "onesided" | "onesided2X" => 16 / 2 + 1, // 9 bins
            _ => 16,                                 // Full spectrum
        };

        assert_eq!(
            stft_result.len(),
            expected_freq_bins,
            "Mode {} should have {} frequency bins",
            mode,
            expected_freq_bins
        );

        // Inverse STFT (STFT already returns [freq][time] format)
        let reconstructed = stft.istft(&stft_result, None, None).unwrap();

        // Check reconstruction
        let min_len = signal.len().min(reconstructed.len());
        let error: f64 = signal[..min_len]
            .iter()
            .zip(reconstructed[..min_len].iter())
            .map(|(a, b)| (a - b).abs())
            .fold(0.0, f64::max);

        println!("  Reconstruction error: {:.2e}", error);
        assert!(
            error < 1e-14,
            "Mode {} reconstruction error should be < 1e-14",
            mode
        );
    }
}

#[test]
fn test_stft_properties() {
    let window = hann_window(16);
    let stft = StandaloneSTFT::new(window, 4, 1000.0, Some("onesided"), None, None, None).unwrap();

    // Test basic properties
    assert_eq!(stft.hop(), 4);
    assert_eq!(stft.fs(), 1000.0);
    assert_eq!(stft.mfft(), 16);
    assert_eq!(stft.m_num(), 16);
    assert_eq!(stft.m_num_mid(), 8);
    assert_eq!(stft.f_pts(), 9); // onesided: mfft/2 + 1
    assert!(stft.onesided_fft());

    // Test frequency axis
    let freqs = stft.f();
    assert_eq!(freqs.len(), 9);
    assert_eq!(freqs[0], 0.0); // DC component
    assert!((freqs[8] - 500.0).abs() < 1e-10); // Nyquist frequency
}

#[test]
fn test_time_axis() {
    let window = hann_window(16);
    let stft = StandaloneSTFT::new(window, 4, 1000.0, Some("onesided"), None, None, None).unwrap();

    let signal_length = 64;
    let time_axis = stft.t(signal_length, None, None, None).unwrap();

    assert!(!time_axis.is_empty());
    assert_eq!(time_axis[0], stft.p_min() as f64 * stft.delta_t());
}

#[test]
fn test_frequency_axes_match_scipy_conventions() {
    let window = hann_window(4);
    let twosided =
        StandaloneSTFT::new(window.clone(), 2, 4.0, Some("twosided"), None, None, None).unwrap();
    assert_eq!(twosided.f(), vec![0.0, 1.0, -2.0, -1.0]);

    let centered = StandaloneSTFT::new(window, 2, 4.0, Some("centered"), None, None, None).unwrap();
    assert_eq!(centered.f(), vec![-2.0, -1.0, 0.0, 1.0]);
}

#[test]
fn test_slice_and_reconstruction_ranges_are_bounded() {
    let window = hann_window(16);
    let mut stft =
        StandaloneSTFT::new(window, 4, 1000.0, Some("onesided"), None, None, Some(-7)).unwrap();
    let signal = vec![1.0; 64];
    assert!(stft
        .stft(&signal, None, Some(stft.p_max(signal.len()) + 1), None)
        .is_err());

    let coefficients = stft.stft(&signal, None, None, None).unwrap();
    assert!(stft.istft(&coefficients, Some(0), Some(10_000)).is_err());

    let mut ragged = coefficients.clone();
    ragged[1].pop();
    assert!(stft.istft(&ragged, Some(0), Some(64)).is_err());
}

/// Test that ensures the same input always produces the same output (deterministic)
#[test]
fn test_deterministic_behavior() {
    let window = hann_window(16);
    let signal: Vec<f64> = (0..64)
        .map(|i| (2.0 * std::f64::consts::PI * 5.0 * i as f64 / 1000.0).sin())
        .collect();

    // Run STFT multiple times
    let mut results = Vec::new();
    for _ in 0..3 {
        let stft = StandaloneSTFT::new(
            window.clone(),
            4,
            1000.0,
            Some("onesided"),
            None,
            None,
            None,
        )
        .unwrap();

        let stft_result = stft.stft(&signal, None, None, None).unwrap();
        results.push(stft_result);
    }

    // Verify all results are identical
    for i in 1..results.len() {
        assert_eq!(results[0].len(), results[i].len());
        for (slice1, slice2) in results[0].iter().zip(results[i].iter()) {
            assert_eq!(slice1.len(), slice2.len());
            for (val1, val2) in slice1.iter().zip(slice2.iter()) {
                assert!((val1.re - val2.re).abs() < 1e-15);
                assert!((val1.im - val2.im).abs() < 1e-15);
            }
        }
    }
}