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
//! Declaration-layer kernel tree: leaves, sums, and products.

use crate::error::GprError;
use crate::kernel::{
    ConstantKernel, CustomKernel, LinearKernel, MaternArdKernel, MaternKernel, PeriodicKernel,
    RationalQuadraticArdKernel, RationalQuadraticKernel, RbfArdKernel, RbfKernel, WhiteKernel,
};
use crate::param::Interval;

use super::leaf_params::LeafParams;
use super::tree::{NoSupply, Supply};
use std::ops::{Add, Mul};

/// Maps a flat optimizer index to a leaf-local parameter.
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::ParameterBinding;
///
/// let binding = ParameterBinding {
///     index: 0,
///     leaf_id: 1,
///     local_index: 0,
/// };
/// assert_eq!(binding.leaf_id, 1);
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ParameterBinding {
    /// Holds the index in the concatenated kernel parameter vector.
    pub index: usize,
    /// Holds the leaf index in depth-first, left-to-right order.
    pub leaf_id: usize,
    /// Holds the parameter index inside that leaf.
    pub local_index: usize,
}

/// Represents the user-facing kernel expression.
///
/// Parameters stay `f64` until compile.
///
/// Built-in leaves are stored directly. Sum and product nest until
/// [`Self::compile`] flattens associative chains into [`super::CompiledKernel`].
/// `S` is [`NoSupply`] for every tree a caller builds: a coordinate tree.
/// `+` builds [`Self::Sum`] and `*` builds [`Self::Product`]. The example on
/// [`super::KernelTerm`] builds a [`Self::Custom`] leaf.
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{
///     ConstantKernel, KernelSpec, LinearKernel, MaternArdKernel, MaternKernel, MaternNu,
///     ParameterBinding, PeriodicKernel, RationalQuadraticArdKernel, RationalQuadraticKernel,
///     RbfArdKernel, RbfKernel, WhiteKernel,
/// };
///
/// # fn main() -> Result<(), gprx::GprError> {
/// let spec = KernelSpec::from(RbfKernel::new(1.0)?)
///     + KernelSpec::from(RbfKernel::new(2.0)?);
/// assert_eq!(spec.num_params(), 2);
///
/// // Every built-in leaf, as a variant: `KernelSpec::from(leaf)` builds the same.
/// let leaves: Vec<KernelSpec> = vec![
///     KernelSpec::Rbf(RbfKernel::new(1.0)?),
///     KernelSpec::RbfArd(RbfArdKernel::new(&[1.0, 2.0])?),
///     KernelSpec::Matern(MaternKernel::new(1.0, MaternNu::FiveHalves)?),
///     KernelSpec::MaternArd(MaternArdKernel::new(&[1.0, 2.0], MaternNu::ThreeHalves)?),
///     KernelSpec::Periodic(PeriodicKernel::new(1.0, 2.0)?),
///     KernelSpec::RationalQuadratic(RationalQuadraticKernel::new(1.0, 1.5)?),
///     KernelSpec::RationalQuadraticArd(RationalQuadraticArdKernel::new(&[1.0, 2.0], 1.5)?),
///     KernelSpec::Constant(ConstantKernel::new(2.0)?),
///     KernelSpec::Linear(LinearKernel::new(0.5)?),
///     KernelSpec::White(WhiteKernel::new(0.01)?),
/// ];
/// let counts: Vec<usize> = leaves.iter().map(KernelSpec::num_params).collect();
/// assert_eq!(counts, [1, 2, 1, 2, 2, 2, 3, 1, 1, 1]);
///
/// // `(c ยท rbf) + (white + linear)`, built from the variants.
/// let mut tree: KernelSpec = KernelSpec::Product(
///     Box::new(KernelSpec::from(ConstantKernel::new(2.0)?)),
///     Box::new(KernelSpec::from(RbfKernel::new(1.0)?)),
/// ) + KernelSpec::Sum(
///     Box::new(KernelSpec::from(WhiteKernel::new(0.01)?)),
///     Box::new(KernelSpec::from(LinearKernel::new(0.5)?)),
/// );
/// // Flattened `ฮธ` in depth-first, left-to-right leaf order, in log space.
/// let mut theta = vec![0.0; tree.num_params()];
/// tree.get_params(&mut theta)?;
/// assert!((theta[0] - 2.0_f64.ln()).abs() < 1e-12);
/// theta[1] = 0.5_f64.ln(); // the RBF lengthscale
/// tree.set_params(&theta)?;
/// assert_eq!(
///     tree.parameter_bindings()[1],
///     ParameterBinding { index: 1, leaf_id: 1, local_index: 0 }
/// );
/// // The same tree for an `f32` compute scalar.
/// let single = tree.compile_as::<f32>();
/// assert_eq!(single.num_params(), 4);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum KernelSpec<S: Supply = NoSupply> {
    /// Marks an isotropic RBF leaf.
    Rbf(RbfKernel),
    /// Marks an ARD RBF leaf (`ฮธ_d = log(โ„“_d)`).
    RbfArd(RbfArdKernel),
    /// Marks an isotropic Matรฉrn leaf (`ฮฝ = 1/2`, `3/2`, or `5/2`).
    Matern(MaternKernel),
    /// Marks an ARD Matรฉrn leaf (`ฮธ_d = log(โ„“_d)`).
    MaternArd(MaternArdKernel),
    /// Marks a periodic (exp-sine-squared) leaf.
    Periodic(PeriodicKernel),
    /// Marks an isotropic rational quadratic leaf.
    RationalQuadratic(RationalQuadraticKernel),
    /// Marks an ARD rational quadratic leaf (`ฮธ_d = log(โ„“_d)`, then `log(ฮฑ)`).
    RationalQuadraticArd(RationalQuadraticArdKernel),
    /// Marks a constant leaf `k = c`.
    Constant(ConstantKernel),
    /// Marks a linear leaf `k = ฯƒยฒ xแต€ x'`.
    Linear(LinearKernel),
    /// Marks a white (nugget) leaf.
    White(WhiteKernel),
    /// Marks a user-defined distance leaf ([`super::KernelTerm`]).
    Custom(CustomKernel),
    /// Marks `k = k_left + k_right`.
    Sum(Box<KernelSpec<S>>, Box<KernelSpec<S>>),
    /// Marks `k = k_left * k_right` (Hadamard product).
    Product(Box<KernelSpec<S>>, Box<KernelSpec<S>>),
    /// A leaf of a [`super::DistanceKernel`]. A coordinate tree
    /// ([`NoSupply`]) cannot hold one.
    #[doc(hidden)]
    Supplied(S),
}

