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
//! [`OnlineSgpr`] on supplied squared distances: save, the query of the
//! predict family, and the insert and delete of points and of inducing
//! points, each with the caller's `d²` per slot.

#[allow(
    unused_imports,
    reason = "a split file takes its parent's imports whole; each uses some"
)]
use super::*;

impl<O, P: crate::precision::GpScalar, C: PointUse> OnlineSgpr<O, P, DistanceKernel<C>> {
    /// Writes this model to `dir` as `config.json` and `model.safetensors`.
    ///
    /// Stores what `save` of a [`crate::FittedSgpr`] on a [`DistanceKernel`]
    /// stores, with the point and inducing identifiers.
    /// [`crate::persist::LoadedDistanceSgpr::load`] loads it as an online
    /// model.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::PersistFailed`] when the directory cannot be
    /// written or a kernel or transform has no persist form.
    ///
    /// See the example on [`crate::persist::LoadedDistanceSgpr`].
    pub fn save(&self, dir: impl AsRef<std::path::Path>) -> Result<(), GprError> {
        crate::persist::save_online_sgpr(self, dir.as_ref())
    }

    /// The factors a prediction reads.
    fn vfe_system(&self) -> VfeSystem<'_, P, SuppliedSpec> {
        VfeSystem::new(
            &self.state.core,
            self.state.k_mm_l.as_ref(),
            self.state.b_l.as_ref(),
            &self.state.predict_w,
        )
    }

    /// Appends one point from its supplied columns (each slot's `m × 1`
    /// squared distances from the inducing points to the new point) and,
    /// for a kernel that also reads coordinates, `x_obs`.
    fn insert_sources<'s>(
        &mut self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        x_obs: &[f64],
        y_obs: f64,
    ) -> Result<PointId, GprError> {
        let d = self.state.core.d;
        if x_obs.len() != d {
            return Err(GprError::DimensionMismatch {
                x_dim: x_obs.len(),
                expected_dim: d,
            });
        }
        if x_obs.iter().any(|v| !v.is_finite()) || !y_obs.is_finite() {
            return Err(GprError::NonFiniteInput);
        }
        self.state.registry.require_room()?;
        // The model's buffers, taken for the call as a predict takes them.
        let mut scratch = std::mem::take(&mut self.scratch.predict.query64);
        let result = self.insert_bound(sources, x_obs, y_obs, &mut scratch);
        self.scratch.predict.query64 = scratch;
        result
    }

    /// [`Self::insert_sources`] with the columns bound in `f64`: the new
    /// column of `A` is evaluated in `f64` whatever the storage scalar
    /// ([`OnlineSgpr::append_point`]).
    fn insert_bound<'s>(
        &mut self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        x_obs: &[f64],
        y_obs: f64,
        scratch: &mut QueryScratch<f64>,
    ) -> Result<PointId, GprError> {
        let (m, d) = (self.state.core.m, self.state.core.d);
        let cols = QuerySources::bind_column(&self.state.core.supplied.slots, sources, m, scratch)?;
        let mut mapped = std::mem::take(&mut self.scratch.point);
        let result = (|| {
            self.state.core.map_point(x_obs, &mut mapped)?;
            let y_new = self.state.core.map_target(y_obs)?;
            let compiled = self.state.core.kernel.compile_as::<f64>();
            let z64 = pack_points(&self.state.core.z_train, m, d);
            let x64 = pack_points(&mapped, 1, d);
            let views = CrossViews {
                x1: z64.as_ref(),
                x2: x64.as_ref(),
                dist: None,
                slots: <SuppliedSpec as SupplyViews>::rects(&cols),
            };
            let a_col = with_kernel_exp!(self.state.core.math, M => self
                .scratch
                .f64
                .cross::<M, SuppliedSpec>(&compiled, views))?;
            let k_diag = kernel_diag_at::<f64, SuppliedSpec>(&self.state.core.kernel, &mapped, d)?;
            // The new row of every training block, read before anything
            // changes: the columns are checked, so nothing below fails.
            let exact = cols.f64_view();
            let blocks = self.state.core.supplied.supply.exact().xz.block_ids();
            let mut row = Vec::with_capacity(blocks.len() * m);
            for &at in &blocks {
                column_into(&exact, at, m, &mut row)?;
            }
            self.state.core.supplied.supply.reserve_point()?;
            self.atomically(|model| {
                let point = NewPoint {
                    x: &mapped,
                    x_obs,
                    y: y_new,
                    y_obs,
                };
                model.append_point(a_col, k_diag, point, |supply| {
                    supply.push_point(|b, col| row[b * m + col]);
                })
            })
        })();
        self.scratch.point = mapped;
        result
    }

    /// Makes training point `point` one more inducing point, from its
    /// supplied columns (each slot's `n × 1` squared distances from the
    /// training points to it).
    fn insert_inducing_sources<'s>(
        &mut self,
        point: PointId,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
    ) -> Result<InducingId, GprError> {
        let row = self.state.registry.index_of(point)?;
        if let Some(at) = self.state.core.supplied.supply.inducing_at(row) {
            return Err(GprError::InvalidConfig {
                reason: format!("the point is inducing point {at} already"),
            });
        }
        self.state.inducing.require_room()?;
        // Bound in `f64`, as an `X` insert binds its row: only the exact
        // values are read.
        let mut scratch = std::mem::take(&mut self.scratch.predict.query64);
        let result = self.insert_inducing_bound(point, row, sources, &mut scratch);
        self.scratch.predict.query64 = scratch;
        result
    }

    fn insert_inducing_bound<'s>(
        &mut self,
        point: PointId,
        row: usize,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        scratch: &mut QueryScratch<f64>,
    ) -> Result<InducingId, GprError> {
        let (n, m, d) = (self.state.core.n, self.state.core.m, self.state.core.d);
        let cols = QuerySources::bind_column(&self.state.core.supplied.slots, sources, n, scratch)?;
        let supply = &self.state.core.supplied.supply;
        let exact = cols.f64_view();
        let (column, mirror) = new_inducing_column(
            &supply.exact().xz,
            &supply.exact().zz,
            &supply.inducing,
            row,
            &exact,
            |at| cols.tidy(at),
            |at, err| cols.locate(at, err),
        )?;
        // A kernel that also reads coordinates takes the point's as `z`.
        let mut z_train = self.state.core.z_train.clone();
        append_point(
            &mut z_train,
            m,
            d,
            &point_at(&self.state.core.x_train, n, d, row),
        );
        let mut z_obs = self.state.core.z_obs.clone();
        append_point(
            &mut z_obs,
            m,
            d,
            &point_at(&self.state.core.x_obs, n, d, row),
        );
        self.state.core.supplied.supply.reserve_inducing()?;
        self.atomically(|model| {
            let mut saved = Vec::new();
            model.state.core.supplied.supply.add_inducing(
                row,
                |b, i| column[b * n + i],
                |b, col| mirror[b * m + col],
                &mut saved,
            );
            // A tidy source that repaired a pair moved `k(Z, x_row)`, so
            // column `row` of `A` follows the repaired values.
            let repaired = saved
                .iter()
                .zip(&mirror)
                .any(|(old, new)| old.to_bits() != new.to_bits());
            model.commit_inducing(
                |model| {
                    Ok(InducingChange::Insert {
                        border: model.supplied_border(row, m)?,
                        replace: repaired.then_some(row),
                    })
                },
                z_train,
                z_obs,
                m + 1,
                |supply| {
                    supply.undo_add_inducing(row, &saved);
                },
            )?;
            model.state.inducing_points.push(point);
            Ok(model.state.inducing.insert())
        })
    }

    /// The kernel values of training point `row` as the new inducing point
    /// `m` (the training blocks hold it as their last column): `k(X, z)`
    /// from that column, `k(Z, z)` from its rows of the `m` inducing points
    /// before it (the values the squares among the inducing points hold),
    /// and `k(z, z)`.
    ///
    /// # Errors
    ///
    /// Returns the errors of the kernel evaluation.
    fn supplied_border(
        &mut self,
        row: usize,
        m: usize,
    ) -> Result<InducingBorder<P::Storage>, GprError> {
        let core = &self.state.core;
        let (n, d) = (core.n, core.d);
        let compiled = core.kernel.compile_as::<P::Storage>();
        let z_point = point_at(&core.x_train, n, d, row);
        let x64 = pack_points(&core.x_train, n, d);
        let z64 = pack_points(&z_point, 1, d);
        let (mut x_cast, mut z_cast) = (P::Storage::empty_cols(), P::Storage::empty_cols());
        let x = P::Storage::storage_cols(x64.as_ref(), &mut x_cast);
        let z = P::Storage::storage_cols(z64.as_ref(), &mut z_cast);
        let at = core.supplied.supply.at::<P::Storage>()?;
        let ks = &mut self.scratch.storage;
        let k_xz = <SuppliedSpec as SupplyViews>::with_cols(&at.xz, m, 1, |cols| {
            let views = CrossViews {
                x1: x,
                x2: z,
                dist: None,
                slots: <SuppliedSpec as SupplyViews>::rects(cols),
            };
            with_kernel_exp!(core.math, M => ks.cross::<M, SuppliedSpec>(&compiled, views))
        })?;
        // Invariant: the caller has just added the new inducing point, so
        // `supply.inducing` holds `m + 1` training rows (the first `m` are
        // the inducing points before it), each `< n`, and `k_xz` is `n × 1`.
        // The slice and the `(point, 0)` index stay in range.
        let mut k_z = Mat::zeros(m, 1);
        for (i, &point) in core.supplied.supply.inducing[..m].iter().enumerate() {
            k_z[(i, 0)] = k_xz[(point, 0)];
        }
        Ok(InducingBorder {
            k_z,
            k_self: kernel_diag_at::<P::Storage, SuppliedSpec>(&core.kernel, &z_point, d)?,
            k_x: (0..n).map(|i| k_xz[(i, 0)]).collect(),
        })
    }

    /// Returns a copy of the kernel whose hyperparameters this model owns.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{DistanceSlot, RbfKernel, ScalarDistance};
    /// use gprx::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let image = ScalarDistance::new();
    /// // Training points at x = 0, 1, 2, 3; inducing points: samples 0 and 2.
    /// let train = [0.0, 1.0, 4.0, 9.0, 4.0, 1.0, 0.0, 1.0];
    /// let online = Sgpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
    ///     .with_optimizer(Fixed)
    ///     .factor([image.borrow(&train)], 4, &[0.0, 1.0, 0.5, 0.25], &[0, 2])
    ///     .map_err(|(_, e)| e)?
    ///     .into_online();
    /// assert_eq!(online.to_kernel().num_params(), 1);
    /// assert_eq!(online.slots(), [DistanceSlot::Scalar(image)]);
    /// let ids = online.point_ids();
    /// assert!(online.inducing_points().eq([ids[0], ids[2]]));
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_kernel(&self) -> DistanceKernel<C> {
        <DistanceKernel<C> as crate::kernel::ModelKernelParts>::from_spec(
            self.state.core.kernel.clone(),
        )
    }

    /// Returns the slots of the kernel, in the order of
    /// [`DistanceKernel::slots`]; bind supplies to these.
    ///
    /// See the example on [`Self::to_kernel`].
    pub fn slots(&self) -> Vec<DistanceSlot> {
        crate::kernel::spec_slots(&self.state.core.kernel)
    }

    /// Returns the training points that are the inducing points, in the
    /// order of the columns of the training blocks and the rows of a
    /// prediction's blocks. An id stays the same across inserts and
    /// deletes; `insert_inducing` appends one.
    ///
    /// See the example on [`Self::to_kernel`].
    pub fn inducing_points(&self) -> impl Iterator<Item = PointId> + '_ {
        self.inducing_point_ids().iter().copied()
    }

    /// The [`PointId`]s of [`Self::inducing_points`], as a slice.
    pub(crate) fn inducing_point_ids(&self) -> &[PointId] {
        &self.state.inducing_points
    }
}

