Skip to main content

torsh_data/sampler/
core.rs

1//! Core sampling traits and utilities
2//!
3//! This module provides the fundamental building blocks for all sampling strategies.
4
5#[cfg(not(feature = "std"))]
6use alloc::{boxed::Box, vec::Vec};
7
8// ✅ SciRS2 Policy Compliant - Using scirs2_core for all random operations
9use scirs2_core::random::Random;
10
11/// Common RNG utilities for samplers
12pub(crate) mod rng_utils {
13    use super::*;
14
15    /// Create a seeded or default RNG
16    pub fn create_rng(seed: Option<u64>) -> Random<scirs2_core::rngs::StdRng> {
17        if let Some(seed) = seed {
18            Random::seed(seed)
19        } else {
20            Random::seed(42) // Default seed for reproducible behavior
21        }
22    }
23
24    /// Generic shuffle function
25    pub fn shuffle_indices<T: Clone>(indices: &mut [T], seed: Option<u64>) {
26        let mut rng = create_rng(seed);
27
28        // Fisher-Yates shuffle
29        for i in (1..indices.len()).rev() {
30            let j = rng.gen_range(0..=i);
31            indices.swap(i, j);
32        }
33    }
34
35    /// Generate random range
36    pub fn gen_range(
37        rng: &mut Random<scirs2_core::rngs::StdRng>,
38        range: std::ops::Range<usize>,
39    ) -> usize {
40        rng.gen_range(range)
41    }
42}
43
44/// Unified trait for sampling from a dataset
45///
46/// This trait provides a consistent interface for both individual sample
47/// and batch sampling strategies.
48pub trait Sampler: Send {
49    /// Iterator type returned by the sampler
50    type Iter: Iterator<Item = usize> + Send;
51
52    /// Create an iterator over indices
53    fn iter(&self) -> Self::Iter;
54
55    /// Total number of samples that will be yielded
56    fn len(&self) -> usize;
57
58    /// Check if sampler is empty
59    fn is_empty(&self) -> bool {
60        self.len() == 0
61    }
62
63    /// Convert this sampler into a batch sampler
64    fn into_batch_sampler(
65        self,
66        batch_size: usize,
67        drop_last: bool,
68    ) -> super::batch::BatchingSampler<Self>
69    where
70        Self: Sized,
71    {
72        super::batch::BatchingSampler::new(self, batch_size, drop_last)
73    }
74
75    /// Create a distributed version of this sampler
76    fn into_distributed(
77        self,
78        num_replicas: usize,
79        rank: usize,
80    ) -> super::distributed::DistributedWrapper<Self>
81    where
82        Self: Sized,
83    {
84        super::distributed::DistributedWrapper::new(self, num_replicas, rank)
85    }
86}
87
88/// Trait for batch samplers that yield batches of indices
89pub trait BatchSampler: Send {
90    /// Iterator type returned by the batch sampler
91    type Iter: Iterator<Item = Vec<usize>> + Send;
92
93    /// Create an iterator over batches of indices
94    fn iter(&self) -> Self::Iter;
95
96    /// Total number of batches that will be yielded
97    fn num_batches(&self) -> usize;
98
99    /// Total number of batches that will be yielded (alias for num_batches)
100    fn len(&self) -> usize {
101        self.num_batches()
102    }
103
104    /// Check if batch sampler is empty
105    fn is_empty(&self) -> bool {
106        self.num_batches() == 0
107    }
108}
109
110/// Iterator wrapper that provides additional functionality
111pub struct SamplerIterator {
112    indices: Vec<usize>,
113    position: usize,
114}
115
116impl SamplerIterator {
117    /// Create a new sampler iterator
118    pub fn new(indices: Vec<usize>) -> Self {
119        Self {
120            indices,
121            position: 0,
122        }
123    }
124
125    /// Create from a range
126    pub fn from_range(start: usize, end: usize) -> Self {
127        Self::new((start..end).collect())
128    }
129
130    /// Create shuffled indices
131    pub fn shuffled(mut indices: Vec<usize>, seed: Option<u64>) -> Self {
132        // ✅ SciRS2 Policy Compliant - Using scirs2_core for random operations
133        let mut rng = match seed {
134            Some(s) => Random::seed(s),
135            None => Random::seed(42), // Use fixed seed instead of Random::new()
136        };
137
138        // Fisher-Yates shuffle
139        for i in (1..indices.len()).rev() {
140            let j = rng.gen_range(0..=i);
141            indices.swap(i, j);
142        }
143
144        Self::new(indices)
145    }
146
147    /// Get remaining items count
148    pub fn remaining(&self) -> usize {
149        self.indices.len() - self.position
150    }
151}
152
153impl Iterator for SamplerIterator {
154    type Item = usize;
155
156    fn next(&mut self) -> Option<Self::Item> {
157        if self.position < self.indices.len() {
158            let item = self.indices[self.position];
159            self.position += 1;
160            Some(item)
161        } else {
162            None
163        }
164    }
165
166    fn size_hint(&self) -> (usize, Option<usize>) {
167        let remaining = self.remaining();
168        (remaining, Some(remaining))
169    }
170}
171
172impl ExactSizeIterator for SamplerIterator {
173    fn len(&self) -> usize {
174        self.remaining()
175    }
176}
177
178/// Utility functions for sampling operations
179pub mod utils {
180    use super::*;
181
182    /// Generate random indices without replacement
183    ///
184    /// # Panics
185    ///
186    /// Panics if `k > n`. See [`try_random_indices`] for a non-panicking variant.
187    pub fn random_indices(n: usize, k: usize, seed: Option<u64>) -> Vec<usize> {
188        assert!(k <= n, "Cannot sample more items than available");
189
190        // ✅ SciRS2 Policy Compliant - Using scirs2_core for random operations
191        let mut rng = match seed {
192            Some(s) => Random::seed(s),
193            None => Random::seed(42),
194        };
195
196        random_indices_from_rng(n, k, &mut rng)
197    }
198
199    /// Fallible variant of [`random_indices`] that returns an error instead of
200    /// panicking when `k > n`.
201    pub fn try_random_indices(
202        n: usize,
203        k: usize,
204        seed: Option<u64>,
205    ) -> torsh_core::error::Result<Vec<usize>> {
206        if k > n {
207            return Err(torsh_core::error::TorshError::InvalidArgument(format!(
208                "Cannot sample {k} items without replacement from {n} available"
209            )));
210        }
211
212        // ✅ SciRS2 Policy Compliant - Using scirs2_core for random operations
213        let mut rng = match seed {
214            Some(s) => Random::seed(s),
215            None => Random::seed(42),
216        };
217
218        Ok(random_indices_from_rng(n, k, &mut rng))
219    }
220
221    /// Shared sampling core for [`random_indices`]/[`try_random_indices`], run
222    /// once `k <= n` is already known to hold.
223    fn random_indices_from_rng(
224        n: usize,
225        k: usize,
226        rng: &mut Random<scirs2_core::rngs::StdRng>,
227    ) -> Vec<usize> {
228        if k == n {
229            // Return all indices shuffled
230            let mut indices: Vec<usize> = (0..n).collect();
231            for i in (1..indices.len()).rev() {
232                let j = rng.gen_range(0..=i);
233                indices.swap(i, j);
234            }
235            indices
236        } else if k <= n / 2 {
237            // Use rejection sampling for small k, then shuffle the result: the
238            // HashSet-derived order is canonicalized via sort_unstable() first
239            // (HashSet iteration order is randomized per-process by RandomState
240            // and must not leak into the sampled order), and only then is it
241            // Fisher-Yates shuffled with the seeded RNG so the returned subset
242            // comes back in random order rather than ascending order.
243            let mut selected = std::collections::HashSet::new();
244            while selected.len() < k {
245                let idx = rng.gen_range(0..n);
246                selected.insert(idx);
247            }
248            let mut result: Vec<usize> = selected.into_iter().collect();
249            result.sort_unstable(); // Canonicalize HashSet iteration order first
250            for i in (1..result.len()).rev() {
251                let j = rng.gen_range(0..=i);
252                result.swap(i, j);
253            }
254            result
255        } else {
256            // Use exclusion method for large k, then shuffle (same reasoning as above).
257            let mut excluded = std::collections::HashSet::new();
258            while excluded.len() < n - k {
259                let idx = rng.gen_range(0..n);
260                excluded.insert(idx);
261            }
262            let mut result: Vec<usize> = (0..n).filter(|&i| !excluded.contains(&i)).collect();
263            result.sort_unstable(); // Canonicalize before shuffling
264            for i in (1..result.len()).rev() {
265                let j = rng.gen_range(0..=i);
266                result.swap(i, j);
267            }
268            result
269        }
270    }
271
272    /// Stratified split of indices
273    pub fn stratified_split(
274        indices: &[usize],
275        labels: &[usize],
276        test_ratio: f32,
277        seed: Option<u64>,
278    ) -> (Vec<usize>, Vec<usize>) {
279        use std::collections::HashMap;
280
281        // Group indices by label
282        let mut label_groups: HashMap<usize, Vec<usize>> = HashMap::new();
283        for &idx in indices {
284            if idx < labels.len() {
285                label_groups
286                    .entry(labels[idx])
287                    .or_insert_with(Vec::new)
288                    .push(idx);
289            }
290        }
291
292        // ✅ SciRS2 Policy Compliant - Using scirs2_core for random operations
293        let mut rng = match seed {
294            Some(s) => Random::seed(s),
295            None => Random::seed(42),
296        };
297
298        let mut train_indices = Vec::new();
299        let mut test_indices = Vec::new();
300
301        // Split each label group
302        for (_, mut group_indices) in label_groups {
303            // Shuffle group indices
304            for i in (1..group_indices.len()).rev() {
305                let j = rng.gen_range(0..=i);
306                group_indices.swap(i, j);
307            }
308
309            let test_size = ((group_indices.len() as f32) * test_ratio).round() as usize;
310            let test_size = test_size.min(group_indices.len());
311
312            test_indices.extend(group_indices.iter().take(test_size));
313            train_indices.extend(group_indices.iter().skip(test_size));
314        }
315
316        (train_indices, test_indices)
317    }
318
319    /// Calculate class weights for balanced sampling
320    pub fn calculate_class_weights(labels: &[usize], num_classes: usize) -> Vec<f32> {
321        let mut class_counts = vec![0usize; num_classes];
322
323        // Count occurrences
324        for &label in labels {
325            if label < num_classes {
326                class_counts[label] += 1;
327            }
328        }
329
330        // Calculate weights (inverse frequency)
331        let total_samples = labels.len() as f32;
332        class_counts
333            .iter()
334            .map(|&count| {
335                if count > 0 {
336                    total_samples / (num_classes as f32 * count as f32)
337                } else {
338                    0.0
339                }
340            })
341            .collect()
342    }
343
344    /// Validate sampling configuration
345    pub fn validate_sampling_params(
346        dataset_size: usize,
347        num_samples: Option<usize>,
348        replacement: bool,
349    ) -> Result<usize, String> {
350        let actual_num_samples = num_samples.unwrap_or(dataset_size);
351
352        // Allow empty datasets (dataset_size == 0) with 0 samples
353        if dataset_size == 0 {
354            if actual_num_samples == 0 {
355                return Ok(0);
356            } else {
357                return Err("Cannot sample from empty dataset".to_string());
358            }
359        }
360
361        if !replacement && actual_num_samples > dataset_size {
362            return Err(format!(
363                "Cannot sample {} items without replacement from dataset of size {}",
364                actual_num_samples, dataset_size
365            ));
366        }
367
368        if actual_num_samples == 0 && !replacement {
369            return Err(
370                "Number of samples cannot be zero for non-empty dataset without replacement"
371                    .to_string(),
372            );
373        }
374
375        Ok(actual_num_samples)
376    }
377
378    /// Simple train-validation split
379    pub fn train_val_split(
380        dataset_size: usize,
381        val_ratio: f32,
382        seed: Option<u64>,
383    ) -> (Vec<usize>, Vec<usize>) {
384        let val_size = (dataset_size as f32 * val_ratio).round() as usize;
385        let indices = random_indices(dataset_size, dataset_size, seed);
386
387        let (val_indices, train_indices) = indices.split_at(val_size);
388        (train_indices.to_vec(), val_indices.to_vec())
389    }
390
391    /// Generate k-fold cross-validation splits
392    ///
393    /// # Panics
394    ///
395    /// Panics if `k <= 1` or `k > dataset_size`. See [`try_kfold_splits`] for a
396    /// non-panicking variant.
397    pub fn kfold_splits(
398        dataset_size: usize,
399        k: usize,
400        seed: Option<u64>,
401    ) -> Vec<(Vec<usize>, Vec<usize>)> {
402        assert!(k > 1, "K must be greater than 1");
403        assert!(k <= dataset_size, "K cannot be larger than dataset size");
404        kfold_splits_unchecked(dataset_size, k, seed)
405    }
406
407    /// Fallible variant of [`kfold_splits`] that returns an error instead of
408    /// panicking on an invalid `k`.
409    pub fn try_kfold_splits(
410        dataset_size: usize,
411        k: usize,
412        seed: Option<u64>,
413    ) -> torsh_core::error::Result<Vec<(Vec<usize>, Vec<usize>)>> {
414        if k <= 1 {
415            return Err(torsh_core::error::TorshError::InvalidArgument(
416                "K must be greater than 1".to_string(),
417            ));
418        }
419        if k > dataset_size {
420            return Err(torsh_core::error::TorshError::InvalidArgument(format!(
421                "K ({k}) cannot be larger than dataset size ({dataset_size})"
422            )));
423        }
424        Ok(kfold_splits_unchecked(dataset_size, k, seed))
425    }
426
427    /// Shared fold-building core for [`kfold_splits`]/[`try_kfold_splits`], run
428    /// once `1 < k <= dataset_size` is already known to hold.
429    fn kfold_splits_unchecked(
430        dataset_size: usize,
431        k: usize,
432        seed: Option<u64>,
433    ) -> Vec<(Vec<usize>, Vec<usize>)> {
434        let indices = random_indices(dataset_size, dataset_size, seed);
435        let fold_size = dataset_size / k;
436        let mut splits = Vec::new();
437
438        for i in 0..k {
439            let start = i * fold_size;
440            let end = if i == k - 1 {
441                dataset_size // Last fold gets remaining samples
442            } else {
443                (i + 1) * fold_size
444            };
445
446            let val_indices = indices[start..end].to_vec();
447            let train_indices = [&indices[..start], &indices[end..]].concat();
448            splits.push((train_indices, val_indices));
449        }
450
451        splits
452    }
453
454    /// Three-way split: train, validation, test
455    ///
456    /// # Panics
457    ///
458    /// Panics if the ratios are invalid. See [`try_train_val_test_split`] for a
459    /// non-panicking variant.
460    pub fn train_val_test_split(
461        dataset_size: usize,
462        train_ratio: f32,
463        val_ratio: f32,
464        seed: Option<u64>,
465    ) -> (Vec<usize>, Vec<usize>, Vec<usize>) {
466        assert!(
467            train_ratio + val_ratio < 1.0,
468            "Train and val ratios must sum to less than 1.0"
469        );
470        assert!(
471            train_ratio > 0.0 && val_ratio > 0.0,
472            "Ratios must be positive"
473        );
474        train_val_test_split_unchecked(dataset_size, train_ratio, val_ratio, seed)
475    }
476
477    /// Fallible variant of [`train_val_test_split`] that returns an error instead
478    /// of panicking on invalid ratios.
479    pub fn try_train_val_test_split(
480        dataset_size: usize,
481        train_ratio: f32,
482        val_ratio: f32,
483        seed: Option<u64>,
484    ) -> torsh_core::error::Result<(Vec<usize>, Vec<usize>, Vec<usize>)> {
485        if !(train_ratio + val_ratio < 1.0) {
486            return Err(torsh_core::error::TorshError::InvalidArgument(
487                "Train and val ratios must sum to less than 1.0".to_string(),
488            ));
489        }
490        if !(train_ratio > 0.0 && val_ratio > 0.0) {
491            return Err(torsh_core::error::TorshError::InvalidArgument(
492                "Ratios must be positive".to_string(),
493            ));
494        }
495        Ok(train_val_test_split_unchecked(
496            dataset_size,
497            train_ratio,
498            val_ratio,
499            seed,
500        ))
501    }
502
503    /// Shared split core for [`train_val_test_split`]/[`try_train_val_test_split`],
504    /// run once the ratios are already known to be valid.
505    fn train_val_test_split_unchecked(
506        dataset_size: usize,
507        train_ratio: f32,
508        val_ratio: f32,
509        seed: Option<u64>,
510    ) -> (Vec<usize>, Vec<usize>, Vec<usize>) {
511        let train_size = (dataset_size as f32 * train_ratio).round() as usize;
512        let val_size = (dataset_size as f32 * val_ratio).round() as usize;
513        let _test_size = dataset_size - train_size - val_size;
514
515        let indices = random_indices(dataset_size, dataset_size, seed);
516
517        let train_indices = indices[..train_size].to_vec();
518        let val_indices = indices[train_size..train_size + val_size].to_vec();
519        let test_indices = indices[train_size + val_size..].to_vec();
520
521        (train_indices, val_indices, test_indices)
522    }
523}
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528
529    #[test]
530    fn test_sampler_iterator_basic() {
531        let indices = vec![0, 1, 2, 3, 4];
532        let iter = SamplerIterator::new(indices.clone());
533
534        assert_eq!(iter.len(), 5);
535        assert_eq!(iter.remaining(), 5);
536
537        let collected: Vec<usize> = iter.collect();
538        assert_eq!(collected, indices);
539    }
540
541    #[test]
542    fn test_sampler_iterator_from_range() {
543        let iter = SamplerIterator::from_range(0, 5);
544        let collected: Vec<usize> = iter.collect();
545        assert_eq!(collected, vec![0, 1, 2, 3, 4]);
546    }
547
548    #[test]
549    fn test_sampler_iterator_shuffled() {
550        let indices = vec![0, 1, 2, 3, 4];
551        let iter = SamplerIterator::shuffled(indices.clone(), Some(42));
552        let collected: Vec<usize> = iter.collect();
553
554        // Should contain same elements but in different order
555        assert_eq!(collected.len(), indices.len());
556        for &idx in &indices {
557            assert!(collected.contains(&idx));
558        }
559    }
560
561    #[test]
562    fn test_utils_random_indices() {
563        let indices = utils::random_indices(10, 5, Some(42));
564        assert_eq!(indices.len(), 5);
565
566        // All indices should be unique and in range
567        let mut sorted_indices = indices.clone();
568        sorted_indices.sort();
569        sorted_indices.dedup();
570        assert_eq!(sorted_indices.len(), 5);
571
572        for &idx in &indices {
573            assert!(idx < 10);
574        }
575    }
576
577    #[test]
578    fn test_utils_random_indices_all() {
579        let indices = utils::random_indices(5, 5, Some(42));
580        assert_eq!(indices.len(), 5);
581
582        let mut sorted_indices = indices.clone();
583        sorted_indices.sort();
584        assert_eq!(sorted_indices, vec![0, 1, 2, 3, 4]);
585    }
586
587    #[test]
588    fn test_utils_stratified_split() {
589        let indices = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
590        let labels = vec![0, 0, 0, 0, 1, 1, 1, 1, 2, 2];
591
592        let (train, test) = utils::stratified_split(&indices, &labels, 0.3, Some(42));
593
594        // Check that we have roughly the right proportions
595        assert!(train.len() + test.len() == indices.len());
596        assert!(test.len() >= 2); // Should have at least some test samples
597
598        // Verify all indices are accounted for
599        let mut all_indices = train.clone();
600        all_indices.extend(test.clone());
601        all_indices.sort();
602        assert_eq!(all_indices, indices);
603    }
604
605    #[test]
606    fn test_utils_calculate_class_weights() {
607        let labels = vec![0, 0, 1, 1, 1, 2]; // Imbalanced: 2, 3, 1
608        let weights = utils::calculate_class_weights(&labels, 3);
609
610        assert_eq!(weights.len(), 3);
611
612        // Class 2 (1 sample) should have highest weight
613        // Class 1 (3 samples) should have lowest weight
614        assert!(weights[2] > weights[1]);
615        assert!(weights[0] > weights[1]);
616    }
617
618    #[test]
619    fn test_utils_validate_sampling_params() {
620        // Valid cases
621        assert!(utils::validate_sampling_params(10, Some(5), false).is_ok());
622        assert!(utils::validate_sampling_params(10, Some(15), true).is_ok());
623        assert!(utils::validate_sampling_params(10, None, false).is_ok());
624
625        // Empty dataset cases (now valid)
626        assert!(utils::validate_sampling_params(0, Some(0), false).is_ok());
627        assert!(utils::validate_sampling_params(0, None, false).is_ok());
628
629        // Zero samples with replacement (now valid)
630        assert!(utils::validate_sampling_params(10, Some(0), true).is_ok());
631
632        // Invalid cases
633        assert!(utils::validate_sampling_params(0, Some(5), false).is_err()); // Can't sample 5 from empty dataset
634        assert!(utils::validate_sampling_params(10, Some(0), false).is_err()); // Can't sample 0 from non-empty dataset without replacement
635        assert!(utils::validate_sampling_params(10, Some(15), false).is_err()); // Can't sample 15 without replacement from dataset of 10
636    }
637
638    #[test]
639    fn test_size_hints() {
640        let iter = SamplerIterator::new(vec![0, 1, 2]);
641        assert_eq!(iter.size_hint(), (3, Some(3)));
642
643        let mut iter = SamplerIterator::new(vec![0, 1, 2]);
644        iter.next();
645        assert_eq!(iter.size_hint(), (2, Some(2)));
646    }
647}