impl From<RbfKernel> for KernelSpec {
    fn from(kernel: RbfKernel) -> Self {
        Self::Rbf(kernel)
    }
}

impl From<RbfArdKernel> for KernelSpec {
    fn from(kernel: RbfArdKernel) -> Self {
        Self::RbfArd(kernel)
    }
}

impl From<MaternKernel> for KernelSpec {
    fn from(kernel: MaternKernel) -> Self {
        Self::Matern(kernel)
    }
}

impl From<MaternArdKernel> for KernelSpec {
    fn from(kernel: MaternArdKernel) -> Self {
        Self::MaternArd(kernel)
    }
}

impl From<PeriodicKernel> for KernelSpec {
    fn from(kernel: PeriodicKernel) -> Self {
        Self::Periodic(kernel)
    }
}

impl From<RationalQuadraticKernel> for KernelSpec {
    fn from(kernel: RationalQuadraticKernel) -> Self {
        Self::RationalQuadratic(kernel)
    }
}

impl From<RationalQuadraticArdKernel> for KernelSpec {
    fn from(kernel: RationalQuadraticArdKernel) -> Self {
        Self::RationalQuadraticArd(kernel)
    }
}

impl From<ConstantKernel> for KernelSpec {
    fn from(kernel: ConstantKernel) -> Self {
        Self::Constant(kernel)
    }
}

impl From<LinearKernel> for KernelSpec {
    fn from(kernel: LinearKernel) -> Self {
        Self::Linear(kernel)
    }
}