impl<O, P: crate::precision::GpScalar, C: PointUse> DistanceQuery
    for OnlineSgpr<O, P, DistanceKernel<C>>
{
    type Refine = P::Refine;

    fn query_distances<'s>(
        &self,
        cross: impl IntoIterator<Item = DistanceSource<'s>>,
        points: QueryPoints<'_>,
        q: usize,
        options: PredictOptions,
    ) -> Result<Prediction<P::Refine>, GprError> {
        let mut out = Prediction::default();
        predict_vfe_into::<P, SuppliedSpec>(
            &self.state.core,
            &self.vfe_system(),
            points.xs,
            q,
            points.n_cols,
            cross,
            options,
            &mut PredictScratch::default(),
            &mut out,
        )?;
        Ok(out)
    }

    fn query_distances_into<'s>(
        &mut self,
        cross: impl IntoIterator<Item = DistanceSource<'s>>,
        points: QueryPoints<'_>,
        q: usize,
        options: PredictOptions,
        out: &mut Prediction<P::Refine>,
    ) -> Result<(), GprError> {
        let sys = VfeSystem::new(
            &self.state.core,
            self.state.k_mm_l.as_ref(),
            self.state.b_l.as_ref(),
            &self.state.predict_w,
        );
        predict_vfe_into::<P, SuppliedSpec>(
            &self.state.core,
            &sys,
            points.xs,
            q,
            points.n_cols,
            cross,
            options,
            &mut self.scratch.predict,
            out,
        )
    }

    fn query_distance_covariance<'s>(
        &self,
        cross: impl IntoIterator<Item = DistanceSource<'s>>,
        square: impl IntoIterator<Item = DistanceSource<'s>>,
        points: QueryPoints<'_>,
        q: usize,
        options: PredictOptions,
    ) -> Result<PredictiveCovariance<P::Refine>, GprError> {
        predict_vfe_covariance::<P, SuppliedSpec>(
            &self.state.core,
            &self.vfe_system(),
            points.xs,
            q,
            points.n_cols,
            cross,
            square,
            options,
        )
    }

    fn draw_jitter(&self) -> JitterPolicy {
        self.state.core.jitter
    }
}

