sklears-feature-extraction 0.2.0

Feature extraction from raw data (text, images)
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
//! Sampling Methods Module
//!
//! This module provides comprehensive sampling algorithms for efficient
//! feature extraction and data processing with various sampling strategies.

use crate::*;
use scirs2_core::ndarray::{Array1, Array2, ArrayView1, ArrayView2, Axis};
use scirs2_core::random::{Random, rng};
use sklears_core::prelude::SklearsError;
use sklears_core::types::Float;
use std::collections::{HashMap, HashSet};

/// Reservoir Sampling for Large Dataset Processing
///
/// Implements reservoir sampling algorithm for selecting a fixed-size sample
/// from a large or streaming dataset with uniform probability.
///
/// This algorithm maintains a reservoir of fixed size and ensures that each
/// element in the stream has an equal probability of being included in the
/// final sample, regardless of the total size of the stream.
///
/// # Parameters
///
/// * `reservoir_size` - Size of the sample to maintain
/// * `random_state` - Random state for reproducible sampling
///
/// # Examples
///
/// ```
/// # use sklears_feature_extraction::engineering::ReservoirSampler;
/// # use scirs2_core::ndarray::Array2;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let data = Array2::from_shape_vec((1000, 5), (0..5000).map(|x| x as f64).collect())?;
///
/// let mut sampler = ReservoirSampler::new()
///     .reservoir_size(100)
///     .random_state(42);
///
/// let sampled_data = sampler.sample_data(&data.view())?;
/// assert_eq!(sampled_data.nrows(), 100);
/// assert_eq!(sampled_data.ncols(), 5);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct ReservoirSampler {
    reservoir_size: usize,
    random_state: Option<u64>,
    reservoir: Vec<usize>,
    seen_count: usize,
}

impl ReservoirSampler {
    /// Create a new ReservoirSampler
    pub fn new() -> Self {
        Self {
            reservoir_size: 1000,
            random_state: None,
            reservoir: Vec::new(),
            seen_count: 0,
        }
    }

    /// Set the reservoir size
    pub fn reservoir_size(mut self, size: usize) -> Self {
        self.reservoir_size = size;
        self
    }

    /// Set the random state for reproducible sampling
    pub fn random_state(mut self, seed: u64) -> Self {
        self.random_state = Some(seed);
        self
    }

    /// Sample indices from a dataset using reservoir sampling
    pub fn sample_indices(&mut self, dataset_size: usize) -> SklResult<Vec<usize>> {
        let mut rng = if let Some(seed) = self.random_state {
            Random::with_seed(seed)
        } else {
            Random::new()
        };

        let actual_size = self.reservoir_size.min(dataset_size);
        let mut reservoir = Vec::with_capacity(actual_size);

        // Fill reservoir with first k elements
        for i in 0..actual_size {
            reservoir.push(i);
        }

        // Replace elements with gradually decreasing probability
        for i in actual_size..dataset_size {
            let j = rng.gen_range(0..i + 1);
            if j < actual_size {
                reservoir[j] = i;
            }
        }

        self.reservoir = reservoir.clone();
        self.seen_count = dataset_size;
        Ok(reservoir)
    }

    /// Sample data using reservoir sampling
    pub fn sample_data(&mut self, data: &ArrayView2<Float>) -> SklResult<Array2<Float>> {
        let indices = self.sample_indices(data.nrows())?;
        let sampled_data = data.select(Axis(0), &indices);
        Ok(sampled_data)
    }

    /// Get current reservoir indices
    pub fn get_reservoir_indices(&self) -> &[usize] {
        &self.reservoir
    }

    /// Get count of seen samples
    pub fn get_seen_count(&self) -> usize {
        self.seen_count
    }
}

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

/// Importance Sampling for Weighted Data Selection
///
/// Implements importance sampling for selecting samples based on weights,
/// useful for handling imbalanced datasets or focusing on important regions.
///
/// This sampling method allows for biased sampling where certain data points
/// are more likely to be selected based on their importance weights.
///
/// # Parameters
///
/// * `sample_size` - Number of samples to select
/// * `replacement` - Whether to sample with replacement
/// * `random_state` - Random state for reproducible sampling
///
/// # Examples
///
/// ```
/// # use sklears_feature_extraction::engineering::ImportanceSampler;
/// # use scirs2_core::ndarray::{Array1, Array2};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let data = Array2::from_shape_vec((100, 3), (0..300).map(|x| x as f64).collect())?;
/// let weights = Array1::from_vec((0..100).map(|x| (x + 1) as f64).collect());
///
/// let sampler = ImportanceSampler::new()
///     .sample_size(20)
///     .replacement(true)
///     .random_state(42);
///
/// let indices = sampler.sample_indices(&weights.view())?;
/// assert_eq!(indices.len(), 20);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct ImportanceSampler {
    sample_size: usize,
    replacement: bool,
    random_state: Option<u64>,
}

