sklears-utils 0.1.1

Shared utilities for sklears: validation, data generation, helpers
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
//! Property-based tests for utility functions
//!
//! These tests verify mathematical properties and invariants that should hold
//! for all inputs using proptest.

use crate::array_utils::{label_counts, unique_labels};
use crate::data_generation::*;
use crate::multiclass::type_of_target;
use crate::validation::check_finite;
use proptest::prelude::*;
use scirs2_core::ndarray::{Array1, Array2};

proptest! {
    #[test]
    fn test_make_classification_properties(
        n_samples in 10..100usize,
        n_features in 2..10usize,
        n_classes in 2..5usize,
        flip_y in 0.0..0.3f64,
        class_sep in 0.5..3.0f64
    ) {
        let result = make_classification(
            n_samples, n_features, n_classes,
            None, None, flip_y, class_sep, Some(42)
        );

        if let Ok((x, y)) = result {
            // Check shapes
            prop_assert_eq!(x.shape(), &[n_samples, n_features]);
            prop_assert_eq!(y.len(), n_samples);

            // Check that all labels are valid
            for &label in y.iter() {
                prop_assert!(label >= 0 && label < n_classes as i32);
            }

            // Check that at least some classes are present (unless heavily flipped)
            let unique_classes: std::collections::HashSet<i32> = y.iter().copied().collect();
            if flip_y < 0.9 {
                prop_assert!(!unique_classes.is_empty());
            }

            // All feature values should be finite
            for &val in x.iter() {
                prop_assert!(val.is_finite());
            }
        }
    }

    #[test]
    fn test_make_regression_properties(
        n_samples in 10..100usize,
        n_features in 2..10usize,
        noise in 0.0..2.0f64,
        bias in -10.0..10.0f64
    ) {
        let result = make_regression(
            n_samples, n_features, Some(n_features),
            noise, bias, Some(42)
        );

        if let Ok((x, y)) = result {
            // Check shapes
            prop_assert_eq!(x.shape(), &[n_samples, n_features]);
            prop_assert_eq!(y.len(), n_samples);

            // All values should be finite
            for &val in x.iter() {
                prop_assert!(val.is_finite());
            }
            for &val in y.iter() {
                prop_assert!(val.is_finite());
            }
        }
    }

    #[test]
    fn test_make_blobs_properties(
        n_samples in 10..100usize,
        n_features in 2..8usize,
        centers in 2..6usize,
        cluster_std in 0.1..3.0f64
    ) {
        let result = make_blobs(
            n_samples, n_features, Some(centers),
            cluster_std, (-10.0, 10.0), Some(42)
        );

        if let Ok((x, y)) = result {
            // Check shapes
            prop_assert_eq!(x.shape(), &[n_samples, n_features]);
            prop_assert_eq!(y.len(), n_samples);

            // Check that all cluster labels are valid
            for &label in y.iter() {
                prop_assert!(label >= 0 && label < centers as i32);
            }

            // All cluster IDs should be present
            let unique_clusters: std::collections::HashSet<i32> = y.iter().copied().collect();
            prop_assert_eq!(unique_clusters.len(), centers);

            // All values should be finite
            for &val in x.iter() {
                prop_assert!(val.is_finite());
            }
        }
    }

    // Removed check_range test - function signature is different than expected

    #[test]
    fn test_check_finite_2d_properties(
        values in prop::collection::vec(-100.0..100.0f64, 4..40)
    ) {
        let size = values.len();
        let rows = (size as f64).sqrt() as usize;
        let cols = size / rows;
        let actual_size = rows * cols;

        if actual_size > 0 {
            let trimmed_values: Vec<f64> = values.into_iter().take(actual_size).collect();
            let array = Array2::from_shape_vec((rows, cols), trimmed_values).expect("operation should succeed");

            // All finite values should pass
            prop_assert!(check_finite(&array).is_ok());
        }
    }

    // Removed test_check_finite_properties since check_finite only works with 2D arrays

    #[test]
    fn test_unique_labels_properties(
        labels in prop::collection::vec(0..10i32, 1..20)
    ) {
        let array = Array1::from_vec(labels.clone());
        let unique = unique_labels(&array);

        // Unique should contain all distinct values
        let expected_unique: std::collections::HashSet<i32> = labels.into_iter().collect();
        let actual_unique: std::collections::HashSet<i32> = unique.into_iter().collect();

        prop_assert_eq!(expected_unique, actual_unique);
    }

    #[test]
    fn test_label_counts_properties(
        labels in prop::collection::vec(0..5i32, 1..50)
    ) {
        let array = Array1::from_vec(labels.clone());
        let counts = label_counts(&array);

        // Sum of counts should equal total number of labels
        let total_count: usize = counts.values().sum();
        prop_assert_eq!(total_count, labels.len());

        // Each unique label should have a positive count
        for &count in counts.values() {
            prop_assert!(count > 0);
        }

        // Manual count verification for a few labels
        let manual_counts: std::collections::HashMap<i32, usize> =
            labels.iter().fold(std::collections::HashMap::new(), |mut acc, &label| {
                *acc.entry(label).or_insert(0) += 1;
                acc
            });

        prop_assert_eq!(counts, manual_counts);
    }

    #[test]
    fn test_type_of_target_properties(
        target_type in 0..3usize,
        size in 5..30usize
    ) {
        let y = match target_type {
            0 => Array1::from_vec((0..size).map(|i| (i % 2) as i32).collect()), // binary
            1 => Array1::from_vec((0..size).map(|i| (i % 5) as i32).collect()), // multiclass
            _ => Array1::from_vec(vec![0i32; size]), // constant
        };

        let target_type_result = type_of_target(&y);

        // Should return a valid target type string
        if let Ok(target_type_str) = target_type_result {
            prop_assert!(target_type_str == "binary" ||
                        target_type_str == "multiclass" ||
                        target_type_str == "unknown");
        }
    }

    #[test]
    fn test_train_test_split_properties(
        n_samples in 10..100usize,
        n_features in 2..10usize,
        test_size in 0.1..0.5f64
    ) {
        let _x = Array2::<f64>::zeros((n_samples, n_features));
        let _y = Array1::from_vec((0..n_samples).map(|i| (i % 3) as i32).collect());

        use crate::random::train_test_split_indices;
        let result = train_test_split_indices(n_samples, test_size, true, Some(42));

        if let Ok((train_indices, test_indices)) = result {
            // Check that all samples are accounted for
            let total_samples = train_indices.len() + test_indices.len();
            prop_assert_eq!(total_samples, n_samples);

            // Check that test size is approximately correct
            let actual_test_ratio = test_indices.len() as f64 / n_samples as f64;
            let tolerance = 0.1; // Allow 10% tolerance
            prop_assert!((actual_test_ratio - test_size).abs() <= tolerance);

            // Check that indices are unique and valid
            let mut all_indices = train_indices.clone();
            all_indices.extend(test_indices.clone());
            all_indices.sort_unstable();
            let expected_indices: Vec<usize> = (0..n_samples).collect();
            prop_assert_eq!(all_indices, expected_indices);
        }
    }

    #[test]
    fn test_bootstrap_indices_properties(
        n_samples in 10..100usize
    ) {
        use crate::random::bootstrap_indices;
        let indices = bootstrap_indices(n_samples, Some(42));

        // Check length
        prop_assert_eq!(indices.len(), n_samples);

        // Check that all indices are valid
        for &idx in indices.iter() {
            prop_assert!(idx < n_samples);
        }

        // Bootstrap should allow repetition, so with enough samples,
        // we should see some repeated indices
        if n_samples > 10 {
            let unique_indices: std::collections::HashSet<usize> = indices.into_iter().collect();
            // Usually we should see some repetition in bootstrap samples
            prop_assert!(unique_indices.len() <= n_samples);
        }
    }

    #[test]
    fn test_stratified_split_properties(
        n_samples in 20..100usize,
        n_classes in 2..5usize,
        test_size in 0.2..0.5f64
    ) {
        use crate::random::stratified_split_indices;

        // Create stratified labels
        let labels: Vec<i32> = (0..n_samples)
            .map(|i| (i % n_classes) as i32)
            .collect();

        let result = stratified_split_indices(&labels, test_size, Some(42));

        if let Ok((train_indices, test_indices)) = result {
            // Check total samples
            prop_assert_eq!(train_indices.len() + test_indices.len(), n_samples);

            // Check that stratification is maintained
            let train_labels: Vec<i32> = train_indices.iter()
                .map(|&i| labels[i])
                .collect();
            let test_labels: Vec<i32> = test_indices.iter()
                .map(|&i| labels[i])
                .collect();

            // Each class should be represented in both sets (if possible)
            let train_classes: std::collections::HashSet<i32> = train_labels.into_iter().collect();
            let test_classes: std::collections::HashSet<i32> = test_labels.into_iter().collect();

            // At least some overlap in classes between train and test
            let overlap: std::collections::HashSet<_> = train_classes.intersection(&test_classes).collect();
            if test_size < 0.9 && n_samples >= n_classes * 4 {
                prop_assert!(!overlap.is_empty());
            }
        }
    }

    #[test]
    fn test_shuffle_indices_properties(
        n_samples in 5..50usize
    ) {
        use crate::random::random_permutation;

        let indices = random_permutation(n_samples, Some(42));

        // Check length
        prop_assert_eq!(indices.len(), n_samples);

        // Check that all original indices are present
        let mut sorted_indices = indices.clone();
        sorted_indices.sort_unstable();
        let expected: Vec<usize> = (0..n_samples).collect();
        prop_assert_eq!(sorted_indices, expected);

        // Check uniqueness (no duplicates)
        let unique_indices: std::collections::HashSet<usize> = indices.into_iter().collect();
        prop_assert_eq!(unique_indices.len(), n_samples);
    }

    #[test]
    fn test_k_fold_indices_properties(
        n_samples in 10..100usize,
        n_splits in 2..10usize
    ) {
        use crate::random::k_fold_indices;

        let result = k_fold_indices(n_samples, n_splits, true, Some(42));

        if let Ok(folds) = result {
            prop_assert_eq!(folds.len(), n_splits);

            // Check that all samples are used exactly once across all folds
            let mut all_test_indices = Vec::new();
            for (_, test_indices) in &folds {
                all_test_indices.extend(test_indices.iter().copied());
            }

            all_test_indices.sort_unstable();
            let expected: Vec<usize> = (0..n_samples).collect();
            prop_assert_eq!(all_test_indices, expected);

            // Check that fold sizes are balanced
            let mut fold_sizes: Vec<usize> = folds.iter().map(|(_, test)| test.len()).collect();
            fold_sizes.sort_unstable();

            // Max difference between fold sizes should be at most 1
            if fold_sizes.len() > 1 {
                prop_assert!(fold_sizes[fold_sizes.len() - 1] - fold_sizes[0] <= 1);
            }
        }
    }

    #[test]
    fn test_cross_validation_split_consistency(
        n_samples in 20..80usize,
        n_splits in 3..8usize
    ) {
        use crate::random::k_fold_indices;

        // Test that K-fold provides consistent splits
        let result1 = k_fold_indices(n_samples, n_splits, true, Some(42));
        let result2 = k_fold_indices(n_samples, n_splits, true, Some(42));

        if let (Ok(folds1), Ok(folds2)) = (result1, result2) {
            // Same seed should produce identical results
            prop_assert_eq!(folds1.len(), folds2.len());

            for (fold1, fold2) in folds1.iter().zip(folds2.iter()) {
                prop_assert_eq!(&fold1.0, &fold2.0); // train indices
                prop_assert_eq!(&fold1.1, &fold2.1); // test indices
            }
        }
    }

    #[test]
    fn test_array_validation_properties(
        n_features in 2..10usize,
        n_samples in 5..20usize
    ) {
        use crate::validation::{check_array_2d, check_consistent_length_xy};

        // Create valid array
        let x = Array2::<f64>::zeros((n_samples, n_features));
        let y = Array1::<i32>::zeros(n_samples);

        // Valid arrays should pass validation
        prop_assert!(check_array_2d(&x).is_ok());
        prop_assert!(check_consistent_length_xy(&x, &y).is_ok());

        // Check inconsistent length detection
        let y_wrong = Array1::<i32>::zeros(n_samples + 1);
        prop_assert!(check_consistent_length_xy(&x, &y_wrong).is_err());
    }

    #[test]
    fn test_distance_computation_properties(
        dim in 2..8usize
    ) {
        use crate::metrics::{euclidean_distance, manhattan_distance};

        let point1 = Array1::<f64>::zeros(dim);
        let point2 = Array1::<f64>::ones(dim);

        // Distance should be non-negative
        let euclidean_dist = euclidean_distance(&point1, &point2);
        let manhattan_dist = manhattan_distance(&point1, &point2);

        prop_assert!(euclidean_dist >= 0.0);
        prop_assert!(manhattan_dist >= 0.0);

        // Distance from point to itself should be zero
        let self_euclidean = euclidean_distance(&point1, &point1);
        let self_manhattan = manhattan_distance(&point1, &point1);

        prop_assert!((self_euclidean - 0.0).abs() < 1e-10);
        prop_assert!((self_manhattan - 0.0).abs() < 1e-10);

        // Manhattan distance should equal sqrt(dim) for unit vectors
        prop_assert!((manhattan_dist - dim as f64).abs() < 1e-10);
    }

    #[test]
    fn test_data_scaling_properties(
        n_samples in 10..50usize,
        n_features in 2..10usize,
        scale in 0.1..10.0f64
    ) {
        // Create test data with known scale
        let mut x = Array2::<f64>::zeros((n_samples, n_features));
        for i in 0..n_samples {
            for j in 0..n_features {
                x[[i, j]] = scale * (i as f64 + j as f64);
            }
        }

        // Check that data has expected properties
        prop_assert!(x.iter().all(|&val| val.is_finite()));

        // Check that scaling preserves relationships
        let max_val = x.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b));
        let min_val = x.iter().fold(f64::INFINITY, |a, &b| a.min(b));

        prop_assert!(max_val >= min_val);
        if scale > 0.0 {
            prop_assert!(max_val > min_val || n_samples <= 1 || n_features <= 1);
        }
    }

}