impl<O, P: crate::precision::GpScalar> OnlineSgpr<O, P, DistanceKernel<DistanceOnly>> {
    /// Appends one training point at the current `θ` with the rank-1 VFE
    /// update of the coordinate `insert`, from its squared distances to the
    /// inducing points. The VFE system is assembled again instead under
    /// the same condition (a pivot of the factor of `K_mm` at most `8 ε`
    /// times its diagonal; see [`OnlineSgpr`]); [`Self::delete`] removes a point as the coordinate
    /// model does.
    ///
    /// `sources` binds, per slot, the `m × 1` column from the `m` inducing
    /// points (in [`Self::inducing_points`] order) to the new point; an ARD slot
    /// binds one such column per dimension. A table may be borrowed, owned,
    /// or filled. Every value is checked (finite, `≥ 0`; see
    /// [`DistanceSource::tidy`]) and the column is kept as the point's row
    /// of the training blocks: the blocks keep room for more rows (a
    /// quarter more each time they fill), so most inserts write only the
    /// row. The returned [`PointId`] is never reused after a later
    /// [`Self::delete`].
    ///
    /// # Errors
    ///
    /// Returns [`GprError::NonFiniteInput`] if `y_new` is `NaN` or `Inf`,
    /// [`GprError::InvalidDistance`] for a negative or non-finite distance,
    /// [`GprError::LengthMismatch`] for a column whose length is not `m`,
    /// [`GprError::DistanceSlot`] if a source names a slot the kernel does
    /// not read, two name one slot, or a slot has none,
    /// [`GprError::IndexOutOfRange`] if no new
    /// [`PointId`] is left, [`GprError::SizeOverflow`] if the training
    /// blocks cannot grow, or [`GprError::CholeskyFailed`] if the system
    /// assembled again does not factor or a precision that refines in
    /// `f64` cannot factor its predict weights again. On an error the model
    /// holds the same points.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{RbfKernel, ScalarDistance};
    /// use gprx::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let image = ScalarDistance::new();
    /// // Training points at x = 0, 1, 2, 3; inducing points: samples 0 and 2.
    /// let train = [0.0, 1.0, 4.0, 9.0, 4.0, 1.0, 0.0, 1.0];
    /// let fitted = Sgpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
    ///     .with_optimizer(Fixed)
    ///     .factor([image.borrow(&train)], 4, &[0.0, 1.0, 0.5, 0.25], &[0, 2])
    ///     .map_err(|(_, e)| e)?;
    /// let mut online = fitted.into_online();
    /// // A point at x = 4: its squared distances to the inducing points.
    /// let id = online.insert([image.from_vec(vec![16.0, 4.0])], 0.1)?;
    /// assert_eq!(online.n(), 5);
    /// assert_eq!(online.slots().len(), 1);
    /// let _kernel = online.to_kernel();
    /// // A query at x = 0.5: inducing points × query.
    /// let pred = online.predict([image.from_vec(vec![0.25, 2.25])], 1)?;
    /// assert_eq!(pred.mean.len(), 1);
    /// online.delete(id)?;
    /// assert_eq!(online.n(), 4);
    /// # Ok(())
    /// # }
    /// ```
    pub fn insert<'s>(
        &mut self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        y_new: f64,
    ) -> Result<PointId, GprError> {
        self.insert_sources(sources, &[], y_new)
    }

    /// Makes training point `point` one more inducing point at the current
    /// `θ`, from its squared distances to the training points.
    ///
    /// `sources` binds, per slot, the `n × 1` column from the `n` training
    /// points (in [`Self::point_ids`] order) to `point`; an ARD slot binds
    /// one such column per dimension. The column is checked as a training
    /// block is, and its square among the inducing points as a training
    /// square is: the value at `point` itself is zero, and the value at
    /// each inducing point equals the one the training blocks hold for that
    /// pair (a [`DistanceSource::tidy`] source repairs both to their mean).
    /// The column is kept as a new column of the training blocks, and the
    /// VFE factors grow by the bordered update of the coordinate
    /// `insert_inducing`, with `k(X, point)` read from that column and
    /// `k(Z, point)` from its rows of the inducing points. When the repair
    /// of a tidy source moved a value of `point`'s own row, its column of
    /// `A` is replaced first (a rank-1 update and downdate of `B`). The VFE
    /// system is assembled again instead under the conditions on
    /// [`OnlineSgpr`] (an `f32` storage scalar, a jitter offset `j > 0` of
    /// the factor of `K_mm` or a pivot of it at most `1e-5` times its
    /// diagonal, or a bordered pivot at most `1e-5` times its diagonal).
    /// The returned
    /// [`InducingId`] is never reused after a later
    /// [`Self::delete_inducing`].
    ///
    /// # Errors
    ///
    /// Returns [`GprError::InvalidPointId`] if `point` is unknown or
    /// deleted, [`GprError::InvalidConfig`] if it is an inducing point
    /// already, [`GprError::InvalidDistance`] for a value the check refuses
    /// (located in the caller's column), [`GprError::LengthMismatch`] for a
    /// column whose length is not `n`, [`GprError::DistanceSlot`] if a
    /// source names a slot the kernel does not read, two name one slot, or a
    /// slot has none, [`GprError::IndexOutOfRange`] if no new [`InducingId`] is left,
    /// [`GprError::SizeOverflow`] if the training blocks cannot grow, or
    /// [`GprError::CholeskyFailed`] if the reassembled enlarged system does
    /// not factor. On an error the model holds the same inducing points.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{RbfKernel, ScalarDistance};
    /// use gprx::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let image = ScalarDistance::new();
    /// // Training points at x = 0, 1, 2, 3; inducing points: samples 0 and 2.
    /// let train = [0.0, 1.0, 4.0, 9.0, 4.0, 1.0, 0.0, 1.0];
    /// let mut online = Sgpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
    ///     .with_optimizer(Fixed)
    ///     .factor([image.borrow(&train)], 4, &[0.0, 1.0, 0.5, 0.25], &[0, 2])
    ///     .map_err(|(_, e)| e)?
    ///     .into_online();
    /// // Sample 1 (x = 1) becomes an inducing point: its squared distances
    /// // to the four training points.
    /// let point = online.point_ids()[1];
    /// let id = online.insert_inducing(point, [image.from_vec(vec![1.0, 0.0, 1.0, 4.0])])?;
    /// let ids = online.point_ids();
    /// let inducing: Vec<_> = online.inducing_points().collect();
    /// assert_eq!(inducing, [ids[0], ids[2], point]);
    /// // A query at x = 0.5: the three inducing points × query.
    /// let pred = online.predict([image.from_vec(vec![0.25, 2.25, 0.25])], 1)?;
    /// assert_eq!(pred.mean.len(), 1);
    /// online.delete_inducing(id)?;
    /// assert_eq!(online.m(), 2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn insert_inducing<'s>(
        &mut self,
        point: PointId,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
    ) -> Result<InducingId, GprError> {
        self.insert_inducing_sources(point, sources)
    }
}