impl From<WhiteKernel> for KernelSpec {
    fn from(kernel: WhiteKernel) -> Self {
        Self::White(kernel)
    }
}

impl From<CustomKernel> for KernelSpec {
    fn from(kernel: CustomKernel) -> Self {
        Self::Custom(kernel)
    }
}

impl<S: Supply> Add for KernelSpec<S> {
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        Self::Sum(Box::new(self), Box::new(rhs))
    }
}

impl<S: Supply> Mul for KernelSpec<S> {
    type Output = Self;

    fn mul(self, rhs: Self) -> Self {
        Self::Product(Box::new(self), Box::new(rhs))
    }
}

impl KernelSpec {
    /// Wraps a user [`super::KernelTerm`] as a distance leaf.
    ///
    /// This is `Self::Custom(CustomKernel::new(term))`. The leaf clones into
    /// [`super::CompiledKernel`] at [`Self::compile`]. Sum and product with
    /// other distance leaves work. Mixing with points-mode leaves (Linear,
    /// ARD) evaluates each leaf in its own mode.
    ///
    /// One generic `impl<T: KernelScalar> KernelTerm<T>` on a `Clone` type
    /// serves both precisions.
    ///
    /// See the example on [`super::KernelTerm`].
    pub fn custom<K>(term: K) -> Self
    where
        K: super::KernelTerm<f64>
            + super::KernelTerm<f32>
            + Clone
            + std::fmt::Debug
            + Send
            + Sync
            + 'static,
    {
        Self::Custom(CustomKernel::new(term))
    }

    /// This coordinate tree in a tree of kind `S`.
    pub(crate) fn widen<S: Supply>(self) -> KernelSpec<S> {
        match self {
            Self::Rbf(leaf) => KernelSpec::Rbf(leaf),
            Self::RbfArd(leaf) => KernelSpec::RbfArd(leaf),
            Self::Matern(leaf) => KernelSpec::Matern(leaf),
            Self::MaternArd(leaf) => KernelSpec::MaternArd(leaf),
            Self::Periodic(leaf) => KernelSpec::Periodic(leaf),
            Self::RationalQuadratic(leaf) => KernelSpec::RationalQuadratic(leaf),
            Self::RationalQuadraticArd(leaf) => KernelSpec::RationalQuadraticArd(leaf),
            Self::Constant(leaf) => KernelSpec::Constant(leaf),
            Self::Linear(leaf) => KernelSpec::Linear(leaf),
            Self::White(leaf) => KernelSpec::White(leaf),
            Self::Custom(leaf) => KernelSpec::Custom(leaf),
            Self::Sum(left, right) => {
                KernelSpec::Sum(Box::new(left.widen()), Box::new(right.widen()))
            }
            Self::Product(left, right) => {
                KernelSpec::Product(Box::new(left.widen()), Box::new(right.widen()))
            }
            Self::Supplied(never) => match never {},
        }
    }
}

impl<S: Supply> KernelSpec<S> {
    /// Returns the number of flattened kernel parameters.
    ///
    /// See the example on [`KernelSpec`].
    pub fn num_params(&self) -> usize {
        match self {
            Self::Rbf(leaf) => leaf.num_params(),
            Self::RbfArd(leaf) => leaf.num_params(),
            Self::Matern(leaf) => leaf.num_params(),
            Self::MaternArd(leaf) => leaf.num_params(),
            Self::Periodic(leaf) => leaf.num_params(),
            Self::RationalQuadratic(leaf) => leaf.num_params(),
            Self::RationalQuadraticArd(leaf) => leaf.num_params(),
            Self::Constant(leaf) => leaf.num_params(),
            Self::Linear(leaf) => leaf.num_params(),
            Self::White(leaf) => leaf.num_params(),
            Self::Custom(leaf) => leaf.num_params(),
            Self::Supplied(leaf) => S::spec(leaf).leaf.leaf_num_params(),
            Self::Sum(left, right) | Self::Product(left, right) => {
                left.num_params() + right.num_params()
            }
        }
    }