impl ImportanceSampler {
    /// Create a new ImportanceSampler
    pub fn new() -> Self {
        Self {
            sample_size: 1000,
            replacement: false,
            random_state: None,
        }
    }

    /// Set the sample size
    pub fn sample_size(mut self, size: usize) -> Self {
        self.sample_size = size;
        self
    }

    /// Set whether to sample with replacement
    pub fn replacement(mut self, replacement: bool) -> Self {
        self.replacement = replacement;
        self
    }

    /// Set the random state for reproducible sampling
    pub fn random_state(mut self, seed: u64) -> Self {
        self.random_state = Some(seed);
        self
    }

    /// Sample indices based on importance weights
    pub fn sample_indices(&self, weights: &ArrayView1<Float>) -> SklResult<Vec<usize>> {
        if weights.is_empty() {
            return Err(SklearsError::InvalidInput(
                "Weights cannot be empty".to_string(),
            ));
        }

        // Normalize weights to probabilities
        let weight_sum: Float = weights.sum();
        if weight_sum <= 0.0 {
            return Err(SklearsError::InvalidInput(
                "Weights must be positive".to_string(),
            ));
        }

        let mut rng = if let Some(seed) = self.random_state {
            Random::with_seed(seed)
        } else {
            Random::new()
        };

        // Create cumulative distribution
        let mut cumulative = Vec::with_capacity(weights.len());
        let mut sum = 0.0;
        for &weight in weights.iter() {
            sum += weight / weight_sum;
            cumulative.push(sum);
        }

        let mut selected_indices = Vec::with_capacity(self.sample_size);
        let mut used_indices = HashSet::new();

        for _ in 0..self.sample_size {
            let random_value: Float = rng.random_range(0.0..1.0);

            // Find index using binary search on cumulative distribution
            let mut idx = 0;
            for (i, &cum_prob) in cumulative.iter().enumerate() {
                if random_value <= cum_prob {
                    idx = i;
                    break;
                }
            }

            if self.replacement || !used_indices.contains(&idx) {
                selected_indices.push(idx);
                if !self.replacement {
                    used_indices.insert(idx);
                }
            } else if !self.replacement {
                // Find next available index
                for i in 0..weights.len() {
                    if !used_indices.contains(&i) {
                        selected_indices.push(i);
                        used_indices.insert(i);
                        break;
                    }
                }
            }

            if !self.replacement && used_indices.len() == weights.len() {
                break;
            }
        }

        Ok(selected_indices)
    }

    /// Sample data using importance sampling
    pub fn sample_data(
        &self,
        data: &ArrayView2<Float>,
        weights: &ArrayView1<Float>,
    ) -> SklResult<Array2<Float>> {
        if data.nrows() != weights.len() {
            return Err(SklearsError::InvalidInput(
                "Data rows and weights length must match".to_string(),
            ));
        }

        let indices = self.sample_indices(weights)?;
        let sampled_data = data.select(Axis(0), &indices);
        Ok(sampled_data)
    }
}

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

/// Stratified Sampling for Balanced Data Selection
///
/// Implements stratified sampling to maintain the same proportion of samples
/// in each stratum as in the original dataset, useful for maintaining class balance.
///
/// This method ensures that each subgroup (stratum) is represented proportionally
/// in the sample, which is particularly important for classification tasks.
///
/// # Parameters
///
/// * `sample_size` - Total number of samples to select
/// * `random_state` - Random state for reproducible sampling
///
/// # Examples
///
/// ```
/// # use sklears_feature_extraction::engineering::StratifiedSampler;
/// # use scirs2_core::ndarray::{Array1, Array2};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let data = Array2::from_shape_vec((100, 3), (0..300).map(|x| x as f64).collect())?;
/// let strata = Array1::from_vec((0..100).map(|x| (x % 3) as f64).collect());
///
/// let sampler = StratifiedSampler::new()
///     .sample_size(30)
///     .random_state(42);
///
/// let sampled_data = sampler.sample_data(&data.view(), &strata.view())?;
/// assert_eq!(sampled_data.nrows(), 30);
/// assert_eq!(sampled_data.ncols(), 3);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct StratifiedSampler {
    sample_size: usize,
    random_state: Option<u64>,
}