impl<O, P: crate::precision::GpScalar> OnlineSgpr<O, P, DistanceKernel<WithPoints>> {
    /// Appends one training point at the current `θ`, from its squared
    /// distances to the inducing points and its coordinates `x_new`
    /// (length [`Self::d`]).
    ///
    /// The columns are as in the insert of a [`DistanceOnly`] model;
    /// `x_new` goes through the stored input transform, which is not
    /// re-fit.
    ///
    /// # Errors
    ///
    /// Those of the insert of a [`DistanceOnly`] model, and
    /// [`GprError::DimensionMismatch`] if `x_new` is the wrong length or
    /// [`GprError::NonFiniteInput`] if one of its values is `NaN` or `Inf`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel, ScalarDistance};
    /// use gprx::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let image = ScalarDistance::new();
    /// let kernel = image.kernel(RbfKernel::new(1.0)?) * KernelSpec::from(RbfKernel::new(2.0)?);
    /// let train = [0.0, 1.0, 4.0, 9.0, 4.0, 1.0, 0.0, 1.0];
    /// let x = [0.0, 0.5, 1.0, 1.5];
    /// let mut online = Sgpr::new(kernel, GaussianLikelihood::new(0.1)?)
    ///     .with_optimizer(Fixed)
    ///     .factor([image.borrow(&train)], 4, &x, 1, &[0.0, 1.0, 0.5, 0.25], &[0, 2])
    ///     .map_err(|(_, e)| e)?
    ///     .into_online();
    /// online.insert([image.from_vec(vec![16.0, 4.0])], &[2.0], 0.1)?;
    /// // Sample 1 becomes an inducing point; its coordinates come along.
    /// let point = online.point_ids()[1];
    /// online.insert_inducing(point, [image.from_vec(vec![1.0, 0.0, 1.0, 4.0, 9.0])])?;
    /// assert_eq!(online.z(), &[0.0, 1.0, 0.5]);
    /// let pred = online.predict([image.from_vec(vec![0.25, 2.25, 0.25])], &[0.25], 1, 1)?;
    /// assert_eq!(pred.mean.len(), 1);
    /// # Ok(())
    /// # }
    /// ```
    pub fn insert<'s>(
        &mut self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        x_new: &[f64],
        y_new: f64,
    ) -> Result<PointId, GprError> {
        self.insert_sources(sources, x_new, y_new)
    }

    /// Makes training point `point` one more inducing point, as the
    /// [`DistanceOnly`] model does; its coordinates are those of `point`.
    ///
    /// # Errors
    ///
    /// Those of the [`DistanceOnly`] model's `insert_inducing`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel, ScalarDistance};
    /// use gprx::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let image = ScalarDistance::new();
    /// let kernel = image.kernel(RbfKernel::new(1.0)?) * KernelSpec::from(RbfKernel::new(2.0)?);
    /// // Training points at x = 0, 1, 2, 3 (`d²`) and 0, 0.5, 1, 1.5 (coordinates).
    /// let train = [0.0, 1.0, 4.0, 9.0, 4.0, 1.0, 0.0, 1.0];
    /// let x = [0.0, 0.5, 1.0, 1.5];
    /// let mut online = Sgpr::new(kernel, GaussianLikelihood::new(0.1)?)
    ///     .with_optimizer(Fixed)
    ///     .factor([image.borrow(&train)], 4, &x, 1, &[0.0, 1.0, 0.5, 0.25], &[0, 2])
    ///     .map_err(|(_, e)| e)?
    ///     .into_online();
    /// // Sample 1 becomes an inducing point: its squared distances to the four points.
    /// let point = online.point_ids()[1];
    /// let id = online.insert_inducing(point, [image.from_vec(vec![1.0, 0.0, 1.0, 4.0])])?;
    /// assert_eq!(online.z(), &[0.0, 1.0, 0.5]);
    /// online.delete_inducing(id)?;
    /// assert_eq!(online.m(), 2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn insert_inducing<'s>(
        &mut self,
        point: PointId,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
    ) -> Result<InducingId, GprError> {
        self.insert_inducing_sources(point, sources)
    }
}