    /// Writes flattened `ฮธ` in depth-first, left-to-right leaf order.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::LengthMismatch`] if `out` is not
    /// [`Self::num_params`] long, or the error a [`Self::Custom`] leaf's
    /// [`super::KernelTerm::get_params`] returns.
    ///
    /// See the example on [`KernelSpec`].
    pub fn get_params(&self, out: &mut [f64]) -> Result<(), GprError> {
        crate::data::require_count(out.len(), self.num_params(), "kernel parameters")?;
        let mut offset = 0;
        self.write_params(out, &mut offset)
    }

    /// Replaces flattened `ฮธ`.
    ///
    /// All leaves are updated or none are.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::LengthMismatch`] if `params` is not
    /// [`Self::num_params`] long, or the error of the first leaf that rejects
    /// its slice: [`GprError::InvalidHyperparameter`] or
    /// [`GprError::InvalidInterval`] from a built-in leaf, or whatever a
    /// [`Self::Custom`] leaf's [`super::KernelTerm::set_params`] returns.
    ///
    /// See the example on [`KernelSpec`].
    pub fn set_params(&mut self, params: &[f64]) -> Result<(), GprError> {
        crate::data::require_count(params.len(), self.num_params(), "kernel parameters")?;
        let mut next = self.clone();
        let mut offset = 0;
        next.apply_params(params, &mut offset)?;
        *self = next;
        Ok(())
    }

    /// Writes flattened `ฮธ` in place without cloning the tree.
    ///
    /// `prev` is the current `ฮธ`. When a leaf rejects its slice, the leaves
    /// already written are put back from `prev`, so the tree is unchanged on
    /// error. Built-in leaves validate before they write; a custom leaf that
    /// rejects `prev` on the way back leaves its own value as it chose.
    pub(crate) fn set_params_in_place(
        &mut self,
        params: &[f64],
        prev: &[f64],
    ) -> Result<(), GprError> {
        crate::data::require_count(params.len(), self.num_params(), "kernel parameters")?;
        let mut offset = 0;
        if let Err(err) = self.apply_params(params, &mut offset) {
            let mut offset = 0;
            let _ = self.apply_params(prev, &mut offset);
            return Err(err);
        }
        Ok(())
    }

    /// Returns the mapping from flat indices to leaves.
    ///
    /// See the example on [`KernelSpec`].
    pub fn parameter_bindings(&self) -> Vec<ParameterBinding> {
        let mut out = Vec::new();
        let mut index = 0;
        let mut leaf_id = 0;
        self.collect_bindings(&mut out, &mut index, &mut leaf_id);
        out
    }

    /// Compiles this tree.
    ///
    /// Associative sums and products become a single list.
    ///
    /// Mixed operators keep their grouping: `(A + B) * C` is a product of a
    /// flattened sum and `C`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{CompiledKernel, KernelSpec, RbfKernel};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let spec = (KernelSpec::from(RbfKernel::new(1.0)?)
    ///     + KernelSpec::from(RbfKernel::new(2.0)?))
    ///     + KernelSpec::from(RbfKernel::new(3.0)?);
    /// assert!(matches!(spec.compile(), CompiledKernel::Sum(terms) if terms.len() == 3));
    /// # Ok(())
    /// # }
    /// ```
    pub fn compile(&self) -> crate::kernel::CompiledKernel<f64, S> {
        crate::kernel::CompiledKernel::<f64, S>::from_spec(self)
    }

    /// Compiles this tree for compute scalar `T`.
    ///
    /// [`Self::compile`] is `T = f64`. `f32` and `f64` run the same operations.
    /// Parameters stay `f64`. There is no conversion between the two compiled
    /// types: each call builds the tree for the scalar you name.
    ///
    /// See the example on [`KernelSpec`].
    pub fn compile_as<T>(&self) -> crate::kernel::CompiledKernel<T, S>
    where
        T: crate::kernel::KernelScalar,
    {
        crate::kernel::CompiledKernel::<T, S>::from_spec(self)
    }

