axonml-data 0.6.2

Data loading utilities for the Axonml ML framework
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
//! Samplers - Data Access Patterns
//!
//! # File
//! `crates/axonml-data/src/sampler.rs`
//!
//! # Author
//! Andrew Jewell Sr. — AutomataNexus LLC
//! ORCID: 0009-0005-2158-7060
//!
//! # Updated
//! April 14, 2026 11:15 PM EST
//!
//! # Disclaimer
//! Use at own risk. This software is provided "as is", without warranty of any
//! kind, express or implied. The author and AutomataNexus shall not be held
//! liable for any damages arising from the use of this software.

use rand::Rng;
use rand::seq::SliceRandom;

// =============================================================================
// Sampler Trait
// =============================================================================

/// Trait for all samplers.
///
/// A sampler generates indices that define the order of data access.
pub trait Sampler: Send + Sync {
    /// Returns the number of samples.
    fn len(&self) -> usize;

    /// Returns true if empty.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Creates an iterator over indices.
    fn iter(&self) -> Box<dyn Iterator<Item = usize> + '_>;
}

// =============================================================================
// SequentialSampler
// =============================================================================

/// Samples elements sequentially.
pub struct SequentialSampler {
    len: usize,
}

impl SequentialSampler {
    /// Creates a new `SequentialSampler`.
    #[must_use]
    pub fn new(len: usize) -> Self {
        Self { len }
    }
}

impl Sampler for SequentialSampler {
    fn len(&self) -> usize {
        self.len
    }

    fn iter(&self) -> Box<dyn Iterator<Item = usize> + '_> {
        Box::new(0..self.len)
    }
}

// =============================================================================
// RandomSampler
// =============================================================================

/// Samples elements randomly.
pub struct RandomSampler {
    len: usize,
    replacement: bool,
    num_samples: Option<usize>,
}

impl RandomSampler {
    /// Creates a new `RandomSampler` without replacement.
    #[must_use]
    pub fn new(len: usize) -> Self {
        Self {
            len,
            replacement: false,
            num_samples: None,
        }
    }

    /// Creates a `RandomSampler` with replacement.
    #[must_use]
    pub fn with_replacement(len: usize, num_samples: usize) -> Self {
        Self {
            len,
            replacement: true,
            num_samples: Some(num_samples),
        }
    }
}

impl Sampler for RandomSampler {
    fn len(&self) -> usize {
        self.num_samples.unwrap_or(self.len)
    }

    fn iter(&self) -> Box<dyn Iterator<Item = usize> + '_> {
        if self.replacement {
            // With replacement: random sampling
            let len = self.len;
            let num = self.num_samples.unwrap_or(len);
            Box::new(RandomWithReplacementIter::new(len, num))
        } else {
            // Without replacement: shuffled indices
            let mut indices: Vec<usize> = (0..self.len).collect();
            indices.shuffle(&mut rand::thread_rng());
            Box::new(indices.into_iter())
        }
    }
}

/// Iterator for random sampling with replacement.
struct RandomWithReplacementIter {
    len: usize,
    remaining: usize,
}

impl RandomWithReplacementIter {
    fn new(len: usize, num_samples: usize) -> Self {
        Self {
            len,
            remaining: num_samples,
        }
    }
}

impl Iterator for RandomWithReplacementIter {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        self.remaining -= 1;
        Some(rand::thread_rng().gen_range(0..self.len))
    }
}

// =============================================================================
// SubsetRandomSampler
// =============================================================================

/// Samples randomly from a subset of indices.
pub struct SubsetRandomSampler {
    indices: Vec<usize>,
}

impl SubsetRandomSampler {
    /// Creates a new `SubsetRandomSampler`.
    #[must_use]
    pub fn new(indices: Vec<usize>) -> Self {
        Self { indices }
    }
}

impl Sampler for SubsetRandomSampler {
    fn len(&self) -> usize {
        self.indices.len()
    }

    fn iter(&self) -> Box<dyn Iterator<Item = usize> + '_> {
        let mut shuffled = self.indices.clone();
        shuffled.shuffle(&mut rand::thread_rng());
        Box::new(shuffled.into_iter())
    }
}

