Skip to main content

gprx/kernel/
white.rs

1//! White kernel `k(x, x') = σw² δ_{xx'}`.
2
3use super::{
4    Triangle, require_same_shape, require_square_pair, validate_log_positive,
5    validate_positive_finite, write_square,
6};
7use crate::error::GprError;
8use crate::kernel::KernelScalar;
9use crate::param::{BoundedParam, Interval};
10use faer::{MatMut, MatRef};
11
12/// Evaluates the white (nugget) kernel `σw²` on the training diagonal and zero elsewhere.
13///
14/// The optimizer parameter is `θ = log(σw²)`. Cross-covariance is identically
15/// zero. Observation noise belongs in [`crate::GaussianLikelihood`]; do not
16/// also add a large white kernel, which double-counts noise. Cholesky jitter
17/// is a separate numerical stabilizer.
18///
19/// # Examples
20///
21/// ```rust
22/// use faer::Mat;
23/// use gprx::Interval;
24/// use gprx::kernel::{Triangle, WhiteKernel};
25///
26/// # fn main() -> Result<(), gprx::GprError> {
27/// // Parameter: `θ = log(σw²)`; the bounds are on `σw²`.
28/// let k = WhiteKernel::new(0.05)?;
29/// assert!((k.variance() - 0.05).abs() < 1e-12);
30/// let same = WhiteKernel::from_log_variance(k.log_variance())?;
31/// assert!((same.variance() - 0.05).abs() < 1e-12);
32/// let mut k = k.with_bounds(Interval::new(1e-4, 1.0)?)?;
33/// assert!((k.bounds().hi() - 1.0).abs() < 1e-12);
34/// let mut theta = vec![0.0; k.num_params()];
35/// k.get_params(&mut theta)?;
36/// k.set_params(&[0.1_f64.ln()])?; // σw² = 0.1
37///
38/// // `dist` (squared distances) and `x` (coordinates) only give the shape.
39/// let dist = Mat::<f64>::zeros(3, 3);
40/// let x = Mat::from_fn(3, 1, |i, _| i as f64);
41/// let mut gram = Mat::<f64>::zeros(3, 3);
42/// k.apply(dist.as_ref(), gram.as_mut(), Triangle::Full)?;
43/// assert!((gram[(1, 1)] - 0.1).abs() < 1e-12);
44/// assert!(gram[(1, 0)].abs() < 1e-12);
45/// k.apply_points(x.as_ref(), gram.as_mut(), Triangle::Lower)?;
46/// // Train × query is zero.
47/// let xs = Mat::from_fn(1, 1, |_, _| 0.5);
48/// let mut k_cross = Mat::<f64>::zeros(3, 1);
49/// k.apply_cross(Mat::<f64>::zeros(3, 1).as_ref(), k_cross.as_mut())?;
50/// k.apply_cross_points(x.as_ref(), xs.as_ref(), k_cross.as_mut())?;
51/// let mut diag = [0.0; 3];
52/// k.fill_diag(&mut diag);
53///
54/// // ∂K/∂θ and ∂²K/∂θ² are `σw²` on the diagonal, from either view; the
55/// // coordinate derivative is zero.
56/// let mut d_k = Mat::<f64>::zeros(3, 3);
57/// k.grad(dist.as_ref(), d_k.as_mut(), 0, Triangle::Lower)?;
58/// k.grad_points(x.as_ref(), d_k.as_mut(), 0, Triangle::Lower)?;
59/// let mut d2_k = Mat::<f64>::zeros(3, 3);
60/// k.hess(dist.as_ref(), d2_k.as_mut(), 0, 0, Triangle::Lower)?;
61/// k.hess_points(x.as_ref(), d2_k.as_mut(), 0, 0, Triangle::Lower)?;
62/// let mut d_x = Mat::<f64>::zeros(3, 1);
63/// k.grad_wrt_coord_dim(x.as_ref(), xs.as_ref(), d_x.as_mut(), 0)?;
64/// # Ok(())
65/// # }
66/// ```
67#[derive(Clone, Copy, Debug, PartialEq)]
68pub struct WhiteKernel {
69    variance: BoundedParam,
70}
71
72impl WhiteKernel {
73    /// Builds a white kernel from a positive finite variance `σw²`.
74    ///
75    /// # Errors
76    ///
77    /// Returns [`GprError::InvalidHyperparameter`] if `variance` is not finite
78    /// or not strictly positive, or [`GprError::InvalidInterval`] if it is
79    /// not inside [`Interval::DEFAULT_POSITIVE`], the bounds a new leaf
80    /// starts with.
81    ///
82    /// See the example on [`WhiteKernel`].
83    pub fn new(variance: f64) -> Result<Self, GprError> {
84        validate_positive_finite(variance, "white kernel variance")?;
85        Ok(Self {
86            variance: BoundedParam::default_positive(variance)?,
87        })
88    }
89
90    /// Builds a white kernel from `θ = log(σw²)`.
91    ///
92    /// # Errors
93    ///
94    /// Returns [`GprError::InvalidHyperparameter`] if `θ` is not finite, if
95    /// `exp(θ)` overflows, or if `exp(θ)` underflows to zero, or
96    /// [`GprError::InvalidInterval`] if `exp(θ)` is not inside
97    /// [`Interval::DEFAULT_POSITIVE`].
98    ///
99    /// See the example on [`WhiteKernel`].
100    pub fn from_log_variance(log_variance: f64) -> Result<Self, GprError> {
101        let log_variance = validate_log_positive(log_variance, "white kernel variance")?;
102        Ok(Self {
103            variance: BoundedParam::default_positive(log_variance.exp())?,
104        })
105    }
106
107    /// Returns `σw² = exp(θ)`.
108    ///
109    /// See the example on [`WhiteKernel`].
110    pub fn variance(&self) -> f64 {
111        self.variance.value()
112    }
113
114    /// Returns `θ = log(σw²)`.
115    ///
116    /// See the example on [`WhiteKernel`].
117    pub fn log_variance(&self) -> f64 {
118        self.variance.ln()
119    }
120
121    /// Returns the open interval on `σw²`.
122    ///
123    /// See the example on [`WhiteKernel`].
124    pub fn bounds(&self) -> Interval {
125        self.variance.interval()
126    }
127
128    /// Rebuilds this kernel with a new interval on `σw²`.
129    ///
130    /// # Errors
131    ///
132    /// Returns [`crate::IntervalError`] if the current `σw²` is not strictly
133    /// inside `interval`.
134    ///
135    /// See the example on [`WhiteKernel`].
136    pub fn with_bounds(self, interval: Interval) -> Result<Self, crate::IntervalError> {
137        Ok(Self {
138            variance: self.variance.with_interval(interval)?,
139        })
140    }
141
142    /// Returns the number of optimizer parameters (always 1).
143    ///
144    /// See the example on [`WhiteKernel`].
145    pub fn num_params(&self) -> usize {
146        1
147    }
148
149    /// Writes `θ` into a length-1 slice.
150    ///
151    /// # Errors
152    ///
153    /// Returns [`GprError::LengthMismatch`] if `out` is not length 1.
154    ///
155    /// See the example on [`WhiteKernel`].
156    pub fn get_params(&self, out: &mut [f64]) -> Result<(), GprError> {
157        crate::data::require_count(out.len(), 1, "white parameter")?;
158        out[0] = self.variance.ln();
159        Ok(())
160    }
161
162    /// Replaces `θ` from a length-1 slice.
163    ///
164    /// # Errors
165    ///
166    /// Returns [`GprError::LengthMismatch`] if `params` is not length 1,
167    /// [`GprError::InvalidHyperparameter`] if the new `θ` is invalid, or
168    /// [`GprError::InvalidInterval`] if the new `σw²` is not inside
169    /// [`Self::bounds`].
170    ///
171    /// See the example on [`WhiteKernel`].
172    pub fn set_params(&mut self, params: &[f64]) -> Result<(), GprError> {
173        crate::data::require_count(params.len(), 1, "white parameter")?;
174        let log_variance = validate_log_positive(params[0], "white kernel variance")?;
175        self.variance = BoundedParam::new(log_variance.exp(), self.variance.interval())?;
176        Ok(())
177    }
178
179    /// Writes `σw²` on the diagonal of `out` and zero off-diagonal.
180    ///
181    /// Duplicate training points still get the nugget only on `i = j`, not
182    /// from a zero distance. `dist` is used only for shape checks.
183    ///
184    /// # Errors
185    ///
186    /// Returns [`GprError::ShapeMismatch`] if `dist` is not square or `out` is not
187    /// its shape, or [`GprError::EmptyInput`] if they are empty.
188    ///
189    /// See the example on [`WhiteKernel`].
190    pub fn apply<T: KernelScalar>(
191        &self,
192        dist: MatRef<'_, T>,
193        out: MatMut<'_, T>,
194        uplo: Triangle,
195    ) -> Result<(), GprError> {
196        require_square_pair(dist, out.as_ref())?;
197        self.write_square(out, uplo)
198    }
199
200    /// Writes a zero rectangular cross-covariance.
201    ///
202    /// # Errors
203    ///
204    /// Returns [`GprError::ShapeMismatch`] if `out` is not the shape of `dist`, or
205    /// [`GprError::EmptyInput`] if they are empty.
206    ///
207    /// See the example on [`WhiteKernel`].
208    pub fn apply_cross<T: KernelScalar>(
209        &self,
210        dist: MatRef<'_, T>,
211        mut out: MatMut<'_, T>,
212    ) -> Result<(), GprError> {
213        require_same_shape(dist, out.as_ref())?;
214        for col in 0..out.ncols() {
215            for row in 0..out.nrows() {
216                out[(row, col)] = T::from_f64(0.0);
217            }
218        }
219        Ok(())
220    }
221
222    /// Writes the square white kernel from the number of rows of `x`.
223    ///
224    /// # Errors
225    ///
226    /// Returns [`GprError::EmptyInput`] if `x` has no row or no column, or
227    /// [`GprError::ShapeMismatch`] if `out` is not `n×n`.
228    ///
229    /// See the example on [`WhiteKernel`].
230    pub fn apply_points<T: KernelScalar>(
231        &self,
232        x: MatRef<'_, T>,
233        out: MatMut<'_, T>,
234        uplo: Triangle,
235    ) -> Result<(), GprError> {
236        require_columns(x)?;
237        self.apply_rows(x, out, uplo)
238    }
239
240    /// [`Self::apply_points`] without the column check: only the shape of the
241    /// rows is read, so a tree on supplied distances passes no columns.
242    pub(crate) fn apply_rows<T: KernelScalar>(
243        &self,
244        x: MatRef<'_, T>,
245        out: MatMut<'_, T>,
246        uplo: Triangle,
247    ) -> Result<(), GprError> {
248        require_points_square(x, out.as_ref())?;
249        self.write_square(out, uplo)
250    }
251
252    /// Writes a zero rectangular cross-covariance from coordinates.
253    ///
254    /// # Errors
255    ///
256    /// Returns [`GprError::EmptyInput`] if `x` or `xs` has no row or no column, or
257    /// [`GprError::ShapeMismatch`] if `out` is not `x.nrows() × xs.nrows()`.
258    ///
259    /// See the example on [`WhiteKernel`].
260    pub fn apply_cross_points<T: KernelScalar>(
261        &self,
262        x: MatRef<'_, T>,
263        xs: MatRef<'_, T>,
264        out: MatMut<'_, T>,
265    ) -> Result<(), GprError> {
266        require_columns(x)?;
267        require_columns(xs)?;
268        self.apply_cross_rows(x, xs, out)
269    }
270
271    /// [`Self::apply_cross_points`] without the column check: only the shape of the
272    /// rows is read, so a tree on supplied distances passes no columns.
273    pub(crate) fn apply_cross_rows<T: KernelScalar>(
274        &self,
275        x: MatRef<'_, T>,
276        xs: MatRef<'_, T>,
277        mut out: MatMut<'_, T>,
278    ) -> Result<(), GprError> {
279        require_cross_points(x, xs, out.as_ref())?;
280        for col in 0..out.ncols() {
281            for row in 0..out.nrows() {
282                out[(row, col)] = T::from_f64(0.0);
283            }
284        }
285        Ok(())
286    }
287
288    /// Writes the diagonal `k(x, x) = σw²` into `out`.
289    ///
290    /// See the example on [`WhiteKernel`].
291    pub fn fill_diag<T: KernelScalar>(&self, out: &mut [T]) {
292        out.fill(T::from_f64(self.variance()));
293    }
294
295    /// Writes `∂K/∂θ` for `θ = log(σw²)` (`σw²` on the diagonal).
296    ///
297    /// # Errors
298    ///
299    /// Returns [`GprError::IndexOutOfRange`] if `param_idx` is not 0, or
300    /// the same shape errors as [`Self::apply`].
301    ///
302    /// See the example on [`WhiteKernel`].
303    pub fn grad<T: KernelScalar>(
304        &self,
305        dist: MatRef<'_, T>,
306        d_k: MatMut<'_, T>,
307        param_idx: usize,
308        uplo: Triangle,
309    ) -> Result<(), GprError> {
310        require_param_idx(param_idx)?;
311        require_square_pair(dist, d_k.as_ref())?;
312        self.write_square(d_k, uplo)
313    }
314
315    /// Writes `∂K/∂θ` from coordinates.
316    ///
317    /// `x` is used only for shape.
318    ///
319    /// # Errors
320    ///
321    /// Same as [`Self::grad`], with `x` in place of `dist`.
322    ///
323    /// See the example on [`WhiteKernel`].
324    pub fn grad_points<T: KernelScalar>(
325        &self,
326        x: MatRef<'_, T>,
327        d_k: MatMut<'_, T>,
328        param_idx: usize,
329        uplo: Triangle,
330    ) -> Result<(), GprError> {
331        require_columns(x)?;
332        self.grad_rows(x, d_k, param_idx, uplo)
333    }
334
335    /// [`Self::grad_points`] without the column check: only the shape of the
336    /// rows is read, so a tree on supplied distances passes no columns.
337    pub(crate) fn grad_rows<T: KernelScalar>(
338        &self,
339        x: MatRef<'_, T>,
340        d_k: MatMut<'_, T>,
341        param_idx: usize,
342        uplo: Triangle,
343    ) -> Result<(), GprError> {
344        require_param_idx(param_idx)?;
345        require_points_square(x, d_k.as_ref())?;
346        self.write_square(d_k, uplo)
347    }
348
349    /// Writes `∂²K/∂θ²` for `θ = log(σw²)` (`σw²` on the diagonal).
350    ///
351    /// # Errors
352    ///
353    /// Returns [`GprError::IndexOutOfRange`] if `i` or `j` is not 0, or
354    /// the same shape errors as [`Self::apply`].
355    ///
356    /// See the example on [`WhiteKernel`].
357    pub fn hess<T: KernelScalar>(
358        &self,
359        dist: MatRef<'_, T>,
360        d2_k: MatMut<'_, T>,
361        i: usize,
362        j: usize,
363        uplo: Triangle,
364    ) -> Result<(), GprError> {
365        require_hess_idx(i, j)?;
366        require_square_pair(dist, d2_k.as_ref())?;
367        self.write_square(d2_k, uplo)
368    }
369
370    /// Writes `∂²K/∂θ²` from coordinates.
371    ///
372    /// `x` is used only for shape.
373    ///
374    /// # Errors
375    ///
376    /// Same as [`Self::hess`], with `x` in place of `dist`.
377    ///
378    /// See the example on [`WhiteKernel`].
379    pub fn hess_points<T: KernelScalar>(
380        &self,
381        x: MatRef<'_, T>,
382        d2_k: MatMut<'_, T>,
383        i: usize,
384        j: usize,
385        uplo: Triangle,
386    ) -> Result<(), GprError> {
387        require_columns(x)?;
388        self.hess_rows(x, d2_k, i, j, uplo)
389    }
390
391    /// [`Self::hess_points`] without the column check: only the shape of the
392    /// rows is read, so a tree on supplied distances passes no columns.
393    pub(crate) fn hess_rows<T: KernelScalar>(
394        &self,
395        x: MatRef<'_, T>,
396        d2_k: MatMut<'_, T>,
397        i: usize,
398        j: usize,
399        uplo: Triangle,
400    ) -> Result<(), GprError> {
401        require_hess_idx(i, j)?;
402        require_points_square(x, d2_k.as_ref())?;
403        self.write_square(d2_k, uplo)
404    }
405
406    /// Writes the zero coordinate derivative of a white kernel.
407    ///
408    /// Cross-covariance is identically zero, and the square diagonal does not
409    /// depend on coordinates.
410    ///
411    /// # Errors
412    ///
413    /// Returns [`GprError::EmptyInput`] if a view is empty,
414    /// [`GprError::DimensionMismatch`] if `x1` and `x2` have different column
415    /// counts, [`GprError::IndexOutOfRange`] if `dim` is not a column, or
416    /// [`GprError::ShapeMismatch`] if `d_k` is not `x1.nrows() × x2.nrows()`.
417    ///
418    /// See the example on [`WhiteKernel`].
419    pub fn grad_wrt_coord_dim<T: KernelScalar>(
420        &self,
421        x1: MatRef<'_, T>,
422        x2: MatRef<'_, T>,
423        mut d_k: MatMut<'_, T>,
424        dim: usize,
425    ) -> Result<(), GprError> {
426        super::require_coord_grad(x1, x2, d_k.as_ref(), dim)?;
427        for col in 0..d_k.ncols() {
428            for row in 0..d_k.nrows() {
429                d_k[(row, col)] = T::from_f64(0.0);
430            }
431        }
432        Ok(())
433    }
434
435    pub(crate) fn hess_wrt_coord_dims<T: KernelScalar>(
436        &self,
437        x1: MatRef<'_, T>,
438        x2: MatRef<'_, T>,
439        mut d2_k: MatMut<'_, T>,
440        dim_a: usize,
441        dim_b: usize,
442    ) -> Result<(), GprError> {
443        super::require_coord_grad(x1, x2, d2_k.as_ref(), dim_a)?;
444        super::require_coord_grad(x1, x2, d2_k.as_ref(), dim_b)?;
445        fill_zero(d2_k.as_mut());
446        Ok(())
447    }
448
449    pub(crate) fn hess_wrt_coord_mixed<T: KernelScalar>(
450        &self,
451        x1: MatRef<'_, T>,
452        x2: MatRef<'_, T>,
453        mut d2_k: MatMut<'_, T>,
454        dim_x1: usize,
455        dim_x2: usize,
456    ) -> Result<(), GprError> {
457        super::require_coord_grad(x1, x2, d2_k.as_ref(), dim_x1)?;
458        super::require_coord_grad(x1, x2, d2_k.as_ref(), dim_x2)?;
459        fill_zero(d2_k.as_mut());
460        Ok(())
461    }
462
463    pub(crate) fn hess_theta_coord_dim<T: KernelScalar>(
464        &self,
465        x1: MatRef<'_, T>,
466        x2: MatRef<'_, T>,
467        mut d2_k: MatMut<'_, T>,
468        param_idx: usize,
469        dim: usize,
470    ) -> Result<(), GprError> {
471        require_param_idx(param_idx)?;
472        super::require_coord_grad(x1, x2, d2_k.as_ref(), dim)?;
473        fill_zero(d2_k.as_mut());
474        Ok(())
475    }
476
477    fn write_square<T: KernelScalar>(
478        &self,
479        out: MatMut<'_, T>,
480        uplo: Triangle,
481    ) -> Result<(), GprError> {
482        let var = T::from_f64(self.variance());
483        write_square(out, uplo, |row, col| {
484            Ok(if row == col { var } else { T::from_f64(0.0) })
485        })
486    }
487}
488
489fn fill_zero<T: KernelScalar>(mut out: MatMut<'_, T>) {
490    for col in 0..out.ncols() {
491        for row in 0..out.nrows() {
492            out[(row, col)] = T::from_f64(0.0);
493        }
494    }
495}
496
497fn require_param_idx(param_idx: usize) -> Result<(), GprError> {
498    if param_idx == 0 {
499        Ok(())
500    } else {
501        Err(GprError::IndexOutOfRange {
502            reason: "white kernel has a single parameter at index 0".to_owned(),
503        })
504    }
505}
506
507fn require_hess_idx(i: usize, j: usize) -> Result<(), GprError> {
508    if i == 0 && j == 0 {
509        Ok(())
510    } else {
511        Err(GprError::IndexOutOfRange {
512            reason: format!("white kernel has a single parameter; got pair ({i}, {j})"),
513        })
514    }
515}
516
517fn require_points_square<T: KernelScalar>(
518    x: MatRef<'_, T>,
519    out: MatRef<'_, T>,
520) -> Result<(), GprError> {
521    if x.nrows() == 0 {
522        return Err(GprError::EmptyInput);
523    }
524    if out.nrows() != x.nrows() || out.ncols() != x.nrows() {
525        return Err(GprError::ShapeMismatch {
526            reason: format!(
527                "output is {}x{}, expected {}x{}",
528                out.nrows(),
529                out.ncols(),
530                x.nrows(),
531                x.nrows()
532            ),
533        });
534    }
535    Ok(())
536}
537
538fn require_cross_points<T: KernelScalar>(
539    x: MatRef<'_, T>,
540    xs: MatRef<'_, T>,
541    out: MatRef<'_, T>,
542) -> Result<(), GprError> {
543    if x.nrows() == 0 || xs.nrows() == 0 {
544        return Err(GprError::EmptyInput);
545    }
546    if out.nrows() != x.nrows() || out.ncols() != xs.nrows() {
547        return Err(GprError::ShapeMismatch {
548            reason: format!(
549                "output is {}x{}, expected {}x{}",
550                out.nrows(),
551                out.ncols(),
552                x.nrows(),
553                xs.nrows()
554            ),
555        });
556    }
557    Ok(())
558}
559
560/// Rejects coordinates without a column ([`GprError::EmptyInput`]).
561fn require_columns<T>(x: MatRef<'_, T>) -> Result<(), GprError> {
562    if x.ncols() == 0 {
563        return Err(GprError::EmptyInput);
564    }
565    Ok(())
566}
567
568#[cfg(test)]
569mod tests {
570    use super::WhiteKernel;
571    use crate::error::GprError;
572    use crate::kernel::Triangle;
573    use faer::{Mat, mat};
574
575    const TOL: f64 = 1e-8;
576
577    use crate::test_check::{assert_close, assert_lower_close, fill};
578
579    fn dummy_dist(n: usize) -> Mat<f64> {
580        Mat::zeros(n, n)
581    }
582
583    #[test]
584    fn apply_is_diagonal_even_when_dist_is_zero() {
585        let kernel = WhiteKernel::new(0.4).expect("valid");
586        let dist = dummy_dist(3);
587        let mut k = fill(3, 1.0);
588        kernel
589            .apply(dist.as_ref(), k.as_mut(), Triangle::Full)
590            .expect("shape");
591        for col in 0..3 {
592            for row in 0..3 {
593                let expected = if row == col { 0.4 } else { 0.0 };
594                assert_close(k[(row, col)], expected, TOL);
595                assert_close(k[(row, col)], k[(col, row)], TOL);
596            }
597        }
598    }
599
600    #[test]
601    fn lower_matches_full_and_leaves_upper() {
602        let kernel = WhiteKernel::new(0.2).expect("valid");
603        let dist = dummy_dist(3);
604        let mut full = fill(3, 0.0);
605        kernel
606            .apply(dist.as_ref(), full.as_mut(), Triangle::Full)
607            .expect("shape");
608        let mut lower = fill(3, 42.0);
609        kernel
610            .apply(dist.as_ref(), lower.as_mut(), Triangle::Lower)
611            .expect("shape");
612        assert_lower_close(lower.as_ref(), full.as_ref(), TOL);
613        assert_close(lower[(0, 1)], 42.0, TOL);
614    }
615
616    #[test]
617    fn apply_cross_is_zero() {
618        let kernel = WhiteKernel::new(1.0).expect("valid");
619        let dist = mat![[0.0, 0.0], [1.0, 0.0]];
620        let mut out = fill(2, 9.0);
621        kernel
622            .apply_cross(dist.as_ref(), out.as_mut())
623            .expect("rect");
624        assert_close(out[(0, 0)], 0.0, TOL);
625        assert_close(out[(0, 1)], 0.0, TOL);
626    }
627
628    #[test]
629    fn grad_matches_finite_difference() {
630        let kernel = WhiteKernel::from_log_variance(-1.0).expect("valid");
631        let theta = kernel.log_variance();
632        let h = 1e-6;
633        let plus = WhiteKernel::from_log_variance(theta + h).expect("valid");
634        let minus = WhiteKernel::from_log_variance(theta - h).expect("valid");
635        let dist = dummy_dist(2);
636        let mut kp = fill(2, 0.0);
637        let mut km = fill(2, 0.0);
638        let mut dk = fill(2, 0.0);
639        plus.apply(dist.as_ref(), kp.as_mut(), Triangle::Full)
640            .expect("shape");
641        minus
642            .apply(dist.as_ref(), km.as_mut(), Triangle::Full)
643            .expect("shape");
644        kernel
645            .grad(dist.as_ref(), dk.as_mut(), 0, Triangle::Full)
646            .expect("idx 0");
647        let fd = (kp[(0, 0)] - km[(0, 0)]) / (2.0 * h);
648        assert_close(dk[(0, 0)], fd, TOL);
649        assert_close(dk[(0, 1)], 0.0, TOL);
650    }
651
652    #[test]
653    fn get_set_params_roundtrip() {
654        let mut kernel = WhiteKernel::new(0.3).expect("valid");
655        let mut params = [0.0];
656        kernel.get_params(&mut params).expect("len 1");
657        assert_close(params[0], 0.3_f64.ln(), TOL);
658        params[0] = 0.1_f64.ln();
659        kernel.set_params(&params).expect("len 1");
660        assert_close(kernel.variance(), 0.1, TOL);
661    }
662
663    #[test]
664    fn rejects_non_positive() {
665        assert!(matches!(
666            WhiteKernel::new(0.0),
667            Err(GprError::InvalidHyperparameter { .. })
668        ));
669    }
670}