Skip to main content

torsh_data/sampler/
mod.rs

1//! # Unified Data Sampling Interface
2//!
3//! This module provides a comprehensive data sampling system for machine learning workflows,
4//! supporting everything from basic sequential sampling to advanced distributed training scenarios.
5//! The system is built on SciRS2's random number generation and designed for high-performance
6//! data loading pipelines.
7//!
8//! ## Architecture
9//!
10//! The sampling system is organized into specialized modules:
11//!
12//! - **core**: Foundation traits, iterators, and RNG utilities
13//! - **basic**: Sequential, random, and subset sampling strategies
14//! - **batch**: Batch sampling functionality for converting individual samplers
15//! - **distributed**: Multi-GPU/multi-node training support with epoch management
16//! - **weighted**: Weighted and subset sampling for imbalanced datasets
17//! - **stratified**: Stratified sampling for maintaining class proportions
18//! - **curriculum**: Curriculum learning that gradually introduces harder samples
19//! - **active_learning**: Active learning strategies for efficient labeling
20//! - **adaptive**: Adaptive sampling that adjusts based on training progress
21//! - **importance**: Importance sampling for bias correction and emphasis
22//!
23//! ## Quick Start
24//!
25//! ```rust,ignore
26//! use torsh_data::sampler::{RandomSampler, SequentialSampler, Sampler};
27//!
28//! // Basic random sampling
29//! let sampler = RandomSampler::new(1000, false, Some(42));
30//! let indices: Vec<usize> = sampler.iter().collect();
31//!
32//! // Sequential sampling with batching
33//! let sampler = SequentialSampler::new(1000)
34//!     .into_batch_sampler(32, true);
35//!
36//! // Distributed training setup
37//! let sampler = RandomSampler::new(10000, false, Some(42))
38//!     .into_distributed(4, 0); // 4 GPUs, rank 0
39//! ```
40//!
41//! ## Advanced Usage
42//!
43//! ```rust,ignore
44//! use torsh_data::sampler::{WeightedRandomSampler, StratifiedSampler};
45//!
46//! // Weighted sampling with alias table optimization
47//! let weights = vec![0.1, 0.3, 0.6];
48//! let sampler = WeightedRandomSampler::from_weights(&weights, true, Some(42))
49//!     .expect("Invalid weights");
50//!
51//! // Stratified sampling for balanced datasets
52//! let mut strata = std::collections::HashMap::new();
53//! strata.insert(0, vec![0, 1, 2]);  // Class 0 samples
54//! strata.insert(1, vec![3, 4, 5]);  // Class 1 samples
55//! let sampler = StratifiedSampler::new(strata, true, 1, Some(42));
56//! ```
57//!
58//! ## Performance Considerations
59//!
60//! - **Alias Table**: WeightedRandomSampler uses O(1) sampling via alias method
61//! - **SIMD Operations**: Vectorized operations for shuffle and permutation
62//! - **Memory Efficiency**: Lazy evaluation and streaming for large datasets
63//! - **Distributed Coordination**: Synchronized epoch management across ranks
64//! - **SciRS2 Integration**: Leverages high-performance random number generation
65
66// Core sampling infrastructure
67pub mod active_learning;
68pub mod adaptive;
69pub mod advanced;
70pub mod basic;
71pub mod batch;
72pub mod core;
73pub mod curriculum;
74pub mod distributed;
75pub mod importance;
76pub mod stratified;
77pub mod weighted;
78
79// Re-export core traits and utilities
80pub use core::{utils, BatchSampler, Sampler, SamplerIterator};
81
82// Re-export basic sampling strategies
83pub use basic::{
84    random, random_subset, random_with_replacement, sequential, RandomSampler, SequentialSampler,
85};
86
87// Re-export batch sampling
88pub use batch::{batch, batch_drop_last, batch_keep_last, BatchSamplerIter, BatchingSampler};
89
90// Re-export distributed sampling support
91pub use distributed::{distributed, distributed_sampler, DistributedSampler, DistributedWrapper};
92
93// Re-export weighted and subset sampling
94pub use weighted::{
95    balanced_weighted, subset_random, weighted_random, SubsetRandomSampler, WeightedRandomSampler,
96};
97
98// Re-export stratified sampling
99pub use stratified::{
100    balanced_stratified, stratified, stratified_train_test_split, StratifiedSampler,
101};
102
103// Re-export curriculum learning
104pub use curriculum::{
105    anti_curriculum, exponential_curriculum, linear_curriculum, step_curriculum, CurriculumSampler,
106    CurriculumStats, CurriculumStrategy,
107};
108
109// Re-export active learning
110pub use active_learning::{
111    diversity_sampler, uncertainty_diversity_sampler, uncertainty_sampler, AcquisitionStrategy,
112    ActiveLearningSampler, ActiveLearningStats,
113};
114
115// Re-export adaptive sampling
116pub use adaptive::{
117    frequency_balanced_sampler, hard_adaptive_sampler, uncertainty_adaptive_sampler,
118    AdaptiveSampler, AdaptiveStats, AdaptiveStrategy,
119};
120
121// Re-export importance sampling
122pub use importance::{
123    class_balanced_importance_sampler, exponential_importance_sampler,
124    loss_based_importance_sampler, uniform_importance_sampler, ImportanceSampler, ImportanceStats,
125};
126
127// Re-export advanced sampling strategies
128pub use advanced::{
129    GroupedSampler, ImportanceSampler as AdvancedImportanceSampler,
130    StratifiedSampler as AdvancedStratifiedSampler,
131    WeightedRandomSampler as AdvancedWeightedRandomSampler,
132};
133
134// Convenience type aliases for backward compatibility
135pub type DefaultSampler = RandomSampler;
136pub type DefaultBatchSampler = BatchingSampler<RandomSampler>;
137
138/// Creates a default random sampler with optional configuration
139///
140/// This is a convenience function that provides a simple interface for the most
141/// common sampling use case: random sampling without replacement.
142///
143/// # Arguments
144///
145/// * `dataset_size` - Total number of samples in the dataset
146/// * `seed` - Optional seed for reproducible sampling
147///
148/// # Examples
149///
150/// ```rust,ignore
151/// use torsh_data::sampler::default_sampler;
152///
153/// // Create sampler for 1000 samples with reproducible results
154/// let sampler = default_sampler(1000, Some(42));
155/// let indices: Vec<usize> = sampler.iter().collect();
156/// assert_eq!(indices.len(), 1000);
157/// ```
158pub fn default_sampler(dataset_size: usize, seed: Option<u64>) -> RandomSampler {
159    random(dataset_size, seed)
160}
161
162/// Creates a default batch sampler with common configuration
163///
164/// This convenience function creates a batched random sampler, which is the most
165/// common configuration for training neural networks.
166///
167/// # Arguments
168///
169/// * `dataset_size` - Total number of samples in the dataset
170/// * `batch_size` - Number of samples per batch
171/// * `drop_last` - Whether to drop the last incomplete batch
172/// * `seed` - Optional seed for reproducible sampling
173///
174/// # Examples
175///
176/// ```rust,ignore
177/// use torsh_data::sampler::default_batch_sampler;
178///
179/// // Create batch sampler for training
180/// let sampler = default_batch_sampler(1000, 32, true, Some(42));
181/// let batches: Vec<Vec<usize>> = sampler.iter().collect();
182/// assert_eq!(batches.len(), 31); // 1000 / 32 = 31.25, drop_last=true
183/// ```
184pub fn default_batch_sampler(
185    dataset_size: usize,
186    batch_size: usize,
187    drop_last: bool,
188    seed: Option<u64>,
189) -> BatchingSampler<RandomSampler> {
190    random(dataset_size, seed).into_batch_sampler(batch_size, drop_last)
191}
192
193/// Creates a default distributed sampler for multi-GPU training
194///
195/// This convenience function sets up distributed sampling with common defaults
196/// for multi-GPU training scenarios.
197///
198/// # Arguments
199///
200/// * `dataset_size` - Total number of samples in the dataset
201/// * `num_replicas` - Total number of distributed processes (usually number of GPUs)
202/// * `rank` - Rank of the current process (0 to num_replicas-1)
203/// * `seed` - Optional seed for reproducible sampling
204///
205/// # Examples
206///
207/// ```rust,ignore
208/// use torsh_data::sampler::default_distributed_sampler;
209///
210/// // Setup for 4-GPU training, current process is rank 0
211/// let sampler = default_distributed_sampler(10000, 4, 0, Some(42));
212/// let local_indices: Vec<usize> = sampler.iter().collect();
213/// assert_eq!(local_indices.len(), 2500); // 10000 / 4 = 2500 per GPU
214/// ```
215pub fn default_distributed_sampler(
216    dataset_size: usize,
217    num_replicas: usize,
218    rank: usize,
219    seed: Option<u64>,
220) -> DistributedSampler {
221    let mut sampler = distributed_sampler(dataset_size, num_replicas, rank, true);
222    if let Some(seed) = seed {
223        sampler = sampler.with_generator(seed);
224    }
225    sampler
226}
227
228/// Factory function for creating samplers based on configuration
229///
230/// This function provides a unified interface for creating different types of samplers
231/// based on string configuration, useful for configuration files and dynamic setup.
232///
233/// # Arguments
234///
235/// * `sampler_type` - Type of sampler ("sequential", "random", "weighted", etc.)
236/// * `dataset_size` - Total number of samples in the dataset
237/// * `config` - Additional configuration as key-value pairs
238///
239/// # Supported Sampler Types
240///
241/// - `"sequential"`: Sequential sampling from 0 to dataset_size-1
242/// - `"random"`: Random sampling without replacement
243/// - `"random_replacement"`: Random sampling with replacement
244/// - `"weighted"`: Weighted random sampling (requires "weights" in config)
245/// - `"stratified"`: Stratified sampling (requires "strata" in config)
246/// - `"distributed"`: Distributed sampling (requires "num_replicas" and "rank" in config)
247///
248/// # Examples
249///
250/// ```rust,ignore
251/// use torsh_data::sampler::create_sampler;
252/// use std::collections::HashMap;
253///
254/// let mut config = HashMap::new();
255/// config.insert("seed".to_string(), "42".to_string());
256///
257/// // This would return a boxed sampler trait object
258/// // let sampler = create_sampler("random", 1000, &config);
259/// ```
260pub fn create_sampler(
261    sampler_type: &str,
262    dataset_size: usize,
263    config: &std::collections::HashMap<String, String>,
264) -> Result<Box<dyn Sampler<Iter = Box<dyn Iterator<Item = usize> + Send>> + Send>, String> {
265    let seed = config.get("seed").and_then(|s| s.parse::<u64>().ok());
266
267    match sampler_type {
268        "sequential" => {
269            let sampler = sequential(dataset_size);
270            Ok(Box::new(SamplerWrapper::Sequential(sampler)))
271        }
272        "random" => {
273            let sampler = random(dataset_size, seed);
274            Ok(Box::new(SamplerWrapper::Random(sampler)))
275        }
276        "random_replacement" => {
277            let sampler = random_with_replacement(dataset_size, dataset_size, seed);
278            Ok(Box::new(SamplerWrapper::Random(sampler)))
279        }
280        "weighted" => {
281            let weights_str = config
282                .get("weights")
283                .ok_or("Weighted sampler requires 'weights' configuration")?;
284            let weights: Vec<f64> = weights_str
285                .split(',')
286                .map(|s| s.trim().parse::<f64>())
287                .collect::<Result<Vec<_>, _>>()
288                .map_err(|_| "Invalid weights format")?;
289
290            let replacement = config
291                .get("replacement")
292                .map(|s| s.parse::<bool>().unwrap_or(false))
293                .unwrap_or(false);
294
295            let num_samples = config
296                .get("num_samples")
297                .and_then(|s| s.parse::<usize>().ok())
298                .unwrap_or(weights.len());
299
300            let sampler = weighted_random(weights, num_samples, replacement, seed);
301            Ok(Box::new(SamplerWrapper::Weighted(sampler)))
302        }
303        "distributed" => {
304            let num_replicas = config
305                .get("num_replicas")
306                .and_then(|s| s.parse::<usize>().ok())
307                .ok_or("Distributed sampler requires 'num_replicas' configuration")?;
308            let rank = config
309                .get("rank")
310                .and_then(|s| s.parse::<usize>().ok())
311                .ok_or("Distributed sampler requires 'rank' configuration")?;
312            let shuffle = config
313                .get("shuffle")
314                .map(|s| s.parse::<bool>().unwrap_or(true))
315                .unwrap_or(true);
316            let _drop_last = config
317                .get("drop_last")
318                .map(|s| s.parse::<bool>().unwrap_or(false))
319                .unwrap_or(false);
320
321            let sampler = DistributedSampler::new(dataset_size, num_replicas, rank, shuffle);
322            Ok(Box::new(SamplerWrapper::Distributed(sampler)))
323        }
324        _ => Err(format!("Unknown sampler type: {}", sampler_type)),
325    }
326}
327
328/// Wrapper enum for dynamic sampler dispatch
329///
330/// This enum allows for dynamic dispatch of different sampler types while maintaining
331/// the Sampler trait interface. Used internally by the factory function.
332#[derive(Debug)]
333enum SamplerWrapper {
334    Sequential(SequentialSampler),
335    Random(RandomSampler),
336    Weighted(WeightedRandomSampler),
337    Distributed(DistributedSampler),
338}
339
340impl Sampler for SamplerWrapper {
341    type Iter = Box<dyn Iterator<Item = usize> + Send>;
342
343    fn iter(&self) -> Self::Iter {
344        match self {
345            SamplerWrapper::Sequential(s) => Box::new(s.iter()),
346            SamplerWrapper::Random(s) => Box::new(s.iter()),
347            SamplerWrapper::Weighted(s) => Box::new(s.iter()),
348            SamplerWrapper::Distributed(s) => Box::new(s.iter()),
349        }
350    }
351
352    fn len(&self) -> usize {
353        match self {
354            SamplerWrapper::Sequential(s) => s.len(),
355            SamplerWrapper::Random(s) => s.len(),
356            SamplerWrapper::Weighted(s) => s.len(),
357            SamplerWrapper::Distributed(s) => s.len(),
358        }
359    }
360
361    fn into_batch_sampler(self, batch_size: usize, drop_last: bool) -> BatchingSampler<Self>
362    where
363        Self: Sized,
364    {
365        BatchingSampler::new(self, batch_size, drop_last)
366    }
367
368    fn into_distributed(self, num_replicas: usize, rank: usize) -> DistributedWrapper<Self>
369    where
370        Self: Sized,
371    {
372        DistributedWrapper::new(self, num_replicas, rank)
373    }
374}
375
376/// Resolve an optional seed to a concrete one.
377///
378/// `Some(seed)` is passed through unchanged (reproducible). `None` means
379/// "random", not "no shuffle": a fresh seed is drawn from a real entropy
380/// source (`scirs2_core::random`'s thread RNG) so callers who don't ask for
381/// reproducibility still get a genuinely random split/shuffle on every call.
382fn resolve_seed(seed: Option<u64>) -> u64 {
383    match seed {
384        Some(s) => s,
385        None => {
386            use scirs2_core::random::Random;
387            let mut entropy_rng = Random::default();
388            entropy_rng.gen_range(0..=u64::MAX)
389        }
390    }
391}
392
393/// Utility function to split dataset into train and validation sets
394///
395/// # Arguments
396///
397/// * `dataset_size` - Total number of samples
398/// * `val_ratio` - Fraction of data to use for validation (0.0 to 1.0)
399/// * `seed` - Optional seed for reproducible splits. `None` means the split is
400///   still shuffled, just with a fresh, non-reproducible seed drawn from
401///   entropy on every call.
402///
403/// # Returns
404///
405/// A tuple of (train_indices, val_indices)
406pub fn train_val_split(
407    dataset_size: usize,
408    val_ratio: f32,
409    seed: Option<u64>,
410) -> (Vec<usize>, Vec<usize>) {
411    assert!(
412        val_ratio >= 0.0 && val_ratio <= 1.0,
413        "Validation ratio must be in [0, 1]"
414    );
415
416    let val_size = (dataset_size as f32 * val_ratio).round() as usize;
417    let train_size = dataset_size - val_size;
418
419    let mut indices: Vec<usize> = (0..dataset_size).collect();
420
421    {
422        use scirs2_core::random::Random;
423        let mut rng = Random::seed(resolve_seed(seed));
424        // Simple Fisher-Yates shuffle - always runs, regardless of seed.
425        for i in (1..indices.len()).rev() {
426            let j = rng.gen_range(0..=i);
427            indices.swap(i, j);
428        }
429    }
430
431    let train_indices = indices[..train_size].to_vec();
432    let val_indices = indices[train_size..].to_vec();
433
434    (train_indices, val_indices)
435}
436
437/// Utility function to split dataset into train, validation, and test sets
438///
439/// # Arguments
440///
441/// * `dataset_size` - Total number of samples
442/// * `train_ratio` - Fraction for training
443/// * `val_ratio` - Fraction for validation
444/// * `seed` - Optional seed for reproducible splits
445///
446/// # Returns
447///
448/// A tuple of (train_indices, val_indices, test_indices)
449pub fn train_val_test_split(
450    dataset_size: usize,
451    train_ratio: f32,
452    val_ratio: f32,
453    seed: Option<u64>,
454) -> (Vec<usize>, Vec<usize>, Vec<usize>) {
455    assert!(
456        train_ratio >= 0.0 && train_ratio <= 1.0,
457        "Train ratio must be in [0, 1]"
458    );
459    assert!(
460        val_ratio >= 0.0 && val_ratio <= 1.0,
461        "Val ratio must be in [0, 1]"
462    );
463    assert!(
464        train_ratio + val_ratio <= 1.0,
465        "Train + val ratios must not exceed 1.0"
466    );
467
468    let train_size = (dataset_size as f32 * train_ratio).round() as usize;
469    let val_size = (dataset_size as f32 * val_ratio).round() as usize;
470    let _test_size = dataset_size - train_size - val_size;
471
472    let mut indices: Vec<usize> = (0..dataset_size).collect();
473
474    {
475        use scirs2_core::random::Random;
476        let mut rng = Random::seed(resolve_seed(seed));
477        // Simple Fisher-Yates shuffle - always runs, regardless of seed.
478        for i in (1..indices.len()).rev() {
479            let j = rng.gen_range(0..=i);
480            indices.swap(i, j);
481        }
482    }
483
484    let train_indices = indices[..train_size].to_vec();
485    let val_indices = indices[train_size..train_size + val_size].to_vec();
486    let test_indices = indices[train_size + val_size..].to_vec();
487
488    (train_indices, val_indices, test_indices)
489}
490
491/// Generate k-fold cross-validation splits
492///
493/// # Arguments
494///
495/// * `dataset_size` - Total number of samples
496/// * `k` - Number of folds
497/// * `seed` - Optional seed for reproducible splits
498///
499/// # Returns
500///
501/// A vector of k (train_indices, val_indices) tuples
502pub fn kfold_splits(
503    dataset_size: usize,
504    k: usize,
505    seed: Option<u64>,
506) -> Vec<(Vec<usize>, Vec<usize>)> {
507    assert!(k > 1, "Number of folds must be greater than 1");
508    assert!(
509        k <= dataset_size,
510        "Number of folds cannot exceed dataset size"
511    );
512
513    let mut indices: Vec<usize> = (0..dataset_size).collect();
514
515    {
516        use scirs2_core::random::Random;
517        let mut rng = Random::seed(resolve_seed(seed));
518        // Simple Fisher-Yates shuffle - always runs, regardless of seed.
519        for i in (1..indices.len()).rev() {
520            let j = rng.gen_range(0..=i);
521            indices.swap(i, j);
522        }
523    }
524
525    let fold_size = dataset_size / k;
526    let mut splits = Vec::with_capacity(k);
527
528    for i in 0..k {
529        let val_start = i * fold_size;
530        let val_end = if i == k - 1 {
531            dataset_size
532        } else {
533            (i + 1) * fold_size
534        };
535
536        let val_indices = indices[val_start..val_end].to_vec();
537        let mut train_indices = Vec::new();
538        train_indices.extend(&indices[..val_start]);
539        train_indices.extend(&indices[val_end..]);
540
541        splits.push((train_indices, val_indices));
542    }
543
544    splits
545}
546
547#[cfg(test)]
548mod tests {
549    use super::*;
550    use std::collections::HashSet;
551
552    #[test]
553    fn test_default_sampler() {
554        let sampler = default_sampler(100, Some(42));
555        let indices: Vec<usize> = sampler.iter().collect();
556
557        assert_eq!(indices.len(), 100);
558        assert_eq!(indices.iter().collect::<HashSet<_>>().len(), 100); // All unique
559
560        // Test reproducibility
561        let sampler2 = default_sampler(100, Some(42));
562        let indices2: Vec<usize> = sampler2.iter().collect();
563        assert_eq!(indices, indices2);
564    }
565
566    #[test]
567    fn test_default_batch_sampler() {
568        let sampler = default_batch_sampler(100, 32, true, Some(42));
569        let batches: Vec<Vec<usize>> = sampler.iter().collect();
570
571        assert_eq!(batches.len(), 3); // 100 / 32 = 3.125, drop_last=true
572        assert_eq!(batches[0].len(), 32);
573        assert_eq!(batches[1].len(), 32);
574        assert_eq!(batches[2].len(), 32);
575
576        // Test without dropping last batch
577        let sampler = default_batch_sampler(100, 32, false, Some(42));
578        let batches: Vec<Vec<usize>> = sampler.iter().collect();
579        assert_eq!(batches.len(), 4); // 100 / 32 = 3.125, drop_last=false
580        assert_eq!(batches[3].len(), 4); // Remainder
581    }
582
583    #[test]
584    fn test_default_distributed_sampler() {
585        let sampler = default_distributed_sampler(1000, 4, 0, Some(42));
586        let indices: Vec<usize> = sampler.iter().collect();
587
588        assert_eq!(indices.len(), 250); // 1000 / 4 = 250 per rank
589
590        // Verify rank 0 gets first portion
591        assert!(indices.iter().all(|&i| i < 1000));
592
593        // Test different rank
594        let sampler_rank1 = default_distributed_sampler(1000, 4, 1, Some(42));
595        let indices_rank1: Vec<usize> = sampler_rank1.iter().collect();
596
597        assert_eq!(indices_rank1.len(), 250);
598
599        // Indices should be different between ranks
600        let intersection: HashSet<_> = indices
601            .iter()
602            .filter(|&x| indices_rank1.contains(x))
603            .collect();
604        assert!(intersection.is_empty()); // No overlap between ranks
605    }
606
607    #[test]
608    fn test_sampler_factory() {
609        let mut config = std::collections::HashMap::new();
610        config.insert("seed".to_string(), "42".to_string());
611
612        // Test sequential sampler
613        let sampler =
614            create_sampler("sequential", 100, &config).expect("create sampler should succeed");
615        assert_eq!(sampler.len(), 100);
616
617        // Test random sampler
618        let sampler =
619            create_sampler("random", 100, &config).expect("create sampler should succeed");
620        assert_eq!(sampler.len(), 100);
621
622        // Test weighted sampler
623        config.insert("weights".to_string(), "0.1,0.3,0.6".to_string());
624        let sampler =
625            create_sampler("weighted", 3, &config).expect("create sampler should succeed");
626        assert_eq!(sampler.len(), 3);
627
628        // Test distributed sampler
629        config.insert("num_replicas".to_string(), "4".to_string());
630        config.insert("rank".to_string(), "0".to_string());
631        let sampler =
632            create_sampler("distributed", 1000, &config).expect("create sampler should succeed");
633        assert_eq!(sampler.len(), 250); // 1000 / 4 = 250
634    }
635
636    #[test]
637    fn test_sampler_factory_errors() {
638        let config = std::collections::HashMap::new();
639
640        // Test unknown sampler type
641        assert!(create_sampler("unknown", 100, &config).is_err());
642
643        // Test weighted sampler without weights
644        assert!(create_sampler("weighted", 100, &config).is_err());
645
646        // Test distributed sampler without required config
647        assert!(create_sampler("distributed", 100, &config).is_err());
648    }
649
650    #[test]
651    fn test_backward_compatibility() {
652        // Test that all original sampler types are still accessible
653        let _seq = SequentialSampler::new(100);
654        let _rand = RandomSampler::new(100, None, false).with_generator(42);
655        let _subset = SubsetRandomSampler::new(vec![0, 1, 2, 3, 4]).with_generator(42);
656        let _distributed = DistributedSampler::new(100, 4, 0, true).with_generator(42);
657
658        // Test that utility functions are accessible
659        let (train, val) = train_val_split(1000, 0.2, Some(42));
660        assert_eq!(train.len(), 800);
661        assert_eq!(val.len(), 200);
662
663        // Test that alias types work
664        let _default: DefaultSampler = RandomSampler::new(100, None, false).with_generator(42);
665    }
666
667    #[test]
668    fn test_modular_integration() {
669        // Test that all modules work together seamlessly
670        let base_sampler = RandomSampler::new(1000, None, false).with_generator(42);
671
672        // Chain transformations
673        let batch_sampler = base_sampler.into_batch_sampler(32, true);
674        let distributed_sampler = batch_sampler.into_distributed(4, 0);
675
676        let batches: Vec<Vec<usize>> = distributed_sampler.iter().collect();
677        assert!(!batches.is_empty());
678
679        // Verify each batch has correct size
680        for batch in batches.iter().take(batches.len() - 1) {
681            assert_eq!(batch.len(), 32);
682        }
683    }
684
685    #[test]
686    fn test_comprehensive_api_coverage() {
687        // Test that all major sampling strategies are available
688
689        // Basic samplers
690        let _seq = SequentialSampler::new(100);
691        let _rand = RandomSampler::new(100, None, false).with_generator(42);
692        let _subset = SubsetRandomSampler::new(vec![0, 1, 2]).with_generator(42);
693
694        // Advanced samplers
695        let weights = vec![0.1, 0.3, 0.6];
696        let _weighted = WeightedRandomSampler::new(weights, 3, false).with_generator(42);
697
698        // Create labels for stratified sampling
699        let labels = vec![0, 0, 0, 1, 1, 1]; // 6 samples with 2 strata
700        let _stratified = StratifiedSampler::new(&labels, 6, false);
701
702        // Distributed samplers
703        let _distributed = DistributedSampler::new(100, 4, 0, true);
704
705        // Utility functions
706        let _splits = kfold_splits(100, 5, Some(42));
707        let (train, val, test) = train_val_test_split(1000, 0.6, 0.2, Some(42));
708        assert_eq!(train.len() + val.len() + test.len(), 1000);
709    }
710}