    fn write_params(&self, out: &mut [f64], offset: &mut usize) -> Result<(), GprError> {
        match self {
            Self::Rbf(leaf) => leaf.write_leaf_params(out, offset),
            Self::RbfArd(leaf) => leaf.write_leaf_params(out, offset),
            Self::Matern(leaf) => leaf.write_leaf_params(out, offset),
            Self::MaternArd(leaf) => leaf.write_leaf_params(out, offset),
            Self::Periodic(leaf) => leaf.write_leaf_params(out, offset),
            Self::RationalQuadratic(leaf) => leaf.write_leaf_params(out, offset),
            Self::RationalQuadraticArd(leaf) => leaf.write_leaf_params(out, offset),
            Self::Constant(leaf) => leaf.write_leaf_params(out, offset),
            Self::Linear(leaf) => leaf.write_leaf_params(out, offset),
            Self::White(leaf) => leaf.write_leaf_params(out, offset),
            Self::Custom(leaf) => leaf.write_leaf_params(out, offset),
            Self::Supplied(leaf) => S::spec(leaf).leaf.write_leaf_params(out, offset),
            Self::Sum(left, right) | Self::Product(left, right) => {
                left.write_params(out, offset)?;
                right.write_params(out, offset)
            }
        }
    }

    pub(crate) fn write_intervals(
        &self,
        out: &mut [Interval],
        offset: &mut usize,
    ) -> Result<(), GprError> {
        match self {
            Self::Rbf(leaf) => leaf.write_leaf_intervals(out, offset),
            Self::RbfArd(leaf) => leaf.write_leaf_intervals(out, offset),
            Self::Matern(leaf) => leaf.write_leaf_intervals(out, offset),
            Self::MaternArd(leaf) => leaf.write_leaf_intervals(out, offset),
            Self::Periodic(leaf) => leaf.write_leaf_intervals(out, offset),
            Self::RationalQuadratic(leaf) => leaf.write_leaf_intervals(out, offset),
            Self::RationalQuadraticArd(leaf) => leaf.write_leaf_intervals(out, offset),
            Self::Constant(leaf) => leaf.write_leaf_intervals(out, offset),
            Self::Linear(leaf) => leaf.write_leaf_intervals(out, offset),
            Self::White(leaf) => leaf.write_leaf_intervals(out, offset),
            Self::Custom(leaf) => leaf.write_leaf_intervals(out, offset),
            Self::Supplied(leaf) => S::spec(leaf).leaf.write_leaf_intervals(out, offset),
            Self::Sum(left, right) | Self::Product(left, right) => {
                left.write_intervals(out, offset)?;
                right.write_intervals(out, offset)
            }
        }
    }

    fn apply_params(&mut self, params: &[f64], offset: &mut usize) -> Result<(), GprError> {
        match self {
            Self::Rbf(leaf) => leaf.apply_leaf_params(params, offset),
            Self::RbfArd(leaf) => leaf.apply_leaf_params(params, offset),
            Self::Matern(leaf) => leaf.apply_leaf_params(params, offset),
            Self::MaternArd(leaf) => leaf.apply_leaf_params(params, offset),
            Self::Periodic(leaf) => leaf.apply_leaf_params(params, offset),
            Self::RationalQuadratic(leaf) => leaf.apply_leaf_params(params, offset),
            Self::RationalQuadraticArd(leaf) => leaf.apply_leaf_params(params, offset),
            Self::Constant(leaf) => leaf.apply_leaf_params(params, offset),
            Self::Linear(leaf) => leaf.apply_leaf_params(params, offset),
            Self::White(leaf) => leaf.apply_leaf_params(params, offset),
            Self::Custom(leaf) => leaf.apply_leaf_params(params, offset),
            Self::Supplied(leaf) => S::spec_mut(leaf).leaf.apply_leaf_params(params, offset),
            Self::Sum(left, right) | Self::Product(left, right) => {
                left.apply_params(params, offset)?;
                right.apply_params(params, offset)
            }
        }
    }

