gprx 0.2.0

Gaussian process regression in Rust: exact GPR, sparse GPR (VFE), and SVGP.
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
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
//! Kernels on squared distances the caller supplies.
//!
//! A slot ([`ScalarDistance`] or [`ArdDistance`]) names one supply of
//! squared distances `d²` between samples the caller owns. Leaves made from
//! a slot ([`ScalarDistance::kernel`], [`ArdDistance::kernel`]) read that
//! supply; every leaf of one slot reads the same supply. A
//! [`DistanceKernel`] is the expression those leaves form, with
//! [`ConstantKernel`] / [`WhiteKernel`] and, as [`DistanceKernel<WithPoints>`],
//! coordinate leaves of a [`KernelSpec`]. A [`DistanceSource`] binds a supply
//! to its slot for one call.

use std::borrow::Cow;
use std::fmt;
use std::marker::PhantomData;
use std::ops::{Add, Mul};
use std::sync::atomic::{AtomicU64, Ordering};

use crate::error::GprError;
use crate::kernel::leaf_params::LeafParams;
use crate::kernel::{
    ConstantKernel, CustomKernel, KernelSpec, KernelTerm, MaternArdKernel, MaternKernel,
    ParameterBinding, PeriodicKernel, RationalQuadraticArdKernel, RationalQuadraticKernel,
    RbfArdKernel, RbfKernel, WhiteKernel,
};
use crate::kernel::{NoSupply, Supply};
use crate::param::Interval;

static NEXT_SLOT: AtomicU64 = AtomicU64::new(1);

/// Identity of one distance slot. Unique within the process.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct SlotId(u64);

impl SlotId {
    pub(crate) fn fresh() -> Self {
        Self(NEXT_SLOT.fetch_add(1, Ordering::Relaxed))
    }
}

/// What one slot supplies: one `d²`, or one `d²` per dimension.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum SlotShape {
    Scalar,
    Ard(usize),
}

impl SlotShape {
    /// Number of `d²` blocks one fill writes.
    pub(crate) fn blocks(self) -> usize {
        match self {
            Self::Scalar => 1,
            Self::Ard(d) => d,
        }
    }
}

/// A leaf of a [`DistanceKernel`] that reads the supply of one slot.
///
/// Crate-private payload of the hidden [`KernelSpec`] variant, in a tree of
/// this [`Supply`] kind. A coordinate tree ([`NoSupply`]) cannot hold one.
/// The slot's shape is the leaf's: a scalar slot holds an isotropic or
/// custom leaf, an ARD slot an ARD leaf.
#[derive(Clone, Debug, PartialEq)]
pub struct SuppliedSpec {
    pub(crate) slot: SlotId,
    /// The slot's number among the slots of its shape in the tree that
    /// holds the leaf: depth first, in order of first appearance, the
    /// order of [`DistanceKernel::slots`] split by shape. Every supply of
    /// the tree keeps its slots in this order. Set when the tree is built
    /// ([`DistanceKernel::from_spec`]).
    pub(crate) at: usize,
    pub(crate) leaf: SuppliedLeafSpec,
}

impl SuppliedSpec {
    /// What the slot supplies, from the leaf.
    pub(crate) fn shape(&self) -> SlotShape {
        match &self.leaf {
            SuppliedLeafSpec::Scalar(_) => SlotShape::Scalar,
            SuppliedLeafSpec::Ard(leaf) => SlotShape::Ard(leaf.dims()),
        }
    }
}

/// The leaf of a [`SuppliedSpec`], typed by the shape of its slot.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum SuppliedLeafSpec {
    Scalar(ScalarLeafSpec),
    Ard(ArdLeafSpec),
}

/// Calls `$on` with the pairs of every leaf that reads supplied distances:
/// `scalar` leaves as `ScalarLeafSpec` variant = `KernelSpec` variant, then
/// `ard` leaves as `ArdLeafSpec` variant = `KernelSpec` variant. A new
/// distance leaf is added here once; the maps below follow.
macro_rules! with_distance_leaves {
    ($on:ident) => {
        $on! {
            scalar: Rbf = Rbf, Matern = Matern, Periodic = Periodic,
                RationalQuadratic = RationalQuadratic, Custom = Custom;
            ard: Rbf = RbfArd, Matern = MaternArd, RationalQuadratic = RationalQuadraticArd;
        }
    };
}

macro_rules! leaf_maps {
    (
        scalar: $($s:ident = $sk:ident),+;
        ard: $($a:ident = $ak:ident),+;
    ) => {
        impl SuppliedLeafSpec {
            /// The coordinate leaf of the same parameters: what a save
            /// writes for this leaf.
            pub(crate) fn into_coordinate(self) -> KernelSpec {
                match self {
                    $(Self::Scalar(ScalarLeafSpec::$s(k)) => KernelSpec::$sk(k),)+
                    $(Self::Ard(ArdLeafSpec::$a(k)) => KernelSpec::$ak(k),)+
                }
            }

            /// The leaf of a slot of `shape` with the parameters of the
            /// coordinate leaf `spec`; `None` when a slot of that shape
            /// holds no such leaf. An ARD leaf's lengthscale count is not
            /// checked against the slot's dimensions.
            pub(crate) fn from_coordinate(shape: SlotShape, spec: KernelSpec) -> Option<Self> {
                match (shape, spec) {
                    $((SlotShape::Scalar, KernelSpec::$sk(k)) => {
                        Some(Self::Scalar(ScalarLeafSpec::$s(k)))
                    })+
                    $((SlotShape::Ard(_), KernelSpec::$ak(k)) => {
                        Some(Self::Ard(ArdLeafSpec::$a(k)))
                    })+
                    _ => None,
                }
            }
        }
    };
}

with_distance_leaves!(leaf_maps);

/// A leaf on one `d²` per pair.
#[derive(Clone, Debug, PartialEq)]
pub enum ScalarLeafSpec {
    Rbf(RbfKernel),
    Matern(MaternKernel),
    Periodic(PeriodicKernel),
    RationalQuadratic(RationalQuadraticKernel),
    Custom(CustomKernel),
}

/// A leaf on one `d²` per dimension per pair.
#[derive(Clone, Debug, PartialEq)]
pub enum ArdLeafSpec {
    Rbf(RbfArdKernel),
    Matern(MaternArdKernel),
    RationalQuadratic(RationalQuadraticArdKernel),
}

impl ArdLeafSpec {
    /// Number of lengthscales, one per dimension of the slot.
    pub(crate) fn dims(&self) -> usize {
        match self {
            Self::Rbf(leaf) => leaf.lengthscales().num_params(),
            Self::Matern(leaf) => leaf.lengthscales().num_params(),
            Self::RationalQuadratic(leaf) => leaf.lengthscales().num_params(),
        }
    }
}

