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
//! Typed hyperparameter search over FerricML's own parameter builders.

use std::error::Error;
use std::fmt;

use crate::api::{ModelError, Regressor};
use crate::data::{ClassificationTargets, MatrixView, RegressionTargets};

use super::cross_validation::{validate_split_sample_count, validate_target_length};
use super::{
    ClassificationScore, CrossValidationError, CrossValidationResult, RegressionScore,
    ScorableClassifier, Split, cross_validate_classifier, cross_validate_regressor,
};

/// An ordered, explicit set of typed parameter candidates.
///
/// FerricML's whole parameter story is typed builders, so a search grid is too:
/// there are no string keys, no runtime name lookup, and no way to name a
/// parameter that does not exist. An axis is a *builder method* plus the values
/// to pass it, which is why a misspelled parameter is a compile error here and a
/// silent misconfiguration in a stringly-typed grid.
///
/// ```
/// use ferricml::linear_model::RidgeParams;
/// use ferricml::model_selection::ParameterGrid;
///
/// let grid = ParameterGrid::new(RidgeParams::default())
///     .axis([0.1_f32, 1.0], RidgeParams::with_alpha)
///     .axis([true, false], RidgeParams::with_fit_intercept);
///
/// // Two alphas by two intercept choices, and the axis added last varies
/// // fastest.
/// assert_eq!(grid.len(), 4);
/// assert_eq!(grid.candidates()[0].alpha(), 0.1);
/// assert!(grid.candidates()[0].fit_intercept());
/// assert_eq!(grid.candidates()[1].alpha(), 0.1);
/// assert!(!grid.candidates()[1].fit_intercept());
/// ```
///
/// # Candidate order
///
/// Candidates are materialized when each axis is added, so the order is fixed
/// at construction and never depends on iteration of an unordered collection.
/// Adding an axis replaces every existing candidate with one candidate per
/// value, in value order, so the **axis added last varies fastest** and the
/// first candidate is the base value with the first value of every axis.
///
/// That order is part of the contract: search reports per-candidate results in
/// it and breaks ties toward the earliest candidate, so a caller who puts the
/// cheapest or most conservative value first gets it on a tie.
///
/// # Dependent parameters
///
/// A cross product cannot express "this depth only with that leaf count".
/// [`ParameterGrid::from_candidates`] takes the list directly for that case, and
/// search treats both the same way.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParameterGrid<P> {
    candidates: Vec<P>,
}

impl<P> ParameterGrid<P> {
    /// Starts a grid from one base parameter value.
    ///
    /// With no axes this is a one-candidate grid, which is a legitimate way to
    /// cross-validate a single configuration through the same entry point.
    pub fn new(base: P) -> Self {
        Self {
            candidates: vec![base],
        }
    }

    /// Takes an explicit candidate list in the order it will be evaluated.
    ///
    /// An empty list is accepted here and rejected by the search entry point as
    /// [`SearchError::EmptyGrid`], so a grid built by a caller's own loop is
    /// refused exactly as an axis with no values is.
    pub fn from_candidates(candidates: Vec<P>) -> Self {
        Self { candidates }
    }

    /// Candidates in evaluation order.
    pub fn candidates(&self) -> &[P] {
        &self.candidates
    }

    /// Number of candidates the grid names.
    pub fn len(&self) -> usize {
        self.candidates.len()
    }

    /// Returns whether the grid names no candidate at all.
    pub fn is_empty(&self) -> bool {
        self.candidates.is_empty()
    }
}

impl<P: Clone> ParameterGrid<P> {
    /// Crosses every current candidate with one typed builder setting.
    ///
    /// `set` is the parameter type's own `with_*` builder method and `values`
    /// are the values to pass it, so each axis keeps the parameter's real type.
    /// Different axes may therefore carry different value types, which is what
    /// a single erased key/value map could not do without giving up the types.
    ///
    /// An axis with no values empties the grid rather than being ignored: a grid
    /// that silently dropped an axis would search something the caller did not
    /// ask for.
    #[must_use]
    pub fn axis<T, F>(self, values: impl IntoIterator<Item = T>, set: F) -> Self
    where
        T: Clone,
        F: Fn(P, T) -> P,
    {
        let values = values.into_iter().collect::<Vec<_>>();
        let mut candidates = Vec::with_capacity(self.candidates.len().saturating_mul(values.len()));
        for candidate in self.candidates {
            for value in &values {
                candidates.push(set(candidate.clone(), value.clone()));
            }
        }
        Self { candidates }
    }
}

