1pub 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
79pub use core::{utils, BatchSampler, Sampler, SamplerIterator};
81
82pub use basic::{
84 random, random_subset, random_with_replacement, sequential, RandomSampler, SequentialSampler,
85};
86
87pub use batch::{batch, batch_drop_last, batch_keep_last, BatchSamplerIter, BatchingSampler};
89
90pub use distributed::{distributed, distributed_sampler, DistributedSampler, DistributedWrapper};
92
93pub use weighted::{
95 balanced_weighted, subset_random, weighted_random, SubsetRandomSampler, WeightedRandomSampler,
96};
97
98pub use stratified::{
100 balanced_stratified, stratified, stratified_train_test_split, StratifiedSampler,
101};
102
103pub use curriculum::{
105 anti_curriculum, exponential_curriculum, linear_curriculum, step_curriculum, CurriculumSampler,
106 CurriculumStats, CurriculumStrategy,
107};
108
109pub use active_learning::{
111 diversity_sampler, uncertainty_diversity_sampler, uncertainty_sampler, AcquisitionStrategy,
112 ActiveLearningSampler, ActiveLearningStats,
113};
114
115pub use adaptive::{
117 frequency_balanced_sampler, hard_adaptive_sampler, uncertainty_adaptive_sampler,
118 AdaptiveSampler, AdaptiveStats, AdaptiveStrategy,
119};
120
121pub use importance::{
123 class_balanced_importance_sampler, exponential_importance_sampler,
124 loss_based_importance_sampler, uniform_importance_sampler, ImportanceSampler, ImportanceStats,
125};
126
127pub use advanced::{
129 GroupedSampler, ImportanceSampler as AdvancedImportanceSampler,
130 StratifiedSampler as AdvancedStratifiedSampler,
131 WeightedRandomSampler as AdvancedWeightedRandomSampler,
132};
133
134pub type DefaultSampler = RandomSampler;
136pub type DefaultBatchSampler = BatchingSampler<RandomSampler>;
137
138pub fn default_sampler(dataset_size: usize, seed: Option<u64>) -> RandomSampler {
159 random(dataset_size, seed)
160}
161
162pub 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
193pub 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
228pub 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#[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
376fn 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
393pub 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 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
437pub 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 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
491pub 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 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); 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); assert_eq!(batches[0].len(), 32);
573 assert_eq!(batches[1].len(), 32);
574 assert_eq!(batches[2].len(), 32);
575
576 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); assert_eq!(batches[3].len(), 4); }
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); assert!(indices.iter().all(|&i| i < 1000));
592
593 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 let intersection: HashSet<_> = indices
601 .iter()
602 .filter(|&x| indices_rank1.contains(x))
603 .collect();
604 assert!(intersection.is_empty()); }
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 let sampler =
614 create_sampler("sequential", 100, &config).expect("create sampler should succeed");
615 assert_eq!(sampler.len(), 100);
616
617 let sampler =
619 create_sampler("random", 100, &config).expect("create sampler should succeed");
620 assert_eq!(sampler.len(), 100);
621
622 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 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); }
635
636 #[test]
637 fn test_sampler_factory_errors() {
638 let config = std::collections::HashMap::new();
639
640 assert!(create_sampler("unknown", 100, &config).is_err());
642
643 assert!(create_sampler("weighted", 100, &config).is_err());
645
646 assert!(create_sampler("distributed", 100, &config).is_err());
648 }
649
650 #[test]
651 fn test_backward_compatibility() {
652 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 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 let _default: DefaultSampler = RandomSampler::new(100, None, false).with_generator(42);
665 }
666
667 #[test]
668 fn test_modular_integration() {
669 let base_sampler = RandomSampler::new(1000, None, false).with_generator(42);
671
672 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 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 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 let weights = vec![0.1, 0.3, 0.6];
696 let _weighted = WeightedRandomSampler::new(weights, 3, false).with_generator(42);
697
698 let labels = vec![0, 0, 0, 1, 1, 1]; let _stratified = StratifiedSampler::new(&labels, 6, false);
701
702 let _distributed = DistributedSampler::new(100, 4, 0, true);
704
705 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}