/// Every variant of a typed leaf enum, with the leaf bound to `$leaf`.
macro_rules! each_leaf {
    ($value:expr, $leaf:ident => $body:expr) => {
        match $value {
            SuppliedLeafSpec::Scalar(ScalarLeafSpec::Rbf($leaf)) => $body,
            SuppliedLeafSpec::Scalar(ScalarLeafSpec::Matern($leaf)) => $body,
            SuppliedLeafSpec::Scalar(ScalarLeafSpec::Periodic($leaf)) => $body,
            SuppliedLeafSpec::Scalar(ScalarLeafSpec::RationalQuadratic($leaf)) => $body,
            SuppliedLeafSpec::Scalar(ScalarLeafSpec::Custom($leaf)) => $body,
            SuppliedLeafSpec::Ard(ArdLeafSpec::Rbf($leaf)) => $body,
            SuppliedLeafSpec::Ard(ArdLeafSpec::Matern($leaf)) => $body,
            SuppliedLeafSpec::Ard(ArdLeafSpec::RationalQuadratic($leaf)) => $body,
        }
    };
}

impl LeafParams for SuppliedLeafSpec {
    fn leaf_num_params(&self) -> usize {
        each_leaf!(self, leaf => leaf.leaf_num_params())
    }

    fn write_leaf_params(&self, out: &mut [f64], offset: &mut usize) -> Result<(), GprError> {
        each_leaf!(self, leaf => leaf.write_leaf_params(out, offset))
    }

    fn write_leaf_intervals(
        &self,
        out: &mut [Interval],
        offset: &mut usize,
    ) -> Result<(), GprError> {
        each_leaf!(self, leaf => leaf.write_leaf_intervals(out, offset))
    }

    fn apply_leaf_params(&mut self, params: &[f64], offset: &mut usize) -> Result<(), GprError> {
        each_leaf!(self, leaf => leaf.apply_leaf_params(params, offset))
    }
}

/// Names a supply of one squared distance per pair of samples.
///
/// [`Self::kernel`] makes a leaf that reads this supply. Every leaf made
/// from the same slot reads one supply, filled once. The supply itself is
/// bound to the slot for one call: [`Self::from_vec`] (moves),
/// [`Self::from_slice`] (copies), [`Self::borrow`] (reads in place for the
/// call), or [`Self::fill`] (a function writes it). A squared distance is
/// `d²`, column-major: the pair `(i, j)` is at `i + j * n_rows`.
///
/// Every `d²` must be finite and non-negative, and a square of the pairs of
/// one set (the training square, or the query square of a covariance) must
/// have a zero diagonal and be symmetric, exactly; otherwise the model
/// returns [`GprError::InvalidDistance`] at the first value that is not.
/// [`DistanceSource::tidy`] repairs what rounding leaves, within a
/// tolerance the caller names.
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{
///     DistanceKernel, DistanceSource, MaternKernel, MaternNu, RbfKernel, ScalarDistance,
///     ScalarDistanceLeaf,
/// };
/// use gprx::{GaussianLikelihood, Gpr};
///
/// /// Adds a second leaf on the slot of `image`.
/// fn plus(kernel: DistanceKernel, image: ScalarDistance, leaf: impl ScalarDistanceLeaf) -> DistanceKernel {
///     kernel + image.kernel(leaf)
/// }
///
/// # fn main() -> Result<(), gprx::GprError> {
/// let image = ScalarDistance::new();
/// let kernel = image.kernel(RbfKernel::new(1.0)?);
/// let kernel = plus(kernel, image, MaternKernel::new(1.0, MaternNu::FiveHalves)?);
/// // Squared distances between three training samples.
/// let train = vec![0.0, 1.0, 4.0, 1.0, 0.0, 1.0, 4.0, 1.0, 0.0];
/// let fitted = Gpr::new(kernel, GaussianLikelihood::new(0.1)?)
///     .fit([image.from_vec(train)], 3, &[0.0, 1.0, 0.5])
///     .map_err(|(_, e)| e)?;
/// // Squared distances from the three training samples to one query.
/// let cross = [0.25, 0.25, 2.25];
/// let source: DistanceSource<'_> = image.borrow(&cross);
/// let pred = fitted.predict([source], 1)?;
/// assert_eq!(pred.mean.len(), 1);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct ScalarDistance {
    slot: SlotId,
}

impl ScalarDistance {
    /// Returns a new slot, distinct from every other slot.
    ///
    /// See the example on [`ScalarDistance`].
    #[allow(
        clippy::new_without_default,
        reason = "every call makes a new slot, which a `Default` would hide"
    )]
    pub fn new() -> Self {
        Self {
            slot: SlotId::fresh(),
        }
    }

    pub(crate) fn with_slot(slot: SlotId) -> Self {
        Self { slot }
    }

    /// Returns a leaf that evaluates `leaf` on this slot's `d²`.
    ///
    /// The leaf is an isotropic RBF, Matérn, periodic, or rational
    /// quadratic, a [`CustomKernel`], or a `Clone` user type that implements
    /// [`KernelTerm`] at both `f64` and `f32`.
    ///
    /// See the example on [`ScalarDistance`].
    pub fn kernel(&self, leaf: impl ScalarDistanceLeaf) -> DistanceKernel {
        DistanceKernel::leaf(SuppliedSpec {
            slot: self.slot,
            at: 0,
            leaf: SuppliedLeafSpec::Scalar(leaf.into_leaf()),
        })
    }

    /// Binds an owned table of `d²` to this slot. An `f64` model keeps the
    /// buffer as its store, without a copy; an `f32` model casts it into a
    /// buffer of its own, and a `MixedPrecision` model keeps it and adds
    /// that cast.
    ///
    /// See the example on [`ScalarDistance`].
    pub fn from_vec(&self, d2: Vec<f64>) -> DistanceSource<'static> {
        self.source(ScalarData::Values(Cow::Owned(d2)))
    }

    /// Binds a copy of `d2` to this slot.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::ScalarDistance;
    ///
    /// let image = ScalarDistance::new();
    /// let train = [0.0, 1.0, 1.0, 0.0];
    /// let _source = image.from_slice(&train);
    /// ```
    pub fn from_slice(&self, d2: &[f64]) -> DistanceSource<'static> {
        self.source(ScalarData::Values(Cow::Owned(d2.to_vec())))
    }

    /// Binds `d2` to this slot for one call. Prediction reads it in place;
    /// a fit copies it into the model.
    ///
    /// See the example on [`ScalarDistance`].
    pub fn borrow<'a>(&self, d2: &'a [f64]) -> DistanceSource<'a> {
        self.source(ScalarData::Values(Cow::Borrowed(d2)))
    }

    /// Binds a function that writes this slot's `d²`.
    ///
    /// A fit fills the table once, into the buffer the model keeps, whatever
    /// the [`crate::DistanceCachePolicy`]; a prediction fills it once into
    /// scratch. [`DistanceFill`] says which columns and rows it asks for.
    ///
    /// See the example on [`DistanceFill`].
    pub fn fill<'a>(&self, filler: &'a dyn DistanceFill) -> DistanceSource<'a> {
        self.source(ScalarData::Fill(filler))
    }

    fn source<'a>(&self, data: ScalarData<'a>) -> DistanceSource<'a> {
        DistanceSource {
            slot: self.slot,
            data: SourceData::Scalar(data),
            tidy: Tidy::Exact,
        }
    }
}

