ferricml 0.2.1

A lean, pure-Rust toolkit for classical machine learning
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
//! Deterministic validated dataset partitions.

use std::collections::BinaryHeap;
use std::error::Error;
use std::fmt;

use crate::numeric::{OwnedRng, derive_repetition_seed};

mod group_shuffle;
mod grouped;
mod repeated;
mod time_series;

pub use group_shuffle::{GroupShuffleSplit, GroupShuffleSplitIter, TestGroupSize};
pub use grouped::{GroupKFold, GroupKFoldIter};
pub use repeated::{RepeatedKFold, RepeatedKFoldIter};
pub use time_series::{LeaveOneOut, LeaveOneOutIter, TimeSeriesSplit, TimeSeriesSplitIter};

/// Identifies one side of a train/test split.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SplitPartition {
    /// Indices used for fitting.
    Train,
    /// Indices held out for evaluation.
    Test,
}

/// Errors produced while constructing deterministic dataset splits.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SplitError {
    /// At least two samples are required for a non-empty train/test split.
    NotEnoughSamples {
        /// Available sample count.
        samples: usize,
    },
    /// A requested test count would leave an empty train or test partition.
    InvalidTestCount {
        /// Requested test samples.
        test: usize,
        /// Available sample count.
        samples: usize,
    },
    /// A test fraction was not finite and strictly between zero and one.
    InvalidTestFraction,
    /// A fold count was outside `2..=samples`.
    InvalidFoldCount {
        /// Requested fold count.
        folds: usize,
        /// Available sample count.
        samples: usize,
    },
    /// A custom split contained an empty partition.
    EmptyPartition {
        /// Empty side of the split.
        partition: SplitPartition,
    },
    /// A custom split index was outside the dataset.
    IndexOutOfBounds {
        /// Side containing the invalid index.
        partition: SplitPartition,
        /// Position within that side's index list.
        position: usize,
        /// Invalid dataset index.
        index: usize,
        /// Available sample count.
        samples: usize,
    },
    /// A custom split repeated an index within one partition.
    DuplicateIndex {
        /// Side containing the repeated index.
        partition: SplitPartition,
        /// Repeated dataset index.
        index: usize,
    },
    /// A custom split placed one index in both partitions.
    OverlappingIndex {
        /// Overlapping dataset index.
        index: usize,
    },
    /// A custom split did not cover the dataset exactly once.
    IncompleteCoverage {
        /// Required number of covered samples.
        expected: usize,
        /// Number of supplied indices.
        actual: usize,
    },
    /// A class did not contain enough rows for every requested partition.
    InsufficientClassMembers {
        /// Class label.
        label: u8,
        /// Rows carrying this label.
        count: usize,
        /// Required partition count.
        partitions: usize,
    },
    /// Fewer distinct groups than the requested number of partitions.
    InsufficientGroups {
        /// Distinct groups observed.
        groups: usize,
        /// Required partition count.
        partitions: usize,
    },
    /// A requested number of held-out groups would leave an empty side.
    ///
    /// Distinct from [`SplitError::InvalidTestCount`], which counts rows: a
    /// grouped holdout is sized in whole groups, and saying so in the error
    /// keeps the two counting units apart.
    InvalidTestGroupCount {
        /// Requested groups held out.
        test_groups: usize,
        /// Distinct groups observed.
        groups: usize,
    },
    /// A repeat count was zero.
    InvalidRepeatCount {
        /// Requested repeats.
        repeats: usize,
    },
    /// A forward-chaining split left no room for a train or test window.
    InvalidTimeSeriesWindow {
        /// Requested splits.
        splits: usize,
        /// Rows skipped between each train window and its test window.
        gap: usize,
        /// Available sample count.
        samples: usize,
    },
    /// A stratified holdout side could not contain every observed class.
    PartitionTooSmallForClasses {
        /// Side that is too small.
        partition: SplitPartition,
        /// Rows assigned to that side.
        rows: usize,
        /// Number of observed classes.
        classes: usize,
    },
}