    fn collect_bindings(
        &self,
        out: &mut Vec<ParameterBinding>,
        index: &mut usize,
        leaf_id: &mut usize,
    ) {
        match self {
            Self::Rbf(leaf) => {
                push_leaf_bindings(out, index, leaf_id, leaf.num_params());
            }
            Self::RbfArd(leaf) => {
                push_leaf_bindings(out, index, leaf_id, leaf.num_params());
            }
            Self::Matern(leaf) => {
                push_leaf_bindings(out, index, leaf_id, leaf.num_params());
            }
            Self::MaternArd(leaf) => {
                push_leaf_bindings(out, index, leaf_id, leaf.num_params());
            }
            Self::Periodic(leaf) => {
                push_leaf_bindings(out, index, leaf_id, leaf.num_params());
            }
            Self::RationalQuadratic(leaf) => {
                push_leaf_bindings(out, index, leaf_id, leaf.num_params());
            }
            Self::RationalQuadraticArd(leaf) => {
                push_leaf_bindings(out, index, leaf_id, leaf.num_params());
            }
            Self::Constant(leaf) => {
                push_leaf_bindings(out, index, leaf_id, leaf.num_params());
            }
            Self::Linear(leaf) => {
                push_leaf_bindings(out, index, leaf_id, leaf.num_params());
            }
            Self::White(leaf) => {
                push_leaf_bindings(out, index, leaf_id, leaf.num_params());
            }
            Self::Custom(leaf) => {
                push_leaf_bindings(out, index, leaf_id, leaf.num_params());
            }
            Self::Supplied(leaf) => {
                push_leaf_bindings(out, index, leaf_id, S::spec(leaf).leaf.leaf_num_params());
            }
            Self::Sum(left, right) | Self::Product(left, right) => {
                left.collect_bindings(out, index, leaf_id);
                right.collect_bindings(out, index, leaf_id);
            }
        }
    }
}

fn push_leaf_bindings(
    out: &mut Vec<ParameterBinding>,
    index: &mut usize,
    leaf_id: &mut usize,
    n_params: usize,
) {
    let id = *leaf_id;
    *leaf_id += 1;
    for local_index in 0..n_params {
        out.push(ParameterBinding {
            index: *index,
            leaf_id: id,
            local_index,
        });
        *index += 1;
    }
}

#[cfg(test)]
mod tests {
    use super::KernelSpec;
    use crate::kernel::{
        ConstantKernel, MaternArdKernel, MaternKernel, MaternNu, PeriodicKernel,
        RationalQuadraticArdKernel, RationalQuadraticKernel, RbfArdKernel, RbfKernel, WhiteKernel,
    };

    const TOL: f64 = 1e-12;

    use crate::test_check::assert_close;

    fn rbf(ell: f64) -> KernelSpec {
        KernelSpec::from(RbfKernel::new(ell).expect("valid"))
    }

    #[test]
    fn sum_flattens_params_left_to_right() {
        let mut spec = (rbf(1.0) + rbf(2.0)) + rbf(3.0);
        assert_eq!(spec.num_params(), 3);
        let mut params = [0.0; 3];
        spec.get_params(&mut params).expect("len 3");
        assert_close(params[0], 1.0_f64.ln(), TOL);
        assert_close(params[1], 2.0_f64.ln(), TOL);
        assert_close(params[2], 3.0_f64.ln(), TOL);
        params[1] = 4.0_f64.ln();
        spec.set_params(&params).expect("len 3");
        spec.get_params(&mut params).expect("len 3");
        assert_close(params[1], 4.0_f64.ln(), TOL);
        match spec.compile() {
            crate::kernel::CompiledKernel::Sum(terms) => assert_eq!(terms.len(), 3),
            other => panic!("expected flattened sum, got {other:?}"),
        }
    }

    #[test]
    fn product_keeps_sum_nested() {
        let spec = rbf(1.0) * (rbf(2.0) + rbf(3.0));
        match spec.compile() {
            crate::kernel::CompiledKernel::Product(factors) => {
                assert_eq!(factors.len(), 2);
                assert!(matches!(factors[1], crate::kernel::CompiledKernel::Sum(_)));
            }
            other => panic!("expected product, got {other:?}"),
        }
    }