/// Names a supply of `d` squared distances per pair of samples, one per
/// dimension, for the ARD leaves.
///
/// [`Self::from_leaf`] makes the slot from its first leaf, whose
/// lengthscale `ℓ_k` scales dimension `k`: `r² = Σ_k d_k² / ℓ_k²`; the slot
/// has one dimension per lengthscale. [`Self::kernel`] puts further leaves
/// on the same slot. Bind the supply with [`Self::from_vecs`]
/// (moves), [`Self::from_slices`] (copies), [`Self::borrow`] (reads in place
/// for the call), or [`Self::fill`]. Each dimension is a column-major block
/// of `d²`, laid out and checked as for [`ScalarDistance`].
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{
///     ArdDistance, ArdDistanceLeaf, DistanceFill, MaternArdKernel, MaternNu, RbfArdKernel,
/// };
/// use gprx::{GaussianLikelihood, Gpr};
/// use std::ops::Range;
///
/// /// The number of `d²` tables a slot made from `leaf` takes.
/// fn tables(leaf: impl ArdDistanceLeaf) -> usize {
///     ArdDistance::from_leaf(leaf).0.dims()
/// }
///
/// /// Per-feature squared differences between two sets of two-feature
/// /// samples: one run of rows per feature.
/// struct Bands<'a> {
///     rows: &'a [[f64; 2]],
///     cols: &'a [[f64; 2]],
/// }
///
/// impl DistanceFill for Bands<'_> {
///     fn fill_column(&self, col: usize, rows: Range<usize>, out: &mut [f64]) {
///         let len = rows.len();
///         for k in 0..2 {
///             let run = &mut out[k * len..(k + 1) * len];
///             for (slot, i) in run.iter_mut().zip(rows.clone()) {
///                 let diff = self.rows[i][k] - self.cols[col][k];
///                 *slot = diff * diff;
///             }
///         }
///     }
/// }
///
/// # fn main() -> Result<(), gprx::GprError> {
/// let (bands, kernel) = ArdDistance::from_leaf(RbfArdKernel::new(&[1.0, 2.0])?);
/// assert_eq!(bands.dims(), 2);
/// assert_eq!(tables(MaternArdKernel::new(&[1.0, 1.0, 1.0], MaternNu::Half)?), 3);
/// // A second leaf on the same slot reads the same supply.
/// let kernel = kernel + bands.kernel(MaternArdKernel::new(&[1.0, 1.0], MaternNu::FiveHalves)?)?;
/// assert_eq!(kernel.slots().len(), 1);
///
/// // Squared differences of the samples (0, 0) and (1, 2), one table per feature.
/// let b0 = vec![0.0, 1.0, 1.0, 0.0];
/// let b1 = vec![0.0, 4.0, 4.0, 0.0];
/// let fitted = Gpr::new(kernel, GaussianLikelihood::new(0.1)?)
///     .fit([bands.from_vecs(vec![b0, b1])], 2, &[0.0, 1.0])
///     .map_err(|(_, e)| e)?;
/// // The query (0.5, 1.0), from tables and from a fill.
/// let (c0, c1) = ([0.25, 0.25], [1.0, 1.0]);
/// let pred = fitted.predict([bands.borrow(&[&c0, &c1])], 1)?;
/// assert_eq!(pred.mean.len(), 1);
/// let (samples, queries) = ([[0.0, 0.0], [1.0, 2.0]], [[0.5, 1.0]]);
/// let filled = fitted.predict([bands.fill(&Bands { rows: &samples, cols: &queries })], 1)?;
/// assert!((filled.mean[0] - pred.mean[0]).abs() < 1e-12);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct ArdDistance {
    slot: SlotId,
    dims: usize,
}

impl ArdDistance {
    /// Returns a new slot of as many squared distances per pair as `leaf`
    /// has lengthscales, and the leaf that evaluates `leaf` on it. The
    /// slot's dimensions are the leaf's, so they cannot disagree.
    ///
    /// See the example on [`ArdDistance`].
    pub fn from_leaf(leaf: impl ArdDistanceLeaf) -> (Self, DistanceKernel) {
        let bands = Self {
            slot: SlotId::fresh(),
            dims: leaf.lengthscale_count(),
        };
        let kernel = bands.leaf(leaf);
        (bands, kernel)
    }

    /// A slot of `dims` squared distances per pair with no leaf, for the
    /// tests of the stores.
    #[cfg(test)]
    pub(crate) fn of_dims(dims: usize) -> Self {
        Self {
            slot: SlotId::fresh(),
            dims,
        }
    }

    pub(crate) fn with_slot(slot: SlotId, dims: usize) -> Self {
        Self { slot, dims }
    }

    /// Returns the number of squared distances per pair.
    ///
    /// See the example on [`ArdDistance`].
    pub fn dims(&self) -> usize {
        self.dims
    }

    /// Returns another leaf that evaluates the ARD `leaf` on this slot's
    /// `d²` (the first comes from [`Self::from_leaf`]): every leaf of the
    /// slot reads the same supply.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::DimensionMismatch`] if the leaf's lengthscale
    /// count is not [`Self::dims`]: `x_dim` is [`Self::dims`], `expected_dim`
    /// the lengthscale count.
    ///
    /// See the example on [`ArdDistance`].
    pub fn kernel(&self, leaf: impl ArdDistanceLeaf) -> Result<DistanceKernel, GprError> {
        let lengthscales = leaf.lengthscale_count();
        if lengthscales != self.dims {
            // The slot's `d²` per pair are the data's dimensions; the
            // leaf's lengthscales are the ones the kernel expects.
            return Err(GprError::DimensionMismatch {
                x_dim: self.dims,
                expected_dim: lengthscales,
            });
        }
        Ok(self.leaf(leaf))
    }