// =============================================================================
// WeightedRandomSampler
// =============================================================================

/// Samples elements with specified weights.
///
/// Uses precomputed cumulative sums with binary search for O(log n) per sample
/// instead of O(n) linear scan.
pub struct WeightedRandomSampler {
    weights: Vec<f64>,
    /// Precomputed cumulative sum for O(log n) sampling.
    cumulative: Vec<f64>,
    num_samples: usize,
    replacement: bool,
}

impl WeightedRandomSampler {
    /// Creates a new `WeightedRandomSampler`.
    #[must_use]
    pub fn new(weights: Vec<f64>, num_samples: usize, replacement: bool) -> Self {
        let cumulative = Self::build_cumulative(&weights);
        Self {
            weights,
            cumulative,
            num_samples,
            replacement,
        }
    }

    /// Builds cumulative sum array from weights.
    fn build_cumulative(weights: &[f64]) -> Vec<f64> {
        let mut cum = Vec::with_capacity(weights.len());
        let mut total = 0.0;
        for &w in weights {
            total += w;
            cum.push(total);
        }
        cum
    }

    /// Samples an index based on weights using binary search on cumulative sums.
    fn sample_index(&self) -> usize {
        let total = *self.cumulative.last().unwrap_or(&1.0);
        let threshold: f64 = rand::thread_rng().r#gen::<f64>() * total;

        // Binary search: find first index where cumulative > threshold
        match self
            .cumulative
            .binary_search_by(|c| c.partial_cmp(&threshold).unwrap())
        {
            Ok(i) => i,
            Err(i) => i.min(self.cumulative.len() - 1),
        }
    }
}

impl Sampler for WeightedRandomSampler {
    fn len(&self) -> usize {
        self.num_samples
    }

    fn iter(&self) -> Box<dyn Iterator<Item = usize> + '_> {
        if self.replacement {
            Box::new(WeightedIter::new(self))
        } else {
            // Without replacement: use swap-remove for O(1) removal instead of O(n)
            let mut indices = Vec::with_capacity(self.num_samples);
            let mut available: Vec<usize> = (0..self.weights.len()).collect();
            let mut weights = self.weights.clone();
            let mut cumulative = self.cumulative.clone();

            while indices.len() < self.num_samples && !available.is_empty() {
                let total = *cumulative.last().unwrap_or(&0.0);
                if total <= 0.0 {
                    break;
                }

                let threshold: f64 = rand::thread_rng().r#gen::<f64>() * total;
                let selected =
                    match cumulative.binary_search_by(|c| c.partial_cmp(&threshold).unwrap()) {
                        Ok(i) => i,
                        Err(i) => i.min(cumulative.len() - 1),
                    };

                indices.push(available[selected]);

                // O(1) swap-remove instead of O(n) remove
                available.swap_remove(selected);
                weights.swap_remove(selected);

                // Rebuild cumulative (needed after swap_remove reorders)
                cumulative = Self::build_cumulative(&weights);
            }

            Box::new(indices.into_iter())
        }
    }
}

/// Iterator for weighted random sampling with replacement.
struct WeightedIter<'a> {
    sampler: &'a WeightedRandomSampler,
    remaining: usize,
}

impl<'a> WeightedIter<'a> {
    fn new(sampler: &'a WeightedRandomSampler) -> Self {
        Self {
            sampler,
            remaining: sampler.num_samples,
        }
    }
}

impl Iterator for WeightedIter<'_> {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining == 0 {
            return None;
        }
        self.remaining -= 1;
        Some(self.sampler.sample_index())
    }
}

// =============================================================================
// BatchSampler
// =============================================================================

/// Wraps a sampler to yield batches of indices.
pub struct BatchSampler<S: Sampler> {
    sampler: S,
    batch_size: usize,
    drop_last: bool,
}

impl<S: Sampler> BatchSampler<S> {
    /// Creates a new `BatchSampler`.
    pub fn new(sampler: S, batch_size: usize, drop_last: bool) -> Self {
        Self {
            sampler,
            batch_size,
            drop_last,
        }
    }