    #[test]
    fn product_flattens_three_factors() {
        let spec = (rbf(1.0) * rbf(2.0)) * rbf(3.0);
        match spec.compile() {
            crate::kernel::CompiledKernel::Product(factors) => assert_eq!(factors.len(), 3),
            other => panic!("expected flattened product, got {other:?}"),
        }
    }

    #[test]
    fn constant_times_rbf_then_rbf_flattens_like_sklearn() {
        let spec = KernelSpec::from(ConstantKernel::new(1.5).expect("valid")) * rbf(1.0) + rbf(2.0);
        assert_eq!(spec.num_params(), 3);
        let mut params = [0.0; 3];
        spec.get_params(&mut params).expect("len 3");
        assert_close(params[0], 1.5_f64.ln(), TOL);
        assert_close(params[1], 1.0_f64.ln(), TOL);
        assert_close(params[2], 2.0_f64.ln(), TOL);
        match spec.compile() {
            crate::kernel::CompiledKernel::Sum(terms) => {
                assert_eq!(terms.len(), 2);
                assert!(matches!(
                    terms[0],
                    crate::kernel::CompiledKernel::Product(_)
                ));
            }
            other => panic!("expected sum of product and rbf, got {other:?}"),
        }
    }

    #[test]
    fn set_params_is_atomic() {
        let mut spec = rbf(1.0) + rbf(2.0);
        let before = spec.clone();
        assert!(spec.set_params(&[0.0, f64::INFINITY]).is_err());
        assert_eq!(spec, before);
    }

    #[test]
    fn bindings_follow_leaves() {
        let spec = rbf(1.0) + rbf(2.0);
        let b = spec.parameter_bindings();
        assert_eq!(b.len(), 2);
        assert_eq!(b[0].leaf_id, 0);
        assert_eq!(b[1].leaf_id, 1);
        assert_eq!(b[0].local_index, 0);
        assert_eq!(b[1].index, 1);
    }

    #[test]
    fn ard_flattens_per_dimension_params() {
        let mut spec = KernelSpec::from(RbfArdKernel::new(&[1.0, 2.0]).expect("valid"));
        assert_eq!(spec.num_params(), 2);
        let mut params = [0.0; 2];
        spec.get_params(&mut params).expect("len 2");
        assert_close(params[0], 1.0_f64.ln(), TOL);
        assert_close(params[1], 2.0_f64.ln(), TOL);
        params[1] = 3.0_f64.ln();
        spec.set_params(&params).expect("len 2");
        spec.get_params(&mut params).expect("len 2");
        assert_close(params[1], 3.0_f64.ln(), TOL);
        let b = spec.parameter_bindings();
        assert_eq!(b.len(), 2);
        assert_eq!(b[0].leaf_id, 0);
        assert_eq!(b[1].leaf_id, 0);
        assert_eq!(b[1].local_index, 1);
        match spec.compile() {
            crate::kernel::CompiledKernel::RbfArd(leaf) => assert_eq!(leaf.num_params(), 2),
            other => panic!("expected ARD RBF, got {other:?}"),
        }
    }

    #[test]
    fn constant_and_white_flatten_with_rbf() {
        let spec = rbf(1.0)
            + KernelSpec::from(ConstantKernel::new(2.0).expect("valid"))
            + KernelSpec::from(WhiteKernel::new(0.1).expect("valid"));
        assert_eq!(spec.num_params(), 3);
        let mut params = [0.0; 3];
        spec.get_params(&mut params).expect("len 3");
        assert_close(params[1], 2.0_f64.ln(), TOL);
        assert_close(params[2], 0.1_f64.ln(), TOL);
        let compiled = spec.compile();
        assert_eq!(compiled.num_params(), 3);
        assert_eq!(
            compiled.coord_mode().expect("compat"),
            crate::kernel::compiled::CoordMode::Dist
        );
    }