    /// The leaf of `leaf` on this slot, its lengthscale count already
    /// [`Self::dims`].
    fn leaf(&self, leaf: impl ArdDistanceLeaf) -> DistanceKernel {
        DistanceKernel::leaf(SuppliedSpec {
            slot: self.slot,
            at: 0,
            leaf: SuppliedLeafSpec::Ard(leaf.into_leaf()),
        })
    }

    /// Binds owned tables of `d²`, one per dimension, to this slot.
    ///
    /// An `f64` model checks the tables and keeps them as they are, so a
    /// fit copies nothing; it then holds `d · n²` values for the slot
    /// rather than the `d · n(n+1)/2` of the packed lower triangles it
    /// makes from [`Self::borrow`] (or when `tidy` repairs a table). An
    /// `f32` model packs them.
    ///
    /// See the example on [`ArdDistance`].
    pub fn from_vecs(&self, d2: Vec<Vec<f64>>) -> DistanceSource<'static> {
        self.source(ArdData::Blocks(d2))
    }

    /// Binds copies of `d2`, one table per dimension, to this slot: the
    /// copies are then handled as [`Self::from_vecs`], so an `f64` model
    /// keeps `d · n²` values. [`Self::borrow`] fits without the copy.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{ArdDistance, RbfArdKernel};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let (bands, _kernel) = ArdDistance::from_leaf(RbfArdKernel::new(&[1.0, 2.0])?);
    /// let (b0, b1) = ([0.0, 1.0, 1.0, 0.0], [0.0, 4.0, 4.0, 0.0]);
    /// let _source = bands.from_slices(&[&b0, &b1]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_slices(&self, d2: &[&[f64]]) -> DistanceSource<'static> {
        self.source(ArdData::Blocks(
            d2.iter().map(|block| block.to_vec()).collect(),
        ))
    }

    /// Binds `d2`, one table per dimension, for one call. Prediction reads
    /// the tables in place; a fit copies them into the model.
    ///
    /// See the example on [`ArdDistance`].
    pub fn borrow<'a>(&self, d2: &'a [&'a [f64]]) -> DistanceSource<'a> {
        self.source(ArdData::Slices(d2))
    }

    /// Binds a function that writes this slot's `d²`, every dimension in
    /// one call. See [`DistanceFill`].
    ///
    /// See the example on [`DistanceFill`].
    pub fn fill<'a>(&self, filler: &'a dyn DistanceFill) -> DistanceSource<'a> {
        self.source(ArdData::Fill(filler))
    }

    fn source<'a>(&self, data: ArdData<'a>) -> DistanceSource<'a> {
        DistanceSource {
            slot: self.slot,
            data: SourceData::Ard(self.dims, data),
            tidy: Tidy::Exact,
        }
    }
}

/// Names one slot of a [`DistanceKernel`], scalar or ARD.
///
/// [`DistanceKernel::slots`] lists them; each source of a fit or a
/// prediction binds one.
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{ArdDistance, DistanceSlot, RbfArdKernel, RbfKernel, ScalarDistance};
///
/// # fn main() -> Result<(), gprx::GprError> {
/// let image = ScalarDistance::new();
/// let (bands, ard) = ArdDistance::from_leaf(RbfArdKernel::new(&[1.0, 2.0])?);
/// let kernel = image.kernel(RbfKernel::new(1.0)?) * ard;
/// assert_eq!(
///     kernel.slots(),
///     vec![DistanceSlot::Scalar(image), DistanceSlot::Ard(bands)]
/// );
/// // A slot is a key: here, the number of tables to bind to each slot.
/// let tables: std::collections::HashMap<DistanceSlot, usize> = kernel
///     .slots()
///     .into_iter()
///     .map(|slot| match slot {
///         DistanceSlot::Scalar(_) => (slot, 1),
///         DistanceSlot::Ard(ard) => (slot, ard.dims()),
///         _ => (slot, 0),
///     })
///     .collect();
/// assert_eq!(tables[&DistanceSlot::Ard(bands)], 2);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum DistanceSlot {
    /// Marks a slot of one `d²` per pair.
    Scalar(ScalarDistance),
    /// Marks a slot of one `d²` per dimension per pair.
    Ard(ArdDistance),
}

impl DistanceSlot {
    pub(crate) fn id(self) -> SlotId {
        match self {
            Self::Scalar(slot) => slot.slot,
            Self::Ard(slot) => slot.slot,
        }
    }

    pub(crate) fn shape(self) -> SlotShape {
        match self {
            Self::Scalar(_) => SlotShape::Scalar,
            Self::Ard(slot) => SlotShape::Ard(slot.dims),
        }
    }

    pub(crate) fn from_parts(slot: SlotId, shape: SlotShape) -> Self {
        match shape {
            SlotShape::Scalar => Self::Scalar(ScalarDistance::with_slot(slot)),
            SlotShape::Ard(dims) => Self::Ard(ArdDistance::with_slot(slot, dims)),
        }
    }
}

mod sealed {
    use crate::kernel::KernelSpec;

    pub trait Leaf {
        fn into_leaf(self) -> super::ScalarLeafSpec;
    }

    pub trait ArdLeaf {
        fn into_leaf(self) -> super::ArdLeafSpec;
        fn lengthscale_count(&self) -> usize;
    }

    pub trait Points {
        /// Whether the kernel has coordinate leaves that read `x`.
        const POINTS: bool;
    }

    pub trait Model: Sized {
        /// Whether the kernel has coordinate leaves that read `x`.
        const POINTS: bool;
        /// What the tree holds besides coordinate leaves.
        type Supply: crate::kernel::Supply;
        fn into_spec(self) -> KernelSpec<Self::Supply>;
        fn from_spec(spec: KernelSpec<Self::Supply>) -> Self;
    }
}

/// Represents a leaf [`ScalarDistance::kernel`] accepts: [`RbfKernel`],
/// [`MaternKernel`], [`PeriodicKernel`], [`RationalQuadraticKernel`],
/// [`CustomKernel`], or a `Clone` user type that implements [`KernelTerm`]
/// at both `f64` and `f32` (the bound of [`CustomKernel::new`]).
///
/// Sealed: the crate implements it.
///
/// See the example on [`ScalarDistance`].
pub trait ScalarDistanceLeaf: sealed::Leaf {}

/// Represents a leaf [`ArdDistance::kernel`] accepts: [`RbfArdKernel`],
/// [`MaternArdKernel`], or [`RationalQuadraticArdKernel`].
///
/// Sealed: the crate implements it.
///
/// See the example on [`ArdDistance`].
pub trait ArdDistanceLeaf: sealed::ArdLeaf {}

macro_rules! scalar_leaf {
    ($($leaf:ty => $variant:ident),*) => {$(
        impl sealed::Leaf for $leaf {
            fn into_leaf(self) -> ScalarLeafSpec {
                ScalarLeafSpec::$variant(self)
            }
        }
        impl ScalarDistanceLeaf for $leaf {}
    )*};
}