    /// Creates an iterator over batches of indices.
    pub fn iter(&self) -> BatchIter {
        let indices: Vec<usize> = self.sampler.iter().collect();
        BatchIter {
            indices,
            batch_size: self.batch_size,
            drop_last: self.drop_last,
            position: 0,
        }
    }

    /// Returns the number of batches.
    pub fn len(&self) -> usize {
        let total = self.sampler.len();
        if self.drop_last {
            total / self.batch_size
        } else {
            total.div_ceil(self.batch_size)
        }
    }

    /// Returns true if empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// Iterator over batches of indices.
pub struct BatchIter {
    indices: Vec<usize>,
    batch_size: usize,
    drop_last: bool,
    position: usize,
}

impl Iterator for BatchIter {
    type Item = Vec<usize>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.position >= self.indices.len() {
            return None;
        }

        let end = (self.position + self.batch_size).min(self.indices.len());
        let batch: Vec<usize> = self.indices[self.position..end].to_vec();

        if batch.len() < self.batch_size && self.drop_last {
            return None;
        }

        self.position = end;
        Some(batch)
    }
}

// =============================================================================
// Tests
// =============================================================================

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

    #[test]
    fn test_sequential_sampler() {
        let sampler = SequentialSampler::new(5);
        let indices: Vec<usize> = sampler.iter().collect();
        assert_eq!(indices, vec![0, 1, 2, 3, 4]);
    }

    #[test]
    fn test_random_sampler() {
        let sampler = RandomSampler::new(10);
        let indices: Vec<usize> = sampler.iter().collect();

        assert_eq!(indices.len(), 10);
        // All indices should be unique (no replacement)
        let mut sorted = indices.clone();
        sorted.sort_unstable();
        sorted.dedup();
        assert_eq!(sorted.len(), 10);
    }

    #[test]
    fn test_random_sampler_with_replacement() {
        let sampler = RandomSampler::with_replacement(5, 20);
        let indices: Vec<usize> = sampler.iter().collect();

        assert_eq!(indices.len(), 20);
        // All indices should be in valid range
        assert!(indices.iter().all(|&i| i < 5));
    }

    #[test]
    fn test_subset_random_sampler() {
        let sampler = SubsetRandomSampler::new(vec![0, 5, 10, 15]);
        let indices: Vec<usize> = sampler.iter().collect();

        assert_eq!(indices.len(), 4);
        // All returned indices should be from the subset
        let mut sorted = indices.clone();
        sorted.sort_unstable();
        assert_eq!(sorted, vec![0, 5, 10, 15]);
    }

    #[test]
    fn test_weighted_random_sampler() {
        // Heavy weight on index 0
        let sampler = WeightedRandomSampler::new(vec![100.0, 1.0, 1.0, 1.0], 100, true);
        let indices: Vec<usize> = sampler.iter().collect();

        assert_eq!(indices.len(), 100);
        // Most samples should be index 0
        let zeros = indices.iter().filter(|&&i| i == 0).count();
        assert!(zeros > 50, "Expected mostly zeros, got {zeros}");
    }

    #[test]
    fn test_batch_sampler() {
        let base = SequentialSampler::new(10);
        let sampler = BatchSampler::new(base, 3, false);

        let batches: Vec<Vec<usize>> = sampler.iter().collect();
        assert_eq!(batches.len(), 4); // 10 / 3 = 3 full + 1 partial

        assert_eq!(batches[0], vec![0, 1, 2]);
        assert_eq!(batches[1], vec![3, 4, 5]);
        assert_eq!(batches[2], vec![6, 7, 8]);
        assert_eq!(batches[3], vec![9]); // Partial batch
    }

    #[test]
    fn test_batch_sampler_drop_last() {
        let base = SequentialSampler::new(10);
        let sampler = BatchSampler::new(base, 3, true);

        let batches: Vec<Vec<usize>> = sampler.iter().collect();
        assert_eq!(batches.len(), 3); // 10 / 3 = 3, drop the partial

        assert_eq!(batches[0], vec![0, 1, 2]);
        assert_eq!(batches[1], vec![3, 4, 5]);
        assert_eq!(batches[2], vec![6, 7, 8]);
    }
}