impl fmt::Display for SplitError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotEnoughSamples { samples } => {
                write!(f, "split requires at least two samples, got {samples}")
            }
            Self::InvalidTestCount { test, samples } => write!(
                f,
                "test count {test} must leave non-empty partitions for {samples} samples"
            ),
            Self::InvalidTestFraction => {
                f.write_str("test fraction must be finite and strictly between zero and one")
            }
            Self::InvalidFoldCount { folds, samples } => {
                write!(f, "fold count {folds} must be in 2..={samples}")
            }
            Self::EmptyPartition { partition } => {
                write!(f, "{partition:?} partition must not be empty")
            }
            Self::IndexOutOfBounds {
                partition,
                position,
                index,
                samples,
            } => write!(
                f,
                "{partition:?} index {index} at position {position} is outside 0..{samples}"
            ),
            Self::DuplicateIndex { partition, index } => {
                write!(f, "{partition:?} partition repeats index {index}")
            }
            Self::OverlappingIndex { index } => {
                write!(f, "train and test partitions overlap at index {index}")
            }
            Self::IncompleteCoverage { expected, actual } => write!(
                f,
                "split must cover {expected} samples exactly once, got {actual} indices"
            ),
            Self::InsufficientClassMembers {
                label,
                count,
                partitions,
            } => write!(
                f,
                "class {label} has {count} rows but needs at least {partitions}"
            ),
            Self::InsufficientGroups { groups, partitions } => write!(
                f,
                "{groups} distinct groups cannot fill {partitions} partitions"
            ),
            Self::InvalidTestGroupCount {
                test_groups,
                groups,
            } => write!(
                f,
                "test group count {test_groups} must leave non-empty partitions for \
                 {groups} groups"
            ),
            Self::InvalidRepeatCount { repeats } => {
                write!(f, "repeat count {repeats} must be at least one")
            }
            Self::InvalidTimeSeriesWindow {
                splits,
                gap,
                samples,
            } => write!(
                f,
                "{splits} forward-chaining splits with gap {gap} leave an empty window for \
                 {samples} samples"
            ),
            Self::PartitionTooSmallForClasses {
                partition,
                rows,
                classes,
            } => write!(
                f,
                "{partition:?} partition has {rows} rows for {classes} observed classes"
            ),
        }
    }
}

impl Error for SplitError {}

/// Owned indices for one train/test partition of a known dataset size.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Split {
    samples: usize,
    train_indices: Vec<usize>,
    test_indices: Vec<usize>,
}

impl Split {
    /// Validates that the two index lists are non-empty, disjoint, unique,
    /// in-bounds, and cover every sample exactly once.
    pub fn new(
        samples: usize,
        train_indices: Vec<usize>,
        test_indices: Vec<usize>,
    ) -> Result<Self, SplitError> {
        Self::validated(samples, train_indices, test_indices, Coverage::Complete)
    }

    /// Validates a split that deliberately leaves some samples out of both
    /// partitions.
    ///
    /// Forward-chaining time-series folds are the reason this exists: an early
    /// fold must not train on rows that come after its test window, so those
    /// rows belong to neither side. Every other guarantee of
    /// [`Split::new`] still holds — in-bounds, unique, and disjoint — and
    /// [`Split::sample_count`] still reports the dataset the split was built
    /// for, so cross-validation validates it exactly as it does a complete
    /// split.
    pub fn partial(
        samples: usize,
        train_indices: Vec<usize>,
        test_indices: Vec<usize>,
    ) -> Result<Self, SplitError> {
        Self::validated(samples, train_indices, test_indices, Coverage::Partial)
    }

    fn validated(
        samples: usize,
        train_indices: Vec<usize>,
        test_indices: Vec<usize>,
        coverage: Coverage,
    ) -> Result<Self, SplitError> {
        validate_sample_count(samples)?;
        if train_indices.is_empty() {
            return Err(SplitError::EmptyPartition {
                partition: SplitPartition::Train,
            });
        }
        if test_indices.is_empty() {
            return Err(SplitError::EmptyPartition {
                partition: SplitPartition::Test,
            });
        }
        validate_bounds(samples, SplitPartition::Train, &train_indices)?;
        validate_bounds(samples, SplitPartition::Test, &test_indices)?;
        let actual = train_indices.len().saturating_add(test_indices.len());
        if coverage == Coverage::Complete && actual != samples {
            return Err(SplitError::IncompleteCoverage {
                expected: samples,
                actual,
            });
        }

        let mut membership = vec![0_u8; samples];
        for &index in &train_indices {
            if membership[index] != 0 {
                return Err(SplitError::DuplicateIndex {
                    partition: SplitPartition::Train,
                    index,
                });
            }
            membership[index] = 1;
        }
        for &index in &test_indices {
            match membership[index] {
                0 => membership[index] = 2,
                1 => return Err(SplitError::OverlappingIndex { index }),
                _ => {
                    return Err(SplitError::DuplicateIndex {
                        partition: SplitPartition::Test,
                        index,
                    });
                }
            }
        }
        if coverage == Coverage::Complete && membership.contains(&0) {
            return Err(SplitError::IncompleteCoverage {
                expected: samples,
                actual,
            });
        }
        Ok(Self {
            samples,
            train_indices,
            test_indices,
        })
    }

    /// Dataset indices used for fitting.
    pub fn train_indices(&self) -> &[usize] {
        &self.train_indices
    }

    /// Dataset indices held out for evaluation.
    pub fn test_indices(&self) -> &[usize] {
        &self.test_indices
    }

    /// Number of dataset samples this split was built for.
    ///
    /// This is the dataset size, not the number of indices the split names, so
    /// it identifies the dataset a split belongs to whether or not the split
    /// covers all of it.
    pub const fn sample_count(&self) -> usize {
        self.samples
    }