scalar_leaf!(
    RbfKernel => Rbf,
    MaternKernel => Matern,
    PeriodicKernel => Periodic,
    RationalQuadraticKernel => RationalQuadratic,
    CustomKernel => Custom
);

impl<K> sealed::Leaf for K
where
    K: KernelTerm<f64> + KernelTerm<f32> + Clone + fmt::Debug + Send + Sync + 'static,
{
    fn into_leaf(self) -> ScalarLeafSpec {
        ScalarLeafSpec::Custom(CustomKernel::new(self))
    }
}

impl<K> ScalarDistanceLeaf for K where
    K: KernelTerm<f64> + KernelTerm<f32> + Clone + fmt::Debug + Send + Sync + 'static
{
}

macro_rules! ard_leaf {
    ($($leaf:ty => $variant:ident),*) => {$(
        impl sealed::ArdLeaf for $leaf {
            fn into_leaf(self) -> ArdLeafSpec {
                ArdLeafSpec::$variant(self)
            }
            fn lengthscale_count(&self) -> usize {
                self.lengthscales().num_params()
            }
        }
        impl ArdDistanceLeaf for $leaf {}
    )*};
}

ard_leaf!(
    RbfArdKernel => Rbf,
    MaternArdKernel => Matern,
    RationalQuadraticArdKernel => RationalQuadratic
);

/// Marks a [`DistanceKernel`] whose leaves read only supplied distances
/// (and [`ConstantKernel`] / [`WhiteKernel`]). A model of it takes no
/// coordinates.
///
/// See the example on [`DistanceKernel`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DistanceOnly;

/// Marks a [`DistanceKernel`] that also holds coordinate leaves of a
/// [`KernelSpec`]. A model of it takes the column-major coordinates `x`
/// with the supplied distances.
///
/// See the example on [`DistanceKernel`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WithPoints;

/// Represents whether a [`DistanceKernel`] reads coordinates:
/// [`DistanceOnly`] or [`WithPoints`]. Sealed.
///
/// A model of `DistanceKernel<C>` with `C: PointUse` has the methods both
/// kinds share.
///
/// See the example on [`DistanceKernel`].
pub trait PointUse: sealed::Points + Send + Sync + 'static {}

impl sealed::Points for DistanceOnly {
    const POINTS: bool = false;
}
impl sealed::Points for WithPoints {
    const POINTS: bool = true;
}

impl PointUse for DistanceOnly {}
impl PointUse for WithPoints {}

/// Represents the [`PointUse`] of a sum or product of two kernels.
///
/// Sealed: [`DistanceOnly`] with [`DistanceOnly`] stays [`DistanceOnly`];
/// anything with [`WithPoints`] is [`WithPoints`].
///
/// See the example on [`DistanceKernel`].
pub trait JoinPoints<Rhs: PointUse>: PointUse {
    /// Names the [`PointUse`] of the sum or product.
    ///
    /// See the example on [`DistanceKernel`].
    type Output: PointUse;
}

impl JoinPoints<DistanceOnly> for DistanceOnly {
    type Output = DistanceOnly;
}
impl JoinPoints<WithPoints> for DistanceOnly {
    type Output = WithPoints;
}
impl JoinPoints<DistanceOnly> for WithPoints {
    type Output = WithPoints;
}
impl JoinPoints<WithPoints> for WithPoints {
    type Output = WithPoints;
}

/// Represents a kernel expression whose leaves read supplied squared
/// distances.
///
/// Leaves come from [`ScalarDistance::kernel`] and [`ArdDistance::kernel`].
/// `+` and `*` combine them with each other, with [`ConstantKernel`] and
/// [`WhiteKernel`] (still [`DistanceOnly`]), and with a coordinate
/// [`KernelSpec`] on the right (then [`WithPoints`]). A coordinate term
/// goes on the left through `DistanceKernel::from`. Parameters follow the
/// leaves in depth-first, left-to-right order, as in [`KernelSpec`].
///
/// The marker `C` ([`PointUse`]) says whether the kernel reads coordinates;
/// [`JoinPoints`] picks the marker of a sum or product. A model takes a
/// [`ModelKernel`] ([`KernelSpec`] or `DistanceKernel`); the models of a
/// [`PointKernel`] also take coordinates and report their feature count.
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{
///     ArdDistance, ConstantKernel, DistanceKernel, DistanceOnly, JoinPoints, KernelSpec,
///     ModelKernel, PointKernel, PointUse, RbfArdKernel, RbfKernel, ScalarDistance, WithPoints,
/// };
/// use gprx::{DoublePrecision, FittedGpr, Fixed, GaussianLikelihood, Gpr};
///
/// /// Sums two distance kernels: the sum reads coordinates when either term does.
/// fn sum<A, B>(a: DistanceKernel<A>, b: DistanceKernel<B>) -> DistanceKernel<A::Output>
/// where
///     A: JoinPoints<B>,
///     B: PointUse,
/// {
///     a + b
/// }
///
/// /// Every model kernel has a training count.
/// fn points<K: ModelKernel>(model: &FittedGpr<Fixed, DoublePrecision, K>) -> usize {
///     model.n()
/// }
///
/// /// Only a kernel that reads coordinates has a feature count.
/// fn features<K: PointKernel>(model: &FittedGpr<Fixed, DoublePrecision, K>) -> usize {
///     model.d()
/// }
///
/// # fn main() -> Result<(), gprx::GprError> {
/// let image = ScalarDistance::new();
/// let (_bands, ard) = ArdDistance::from_leaf(RbfArdKernel::new(&[1.0, 0.5])?);
/// let only: DistanceKernel<DistanceOnly> =
///     ConstantKernel::new(2.0)? * image.kernel(RbfKernel::new(1.0)?) * ard;
/// assert_eq!(only.num_params(), 4);
/// let mixed: DistanceKernel<WithPoints> = only * KernelSpec::from(RbfKernel::new(0.5)?);
/// assert_eq!(mixed.slots().len(), 2);
/// let left = DistanceKernel::from(KernelSpec::from(RbfKernel::new(0.5)?)) + mixed;
/// assert_eq!(left.num_params(), 6);
///
/// // `DistanceOnly` joined with `WithPoints` is `WithPoints`.
/// let coordinates = DistanceKernel::from(KernelSpec::from(RbfKernel::new(0.5)?));
/// let joined: DistanceKernel<WithPoints> = sum(image.kernel(RbfKernel::new(1.0)?), coordinates);
///
/// // A `WithPoints` model takes the coordinates `x` with the distances.
/// let train = [0.0, 1.0, 1.0, 0.0];
/// let fitted = Gpr::new(joined, GaussianLikelihood::new(0.1)?)
///     .with_optimizer(Fixed)
///     .factor([image.from_slice(&train)], 2, &[0.0, 1.0], 1, &[0.0, 1.0])
///     .map_err(|(_, e)| e)?;
/// assert_eq!((points(&fitted), features(&fitted)), (2, 1));
/// # Ok(())
/// # }
/// ```
pub struct DistanceKernel<C: PointUse = DistanceOnly> {
    spec: KernelSpec<SuppliedSpec>,
    _points: PhantomData<C>,
}

impl<C: PointUse> Clone for DistanceKernel<C> {
    fn clone(&self) -> Self {
        // The leaves keep their numbers: the tree is the same.
        Self {
            spec: self.spec.clone(),
            _points: PhantomData,
        }
    }
}

impl<C: PointUse> PartialEq for DistanceKernel<C> {
    fn eq(&self, other: &Self) -> bool {
        self.spec == other.spec
    }
}

impl<C: PointUse> fmt::Debug for DistanceKernel<C> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DistanceKernel")
            .field("spec", &self.spec)
            .finish()
    }
}