/// Unit test for environment detection properties (not property-based)
#[allow(non_snake_case)]
#[cfg(test)]
#[test]
fn test_environment_detection_basic() {
    use crate::environment::{EnvironmentInfo, FeatureChecker, HardwareDetector};

    let hw = HardwareDetector::new();
    let checker = FeatureChecker::new();
    let env = EnvironmentInfo::detect();

    // Basic hardware detection properties
    assert!(hw.cpu_cores() >= 1);
    assert!(hw.logical_cores() >= hw.cpu_cores());
    assert!(hw.total_memory() > 0);
    assert!(!hw.cpu_architecture().is_empty());

    // Feature checking properties
    assert!(checker.recommended_thread_count() >= 1);
    assert!(checker.recommended_simd_width() >= 1);
    assert!(checker.high_resolution_timer_available());

    // Environment summary should be non-empty
    let summary = env.summary();
    assert!(!summary.is_empty());
    assert!(summary.contains("Environment Summary"));
}

/// Comprehensive testing framework utilities
pub mod testing_framework {
    use super::*;
    use std::time::Duration;

    /// Test suite runner for comprehensive validation
    pub struct TestSuite {
        pub name: String,
        pub tests: Vec<Box<dyn Fn() -> Result<(), String> + Send + Sync>>,
        pub setup: Option<Box<dyn Fn() -> Result<(), String> + Send + Sync>>,
        pub teardown: Option<Box<dyn Fn() -> Result<(), String> + Send + Sync>>,
        #[allow(dead_code)] // intentionally deferred: test timeout enforcement pending
        pub timeout: Duration,
    }