    /// Number of samples named by either partition.
    ///
    /// Equal to [`Split::sample_count`] for a complete split, and smaller for
    /// a [`Split::partial`] one.
    pub fn covered_samples(&self) -> usize {
        self.train_indices.len() + self.test_indices.len()
    }

    fn from_test_indices(samples: usize, mut test_indices: Vec<usize>) -> Self {
        test_indices.sort_unstable();
        let mut train_indices = Vec::with_capacity(samples - test_indices.len());
        let mut test_position = 0;
        for index in 0..samples {
            if test_indices.get(test_position) == Some(&index) {
                test_position += 1;
            } else {
                train_indices.push(index);
            }
        }
        Self {
            samples,
            train_indices,
            test_indices,
        }
    }
}

/// Whether a split must name every sample.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Coverage {
    Complete,
    Partial,
}

/// Requested holdout test size.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TestSize {
    /// Exact number of held-out rows.
    Count(usize),
    /// Fraction of rows, rounded upward.
    Fraction(f64),
}

/// Parameters for deterministic train/test splitting.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct HoldoutParams {
    test_size: TestSize,
    shuffle: bool,
    random_state: u64,
}

impl Default for HoldoutParams {
    fn default() -> Self {
        Self {
            test_size: TestSize::Fraction(0.25),
            shuffle: true,
            random_state: 0,
        }
    }
}

impl HoldoutParams {
    /// Sets the exact or fractional test size.
    #[must_use]
    pub fn with_test_size(mut self, test_size: TestSize) -> Self {
        self.test_size = test_size;
        self
    }

    /// Enables or disables deterministic shuffling before membership is chosen.
    #[must_use]
    pub fn with_shuffle(mut self, shuffle: bool) -> Self {
        self.shuffle = shuffle;
        self
    }

    /// Sets the deterministic shuffle seed.
    #[must_use]
    pub fn with_random_state(mut self, random_state: u64) -> Self {
        self.random_state = random_state;
        self
    }

    /// Returns the requested test size.
    pub const fn test_size(&self) -> TestSize {
        self.test_size
    }

    /// Returns whether membership is shuffled.
    pub const fn shuffle(&self) -> bool {
        self.shuffle
    }

    /// Returns the deterministic shuffle seed.
    pub const fn random_state(&self) -> u64 {
        self.random_state
    }
}

/// Splits sample indices into one train and test partition.
pub fn train_test_split(samples: usize, params: HoldoutParams) -> Result<Split, SplitError> {
    let test_count = resolve_test_count(samples, params.test_size)?;
    let train_count = samples - test_count;
    if !params.shuffle {
        return Ok(Split {
            samples,
            train_indices: (0..train_count).collect(),
            test_indices: (train_count..samples).collect(),
        });
    }

    let mut order = (0..samples).collect::<Vec<_>>();
    let mut test_membership = vec![0_u8; samples];
    let mut rng = OwnedRng::new(params.random_state);
    for index in (train_count..samples).rev() {
        let other = rng.index(index + 1);
        order.swap(index, other);
        test_membership[order[index]] = 1;
    }
    drop(order);
    Ok(split_from_test_membership(&test_membership, test_count))
}

/// Splits indices while preserving every observed label in both partitions.
pub fn stratified_train_test_split(
    labels: &[u8],
    params: HoldoutParams,
) -> Result<Split, SplitError> {
    let samples = labels.len();
    let test_count = resolve_test_count(samples, params.test_size)?;
    let counts = class_counts(labels);
    let classes = counts.iter().filter(|&&count| count > 0).count();
    let train_count = samples - test_count;
    if test_count < classes {
        return Err(SplitError::PartitionTooSmallForClasses {
            partition: SplitPartition::Test,
            rows: test_count,
            classes,
        });
    }
    if train_count < classes {
        return Err(SplitError::PartitionTooSmallForClasses {
            partition: SplitPartition::Train,
            rows: train_count,
            classes,
        });
    }
    for (label, &count) in counts.iter().enumerate().filter(|(_, count)| **count > 0) {
        if count < 2 {
            return Err(SplitError::InsufficientClassMembers {
                label: label as u8,
                count,
                partitions: 2,
            });
        }
    }

    let mut remaining_quotas = stratified_test_quotas(&counts, test_count);
    let mut remaining_total = test_count;
    let mut test_membership = vec![0_u8; samples];
    if params.shuffle {
        let mut order = (0..samples).collect::<Vec<_>>();
        let mut rng = OwnedRng::new(params.random_state);
        for position in (1..samples).rev() {
            let other = rng.index(position + 1);
            order.swap(position, other);
            let index = order[position];
            let label = labels[index] as usize;
            if remaining_quotas[label] > 0 {
                test_membership[index] = 1;
                remaining_quotas[label] -= 1;
                remaining_total -= 1;
                if remaining_total == 0 {
                    break;
                }
            }
        }
    } else {
        for index in (0..samples).rev() {
            let label = labels[index] as usize;
            if remaining_quotas[label] > 0 {
                test_membership[index] = 1;
                remaining_quotas[label] -= 1;
                remaining_total -= 1;
                if remaining_total == 0 {
                    break;
                }
            }
        }
    }
    debug_assert_eq!(remaining_total, 0);
    Ok(split_from_test_membership(&test_membership, test_count))
}