impl StratifiedSampler {
    /// Create a new StratifiedSampler
    pub fn new() -> Self {
        Self {
            sample_size: 1000,
            random_state: None,
        }
    }

    /// Set the sample size
    pub fn sample_size(mut self, size: usize) -> Self {
        self.sample_size = size;
        self
    }

    /// Set the random state for reproducible sampling
    pub fn random_state(mut self, seed: u64) -> Self {
        self.random_state = Some(seed);
        self
    }

    /// Sample indices using stratified sampling
    pub fn sample_indices(&self, strata: &ArrayView1<Float>) -> SklResult<Vec<usize>> {
        if strata.is_empty() {
            return Err(SklearsError::InvalidInput(
                "Strata cannot be empty".to_string(),
            ));
        }

        let mut rng = if let Some(seed) = self.random_state {
            Random::with_seed(seed)
        } else {
            Random::new()
        };

        // Group indices by stratum
        let mut stratum_indices: HashMap<String, Vec<usize>> = HashMap::new();
        for (idx, &stratum) in strata.iter().enumerate() {
            let key = format!("{:.6}", stratum); // Use string representation for grouping
            stratum_indices
                .entry(key)
                .or_insert_with(Vec::new)
                .push(idx);
        }

        let total_samples = strata.len();
        let mut selected_indices = Vec::new();

        // Sample from each stratum proportionally
        for (_, indices) in stratum_indices.iter() {
            let stratum_proportion = indices.len() as f64 / total_samples as f64;
            let stratum_sample_size =
                (self.sample_size as f64 * stratum_proportion).round() as usize;
            let stratum_sample_size = stratum_sample_size.min(indices.len());

            if stratum_sample_size > 0 {
                let mut stratum_indices = indices.clone();
                Self::shuffle(&mut stratum_indices, &mut rng);
                selected_indices.extend(stratum_indices.into_iter().take(stratum_sample_size));
            }
        }

        // If we haven't reached the target sample size, add more samples
        while selected_indices.len() < self.sample_size && selected_indices.len() < total_samples {
            let all_indices: Vec<usize> = (0..total_samples).collect();
            let mut remaining: Vec<usize> = all_indices
                .into_iter()
                .filter(|&idx| !selected_indices.contains(&idx))
                .collect();

            if remaining.is_empty() {
                break;
            }

            Self::shuffle(&mut remaining, &mut rng);
            let needed = self.sample_size - selected_indices.len();
            selected_indices.extend(remaining.into_iter().take(needed));
        }

        selected_indices.truncate(self.sample_size);
        Ok(selected_indices)
    }

    /// Sample data using stratified sampling
    pub fn sample_data(
        &self,
        data: &ArrayView2<Float>,
        strata: &ArrayView1<Float>,
    ) -> SklResult<Array2<Float>> {
        if data.nrows() != strata.len() {
            return Err(SklearsError::InvalidInput(
                "Data rows and strata length must match".to_string(),
            ));
        }

        let indices = self.sample_indices(strata)?;
        let sampled_data = data.select(Axis(0), &indices);
        Ok(sampled_data)
    }

    /// Helper function to shuffle a vector using Fisher-Yates algorithm
    fn shuffle<T>(slice: &mut [T], rng: &mut Random) {
        for i in (1..slice.len()).rev() {
            let j = rng.gen_range(0..i + 1);
            slice.swap(i, j);
        }
    }
}

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

/// Bootstrap Sampling for Statistical Inference
///
/// Implements bootstrap sampling for creating multiple resampled datasets
/// with replacement, useful for statistical inference and uncertainty estimation.
///
/// # Parameters
///
/// * `n_bootstrap_samples` - Number of bootstrap samples to generate
/// * `sample_size` - Size of each bootstrap sample (default: same as original)
/// * `random_state` - Random state for reproducible sampling
///
/// # Examples
///
/// ```
/// # use sklears_feature_extraction::engineering::BootstrapSampler;
/// # use scirs2_core::ndarray::Array2;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let data = Array2::from_shape_vec((100, 3), (0..300).map(|x| x as f64).collect())?;
///
/// let sampler = BootstrapSampler::new()
///     .n_bootstrap_samples(10)
///     .random_state(42);
///
/// let bootstrap_samples = sampler.sample_multiple(&data.view())?;
/// assert_eq!(bootstrap_samples.len(), 10);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct BootstrapSampler {
    n_bootstrap_samples: usize,
    sample_size: Option<usize>,
    random_state: Option<u64>,
}

impl BootstrapSampler {
    /// Create a new BootstrapSampler
    pub fn new() -> Self {
        Self {
            n_bootstrap_samples: 100,
            sample_size: None,
            random_state: None,
        }
    }