impl DistanceKernel {
    fn leaf(spec: SuppliedSpec) -> Self {
        Self::from_spec(KernelSpec::Supplied(spec))
    }
}

impl<C: PointUse> DistanceKernel<C> {
    /// The kernel of `spec`, its leaves numbered in their tree
    /// ([`SuppliedSpec::at`]).
    pub(crate) fn from_spec(mut spec: KernelSpec<SuppliedSpec>) -> Self {
        number_leaves(&mut spec, &mut [Vec::new(), Vec::new()]);
        Self {
            spec,
            _points: PhantomData,
        }
    }

    /// Returns the number of flattened parameters.
    ///
    /// See the example on [`DistanceKernel`].
    pub fn num_params(&self) -> usize {
        self.spec.num_params()
    }

    /// Writes flattened `θ` in depth-first, left-to-right leaf order.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::LengthMismatch`] if `out` is the wrong length.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{RbfKernel, ScalarDistance};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let mut kernel = ScalarDistance::new().kernel(RbfKernel::new(1.0)?);
    /// let mut theta = [0.0];
    /// kernel.get_params(&mut theta)?;
    /// kernel.set_params(&[2.0_f64.ln()])?;
    /// assert_eq!(kernel.parameter_bindings().len(), 1);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_params(&self, out: &mut [f64]) -> Result<(), GprError> {
        self.spec.get_params(out)
    }

    /// Replaces flattened `θ`. All leaves are updated or none are.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::LengthMismatch`] if `params` is the wrong length,
    /// or the error of a leaf that rejects its slice.
    ///
    /// See the example on [`Self::get_params`].
    pub fn set_params(&mut self, params: &[f64]) -> Result<(), GprError> {
        self.spec.set_params(params)
    }

    /// Returns the mapping from flat indices to leaves.
    ///
    /// See the example on [`Self::get_params`].
    pub fn parameter_bindings(&self) -> Vec<ParameterBinding> {
        self.spec.parameter_bindings()
    }

    /// Returns the slots this expression reads, in depth-first,
    /// left-to-right order of their first leaf.
    ///
    /// Each source a fit or a prediction takes names one of these slots.
    ///
    /// See the example on [`DistanceSlot`].
    pub fn slots(&self) -> Vec<DistanceSlot> {
        spec_slots(&self.spec)
    }

    #[cfg(test)]
    pub(crate) fn spec(&self) -> &KernelSpec<SuppliedSpec> {
        &self.spec
    }
}

/// The slots of `spec` in depth-first order of first appearance; none for
/// a coordinate tree.
pub(crate) fn spec_slots<S: Supply>(spec: &KernelSpec<S>) -> Vec<DistanceSlot> {
    let mut out = Vec::new();
    collect_slots(spec, &mut out);
    out
}

fn collect_slots<S: Supply>(spec: &KernelSpec<S>, out: &mut Vec<DistanceSlot>) {
    match spec {
        KernelSpec::Supplied(leaf) => {
            let leaf = S::spec(leaf);
            // A slot id is minted by one constructor with its shape, and a
            // leaf takes its shape from the slot it was made on, so every
            // leaf of an id has the same shape.
            match out.iter().find(|slot| slot.id() == leaf.slot) {
                Some(seen) => debug_assert_eq!(seen.shape(), leaf.shape()),
                None => out.push(DistanceSlot::from_parts(leaf.slot, leaf.shape())),
            }
        }
        KernelSpec::Sum(left, right) | KernelSpec::Product(left, right) => {
            collect_slots(left, out);
            collect_slots(right, out);
        }
        _ => {}
    }
}

/// Sets each leaf's [`SuppliedSpec::at`] in one depth-first walk: `seen`
/// lists the slots met so far, scalar and ARD, in order, and a leaf's
/// number is its slot's place in the list of its shape, the slot added
/// when first met.
fn number_leaves(spec: &mut KernelSpec<SuppliedSpec>, seen: &mut [Vec<SlotId>; 2]) {
    match spec {
        KernelSpec::Supplied(leaf) => {
            let list = &mut seen[usize::from(matches!(leaf.shape(), SlotShape::Ard(_)))];
            leaf.at = match list.iter().position(|&slot| slot == leaf.slot) {
                Some(at) => at,
                None => {
                    list.push(leaf.slot);
                    list.len() - 1
                }
            };
        }
        KernelSpec::Sum(left, right) | KernelSpec::Product(left, right) => {
            number_leaves(left, seen);
            number_leaves(right, seen);
        }
        _ => {}
    }
}

/// A coordinate kernel as a [`DistanceKernel`] with no slot, to put a
/// coordinate term on the left of `+` or `*`: `KernelSpec + DistanceKernel`
/// is not implemented, so `KernelSpec + leaf.into()` infers the
/// coordinate `KernelSpec` sum.
impl From<KernelSpec> for DistanceKernel<WithPoints> {
    fn from(spec: KernelSpec) -> Self {
        Self::from_spec(spec.widen())
    }
}