/// Deterministic K-fold splitter configuration.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct KFold {
    n_splits: usize,
    shuffle: bool,
    random_state: u64,
}

impl KFold {
    /// Creates an unshuffled K-fold configuration.
    pub const fn new(n_splits: usize) -> Self {
        Self {
            n_splits,
            shuffle: false,
            random_state: 0,
        }
    }

    /// Enables or disables deterministic shuffling before folds are assigned.
    #[must_use]
    pub const fn with_shuffle(mut self, shuffle: bool) -> Self {
        self.shuffle = shuffle;
        self
    }

    /// Sets the deterministic shuffle seed.
    #[must_use]
    pub const fn with_random_state(mut self, random_state: u64) -> Self {
        self.random_state = random_state;
        self
    }

    /// Returns the number of folds.
    pub const fn n_splits(&self) -> usize {
        self.n_splits
    }

    /// Returns whether membership is shuffled.
    pub const fn shuffle(&self) -> bool {
        self.shuffle
    }

    /// Returns the deterministic shuffle seed.
    pub const fn random_state(&self) -> u64 {
        self.random_state
    }

    /// Validates the sample count and returns an iterator over complete splits.
    pub fn split(&self, samples: usize) -> Result<KFoldIter, SplitError> {
        validate_fold_count(samples, self.n_splits)?;
        let mut order = (0..samples).collect::<Vec<_>>();
        if self.shuffle {
            stable_shuffle(&mut order, self.random_state);
        }
        Ok(KFoldIter {
            order,
            n_splits: self.n_splits,
            next_fold: 0,
        })
    }
}

/// Iterator over deterministic K-fold partitions.
#[derive(Clone, Debug)]
pub struct KFoldIter {
    order: Vec<usize>,
    n_splits: usize,
    next_fold: usize,
}

impl Iterator for KFoldIter {
    type Item = Split;

    fn next(&mut self) -> Option<Self::Item> {
        if self.next_fold == self.n_splits {
            return None;
        }
        let samples = self.order.len();
        let (start, end) = fold_bounds(samples, self.n_splits, self.next_fold);
        self.next_fold += 1;
        Some(Split::from_test_indices(
            samples,
            self.order[start..end].to_vec(),
        ))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.n_splits - self.next_fold;
        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for KFoldIter {}

/// Deterministic label-stratified K-fold splitter configuration.
///
/// Each observed class is dealt round-robin across the folds, so every fold
/// receives that class's members in near-equal number and the per-fold class
/// proportions track the whole dataset's. **What is claimed is the
/// stratification, not the membership.** Which fold a given row lands in is
/// this splitter's own round-robin assignment and is not a parity claim
/// against any other library: a library that fills folds with contiguous
/// blocks of each stratum instead produces the same per-fold class rates from
/// entirely different rows. Both are correct stratified partitions, and a
/// cross-library comparison of fold *contents* is comparing something neither
/// splitter promises. Assignment is reproducible from the labels, `n_splits`,
/// `shuffle`, and `random_state` alone, which is the property cross-validation
/// actually rests on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StratifiedKFold {
    n_splits: usize,
    shuffle: bool,
    random_state: u64,
}

impl StratifiedKFold {
    /// Creates an unshuffled stratified K-fold configuration.
    pub const fn new(n_splits: usize) -> Self {
        Self {
            n_splits,
            shuffle: false,
            random_state: 0,
        }
    }

    /// Enables or disables deterministic shuffling within each class.
    #[must_use]
    pub const fn with_shuffle(mut self, shuffle: bool) -> Self {
        self.shuffle = shuffle;
        self
    }

    /// Sets the deterministic shuffle seed.
    #[must_use]
    pub const fn with_random_state(mut self, random_state: u64) -> Self {
        self.random_state = random_state;
        self
    }

    /// Returns the number of folds.
    pub const fn n_splits(&self) -> usize {
        self.n_splits
    }

    /// Returns whether class membership is shuffled.
    pub const fn shuffle(&self) -> bool {
        self.shuffle
    }

    /// Returns the deterministic shuffle seed.
    pub const fn random_state(&self) -> u64 {
        self.random_state
    }