    /// Set the number of bootstrap samples to generate
    pub fn n_bootstrap_samples(mut self, n_samples: usize) -> Self {
        self.n_bootstrap_samples = n_samples;
        self
    }

    /// Set the size of each bootstrap sample
    pub fn sample_size(mut self, size: usize) -> Self {
        self.sample_size = Some(size);
        self
    }

    /// Set the random state for reproducible sampling
    pub fn random_state(mut self, seed: u64) -> Self {
        self.random_state = Some(seed);
        self
    }

    /// Generate a single bootstrap sample
    pub fn sample_single(&self, data: &ArrayView2<Float>) -> SklResult<Array2<Float>> {
        let mut rng = if let Some(seed) = self.random_state {
            Random::with_seed(seed)
        } else {
            Random::new()
        };

        let sample_size = self.sample_size.unwrap_or(data.nrows());
        let mut indices = Vec::with_capacity(sample_size);

        // Sample with replacement
        for _ in 0..sample_size {
            let idx = rng.gen_range(0..data.nrows());
            indices.push(idx);
        }

        let sampled_data = data.select(Axis(0), &indices);
        Ok(sampled_data)
    }

    /// Generate multiple bootstrap samples
    pub fn sample_multiple(&self, data: &ArrayView2<Float>) -> SklResult<Vec<Array2<Float>>> {
        let mut samples = Vec::with_capacity(self.n_bootstrap_samples);

        for i in 0..self.n_bootstrap_samples {
            // Use different seed for each sample if random_state is set
            let sampler = if let Some(base_seed) = self.random_state {
                self.clone().random_state(base_seed + i as u64)
            } else {
                self.clone()
            };

            let sample = sampler.sample_single(data)?;
            samples.push(sample);
        }

        Ok(samples)
    }

    /// Generate bootstrap indices for external use
    pub fn sample_indices(&self, n_samples: usize) -> SklResult<Vec<Vec<usize>>> {
        let mut rng = if let Some(seed) = self.random_state {
            Random::with_seed(seed)
        } else {
            Random::new()
        };

        let sample_size = self.sample_size.unwrap_or(n_samples);
        let mut all_indices = Vec::with_capacity(self.n_bootstrap_samples);

        for _ in 0..self.n_bootstrap_samples {
            let mut indices = Vec::with_capacity(sample_size);
            for _ in 0..sample_size {
                let idx = rng.gen_range(0..n_samples);
                indices.push(idx);
            }
            all_indices.push(indices);
        }

        Ok(all_indices)
    }
}

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

/// Systematic Sampling for Regular Interval Selection
///
/// Implements systematic sampling where every k-th element is selected
/// after a random starting point, providing good coverage of the dataset.
///
/// # Parameters
///
/// * `sample_size` - Number of samples to select
/// * `random_state` - Random state for reproducible sampling
///
/// # Examples
///
/// ```
/// # use sklears_feature_extraction::engineering::SystematicSampler;
/// # use scirs2_core::ndarray::Array2;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let data = Array2::from_shape_vec((1000, 3), (0..3000).map(|x| x as f64).collect())?;
///
/// let sampler = SystematicSampler::new()
///     .sample_size(100)
///     .random_state(42);
///
/// let sampled_data = sampler.sample_data(&data.view())?;
/// assert_eq!(sampled_data.nrows(), 100);
/// assert_eq!(sampled_data.ncols(), 3);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct SystematicSampler {
    sample_size: usize,
    random_state: Option<u64>,
}

impl SystematicSampler {
    /// Create a new SystematicSampler
    pub fn new() -> Self {
        Self {
            sample_size: 100,
            random_state: None,
        }
    }

    /// Set the sample size
    pub fn sample_size(mut self, size: usize) -> Self {
        self.sample_size = size;
        self
    }

    /// Set the random state for reproducible sampling
    pub fn random_state(mut self, seed: u64) -> Self {
        self.random_state = Some(seed);
        self
    }

    /// Sample indices using systematic sampling
    pub fn sample_indices(&self, population_size: usize) -> SklResult<Vec<usize>> {
        if population_size == 0 {
            return Err(SklearsError::InvalidInput(
                "Population size cannot be zero".to_string(),
            ));
        }

        let sample_size = self.sample_size.min(population_size);
        if sample_size == 0 {
            return Ok(Vec::new());
        }

        let mut rng = if let Some(seed) = self.random_state {
            Random::with_seed(seed)
        } else {
            Random::new()
        };

        let interval = population_size as f64 / sample_size as f64;
        let start = rng.random_range(0.0..interval);

        let mut indices = Vec::with_capacity(sample_size);
        for i in 0..sample_size {
            let idx = (start + i as f64 * interval) as usize;
            if idx < population_size {
                indices.push(idx);
            }
        }

        Ok(indices)
    }