distance_predict!(
    impl [O, P: crate::precision::GpScalar] OnlineSgpr<O, P, DistanceKernel<DistanceOnly>>,
    refine = P::Refine,
    args = (),
    tail = (),
    points = QueryPoints::NONE,
    count = q,
    cross = {
        /// the `m × q` squared distances from the `m` inducing points (in
        /// [`Self::inducing_points`] order) to the `q` queries.
    },
    reads = {
        /// A table is read in place for this call (an `f32` model reads it
        /// in `f64`, as it predicts); a fill writes scratch once.
    },
    predict_doc = {
        /// # Examples
        ///
        /// ```rust
        /// use gprx::kernel::{RbfKernel, ScalarDistance};
        /// use gprx::{Fixed, GaussianLikelihood, PredictOptions, Prediction, Sgpr};
        ///
        /// # fn main() -> Result<(), gprx::GprError> {
        /// let image = ScalarDistance::new();
        /// // Training points at x = 0, 1, 2, 3; inducing points: samples 0 and 2.
        /// let train = [0.0, 1.0, 4.0, 9.0, 4.0, 1.0, 0.0, 1.0];
        /// let mut online = Sgpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
        ///     .with_optimizer(Fixed)
        ///     .factor([image.borrow(&train)], 4, &[0.0, 1.0, 0.5, 0.25], &[0, 2])
        ///     .map_err(|(_, e)| e)?
        ///     .into_online();
        /// // Two queries at 0.5 and 1.5: inducing × query (2 × 2), then query × query.
        /// let cross = [0.25, 2.25, 2.25, 0.25];
        /// let query = [0.0, 1.0, 1.0, 0.0];
        /// let options = PredictOptions::default();
        /// let pred = online.predict([image.borrow(&cross)], 2)?;
        /// assert_eq!(pred.mean.len(), 2);
        /// let mut out = Prediction::default();
        /// online.predict_into([image.borrow(&cross)], 2, &mut out)?;
        /// online.predict_with_into([image.borrow(&cross)], 2, options, &mut out)?;
        /// let _ = online.predict_with([image.borrow(&cross)], 2, options)?;
        /// let cov = online.predict_covariance([image.borrow(&cross)], [image.borrow(&query)], 2)?;
        /// assert_eq!(cov.covariance.len(), 4);
        /// let _ = online.predict_covariance_with([image.borrow(&cross)], [image.borrow(&query)], 2, options)?;
        /// let draws = online.sample([image.borrow(&cross)], [image.borrow(&query)], 2, 3, 7)?;
        /// assert_eq!(draws.len(), 6);
        /// let _ = online.sample_with([image.borrow(&cross)], [image.borrow(&query)], 2, options, 3, 7)?;
        /// # Ok(())
        /// # }
        /// ```
    },
    covariance_doc = {
        /// # Examples
        ///
        /// ```rust
        /// use gprx::kernel::{RbfKernel, ScalarDistance};
        /// use gprx::{Fixed, GaussianLikelihood, PredictOptions, Prediction, Sgpr};
        ///
        /// # fn main() -> Result<(), gprx::GprError> {
        /// let image = ScalarDistance::new();
        /// // Training points at x = 0, 1, 2, 3; inducing points: samples 0 and 2.
        /// let train = [0.0, 1.0, 4.0, 9.0, 4.0, 1.0, 0.0, 1.0];
        /// let mut online = Sgpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
        ///     .with_optimizer(Fixed)
        ///     .factor([image.borrow(&train)], 4, &[0.0, 1.0, 0.5, 0.25], &[0, 2])
        ///     .map_err(|(_, e)| e)?
        ///     .into_online();
        /// // Two queries at 0.5 and 1.5: inducing × query (2 × 2), then query × query.
        /// let cross = [0.25, 2.25, 2.25, 0.25];
        /// let query = [0.0, 1.0, 1.0, 0.0];
        /// let options = PredictOptions::default();
        /// let pred = online.predict([image.borrow(&cross)], 2)?;
        /// assert_eq!(pred.mean.len(), 2);
        /// let mut out = Prediction::default();
        /// online.predict_into([image.borrow(&cross)], 2, &mut out)?;
        /// online.predict_with_into([image.borrow(&cross)], 2, options, &mut out)?;
        /// let _ = online.predict_with([image.borrow(&cross)], 2, options)?;
        /// let cov = online.predict_covariance([image.borrow(&cross)], [image.borrow(&query)], 2)?;
        /// assert_eq!(cov.covariance.len(), 4);
        /// let _ = online.predict_covariance_with([image.borrow(&cross)], [image.borrow(&query)], 2, options)?;
        /// let draws = online.sample([image.borrow(&cross)], [image.borrow(&query)], 2, 3, 7)?;
        /// assert_eq!(draws.len(), 6);
        /// let _ = online.sample_with([image.borrow(&cross)], [image.borrow(&query)], 2, options, 3, 7)?;
        /// # Ok(())
        /// # }
        /// ```
    },
);