macro_rules! distance_ops {
    ($trait:ident, $method:ident, $variant:ident) => {
        impl<C1, C2> $trait<DistanceKernel<C2>> for DistanceKernel<C1>
        where
            C1: JoinPoints<C2>,
            C2: PointUse,
        {
            type Output = DistanceKernel<<C1 as JoinPoints<C2>>::Output>;

            fn $method(self, rhs: DistanceKernel<C2>) -> Self::Output {
                DistanceKernel::from_spec(KernelSpec::$variant(
                    Box::new(self.spec),
                    Box::new(rhs.spec),
                ))
            }
        }

        impl<C: PointUse> $trait<KernelSpec> for DistanceKernel<C> {
            type Output = DistanceKernel<WithPoints>;

            fn $method(self, rhs: KernelSpec) -> Self::Output {
                DistanceKernel::from_spec(KernelSpec::$variant(
                    Box::new(self.spec),
                    Box::new(rhs.widen()),
                ))
            }
        }

        distance_ops!(@leaf $trait, $method, $variant, ConstantKernel);
        distance_ops!(@leaf $trait, $method, $variant, WhiteKernel);
    };
    (@leaf $trait:ident, $method:ident, $variant:ident, $leaf:ty) => {
        impl<C: PointUse> $trait<$leaf> for DistanceKernel<C> {
            type Output = DistanceKernel<C>;

            fn $method(self, rhs: $leaf) -> Self::Output {
                DistanceKernel::from_spec(KernelSpec::$variant(
                    Box::new(self.spec),
                    Box::new(KernelSpec::from(rhs).widen()),
                ))
            }
        }

        impl<C: PointUse> $trait<DistanceKernel<C>> for $leaf {
            type Output = DistanceKernel<C>;

            fn $method(self, rhs: DistanceKernel<C>) -> Self::Output {
                DistanceKernel::from_spec(KernelSpec::$variant(
                    Box::new(KernelSpec::from(self).widen()),
                    Box::new(rhs.spec),
                ))
            }
        }
    };
}

distance_ops!(Add, add, Sum);
distance_ops!(Mul, mul, Product);

/// Represents the kernel type a model is built from: a coordinate
/// [`KernelSpec`] or a [`DistanceKernel`]. Sealed.
///
/// See the example on [`DistanceKernel`].
pub trait ModelKernel: sealed::Model + Clone + fmt::Debug + Send + Sync + 'static {}

impl sealed::Model for KernelSpec {
    const POINTS: bool = true;
    type Supply = NoSupply;

    fn into_spec(self) -> KernelSpec {
        self
    }

    fn from_spec(spec: KernelSpec) -> Self {
        spec
    }
}

impl ModelKernel for KernelSpec {}

impl<C: PointUse> sealed::Model for DistanceKernel<C> {
    const POINTS: bool = <C as sealed::Points>::POINTS;
    type Supply = SuppliedSpec;

    fn into_spec(self) -> KernelSpec<SuppliedSpec> {
        self.spec
    }

    fn from_spec(spec: KernelSpec<SuppliedSpec>) -> Self {
        Self::from_spec(spec)
    }
}

impl<C: PointUse> ModelKernel for DistanceKernel<C> {}

/// Represents a model kernel that reads coordinates: [`KernelSpec`] or
/// [`DistanceKernel<WithPoints>`]. A model of one takes `x`, an input
/// transform, and reports its feature count. Sealed.
///
/// See the example on [`DistanceKernel`].
pub trait PointKernel: ModelKernel {}

impl PointKernel for KernelSpec {}
impl PointKernel for DistanceKernel<WithPoints> {}

pub(crate) use sealed::Model as ModelKernelParts;

/// The declared tree of model kernel `K`.
pub(crate) type SpecOf<K> = KernelSpec<<K as sealed::Model>::Supply>;

/// The compiled tree of model kernel `K` for compute scalar `T`.
pub(crate) type CompiledOf<T, K> = crate::kernel::CompiledKernel<T, <K as sealed::Model>::Supply>;

/// Writes squared distances one column of pairs at a time.
///
/// The crate asks for the columns it needs, into a buffer it reuses, so a
/// fill never makes the crate hold a dense table it would not keep. For a
/// square of the pairs of one set (the training square, or the query square
/// of a covariance) it asks, for each column `col`, only the rows `col..n`
/// (the lower triangle, diagonal included) and mirrors them: the square is
/// symmetric by construction. For a block of two sets (train × query) it
/// asks every row. A fit calls it once per column and keeps what it wrote,
/// whatever the [`crate::DistanceCachePolicy`]; a prediction calls it into
/// scratch. The caller knows which samples the rows and columns are: it
/// binds a filler to a slot for one call with [`ScalarDistance::fill`] or
/// [`ArdDistance::fill`]. The example on [`ArdDistance`] fills an ARD slot.
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{DistanceFill, RbfKernel, ScalarDistance};
/// use gprx::{GaussianLikelihood, Gpr};
/// use std::ops::Range;
///
/// /// Squared distances between two sets of one-dimensional samples.
/// struct Pairs<'a> {
///     rows: &'a [f64],
///     cols: &'a [f64],
/// }
///
/// impl DistanceFill for Pairs<'_> {
///     fn fill_column(&self, col: usize, rows: Range<usize>, out: &mut [f64]) {
///         for (slot, i) in out.iter_mut().zip(rows) {
///             let diff = self.rows[i] - self.cols[col];
///             *slot = diff * diff;
///         }
///     }
/// }
///
/// # fn main() -> Result<(), gprx::GprError> {
/// let samples = [0.0, 1.0, 2.0];
/// let queries = [0.5];
/// let image = ScalarDistance::new();
/// let fitted = Gpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
///     .fit([image.fill(&Pairs { rows: &samples, cols: &samples })], 3, &[0.0, 1.0, 0.5])
///     .map_err(|(_, e)| e)?;
/// let pred = fitted.predict([image.fill(&Pairs { rows: &samples, cols: &queries })], 1)?;
/// assert_eq!(pred.mean.len(), 1);
/// # Ok(())
/// # }
/// ```
pub trait DistanceFill: Send + Sync {
    /// Writes `d²(i, col)` for each row `i` of `rows` into `out`, in row
    /// order.
    ///
    /// A slot of [`ArdDistance::dims`] `d` writes `d` runs one after
    /// another: dimension `k` at `k * rows.len()`.
    ///
    /// See the examples on [`DistanceFill`] and [`ArdDistance`].
    fn fill_column(&self, col: usize, rows: std::ops::Range<usize>, out: &mut [f64]);
}

/// Binds a supply of squared distances to one slot for one call.
///
/// Made by [`ScalarDistance`] and [`ArdDistance`]. A model call takes one
/// source per slot of its kernel, in any order.
///
/// See the example on [`ScalarDistance`].
pub struct DistanceSource<'a> {
    pub(crate) slot: SlotId,
    pub(crate) data: SourceData<'a>,
    pub(crate) tidy: Tidy,
}