    impl TestSuite {
        /// Create a new test suite
        pub fn new(name: &str) -> Self {
            Self {
                name: name.to_string(),
                tests: Vec::new(),
                setup: None,
                teardown: None,
                timeout: Duration::from_secs(60),
            }
        }

        /// Add a test to the suite
        pub fn add_test<F>(&mut self, test: F)
        where
            F: Fn() -> Result<(), String> + Send + Sync + 'static,
        {
            self.tests.push(Box::new(test));
        }

        /// Set setup function
        #[allow(dead_code)] // intentionally deferred: suite lifecycle hooks pending
        pub fn set_setup<F>(&mut self, setup: F)
        where
            F: Fn() -> Result<(), String> + Send + Sync + 'static,
        {
            self.setup = Some(Box::new(setup));
        }

        /// Set teardown function
        #[allow(dead_code)] // intentionally deferred: suite lifecycle hooks pending
        pub fn set_teardown<F>(&mut self, teardown: F)
        where
            F: Fn() -> Result<(), String> + Send + Sync + 'static,
        {
            self.teardown = Some(Box::new(teardown));
        }

        /// Run all tests in the suite
        pub fn run(&self) -> TestResults {
            let mut results = TestResults::new(&self.name);

            // Run setup
            if let Some(ref setup) = self.setup {
                if let Err(e) = setup() {
                    results.add_failure(format!("Setup failed: {e}"));
                    return results;
                }
            }

            // Run tests
            for (i, test) in self.tests.iter().enumerate() {
                let test_name = format!("test_{i}");
                match test() {
                    Ok(()) => results.add_success(test_name),
                    Err(e) => results.add_failure(format!("{test_name}: {e}")),
                }
            }

            // Run teardown
            if let Some(ref teardown) = self.teardown {
                if let Err(e) = teardown() {
                    results.add_failure(format!("Teardown failed: {e}"));
                }
            }

            results
        }
    }