    /// Sample data using systematic sampling
    pub fn sample_data(&self, data: &ArrayView2<Float>) -> SklResult<Array2<Float>> {
        let indices = self.sample_indices(data.nrows())?;
        let sampled_data = data.select(Axis(0), &indices);
        Ok(sampled_data)
    }
}

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

#[allow(non_snake_case)]
#[cfg(test)]
mod tests {
    use super::*;
    use scirs2_core::ndarray::{Array1, Array2};

    #[test]
    fn test_reservoir_sampler_basic() {
        let mut sampler = ReservoirSampler::new()
            .reservoir_size(10)
            .random_state(42);

        let indices = sampler.sample_indices(20).expect("operation should succeed");
        assert_eq!(indices.len(), 10);
        assert_eq!(sampler.get_seen_count(), 20);

        // All indices should be valid
        for &idx in &indices {
            assert!(idx < 20);
        }
    }

    #[test]
    fn test_importance_sampler_basic() {
        let weights = Array1::from_vec(vec![0.1, 0.3, 0.2, 0.4]);
        let sampler = ImportanceSampler::new()
            .sample_size(3)
            .random_state(42);

        let indices = sampler.sample_indices(&weights.view()).expect("operation should succeed");
        assert_eq!(indices.len(), 3);

        // All indices should be valid
        for &idx in &indices {
            assert!(idx < 4);
        }
    }

    #[test]
    fn test_stratified_sampler_basic() {
        let strata = Array1::from_vec(vec![1.0, 1.0, 2.0, 2.0, 3.0, 3.0]);
        let sampler = StratifiedSampler::new()
            .sample_size(4)
            .random_state(42);

        let indices = sampler.sample_indices(&strata.view()).expect("operation should succeed");
        assert_eq!(indices.len(), 4);

        // All indices should be valid
        for &idx in &indices {
            assert!(idx < 6);
        }
    }

    #[test]
    fn test_bootstrap_sampler_basic() {
        let data = Array2::from_shape_vec((10, 3), (0..30).map(|x| x as f64).collect()).expect("operation should succeed");
        let sampler = BootstrapSampler::new()
            .n_bootstrap_samples(5)
            .random_state(42);

        let samples = sampler.sample_multiple(&data.view()).expect("operation should succeed");
        assert_eq!(samples.len(), 5);

        for sample in &samples {
            assert_eq!(sample.nrows(), 10);
            assert_eq!(sample.ncols(), 3);
        }
    }

    #[test]
    fn test_systematic_sampler_basic() {
        let data = Array2::from_shape_vec((100, 2), (0..200).map(|x| x as f64).collect()).expect("operation should succeed");
        let sampler = SystematicSampler::new()
            .sample_size(10)
            .random_state(42);

        let sampled_data = sampler.sample_data(&data.view()).expect("operation should succeed");
        assert_eq!(sampled_data.nrows(), 10);
        assert_eq!(sampled_data.ncols(), 2);
    }

    #[test]
    fn test_sampling_with_empty_data() {
        let empty_data = Array2::zeros((0, 3));

        let mut reservoir_sampler = ReservoirSampler::new().reservoir_size(5);
        let result = reservoir_sampler.sample_data(&empty_data.view());
        assert!(result.is_ok());
        assert_eq!(result.expect("operation should succeed").nrows(), 0);

        let systematic_sampler = SystematicSampler::new().sample_size(5);
        let result = systematic_sampler.sample_data(&empty_data.view());
        assert!(result.is_ok());
        assert_eq!(result.expect("operation should succeed").nrows(), 0);
    }

    #[test]
    fn test_sampling_consistency_with_seed() {
        let data = Array2::from_shape_vec((50, 2), (0..100).map(|x| x as f64).collect()).expect("operation should succeed");

        let mut sampler1 = ReservoirSampler::new()
            .reservoir_size(10)
            .random_state(42);
        let mut sampler2 = ReservoirSampler::new()
            .reservoir_size(10)
            .random_state(42);

        let sample1 = sampler1.sample_data(&data.view()).expect("operation should succeed");
        let sample2 = sampler2.sample_data(&data.view()).expect("operation should succeed");

        // Results should be identical with same seed
        assert_eq!(sample1.shape(), sample2.shape());
        for (a, b) in sample1.iter().zip(sample2.iter()) {
            assert_eq!(a, b);
        }
    }
}