/// Errors produced while searching a parameter grid.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum SearchError {
    /// The grid named no candidate to evaluate.
    EmptyGrid,
    /// The search was rejected before any candidate was fitted.
    ///
    /// These are the failures that do not belong to a candidate — a target
    /// length that does not match the data, no splits at all, or a split built
    /// for a different dataset. They are checked once, up front, so an
    /// unusable call costs no fitting and no candidate is blamed for it.
    Setup(CrossValidationError),
    /// One candidate's cross-validation failed.
    ///
    /// The wrapped error keeps its own zero-based fold index, so a failure is
    /// attributed to an exact candidate *and* an exact fold.
    Candidate {
        /// Zero-based index of the candidate in grid order.
        candidate: usize,
        /// Original cross-validation error.
        source: CrossValidationError,
    },
    /// A score produced a value that cannot be ordered.
    ///
    /// Cross-validation reports whatever a score returns, but search has to
    /// *rank* the results, and a non-finite score has no defensible position in
    /// that ranking. Reporting it is therefore explicit rather than letting a
    /// `NaN` comparison decide a winner silently.
    NonFiniteScore {
        /// Zero-based index of the candidate in grid order.
        candidate: usize,
        /// Zero-based fold index within that candidate.
        fold: usize,
        /// The offending score.
        score: f64,
    },
}

impl fmt::Display for SearchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyGrid => f.write_str("parameter search requires at least one candidate"),
            Self::Setup(source) => write!(f, "search setup failed: {source}"),
            Self::Candidate { candidate, source } => {
                write!(f, "candidate {candidate} failed: {source}")
            }
            Self::NonFiniteScore {
                candidate,
                fold,
                score,
            } => write!(
                f,
                "candidate {candidate} fold {fold} scored {score}, which cannot be ranked"
            ),
        }
    }
}

impl Error for SearchError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Setup(source) | Self::Candidate { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// One candidate's parameters together with its per-fold scores.
#[derive(Clone, Debug, PartialEq)]
pub struct CandidateScores<P> {
    params: P,
    folds: CrossValidationResult,
}

impl<P> CandidateScores<P> {
    /// The parameter value this candidate was evaluated with.
    pub fn params(&self) -> &P {
        &self.params
    }

    /// Every fold's score, in split order.
    ///
    /// Search reports the whole distribution rather than only its summary,
    /// because a candidate that wins on the mean while collapsing on one fold
    /// is a different thing from one that is uniformly good, and the mean alone
    /// cannot tell them apart.
    pub fn folds(&self) -> &CrossValidationResult {
        &self.folds
    }

    /// Fixed-order mean of this candidate's fold scores, which is what the
    /// winner is chosen on.
    pub fn mean_score(&self) -> f64 {
        self.folds.mean()
    }
}

/// Ordered per-candidate results from one deterministic grid search.
///
/// # Winner selection
///
/// The winner is the candidate with the best **mean fold score**: the largest
/// mean when the score declares
/// [`greater_is_better`](super::RegressionScore::greater_is_better), the
/// smallest otherwise. The comparison is strict, so a candidate replaces the
/// incumbent only by being strictly better; **ties therefore go to the earliest
/// candidate in grid order**, which is the order
/// [`ParameterGrid`] fixed at construction. A caller who lists the cheapest or
/// most conservative value first gets it whenever the data cannot tell the
/// candidates apart.
///
/// # Refitting
///
/// Search reports scores and parameters; it does not refit. The winning
/// parameters go back through the same fitting closure on whatever data the
/// caller chooses, which keeps the refit policy visible in the caller's code
/// instead of hidden in a flag.
#[derive(Clone, Debug, PartialEq)]
pub struct SearchResult<P> {
    candidates: Vec<CandidateScores<P>>,
    best: usize,
}

impl<P> SearchResult<P> {
    /// Every candidate's parameters and fold scores, in grid order.
    pub fn candidates(&self) -> &[CandidateScores<P>] {
        &self.candidates
    }

    /// Number of evaluated candidates.
    pub fn len(&self) -> usize {
        self.candidates.len()
    }

    /// Returns whether the result holds no candidate.
    ///
    /// A successful search never does; this keeps the collection-style
    /// interface explicit.
    pub fn is_empty(&self) -> bool {
        self.candidates.is_empty()
    }

    /// Grid-order index of the winning candidate.
    pub fn best_index(&self) -> usize {
        self.best
    }

    /// The winning candidate's parameters and fold scores.
    pub fn best(&self) -> &CandidateScores<P> {
        &self.candidates[self.best]
    }