    /// Test results container
    #[derive(Debug, Clone)]
    pub struct TestResults {
        #[allow(dead_code)] // intentionally deferred: suite name readout pending
        pub suite_name: String,
        pub successes: Vec<String>,
        pub failures: Vec<String>,
        #[allow(dead_code)] // intentionally deferred: elapsed time tracking pending
        pub duration: Duration,
    }

    impl TestResults {
        pub fn new(suite_name: &str) -> Self {
            Self {
                suite_name: suite_name.to_string(),
                successes: Vec::new(),
                failures: Vec::new(),
                duration: Duration::new(0, 0),
            }
        }

        pub fn add_success(&mut self, test_name: String) {
            self.successes.push(test_name);
        }

        pub fn add_failure(&mut self, error: String) {
            self.failures.push(error);
        }

        pub fn total_tests(&self) -> usize {
            self.successes.len() + self.failures.len()
        }

        #[allow(dead_code)] // intentionally deferred: test result analysis pending
        pub fn success_rate(&self) -> f64 {
            if self.total_tests() == 0 {
                0.0
            } else {
                self.successes.len() as f64 / self.total_tests() as f64
            }
        }

        pub fn is_successful(&self) -> bool {
            self.failures.is_empty()
        }

        #[allow(dead_code)] // intentionally deferred: test result summary rendering pending
        pub fn summary(&self) -> String {
            format!(
                "Test Suite: {}\n\
                Total Tests: {}\n\
                Successes: {}\n\
                Failures: {}\n\
                Success Rate: {:.1}%\n\
                Duration: {:?}",
                self.suite_name,
                self.total_tests(),
                self.successes.len(),
                self.failures.len(),
                self.success_rate() * 100.0,
                self.duration
            )
        }
    }