distance_predict!(
    impl [O, P: crate::precision::GpScalar] OnlineSgpr<O, P, DistanceKernel<WithPoints>>,
    refine = P::Refine,
    args = (xs: &[f64]),
    tail = (n_cols: usize),
    points = QueryPoints { xs, n_cols },
    count = q,
    cross = {
        /// the `m × q` squared distances from the `m` inducing points (in
        /// [`Self::inducing_points`] order) to the `q` queries.
    },
    reads = {
        /// A table is read in place for this call (an `f32` model reads it
        /// in `f64`, as it predicts); a fill writes scratch once.
    },
    predict_doc = {
        /// # Examples
        ///
        /// ```rust
        /// use gprx::kernel::{KernelSpec, RbfKernel, ScalarDistance};
        /// use gprx::{Fixed, GaussianLikelihood, PredictOptions, Prediction, Sgpr};
        ///
        /// # fn main() -> Result<(), gprx::GprError> {
        /// let image = ScalarDistance::new();
        /// let kernel = image.kernel(RbfKernel::new(1.0)?) * KernelSpec::from(RbfKernel::new(2.0)?);
        /// let train = [0.0, 1.0, 4.0, 9.0, 4.0, 1.0, 0.0, 1.0];
        /// let x = [0.0, 0.5, 1.0, 1.5];
        /// let mut online = Sgpr::new(kernel, GaussianLikelihood::new(0.1)?)
        ///     .with_optimizer(Fixed)
        ///     .factor([image.borrow(&train)], 4, &x, 1, &[0.0, 1.0, 0.5, 0.25], &[0, 2])
        ///     .map_err(|(_, e)| e)?
        ///     .into_online();
        /// let (cross, query, xs) = ([0.25, 2.25, 2.25, 0.25], [0.0, 1.0, 1.0, 0.0], [0.25, 0.75]);
        /// let options = PredictOptions::default();
        /// let pred = online.predict([image.borrow(&cross)], &xs, 2, 1)?;
        /// assert_eq!(pred.mean.len(), 2);
        /// let mut out = Prediction::default();
        /// online.predict_into([image.borrow(&cross)], &xs, 2, 1, &mut out)?;
        /// online.predict_with_into([image.borrow(&cross)], &xs, 2, 1, options, &mut out)?;
        /// let _ = online.predict_with([image.borrow(&cross)], &xs, 2, 1, options)?;
        /// let cov = online.predict_covariance([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1)?;
        /// assert_eq!(cov.mean.len(), 2);
        /// let _ = online.predict_covariance_with([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1, options)?;
        /// let _ = online.sample([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1, 2, 0)?;
        /// let _ = online.sample_with([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1, options, 2, 0)?;
        /// # Ok(())
        /// # }
        /// ```
    },
    covariance_doc = {
        /// # Examples
        ///
        /// ```rust
        /// use gprx::kernel::{KernelSpec, RbfKernel, ScalarDistance};
        /// use gprx::{Fixed, GaussianLikelihood, PredictOptions, Prediction, Sgpr};
        ///
        /// # fn main() -> Result<(), gprx::GprError> {
        /// let image = ScalarDistance::new();
        /// let kernel = image.kernel(RbfKernel::new(1.0)?) * KernelSpec::from(RbfKernel::new(2.0)?);
        /// let train = [0.0, 1.0, 4.0, 9.0, 4.0, 1.0, 0.0, 1.0];
        /// let x = [0.0, 0.5, 1.0, 1.5];
        /// let mut online = Sgpr::new(kernel, GaussianLikelihood::new(0.1)?)
        ///     .with_optimizer(Fixed)
        ///     .factor([image.borrow(&train)], 4, &x, 1, &[0.0, 1.0, 0.5, 0.25], &[0, 2])
        ///     .map_err(|(_, e)| e)?
        ///     .into_online();
        /// let (cross, query, xs) = ([0.25, 2.25, 2.25, 0.25], [0.0, 1.0, 1.0, 0.0], [0.25, 0.75]);
        /// let options = PredictOptions::default();
        /// let pred = online.predict([image.borrow(&cross)], &xs, 2, 1)?;
        /// assert_eq!(pred.mean.len(), 2);
        /// let mut out = Prediction::default();
        /// online.predict_into([image.borrow(&cross)], &xs, 2, 1, &mut out)?;
        /// online.predict_with_into([image.borrow(&cross)], &xs, 2, 1, options, &mut out)?;
        /// let _ = online.predict_with([image.borrow(&cross)], &xs, 2, 1, options)?;
        /// let cov = online.predict_covariance([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1)?;
        /// assert_eq!(cov.mean.len(), 2);
        /// let _ = online.predict_covariance_with([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1, options)?;
        /// let _ = online.sample([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1, 2, 0)?;
        /// let _ = online.sample_with([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1, options, 2, 0)?;
        /// # Ok(())
        /// # }
        /// ```
    },
);