    #[test]
    fn matern_and_matern_ard_flatten() {
        let iso = KernelSpec::from(MaternKernel::new(1.5, MaternNu::ThreeHalves).expect("valid"));
        assert_eq!(iso.num_params(), 1);
        let mut params = [0.0];
        iso.get_params(&mut params).expect("len 1");
        assert_close(params[0], 1.5_f64.ln(), TOL);
        let mut ard =
            KernelSpec::from(MaternArdKernel::new(&[1.0, 2.0], MaternNu::Half).expect("valid"));
        assert_eq!(ard.num_params(), 2);
        let mut ard_params = [0.0; 2];
        ard.get_params(&mut ard_params).expect("len 2");
        assert_close(ard_params[1], 2.0_f64.ln(), TOL);
        ard_params[1] = 3.0_f64.ln();
        ard.set_params(&ard_params).expect("len 2");
        match ard.compile() {
            crate::kernel::CompiledKernel::MaternArd(leaf) => {
                assert_eq!(leaf.num_params(), 2);
                assert_eq!(leaf.nu(), MaternNu::Half);
            }
            other => panic!("expected ARD Matern, got {other:?}"),
        }
    }

    #[test]
    fn periodic_flattens_lengthscale_then_period() {
        let mut spec = KernelSpec::from(PeriodicKernel::new(1.5, 4.0).expect("valid"));
        assert_eq!(spec.num_params(), 2);
        let mut params = [0.0; 2];
        spec.get_params(&mut params).expect("len 2");
        assert_close(params[0], 1.5_f64.ln(), TOL);
        assert_close(params[1], 4.0_f64.ln(), TOL);
        params[1] = 2.0_f64.ln();
        spec.set_params(&params).expect("len 2");
        let b = spec.parameter_bindings();
        assert_eq!(b.len(), 2);
        assert_eq!(b[0].leaf_id, 0);
        assert_eq!(b[1].local_index, 1);
        match spec.compile() {
            crate::kernel::CompiledKernel::Periodic(leaf) => {
                assert_close(leaf.period(), 2.0, TOL);
            }
            other => panic!("expected Periodic, got {other:?}"),
        }
        assert_eq!(
            spec.compile().coord_mode().expect("compat"),
            crate::kernel::compiled::CoordMode::Dist
        );
    }

    #[test]
    fn rational_quadratic_flattens_iso_and_ard() {
        let mut iso = KernelSpec::from(RationalQuadraticKernel::new(1.5, 0.8).expect("valid"));
        assert_eq!(iso.num_params(), 2);
        let mut params = [0.0; 2];
        iso.get_params(&mut params).expect("len 2");
        assert_close(params[0], 1.5_f64.ln(), TOL);
        assert_close(params[1], 0.8_f64.ln(), TOL);
        params[1] = 2.0_f64.ln();
        iso.set_params(&params).expect("len 2");
        match iso.compile() {
            crate::kernel::CompiledKernel::RationalQuadratic(leaf) => {
                assert_close(leaf.alpha(), 2.0, TOL);
            }
            other => panic!("expected RQ, got {other:?}"),
        }
        assert_eq!(
            iso.compile().coord_mode().expect("compat"),
            crate::kernel::compiled::CoordMode::Dist
        );
        let mut ard =
            KernelSpec::from(RationalQuadraticArdKernel::new(&[1.0, 2.0], 0.5).expect("valid"));
        assert_eq!(ard.num_params(), 3);
        let mut ard_params = [0.0; 3];
        ard.get_params(&mut ard_params).expect("len 3");
        assert_close(ard_params[2], 0.5_f64.ln(), TOL);
        ard_params[2] = 1.25_f64.ln();
        ard.set_params(&ard_params).expect("len 3");
        match ard.compile() {
            crate::kernel::CompiledKernel::RationalQuadraticArd(leaf) => {
                assert_eq!(leaf.num_params(), 3);
                assert_close(leaf.alpha(), 1.25, TOL);
            }
            other => panic!("expected ARD RQ, got {other:?}"),
        }
        assert_eq!(
            ard.compile().coord_mode().expect("compat"),
            crate::kernel::compiled::CoordMode::Points
        );
    }
}