    /// Stress testing utilities
    pub struct StressTester {
        pub iterations: usize,
        pub concurrent_threads: usize,
        #[allow(dead_code)] // intentionally deferred: stress test timeout enforcement pending
        pub timeout: Duration,
    }

    impl StressTester {
        pub fn new() -> Self {
            Self {
                iterations: 1000,
                concurrent_threads: num_cpus::get(),
                timeout: Duration::from_secs(300),
            }
        }

        pub fn with_iterations(mut self, iterations: usize) -> Self {
            self.iterations = iterations;
            self
        }

        pub fn with_threads(mut self, threads: usize) -> Self {
            self.concurrent_threads = threads;
            self
        }

        /// Run stress test on a function
        pub fn stress_test<F, T>(&self, test_fn: F) -> Result<Vec<T>, String>
        where
            F: Fn() -> Result<T, String> + Send + Sync + Clone + 'static,
            T: Send + Clone + 'static,
        {
            use std::sync::{Arc, Mutex};
            use std::thread;

            let results = Arc::new(Mutex::new(Vec::<T>::new()));
            let iterations_per_thread = self.iterations / self.concurrent_threads;
            let test_fn = Arc::new(test_fn);

            let handles: Vec<_> = (0..self.concurrent_threads)
                .map(|_| {
                    let test_fn = Arc::clone(&test_fn);
                    let results = Arc::clone(&results);

                    thread::spawn(move || {
                        for _ in 0..iterations_per_thread {
                            match test_fn() {
                                Ok(result) => {
                                    if let Ok(mut results) = results.lock() {
                                        results.push(result);
                                    }
                                }
                                Err(e) => return Err(e),
                            }
                        }
                        Ok(())
                    })
                })
                .collect();

            // Wait for all threads to complete
            for handle in handles {
                handle
                    .join()
                    .map_err(|_| "Thread panicked".to_string())?
                    .map_err(|e| format!("Stress test failed: {e}"))?;
            }

            let results = results
                .lock()
                .map_err(|_| "Failed to acquire lock".to_string())?;
            Ok(results.to_vec())
        }
    }