    /// The winning candidate's parameters.
    pub fn best_params(&self) -> &P {
        self.best().params()
    }
}

/// Searches a typed parameter grid for a classifier, serially and in order.
///
/// Every candidate is cross-validated over **the same folds**: the split
/// iterator is drained once, up front, so fold membership is identical for
/// every candidate and the comparison between them is not confounded by a
/// re-drawn partition. With a fixed seed, fixed folds, and FerricML's serial
/// fitting, the whole result is reproducible.
///
/// Scoring is not reimplemented here. Each candidate runs through
/// [`cross_validate_classifier`], which runs through the same caller-owned
/// scoring entry point batch scoring and permutation importance use, so a
/// caller-defined score behaves in search exactly as it does anywhere else.
///
/// `view` is that entry point's view argument, forwarded unchanged:
/// [`ScorableClassifier::probabilistic`] for a model that produces
/// probabilities, [`ScorableClassifier::labels_only`] for one that does not.
/// There is no separate label-only search, because there is no separate
/// label-only cross-validation.
///
/// The target vocabulary is forwarded the same way, so tuning a natively
/// multiclass estimator over [`ClassTargets`](crate::data::ClassTargets) is
/// this function with a different `T` rather than a fourth entry point.
pub fn grid_search_classifier<M, T, P, I, F, S, V>(
    data: &MatrixView<'_>,
    targets: &T,
    splits: I,
    grid: &ParameterGrid<P>,
    scorer: S,
    mut fit: F,
    view: V,
) -> Result<SearchResult<P>, SearchError>
where
    T: ClassificationTargets,
    P: Clone,
    I: IntoIterator<Item = Split>,
    F: FnMut(&MatrixView<'_>, &T, &P) -> Result<M, ModelError>,
    S: ClassificationScore,
    V: for<'m> Fn(&'m M) -> ScorableClassifier<'m>,
{
    let splits = validated_setup(data.rows(), targets.as_slice().len(), grid, splits)?;
    let mut candidates = Vec::with_capacity(grid.len());
    for (candidate, params) in grid.candidates().iter().enumerate() {
        let folds = cross_validate_classifier(
            data,
            targets,
            splits.iter().cloned(),
            &scorer,
            |train, train_targets| fit(train, train_targets, params),
            &view,
        )
        .map_err(|source| SearchError::Candidate { candidate, source })?;
        candidates.push(finish_candidate(candidate, params.clone(), folds)?);
    }
    Ok(select_best(candidates, scorer.greater_is_better()))
}

/// Searches a typed parameter grid for a regressor, serially and in order.
///
/// The same contract as [`grid_search_classifier`]: one shared fold list, one
/// scoring implementation, per-candidate fold scores, and a winner chosen by
/// the mean with ties going to the earliest candidate.
///
/// ```
/// use ferricml::data::{DenseMatrix, RegressionTargets};
/// use ferricml::linear_model::{Ridge, RidgeParams};
/// use ferricml::model_selection::{
///     KFold, ParameterGrid, RegressionScorer, grid_search_regressor,
/// };
///
/// let data = DenseMatrix::new(vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0], 6, 1)?;
/// let targets = RegressionTargets::new(vec![0.0, 2.0, 4.0, 6.0, 8.0, 10.0])?;
/// let grid = ParameterGrid::new(RidgeParams::default())
///     .axis([0.01_f32, 1.0, 100.0], RidgeParams::with_alpha);
///
/// let result = grid_search_regressor(
///     &data.as_view(),
///     &targets,
///     KFold::new(3).split(data.rows())?,
///     &grid,
///     RegressionScorer::MeanSquaredError,
///     |train, train_targets, params| Ridge::fit(train, train_targets, params.clone()),
/// )?;
///
/// // Every candidate reports every fold, not only the winner's summary.
/// assert_eq!(result.len(), 3);
/// assert!(result.candidates().iter().all(|candidate| candidate.folds().len() == 3));
/// // The weakest penalty fits this exactly linear target best.
/// assert_eq!(result.best_index(), 0);
/// assert_eq!(result.best_params().alpha(), 0.01);
///
/// // Search does not refit; the winning parameters go back through the same
/// // closure on whatever data the caller chooses.
/// let refitted = Ridge::fit(&data.as_view(), &targets, result.best_params().clone())?;
/// assert_eq!(refitted.get_params().alpha(), 0.01);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn grid_search_regressor<M, P, I, F, S>(
    data: &MatrixView<'_>,
    targets: &RegressionTargets,
    splits: I,
    grid: &ParameterGrid<P>,
    scorer: S,
    mut fit: F,
) -> Result<SearchResult<P>, SearchError>
where
    M: Regressor,
    P: Clone,
    I: IntoIterator<Item = Split>,
    F: FnMut(&MatrixView<'_>, &RegressionTargets, &P) -> Result<M, ModelError>,
    S: RegressionScore,
{
    let splits = validated_setup(data.rows(), targets.len(), grid, splits)?;
    let mut candidates = Vec::with_capacity(grid.len());
    for (candidate, params) in grid.candidates().iter().enumerate() {
        let folds = cross_validate_regressor(
            data,
            targets,
            splits.iter().cloned(),
            &scorer,
            |train, train_targets| fit(train, train_targets, params),
        )
        .map_err(|source| SearchError::Candidate { candidate, source })?;
        candidates.push(finish_candidate(candidate, params.clone(), folds)?);
    }
    Ok(select_best(candidates, scorer.greater_is_better()))
}

/// Drains the split iterator once and rejects everything that is wrong with
/// the call before any candidate is fitted.
fn validated_setup<P, I: IntoIterator<Item = Split>>(
    rows: usize,
    targets: usize,
    grid: &ParameterGrid<P>,
    splits: I,
) -> Result<Vec<Split>, SearchError> {
    if grid.is_empty() {
        return Err(SearchError::EmptyGrid);
    }
    validate_target_length(rows, targets).map_err(SearchError::Setup)?;
    let splits = splits.into_iter().collect::<Vec<_>>();
    if splits.is_empty() {
        return Err(SearchError::Setup(CrossValidationError::NoSplits));
    }
    for (fold, split) in splits.iter().enumerate() {
        validate_split_sample_count(fold, rows, split).map_err(SearchError::Setup)?;
    }
    Ok(splits)
}

/// Rejects a candidate whose scores cannot be ranked, then keeps them.
fn finish_candidate<P>(
    candidate: usize,
    params: P,
    folds: CrossValidationResult,
) -> Result<CandidateScores<P>, SearchError> {
    if let Some((fold, &score)) = folds
        .scores()
        .iter()
        .enumerate()
        .find(|(_, score)| !score.is_finite())
    {
        return Err(SearchError::NonFiniteScore {
            candidate,
            fold,
            score,
        });
    }
    Ok(CandidateScores { params, folds })
}

/// Picks the best mean score, keeping the earliest candidate on an exact tie.
fn select_best<P>(candidates: Vec<CandidateScores<P>>, greater_is_better: bool) -> SearchResult<P> {
    let mut best = 0;
    let mut best_score = candidates[0].mean_score();
    for (candidate, scores) in candidates.iter().enumerate().skip(1) {
        let score = scores.mean_score();
        let improved = if greater_is_better {
            score > best_score
        } else {
            score < best_score
        };
        if improved {
            best = candidate;
            best_score = score;
        }
    }
    SearchResult { candidates, best }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::{BinaryTargets, ClassTargets, DenseMatrix};
    use crate::linear_model::{LogisticRegression, LogisticRegressionParams, Ridge, RidgeParams};
    use crate::model_selection::{
        ClassificationScorer, ClassifierOutput, ClassifierOutputKind, KFold, RegressionScorer,
        ScoringError, StratifiedKFold, score_regressor,
    };
    use std::cell::Cell;

    #[test]
    fn a_grid_with_no_axis_is_the_base_value_alone() {
        let grid = ParameterGrid::new(RidgeParams::default());
        assert_eq!(grid.len(), 1);
        assert!(!grid.is_empty());
        assert_eq!(grid.candidates(), &[RidgeParams::default()]);
    }

    #[test]
    fn the_axis_added_last_varies_fastest() {
        let grid = ParameterGrid::new(RidgeParams::default())
            .axis([0.5_f32, 5.0], RidgeParams::with_alpha)
            .axis([true, false], RidgeParams::with_fit_intercept);
        let observed = grid
            .candidates()
            .iter()
            .map(|params| (params.alpha(), params.fit_intercept()))
            .collect::<Vec<_>>();
        assert_eq!(
            observed,
            vec![(0.5, true), (0.5, false), (5.0, true), (5.0, false)]
        );
    }

    #[test]
    fn axes_may_carry_different_value_types() {
        let grid = ParameterGrid::new(LogisticRegressionParams::default())
            .axis([10_usize, 20], LogisticRegressionParams::with_max_iter)
            .axis([1e-3_f32, 1e-4], LogisticRegressionParams::with_tol);
        assert_eq!(grid.len(), 4);
        let observed = grid
            .candidates()
            .iter()
            .map(|params| (params.max_iter(), params.tol()))
            .collect::<Vec<_>>();
        assert_eq!(
            observed,
            vec![(10, 1e-3), (10, 1e-4), (20, 1e-3), (20, 1e-4)]
        );
    }

    #[test]
    fn a_later_axis_overrides_an_earlier_setting_of_the_same_parameter() {
        // Setting one parameter twice is the caller's business; the grid simply
        // applies the axes in order, so the last one wins per candidate.
        let grid = ParameterGrid::new(RidgeParams::default())
            .axis([1.0_f32], RidgeParams::with_alpha)
            .axis([7.0_f32], RidgeParams::with_alpha);
        assert_eq!(grid.len(), 1);
        assert_eq!(grid.candidates()[0].alpha(), 7.0);
    }

    #[test]
    fn an_axis_with_no_values_empties_the_grid_instead_of_being_ignored() {
        let grid = ParameterGrid::new(RidgeParams::default())
            .axis([0.1_f32, 1.0], RidgeParams::with_alpha)
            .axis(Vec::<bool>::new(), RidgeParams::with_fit_intercept);
        assert!(grid.is_empty());
        assert_eq!(grid.len(), 0);
        // An emptied grid stays empty however many axes follow.
        let grid = grid.axis([1.0_f32], RidgeParams::with_alpha);
        assert!(grid.is_empty());
    }

    #[test]
    fn an_explicit_candidate_list_keeps_its_own_order() {
        let candidates = vec![
            RidgeParams::default().with_alpha(9.0),
            RidgeParams::default().with_alpha(0.25),
        ];
        let grid = ParameterGrid::from_candidates(candidates.clone());
        assert_eq!(grid.candidates(), candidates.as_slice());
        assert!(ParameterGrid::<RidgeParams>::from_candidates(Vec::new()).is_empty());
    }

    #[test]
    fn construction_is_reproducible() {
        let build = || {
            ParameterGrid::new(RidgeParams::default())
                .axis([0.1_f32, 1.0, 10.0], RidgeParams::with_alpha)
                .axis([true, false], RidgeParams::with_fit_intercept)
        };
        assert_eq!(build(), build());
        assert_eq!(build().len(), 6);
    }

    fn regression_fixture() -> (DenseMatrix, RegressionTargets) {
        let data = DenseMatrix::new(
            (0..12)
                .flat_map(|row| [row as f32, ((row * 3) % 7) as f32])
                .collect(),
            12,
            2,
        )
        .unwrap();
        let targets =
            RegressionTargets::new((0..12).map(|row| (row * 2) as f32 + 1.0).collect()).unwrap();
        (data, targets)
    }

    fn folds() -> Vec<Split> {
        KFold::new(3)
            .with_shuffle(true)
            .with_random_state(29)
            .split(12)
            .unwrap()
            .collect()
    }

    fn ridge_grid() -> ParameterGrid<RidgeParams> {
        ParameterGrid::new(RidgeParams::default())
            .axis([0.01_f32, 1.0, 1_000.0], RidgeParams::with_alpha)
    }

    fn ridge_search<S: RegressionScore>(scorer: S) -> SearchResult<RidgeParams> {
        let (data, targets) = regression_fixture();
        grid_search_regressor(
            &data.as_view(),
            &targets,
            folds(),
            &ridge_grid(),
            scorer,
            |train, train_targets, params| Ridge::fit(train, train_targets, params.clone()),
        )
        .unwrap()
    }

    /// A score whose orientation is a constructor argument, so the same
    /// numbers can be ranked either way.
    struct OrientedMeanSquaredError {
        greater_is_better: bool,
    }

    impl RegressionScore for OrientedMeanSquaredError {
        fn greater_is_better(&self) -> bool {
            self.greater_is_better
        }

        fn score(&self, expected: &[f32], predicted: &[f32]) -> Result<f64, ScoringError> {
            RegressionScorer::MeanSquaredError.score(expected, predicted)
        }
    }

    struct AlwaysNaN;

    impl RegressionScore for AlwaysNaN {
        fn greater_is_better(&self) -> bool {
            true
        }

        fn score(&self, _expected: &[f32], _predicted: &[f32]) -> Result<f64, ScoringError> {
            Ok(f64::NAN)
        }
    }

    /// A classification score FerricML does not enumerate, to prove search
    /// reaches the scorer through the trait and honours its declared output.
    struct PositiveRate;

    impl ClassificationScore for PositiveRate {
        fn output_kind(&self) -> ClassifierOutputKind {
            ClassifierOutputKind::PositiveProbabilities
        }

        fn greater_is_better(&self) -> bool {
            true
        }

        fn score(
            &self,
            expected: &[u8],
            output: ClassifierOutput<'_>,
        ) -> Result<f64, ScoringError> {
            let ClassifierOutput::PositiveProbabilities(probabilities) = output else {
                return Err(ScoringError::UnsupportedOutput {
                    required: self.output_kind(),
                    supplied: output.kind(),
                });
            };
            let matched = expected
                .iter()
                .zip(probabilities)
                .filter(|&(&label, &probability)| (probability >= 0.5) == (label == 1))
                .count();
            Ok(matched as f64 / expected.len() as f64)
        }
    }

    #[test]
    fn every_candidate_reports_every_fold_in_grid_order() {
        let result = ridge_search(RegressionScorer::MeanSquaredError);
        assert_eq!(result.len(), 3);
        assert!(!result.is_empty());
        assert_eq!(result.candidates().len(), 3);
        for (candidate, expected) in result.candidates().iter().zip([0.01_f32, 1.0, 1_000.0]) {
            assert_eq!(candidate.params().alpha(), expected);
            assert_eq!(candidate.folds().len(), 3);
            assert_eq!(candidate.mean_score(), candidate.folds().mean());
            assert!(
                candidate
                    .folds()
                    .scores()
                    .iter()
                    .all(|score| score.is_finite())
            );
        }
        assert_eq!(result.best().params(), result.best_params());
        assert_eq!(result.best_index(), 0, "the weakest penalty fits best here");
    }

    /// The exit criterion: search is a loop over the existing cross-validation
    /// entry point, not a second evaluation path.
    #[test]
    fn each_candidate_equals_a_manual_cross_validation_over_the_same_folds() {
        let (data, targets) = regression_fixture();
        let result = ridge_search(RegressionScorer::MeanSquaredError);
        for (candidate, scores) in result.candidates().iter().enumerate() {
            let manual = cross_validate_regressor(
                &data.as_view(),
                &targets,
                folds(),
                RegressionScorer::MeanSquaredError,
                |train, train_targets| Ridge::fit(train, train_targets, scores.params().clone()),
            )
            .unwrap();
            assert_eq!(scores.folds(), &manual, "candidate {candidate}");
        }
    }

    /// And the same scores come out of scoring one fold directly, so search,
    /// cross-validation, and batch scoring share one implementation.
    #[test]
    fn every_fold_score_equals_scoring_that_fold_directly() {
        let (data, targets) = regression_fixture();
        let result = ridge_search(RegressionScorer::MeanSquaredError);
        for (candidate, scores) in result.candidates().iter().enumerate() {
            for (fold, split) in folds().iter().enumerate() {
                let train = data.select_rows(split.train_indices()).unwrap();
                let train_targets = targets.select(split.train_indices()).unwrap();
                let model =
                    Ridge::fit(&train.as_view(), &train_targets, scores.params().clone()).unwrap();
                let test = data.select_rows(split.test_indices()).unwrap();
                let test_targets = targets.select(split.test_indices()).unwrap();
                assert_eq!(
                    Ok(scores.folds().scores()[fold]),
                    score_regressor(
                        &model,
                        &test.as_view(),
                        &test_targets,
                        RegressionScorer::MeanSquaredError
                    ),
                    "candidate {candidate} fold {fold}"
                );
            }
        }
    }

    #[test]
    fn every_candidate_sees_exactly_the_same_folds() {
        let (data, targets) = regression_fixture();
        let expected = folds();
        let observed = std::cell::RefCell::new(Vec::new());
        let result = grid_search_regressor(
            &data.as_view(),
            &targets,
            expected.clone(),
            &ridge_grid(),
            RegressionScorer::MeanSquaredError,
            |train, train_targets, params| {
                observed
                    .borrow_mut()
                    .push(train.iter_rows().map(|row| row[0]).collect::<Vec<_>>());
                Ridge::fit(train, train_targets, params.clone())
            },
        )
        .unwrap();
        assert_eq!(result.len(), 3);

        let observed = observed.into_inner();
        assert_eq!(observed.len(), 9);
        for candidate in 1..3 {
            assert_eq!(
                observed[..3],
                observed[candidate * 3..candidate * 3 + 3],
                "candidate {candidate} was fitted on different folds"
            );
        }
    }

    #[test]
    fn the_declared_orientation_decides_the_winner() {
        let minimized = ridge_search(OrientedMeanSquaredError {
            greater_is_better: false,
        });
        let maximized = ridge_search(OrientedMeanSquaredError {
            greater_is_better: true,
        });
        // Identical fold scores, opposite winners.
        for (left, right) in minimized.candidates().iter().zip(maximized.candidates()) {
            assert_eq!(left.folds(), right.folds());
        }
        assert_eq!(minimized.best_index(), 0);
        assert_eq!(maximized.best_index(), 2);
        // The built-in enum agrees with the explicitly minimizing score.
        assert_eq!(
            ridge_search(RegressionScorer::MeanSquaredError).best_index(),
            minimized.best_index()
        );
    }

    #[test]
    fn an_exact_tie_goes_to_the_earliest_candidate() {
        let (data, targets) = regression_fixture();
        // Candidates 0 and 2 are the same configuration, so their means tie
        // exactly. The odd one out is placed so that the tie is at the winning
        // end for each orientation: worse than the pair when minimizing, better
        // than it when maximizing the same squared error.
        for (greater_is_better, odd_alpha) in [(false, 5_000.0_f32), (true, 0.001)] {
            let grid = ParameterGrid::from_candidates(vec![
                RidgeParams::default().with_alpha(0.5),
                RidgeParams::default().with_alpha(odd_alpha),
                RidgeParams::default().with_alpha(0.5),
            ]);
            let result = grid_search_regressor(
                &data.as_view(),
                &targets,
                folds(),
                &grid,
                OrientedMeanSquaredError { greater_is_better },
                |train, train_targets, params| Ridge::fit(train, train_targets, params.clone()),
            )
            .unwrap();
            let tied = result.candidates()[0].mean_score();
            assert_eq!(tied, result.candidates()[2].mean_score());
            let odd = result.candidates()[1].mean_score();
            assert!(
                if greater_is_better {
                    odd < tied
                } else {
                    odd > tied
                },
                "the tied pair must be the winning value, got tied={tied}, odd={odd}"
            );
            assert_eq!(
                result.best_index(),
                0,
                "a tie must keep the earliest candidate (greater_is_better={greater_is_better})"
            );
        }
    }

    #[test]
    fn identical_inputs_reproduce_identical_results() {
        let first = ridge_search(RegressionScorer::R2);
        let second = ridge_search(RegressionScorer::R2);
        assert_eq!(first, second);
        assert_eq!(first.best_index(), second.best_index());
    }

    #[test]
    fn a_classifier_grid_is_searched_through_the_same_path() {
        let data = DenseMatrix::new(
            (0..16)
                .flat_map(|row| [row as f32, (row % 4) as f32])
                .collect(),
            16,
            2,
        )
        .unwrap();
        let targets = BinaryTargets::new((0..16).map(|row| u8::from(row >= 8)).collect()).unwrap();
        let splits = StratifiedKFold::new(2)
            .with_shuffle(true)
            .with_random_state(5)
            .split(targets.as_slice())
            .unwrap()
            .collect::<Vec<_>>();
        let grid = ParameterGrid::new(LogisticRegressionParams::default())
            .axis([0.1_f32, 1.0], LogisticRegressionParams::with_c)
            .axis([50_usize, 200], LogisticRegressionParams::with_max_iter);

        let by_accuracy = grid_search_classifier(
            &data.as_view(),
            &targets,
            splits.clone(),
            &grid,
            ClassificationScorer::Accuracy,
            |train, train_targets, params| {
                LogisticRegression::fit(train, train_targets, params.clone())
            },
            |model| ScorableClassifier::probabilistic(model),
        )
        .unwrap();
        assert_eq!(by_accuracy.len(), 4);
        assert!(by_accuracy.candidates().iter().all(|candidate| {
            candidate.folds().len() == 2
                && candidate
                    .folds()
                    .scores()
                    .iter()
                    .all(|score| (0.0..=1.0).contains(score))
        }));

        // A caller-defined probability score routes through the same output
        // handling, so search never re-derives the class layout.
        let by_custom = grid_search_classifier(
            &data.as_view(),
            &targets,
            splits,
            &grid,
            PositiveRate,
            |train, train_targets, params| {
                LogisticRegression::fit(train, train_targets, params.clone())
            },
            |model| ScorableClassifier::probabilistic(model),
        )
        .unwrap();
        assert_eq!(by_custom.len(), 4);
        for candidate in by_custom.candidates() {
            assert!(
                candidate
                    .folds()
                    .scores()
                    .iter()
                    .all(|score| (0.0..=1.0).contains(score))
            );
        }
    }

    /// Finding 5's headline consequence: tuning a natively multiclass
    /// estimator, through the same entry point a binary one uses.
    #[test]
    fn an_arbitrary_class_set_is_searched_through_the_same_entry_point() {
        let data = DenseMatrix::new(
            (0..12)
                .flat_map(|row| [row as f32, ((row * 5) % 7) as f32])
                .collect(),
            12,
            2,
        )
        .unwrap();
        // Deliberately non-contiguous, non-zero-based labels.
        let targets =
            ClassTargets::new((0..12).map(|row| [3_u8, 7, 10][row % 3]).collect()).unwrap();
        assert_eq!(targets.classes(), &[3, 7, 10]);
        let splits = StratifiedKFold::new(2)
            .split(targets.as_slice())
            .unwrap()
            .collect::<Vec<_>>();
        let grid = ParameterGrid::new(LogisticRegressionParams::default().with_max_iter(200))
            .axis([0.1_f32, 1.0], LogisticRegressionParams::with_c);

        let result = grid_search_classifier(
            &data.as_view(),
            &targets,
            splits.iter().cloned(),
            &grid,
            ClassificationScorer::MulticlassLogLoss,
            |train, train_targets, params| {
                LogisticRegression::fit_multiclass(train, train_targets, params.clone())
            },
            |model| ScorableClassifier::probabilistic(model),
        )
        .unwrap();
        assert_eq!(result.len(), 2);

        // Search is still a loop over the one cross-validation entry point,
        // with the wider vocabulary forwarded rather than reimplemented.
        for (candidate, scores) in result.candidates().iter().enumerate() {
            let manual = cross_validate_classifier(
                &data.as_view(),
                &targets,
                splits.iter().cloned(),
                ClassificationScorer::MulticlassLogLoss,
                |train, train_targets| {
                    LogisticRegression::fit_multiclass(
                        train,
                        train_targets,
                        scores.params().clone(),
                    )
                },
                |model| ScorableClassifier::probabilistic(model),
            )
            .unwrap();
            assert_eq!(scores.folds(), &manual, "candidate {candidate}");
        }

        // The wider vocabulary buys no leniency: a binary positive-probability
        // metric still fails the candidate that asked for it.
        assert_eq!(
            grid_search_classifier(
                &data.as_view(),
                &targets,
                splits,
                &grid,
                ClassificationScorer::RocAuc,
                |train, train_targets, params| {
                    LogisticRegression::fit_multiclass(train, train_targets, params.clone())
                },
                |model| ScorableClassifier::probabilistic(model),
            ),
            Err(SearchError::Candidate {
                candidate: 0,
                source: CrossValidationError::UnsupportedClasses { fold: 0 },
            })
        );
    }

    #[test]
    fn an_empty_grid_is_refused_before_any_fitting() {
        let (data, targets) = regression_fixture();
        let calls = Cell::new(0_usize);
        assert_eq!(
            grid_search_regressor::<Ridge, _, _, _, _>(
                &data.as_view(),
                &targets,
                folds(),
                &ParameterGrid::from_candidates(Vec::<RidgeParams>::new()),
                RegressionScorer::MeanSquaredError,
                |train, train_targets, params: &RidgeParams| {
                    calls.set(calls.get() + 1);
                    Ridge::fit(train, train_targets, params.clone())
                },
            ),
            Err(SearchError::EmptyGrid)
        );
        assert_eq!(calls.get(), 0);
    }

    #[test]
    fn setup_failures_are_reported_before_any_candidate_is_fitted() {
        let (data, targets) = regression_fixture();
        let calls = Cell::new(0_usize);
        let run = |targets: &RegressionTargets, splits: Vec<Split>| {
            grid_search_regressor::<Ridge, _, _, _, _>(
                &data.as_view(),
                targets,
                splits,
                &ridge_grid(),
                RegressionScorer::MeanSquaredError,
                |train, train_targets, params: &RidgeParams| {
                    calls.set(calls.get() + 1);
                    Ridge::fit(train, train_targets, params.clone())
                },
            )
        };

        assert_eq!(
            run(&RegressionTargets::new(vec![0.0]).unwrap(), folds()),
            Err(SearchError::Setup(CrossValidationError::TargetLength {
                rows: 12,
                targets: 1,
            }))
        );
        assert_eq!(
            run(&targets, Vec::new()),
            Err(SearchError::Setup(CrossValidationError::NoSplits))
        );
        assert_eq!(
            run(
                &targets,
                vec![Split::new(4, vec![0, 1], vec![2, 3]).unwrap()]
            ),
            Err(SearchError::Setup(CrossValidationError::SplitSampleCount {
                fold: 0,
                expected: 12,
                actual: 4,
            }))
        );
        assert_eq!(calls.get(), 0, "setup must cost no fitting");
    }

    #[test]
    fn a_failure_names_both_the_candidate_and_the_fold() {
        let (data, targets) = regression_fixture();
        let splits = KFold::new(2).split(12).unwrap().collect::<Vec<_>>();
        let calls = Cell::new(0_usize);
        // Two folds per candidate, so the fourth call is candidate 1, fold 1.
        assert_eq!(
            grid_search_regressor::<Ridge, _, _, _, _>(
                &data.as_view(),
                &targets,
                splits,
                &ridge_grid(),
                RegressionScorer::MeanSquaredError,
                |train, train_targets, params: &RidgeParams| {
                    let call = calls.get();
                    calls.set(call + 1);
                    if call == 3 {
                        Err(ModelError::LinearSolveFailed)
                    } else {
                        Ridge::fit(train, train_targets, params.clone())
                    }
                },
            ),
            Err(SearchError::Candidate {
                candidate: 1,
                source: CrossValidationError::Fit {
                    fold: 1,
                    source: ModelError::LinearSolveFailed,
                },
            })
        );
        assert_eq!(calls.get(), 4, "search must stop at the first failure");
    }

    #[test]
    fn a_score_that_cannot_be_ranked_is_a_typed_error() {
        let (data, targets) = regression_fixture();
        let error = grid_search_regressor(
            &data.as_view(),
            &targets,
            folds(),
            &ridge_grid(),
            AlwaysNaN,
            |train, train_targets, params: &RidgeParams| {
                Ridge::fit(train, train_targets, params.clone())
            },
        )
        .unwrap_err();
        // `NaN` is not equal to itself, so the variant is matched rather than
        // compared — which is exactly why it cannot be ranked either.
        let SearchError::NonFiniteScore {
            candidate,
            fold,
            score,
        } = error
        else {
            panic!("expected an unrankable score, got {error}");
        };
        assert_eq!((candidate, fold), (0, 0));
        assert!(score.is_nan());
    }

    #[test]
    fn errors_display_and_chain_to_their_source() {
        let candidate = SearchError::Candidate {
            candidate: 2,
            source: CrossValidationError::NoSplits,
        };
        assert_eq!(
            candidate.to_string(),
            "candidate 2 failed: cross-validation requires at least one split"
        );
        assert!(candidate.source().is_some());

        let setup = SearchError::Setup(CrossValidationError::NoSplits);
        assert!(setup.to_string().starts_with("search setup failed"));
        assert!(setup.source().is_some());

        assert_eq!(
            SearchError::EmptyGrid.to_string(),
            "parameter search requires at least one candidate"
        );
        assert!(SearchError::EmptyGrid.source().is_none());

        let unrankable = SearchError::NonFiniteScore {
            candidate: 1,
            fold: 0,
            score: f64::INFINITY,
        };
        assert_eq!(
            unrankable.to_string(),
            "candidate 1 fold 0 scored inf, which cannot be ranked"
        );
        assert!(unrankable.source().is_none());
    }
}