    /// Validates labels and returns an iterator over stratified splits.
    pub fn split(&self, labels: &[u8]) -> Result<StratifiedKFoldIter, SplitError> {
        let samples = labels.len();
        validate_fold_count(samples, self.n_splits)?;
        let counts = class_counts(labels);
        for (label, &count) in counts.iter().enumerate().filter(|(_, count)| **count > 0) {
            if count < self.n_splits {
                return Err(SplitError::InsufficientClassMembers {
                    label: label as u8,
                    count,
                    partitions: self.n_splits,
                });
            }
        }

        let mut buckets = (0..=u8::MAX)
            .map(|_| Vec::<usize>::new())
            .collect::<Vec<_>>();
        for (index, &label) in labels.iter().enumerate() {
            buckets[label as usize].push(index);
        }
        if self.shuffle {
            let mut rng = OwnedRng::new(self.random_state);
            for bucket in &mut buckets {
                shuffle_with_rng(bucket, &mut rng);
            }
        }

        let mut assignments = vec![0_usize; samples];
        let mut offset = 0;
        for bucket in buckets {
            for (position, index) in bucket.iter().copied().enumerate() {
                assignments[index] = (offset + position) % self.n_splits;
            }
            offset = (offset + bucket.len()) % self.n_splits;
        }
        Ok(StratifiedKFoldIter {
            assignments,
            n_splits: self.n_splits,
            next_fold: 0,
        })
    }
}

/// Iterator over deterministic stratified K-fold partitions.
#[derive(Clone, Debug)]
pub struct StratifiedKFoldIter {
    assignments: Vec<usize>,
    n_splits: usize,
    next_fold: usize,
}

impl Iterator for StratifiedKFoldIter {
    type Item = Split;