    /// Property-based test generator
    #[allow(dead_code)] // intentionally deferred: generator strategies not yet used in proptest harness
    pub struct PropertyTestGenerator;

    impl PropertyTestGenerator {
        /// Generate test data for array operations
        #[allow(dead_code)] // intentionally deferred: strategy not yet wired to proptest harness
        pub fn array_data_strategy() -> impl Strategy<Value = (usize, usize)> {
            (10..100usize, 2..20usize)
        }

        /// Generate test data for optimization algorithms
        #[allow(dead_code)] // intentionally deferred: strategy not yet wired to proptest harness
        pub fn optimization_strategy() -> impl Strategy<Value = (f64, f64, usize)> {
            (1e-8..1e-2f64, 1e-8..1e-2f64, 10..1000usize)
        }

        /// Generate test data for spatial operations
        #[allow(dead_code)] // intentionally deferred: strategy not yet wired to proptest harness
        pub fn spatial_strategy() -> impl Strategy<Value = (usize, usize, f64)> {
            (2..4usize, 10..100usize, 1.0..1000.0f64)
        }

        /// Generate test data for statistical tests
        #[allow(dead_code)] // intentionally deferred: strategy not yet wired to proptest harness
        pub fn statistical_strategy() -> impl Strategy<Value = (usize, f64, f64)> {
            (10..1000usize, -100.0..100.0f64, 0.1..10.0f64)
        }
    }

    #[allow(non_snake_case)]
    #[cfg(test)]
    mod framework_tests {
        use super::*;

        #[test]
        fn test_test_suite() {
            let mut suite = TestSuite::new("example_suite");

            suite.add_test(|| Ok(()));
            suite.add_test(|| Err("Test failure".to_string()));
            suite.add_test(|| Ok(()));

            let results = suite.run();

            assert_eq!(results.total_tests(), 3);
            assert_eq!(results.successes.len(), 2);
            assert_eq!(results.failures.len(), 1);
            assert!(!results.is_successful());
        }

        #[test]
        fn test_stress_tester() {
            let tester = StressTester::new().with_iterations(100).with_threads(2);

            let results = tester.stress_test(|| Ok(42));
            assert!(results.is_ok());

            let values = results.expect("operation should succeed");
            assert_eq!(values.len(), 100);
            assert!(values.iter().all(|&x| x == 42));
        }
    }
}

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

    #[test]
    fn test_property_test_setup() {
        // Simple test to ensure property test framework is working
        let (x, y) = make_classification(20, 3, 2, None, None, 0.0, 1.0, Some(42))
            .expect("operation should succeed");

        assert_eq!(x.shape(), &[20, 3]);
        assert_eq!(y.len(), 20);
    }
}