impl DistanceSource<'_> {
    /// Repairs what rounding leaves in this source's tables, within
    /// `rel_tol` times the largest value of each table: a negative value or
    /// a non-zero diagonal becomes `0.0`, and two mirror entries of a
    /// square that differ become their mean. Past it the table is refused.
    ///
    /// Without it, a table must be exact: finite, non-negative, and, for a
    /// square, a zero diagonal and equal mirror entries. Ask for the repair
    /// when the table is built in a way that rounds (`‖a‖² + ‖b‖² − 2a·b`);
    /// a table computed pair by pair needs none. A repaired table that was
    /// borrowed is copied.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::InvalidConfig`] when `rel_tol` is not in
    /// `[0, 1)` (negative, `NaN`, or so large that any table would pass).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{RbfKernel, ScalarDistance};
    /// use gprx::{GaussianLikelihood, Gpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let image = ScalarDistance::new();
    /// // The mirror entries differ in the last digit.
    /// let train = [0.0, 1.0, 1.0 + 1e-15, 0.0];
    /// let fitted = Gpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
    ///     .fit([image.borrow(&train).tidy(1e-12)?], 2, &[0.0, 1.0])
    ///     .map_err(|(_, e)| e)?;
    /// assert_eq!(fitted.n(), 2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn tidy(mut self, rel_tol: f64) -> Result<Self, GprError> {
        // Past `1` the tolerance reaches the largest value itself, so every
        // negative value, diagonal, and mirror gap would pass as rounding.
        if !(0.0..1.0).contains(&rel_tol) {
            return Err(GprError::InvalidConfig {
                reason: format!("tidy tolerance must be in [0, 1), got {rel_tol}"),
            });
        }
        self.tidy = Tidy::Within(rel_tol);
        Ok(self)
    }
}

/// How the crate checks the tables of one source.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Tidy {
    /// Exactly: finite, non-negative, a zero diagonal, equal mirror entries.
    Exact,
    /// Repaired within this tolerance, relative to the largest value.
    Within(f64),
}

impl fmt::Debug for DistanceSource<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let data = match &self.data {
            SourceData::Scalar(ScalarData::Values(v)) => format!("{} values", v.len()),
            SourceData::Ard(_, ArdData::Blocks(b)) => format!("{} blocks", b.len()),
            SourceData::Ard(_, ArdData::Slices(b)) => format!("{} borrowed blocks", b.len()),
            SourceData::Scalar(ScalarData::Fill(_)) | SourceData::Ard(_, ArdData::Fill(_)) => {
                "fill".to_owned()
            }
        };
        f.debug_struct("DistanceSource")
            .field("slot", &self.slot)
            .field("shape", &self.data.shape())
            .field("data", &data)
            .finish()
    }
}

/// The data of a [`DistanceSource`], typed by the shape of its slot: a
/// scalar slot's source holds one table, an ARD slot's one per dimension.
pub(crate) enum SourceData<'a> {
    /// A scalar slot's.
    Scalar(ScalarData<'a>),
    /// An ARD slot's with its number of dimensions.
    Ard(usize, ArdData<'a>),
}

/// The data of a scalar slot's source.
pub(crate) enum ScalarData<'a> {
    /// One table.
    Values(Cow<'a, [f64]>),
    /// A function that writes it.
    Fill(&'a dyn DistanceFill),
}

/// The data of an ARD slot's source.
pub(crate) enum ArdData<'a> {
    /// One owned table per dimension.
    Blocks(Vec<Vec<f64>>),
    /// One borrowed table per dimension.
    Slices(&'a [&'a [f64]]),
    /// A function that writes them.
    Fill(&'a dyn DistanceFill),
}

impl SourceData<'_> {
    /// The shape of the slot the data is for.
    pub(crate) fn shape(&self) -> SlotShape {
        match self {
            Self::Scalar(_) => SlotShape::Scalar,
            Self::Ard(dims, _) => SlotShape::Ard(*dims),
        }
    }
}

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

    #[test]
    fn slots_are_distinct_and_ordered() {
        let a = ScalarDistance::new();
        let (b, ard) = ArdDistance::from_leaf(RbfArdKernel::new(&[1.0, 2.0]).expect("ell"));
        assert_eq!(b.dims(), 2);
        assert_ne!(a, ScalarDistance::new());
        let k = a.kernel(RbfKernel::new(1.0).expect("ell")) * ard
            + a.kernel(MaternKernel::new(1.0, crate::kernel::MaternNu::FiveHalves).expect("ell"))
            + b.kernel(RbfArdKernel::new(&[3.0, 4.0]).expect("ell"))
                .expect("dims");
        // A slot read by two leaves is listed once, with its one shape.
        assert_eq!(
            k.slots(),
            vec![DistanceSlot::Scalar(a), DistanceSlot::Ard(b)]
        );
        assert_eq!(k.num_params(), 6);
    }

    #[test]
    fn a_further_ard_leaf_must_match_the_slot() {
        let (b, _) = ArdDistance::from_leaf(RbfArdKernel::new(&[1.0, 2.0, 3.0]).expect("ell"));
        assert!(matches!(
            b.kernel(RbfArdKernel::new(&[1.0, 2.0]).expect("ell")),
            Err(GprError::DimensionMismatch {
                x_dim: 3,
                expected_dim: 2
            })
        ));
    }

    struct Zeros;

    impl DistanceFill for Zeros {
        fn fill_column(&self, _col: usize, _rows: std::ops::Range<usize>, out: &mut [f64]) {
            out.fill(0.0);
        }
    }

    #[test]
    fn sources_and_kernels_describe_themselves() {
        let a = ScalarDistance::new();
        let b = ArdDistance::of_dims(2);
        let (b0, b1) = ([0.0, 1.0], [0.0, 4.0]);
        let shown = [
            format!("{:?}", a.from_slice(&[0.0])),
            format!("{:?}", b.from_slices(&[&b0, &b1])),
            format!("{:?}", b.fill(&Zeros)),
        ];
        assert!(shown[0].contains("1 values"));
        assert!(shown[1].contains("2 blocks"));
        assert!(shown[2].contains("fill"));
        let rbf = RbfKernel::new(1.0).expect("ell");
        let k = a.kernel(rbf);
        assert_eq!(k.clone(), k);
        assert!(format!("{k:?}").starts_with("DistanceKernel"));
        assert_eq!(k.parameter_bindings().len(), k.num_params());
        // A coordinate kernel on the left makes a `WithPoints` kernel too.
        let mixed = DistanceKernel::from(KernelSpec::from(rbf)) * k.clone();
        assert_eq!(mixed.slots(), k.slots());
        let summed = DistanceKernel::from(KernelSpec::from(rbf)) + k;
        assert_eq!(summed.num_params(), 2);
        // `KernelSpec + x.into()` still infers the coordinate sum: no
        // `KernelSpec + DistanceKernel` competes with it.
        let coordinate: KernelSpec = KernelSpec::from(rbf) + rbf.into();
        assert_eq!(coordinate.num_params(), 2);
    }
}