    fn next(&mut self) -> Option<Self::Item> {
        if self.next_fold == self.n_splits {
            return None;
        }
        let fold = self.next_fold;
        self.next_fold += 1;
        let test_indices = self
            .assignments
            .iter()
            .enumerate()
            .filter_map(|(index, &assigned)| (assigned == fold).then_some(index))
            .collect();
        Some(Split::from_test_indices(
            self.assignments.len(),
            test_indices,
        ))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.n_splits - self.next_fold;
        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for StratifiedKFoldIter {}

fn validate_sample_count(samples: usize) -> Result<(), SplitError> {
    if samples < 2 {
        return Err(SplitError::NotEnoughSamples { samples });
    }
    Ok(())
}

fn validate_bounds(
    samples: usize,
    partition: SplitPartition,
    indices: &[usize],
) -> Result<(), SplitError> {
    if let Some((position, &index)) = indices
        .iter()
        .enumerate()
        .find(|(_, index)| **index >= samples)
    {
        return Err(SplitError::IndexOutOfBounds {
            partition,
            position,
            index,
            samples,
        });
    }
    Ok(())
}

fn resolve_test_count(samples: usize, test_size: TestSize) -> Result<usize, SplitError> {
    validate_sample_count(samples)?;
    let test = match test_size {
        TestSize::Count(count) => count,
        TestSize::Fraction(fraction) => {
            if !fraction.is_finite() || fraction <= 0.0 || fraction >= 1.0 {
                return Err(SplitError::InvalidTestFraction);
            }
            (samples as f64 * fraction).ceil() as usize
        }
    };
    if test == 0 || test >= samples {
        return Err(SplitError::InvalidTestCount { test, samples });
    }
    Ok(test)
}

fn validate_fold_count(samples: usize, folds: usize) -> Result<(), SplitError> {
    validate_sample_count(samples)?;
    if folds < 2 || folds > samples {
        return Err(SplitError::InvalidFoldCount { folds, samples });
    }
    Ok(())
}

fn fold_bounds(samples: usize, folds: usize, fold: usize) -> (usize, usize) {
    let base = samples / folds;
    let larger = samples % folds;
    let start = fold * base + fold.min(larger);
    let size = base + usize::from(fold < larger);
    (start, start + size)
}

fn class_counts(labels: &[u8]) -> [usize; 256] {
    let mut counts = [0_usize; 256];
    for &label in labels {
        counts[label as usize] += 1;
    }
    counts
}

fn split_from_test_membership(test_membership: &[u8], test_count: usize) -> Split {
    let mut train_indices = Vec::with_capacity(test_membership.len() - test_count);
    let mut test_indices = Vec::with_capacity(test_count);
    for (index, &is_test) in test_membership.iter().enumerate() {
        if is_test != 0 {
            test_indices.push(index);
        } else {
            train_indices.push(index);
        }
    }
    Split {
        samples: test_membership.len(),
        train_indices,
        test_indices,
    }
}

fn stratified_test_quotas(counts: &[usize; 256], test_count: usize) -> [usize; 256] {
    let mut quotas = counts.map(|count| usize::from(count > 0));
    let mut remaining = test_count - quotas.iter().sum::<usize>();
    let mut candidates = counts
        .iter()
        .copied()
        .enumerate()
        .filter_map(|(label, count)| {
            (count > 2).then_some(QuotaCandidate {
                label,
                quota: 1,
                count,
            })
        })
        .collect::<BinaryHeap<_>>();
    while remaining > 0 {
        let mut candidate = candidates
            .pop()
            .expect("validated train partition leaves class capacity");
        candidate.quota += 1;
        quotas[candidate.label] = candidate.quota;
        remaining -= 1;
        if candidate.quota + 1 < candidate.count {
            candidates.push(candidate);
        }
    }
    quotas
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct QuotaCandidate {
    label: usize,
    quota: usize,
    count: usize,
}

impl Ord for QuotaCandidate {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        let self_ratio = (self.quota as u128) * (other.count as u128);
        let other_ratio = (other.quota as u128) * (self.count as u128);
        other_ratio
            .cmp(&self_ratio)
            .then_with(|| other.label.cmp(&self.label))
    }
}

impl PartialOrd for QuotaCandidate {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// Derives one repetition's shuffle seed from a configured seed.
///
/// A thin name over [`derive_repetition_seed`], which owns the derivation for
/// the reason `numeric`'s rule 6 gives: seeds mean one thing crate-wide. This
/// module deliberately holds no generator and no mixing constant of its own —
/// it did until 2026-07-26, and the copy was byte-identical to the shared
/// stream while its doc comment claimed independence.
fn repeat_seed(random_state: u64, repetition: usize) -> u64 {
    derive_repetition_seed(random_state, repetition as u64)
}

fn stable_shuffle(values: &mut [usize], seed: u64) {
    shuffle_with_rng(values, &mut OwnedRng::new(seed));
}

fn shuffle_with_rng(values: &mut [usize], rng: &mut OwnedRng) {
    for index in (1..values.len()).rev() {
        let other = rng.index(index + 1);
        values.swap(index, other);
    }
}

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

    fn legacy_train_test_split(samples: usize, params: HoldoutParams) -> Result<Split, SplitError> {
        let test_count = resolve_test_count(samples, params.test_size)?;
        let mut order = (0..samples).collect::<Vec<_>>();
        if params.shuffle {
            stable_shuffle(&mut order, params.random_state);
        }
        let train_count = samples - test_count;
        let mut train_indices = order[..train_count].to_vec();
        let mut test_indices = order[train_count..].to_vec();
        train_indices.sort_unstable();
        test_indices.sort_unstable();
        Ok(Split {
            samples,
            train_indices,
            test_indices,
        })
    }

    fn legacy_stratified_train_test_split(
        labels: &[u8],
        params: HoldoutParams,
    ) -> Result<Split, SplitError> {
        let samples = labels.len();
        let test_count = resolve_test_count(samples, params.test_size)?;
        let counts = class_counts(labels);
        let classes = counts.iter().filter(|&&count| count > 0).count();
        let train_count = samples - test_count;
        if test_count < classes {
            return Err(SplitError::PartitionTooSmallForClasses {
                partition: SplitPartition::Test,
                rows: test_count,
                classes,
            });
        }
        if train_count < classes {
            return Err(SplitError::PartitionTooSmallForClasses {
                partition: SplitPartition::Train,
                rows: train_count,
                classes,
            });
        }
        for (label, &count) in counts.iter().enumerate().filter(|(_, count)| **count > 0) {
            if count < 2 {
                return Err(SplitError::InsufficientClassMembers {
                    label: label as u8,
                    count,
                    partitions: 2,
                });
            }
        }

        let mut order = (0..samples).collect::<Vec<_>>();
        if params.shuffle {
            stable_shuffle(&mut order, params.random_state);
        }
        let mut buckets = (0..=u8::MAX).map(|_| Vec::new()).collect::<Vec<_>>();
        for index in order {
            buckets[labels[index] as usize].push(index);
        }
        let quotas = legacy_stratified_test_quotas(&counts, test_count);
        let mut train_indices = Vec::with_capacity(train_count);
        let mut test_indices = Vec::with_capacity(test_count);
        for (label, bucket) in buckets.into_iter().enumerate() {
            let test_start = bucket.len().saturating_sub(quotas[label]);
            train_indices.extend_from_slice(&bucket[..test_start]);
            test_indices.extend_from_slice(&bucket[test_start..]);
        }
        train_indices.sort_unstable();
        test_indices.sort_unstable();
        Ok(Split {
            samples,
            train_indices,
            test_indices,
        })
    }

    fn legacy_stratified_test_quotas(counts: &[usize; 256], test_count: usize) -> [usize; 256] {
        let mut quotas = counts.map(|count| usize::from(count > 0));
        let mut remaining = test_count - quotas.iter().sum::<usize>();
        while remaining > 0 {
            let label = (0..quotas.len())
                .filter(|&label| quotas[label] + 1 < counts[label])
                .min_by(|&left, &right| {
                    let left_ratio = (quotas[left] as u128) * (counts[right] as u128);
                    let right_ratio = (quotas[right] as u128) * (counts[left] as u128);
                    left_ratio.cmp(&right_ratio).then_with(|| left.cmp(&right))
                })
                .expect("validated train partition leaves class capacity");
            quotas[label] += 1;
            remaining -= 1;
        }
        quotas
    }

    #[test]
    fn custom_split_validates_complete_disjoint_coverage() {
        assert_eq!(
            Split::new(4, vec![0, 1, 2], vec![3])
                .unwrap()
                .train_indices(),
            &[0, 1, 2]
        );
        assert_eq!(
            Split::new(4, vec![0, 1], vec![1, 3]),
            Err(SplitError::OverlappingIndex { index: 1 })
        );
        assert_eq!(
            Split::new(4, vec![0, 0], vec![2, 3]),
            Err(SplitError::DuplicateIndex {
                partition: SplitPartition::Train,
                index: 0,
            })
        );
        assert_eq!(
            Split::new(4, vec![0, 1], vec![2]),
            Err(SplitError::IncompleteCoverage {
                expected: 4,
                actual: 3,
            })
        );
        assert_eq!(
            Split::new(4, vec![0, 4], vec![2, 3]),
            Err(SplitError::IndexOutOfBounds {
                partition: SplitPartition::Train,
                position: 1,
                index: 4,
                samples: 4,
            })
        );
    }

    #[test]
    fn holdout_rounding_order_and_seed_are_frozen() {
        let unshuffled = train_test_split(
            10,
            HoldoutParams::default()
                .with_test_size(TestSize::Fraction(0.21))
                .with_shuffle(false),
        )
        .unwrap();
        assert_eq!(unshuffled.train_indices(), &[0, 1, 2, 3, 4, 5, 6]);
        assert_eq!(unshuffled.test_indices(), &[7, 8, 9]);

        let shuffled = train_test_split(
            10,
            HoldoutParams::default()
                .with_test_size(TestSize::Count(3))
                .with_random_state(42),
        )
        .unwrap();
        assert_eq!(shuffled.train_indices(), &[0, 4, 5, 6, 7, 8, 9]);
        assert_eq!(shuffled.test_indices(), &[1, 2, 3]);
    }

    #[test]
    fn holdout_membership_matches_legacy_for_all_small_partitions() {
        for samples in 2..=128 {
            for test_count in 1..samples {
                for shuffle in [false, true] {
                    for seed in [0, 1, 42, u64::MAX] {
                        let params = HoldoutParams::default()
                            .with_test_size(TestSize::Count(test_count))
                            .with_shuffle(shuffle)
                            .with_random_state(seed);
                        assert_eq!(
                            train_test_split(samples, params),
                            legacy_train_test_split(samples, params),
                            "samples={samples}, test={test_count}, shuffle={shuffle}, seed={seed}"
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn holdout_rejects_invalid_sizes_before_membership_allocation() {
        assert_eq!(
            train_test_split(1, HoldoutParams::default()),
            Err(SplitError::NotEnoughSamples { samples: 1 })
        );
        for fraction in [f64::NAN, f64::INFINITY, -0.1, 0.0, 1.0, 1.1] {
            assert_eq!(
                train_test_split(
                    4,
                    HoldoutParams::default().with_test_size(TestSize::Fraction(fraction))
                ),
                Err(SplitError::InvalidTestFraction)
            );
        }
        assert_eq!(
            train_test_split(
                4,
                HoldoutParams::default().with_test_size(TestSize::Count(4))
            ),
            Err(SplitError::InvalidTestCount {
                test: 4,
                samples: 4,
            })
        );
    }

    #[test]
    fn kfold_exhaustively_covers_each_sample_once() {
        for samples in 2..=64 {
            for folds in 2..=samples {
                for seed in [0, 1, 42] {
                    let splits = KFold::new(folds)
                        .with_shuffle(true)
                        .with_random_state(seed)
                        .split(samples)
                        .unwrap()
                        .collect::<Vec<_>>();
                    assert_eq!(splits.len(), folds);
                    let mut test_counts = vec![0_usize; samples];
                    let sizes = splits
                        .iter()
                        .map(|split| {
                            assert_complete_split(samples, split);
                            for &index in split.test_indices() {
                                test_counts[index] += 1;
                            }
                            split.test_indices().len()
                        })
                        .collect::<Vec<_>>();
                    assert!(sizes.iter().max().unwrap() - sizes.iter().min().unwrap() <= 1);
                    assert_eq!(test_counts, vec![1; samples]);
                }
            }
        }
    }

    #[test]
    fn unshuffled_kfold_has_exact_contiguous_membership() {
        let tests = KFold::new(3)
            .split(8)
            .unwrap()
            .map(|split| split.test_indices().to_vec())
            .collect::<Vec<_>>();
        assert_eq!(tests, vec![vec![0, 1, 2], vec![3, 4, 5], vec![6, 7]]);
    }

    #[test]
    fn stratified_folds_balance_every_class_and_global_size() {
        for folds in 2..=8 {
            for classes in 1..=4_u8 {
                let labels = (0..classes)
                    .flat_map(|label| std::iter::repeat_n(label, folds + label as usize + 2))
                    .collect::<Vec<_>>();
                for seed in [0, 7, 99] {
                    let splits = StratifiedKFold::new(folds)
                        .with_shuffle(true)
                        .with_random_state(seed)
                        .split(&labels)
                        .unwrap()
                        .collect::<Vec<_>>();
                    let global_sizes = splits
                        .iter()
                        .map(|split| split.test_indices().len())
                        .collect::<Vec<_>>();
                    assert!(
                        global_sizes.iter().max().unwrap() - global_sizes.iter().min().unwrap()
                            <= 1
                    );
                    for label in 0..classes {
                        let counts = splits
                            .iter()
                            .map(|split| {
                                split
                                    .test_indices()
                                    .iter()
                                    .filter(|&&index| labels[index] == label)
                                    .count()
                            })
                            .collect::<Vec<_>>();
                        assert!(counts.iter().max().unwrap() - counts.iter().min().unwrap() <= 1);
                    }
                }
            }
        }
    }

    #[test]
    fn stratified_holdout_preserves_classes_and_exact_size() {
        let labels = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1];
        let split = stratified_train_test_split(
            &labels,
            HoldoutParams::default()
                .with_test_size(TestSize::Count(4))
                .with_random_state(17),
        )
        .unwrap();
        assert_eq!(split.test_indices().len(), 4);
        for label in [0, 1] {
            assert!(
                split
                    .test_indices()
                    .iter()
                    .any(|&index| labels[index] == label)
            );
            assert!(
                split
                    .train_indices()
                    .iter()
                    .any(|&index| labels[index] == label)
            );
        }
    }

    #[test]
    fn stratified_holdout_membership_matches_legacy_across_class_shapes() {
        let mut cases = vec![
            (0_u8..4)
                .flat_map(|label| std::iter::repeat_n(label, 8))
                .collect::<Vec<_>>(),
            [2_usize, 3, 7, 11]
                .into_iter()
                .enumerate()
                .flat_map(|(label, count)| std::iter::repeat_n(label as u8, count))
                .collect(),
            [(0_u8, 5_usize), (17, 9), (255, 4)]
                .into_iter()
                .flat_map(|(label, count)| std::iter::repeat_n(label, count))
                .collect(),
        ];
        cases.push(
            (0_u8..=254)
                .flat_map(|label| std::iter::repeat_n(label, 2))
                .collect(),
        );
        cases.push(
            (0_u8..=u8::MAX)
                .flat_map(|label| std::iter::repeat_n(label, 2))
                .collect(),
        );

        for labels in cases {
            let classes = class_counts(&labels)
                .into_iter()
                .filter(|&count| count > 0)
                .count();
            for test_count in classes..=labels.len() - classes {
                for shuffle in [false, true] {
                    for seed in [0, 1, 42, u64::MAX] {
                        let params = HoldoutParams::default()
                            .with_test_size(TestSize::Count(test_count))
                            .with_shuffle(shuffle)
                            .with_random_state(seed);
                        assert_eq!(
                            stratified_train_test_split(&labels, params),
                            legacy_stratified_train_test_split(&labels, params),
                            "rows={}, classes={classes}, test={test_count}, shuffle={shuffle}, seed={seed}",
                            labels.len()
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn stratification_rejects_impossible_class_partitions() {
        assert_eq!(
            StratifiedKFold::new(3).split(&[0, 0, 1, 1, 1]).unwrap_err(),
            SplitError::InsufficientClassMembers {
                label: 0,
                count: 2,
                partitions: 3,
            }
        );
        assert_eq!(
            stratified_train_test_split(
                &[0, 0, 1, 1],
                HoldoutParams::default().with_test_size(TestSize::Count(1))
            ),
            Err(SplitError::PartitionTooSmallForClasses {
                partition: SplitPartition::Test,
                rows: 1,
                classes: 2,
            })
        );
    }

    fn assert_complete_split(samples: usize, split: &Split) {
        assert!(
            split
                .train_indices()
                .windows(2)
                .all(|pair| pair[0] < pair[1])
        );
        assert!(
            split
                .test_indices()
                .windows(2)
                .all(|pair| pair[0] < pair[1])
        );
        let mut membership = vec![0_u8; samples];
        for &index in split.train_indices() {
            membership[index] += 1;
        }
        for &index in split.test_indices() {
            membership[index] += 1;
        }
        assert_eq!(membership, vec![1; samples]);
    }
}