gprx 0.2.0

Gaussian process regression in Rust: exact GPR, sparse GPR (VFE), and SVGP.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
//! The loaded models of a [`DistanceKernel`]: [`LoadedDistanceGpr`],
//! [`LoadedDistanceSgpr`], and [`LoadedDistanceSvgp`].

use std::path::Path;

use crate::error::GprError;
use crate::gpr::{FittedGpr, OnlineGpr};
use crate::kernel::{
    DistanceKernel, DistanceOnly, DistanceSlot, DistanceSource, PointUse, WithPoints,
};
use crate::optimizer::Fixed;
use crate::sgpr::{FittedSgpr, FixedInducing, OnlineSgpr};
use crate::svgp::FittedSvgp;
use crate::{
    DoublePrecision, MixedPrecision, PointId, PredictOptions, Prediction, ReevaluateKernel,
    SinglePrecision,
};

use super::config::{ModelJson, PointsJson};
use super::sparse::{self, SgprVariants};
use super::{PersistRegistry, Variants, load_precision, read_exact_config, widen};

/// Represents the prediction-only Exact model of a [`DistanceKernel`]
/// loaded from a persist directory written by [`FittedGpr::save`] or
/// [`OnlineGpr::save`].
///
/// One variant per precision and factor kind, as [`super::LoadedGpr`]. `C`
/// is the kernel's [`PointUse`]: loading a directory of the other marker,
/// or of a coordinate model, returns [`GprError::PersistFailed`] with
/// [`crate::PersistErrorKind::WrongModel`].
///
/// The loaded model owns the training `d²` it was saved with, and its
/// kernel's slots are new: a [`crate::kernel::ScalarDistance`] or
/// [`crate::kernel::ArdDistance`] from before the save names none of them.
/// Take the slots from [`Self::slots`] (in the order of
/// [`DistanceKernel::slots`] of the saved kernel) and bind each query's
/// sources to them. `predict`, `predict_with` (of either marker), [`Self::n`],
/// [`Self::is_online`], [`Self::slots`], and [`Self::to_kernel`] work on
/// any variant; match a variant for the typed model.
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{DistanceOnly, DistanceSlot, RbfKernel, ScalarDistance};
/// use gprx::persist::{LoadedDistanceGpr, PersistRegistry};
/// use gprx::{GaussianLikelihood, Gpr, PredictOptions, VarianceKind};
///
/// /// Names the precision (and factor kind) a load picked.
/// fn describe(model: &LoadedDistanceGpr<DistanceOnly>) -> &'static str {
///     match model {
///         LoadedDistanceGpr::Double(_) => "f64",
///         LoadedDistanceGpr::Single(_) => "f32",
///         LoadedDistanceGpr::Mixed(_) => "mixed",
///         LoadedDistanceGpr::Reevaluate(_) => "mixed, reevaluated",
///         LoadedDistanceGpr::OnlineDouble(_) => "online f64",
///         LoadedDistanceGpr::OnlineSingle(_) => "online f32",
///         LoadedDistanceGpr::OnlineMixed(_) => "online mixed",
///         LoadedDistanceGpr::OnlineReevaluate(_) => "online mixed, reevaluated",
///         _ => "a variant added later",
///     }
/// }
///
/// # fn main() -> Result<(), gprx::GprError> {
/// let image = ScalarDistance::new();
/// let train = vec![0.0, 1.0, 4.0, 1.0, 0.0, 1.0, 4.0, 1.0, 0.0];
/// let fitted = Gpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
///     .fit([image.from_vec(train)], 3, &[0.0, 1.0, 0.5])
///     .map_err(|(_, e)| e)?;
/// let dir = std::env::temp_dir().join(format!("gprx-doctest-distance-{}", std::process::id()));
/// let _ = std::fs::remove_dir_all(&dir);
/// fitted.save(&dir)?;
/// let loaded = LoadedDistanceGpr::<DistanceOnly>::load(&dir, &PersistRegistry::new())?;
/// assert_eq!(loaded.n(), 3);
/// assert!(!loaded.is_online());
/// assert_eq!(describe(&loaded), "f64");
/// // The loaded kernel has slots of its own: bind the query to them.
/// let [DistanceSlot::Scalar(slot)] = loaded.slots()[..] else {
///     panic!("one scalar slot");
/// };
/// assert_eq!(loaded.to_kernel().slots(), loaded.slots());
/// let cross = [0.25, 0.25, 2.25];
/// let got = loaded.predict([slot.borrow(&cross)], 1)?;
/// let want = fitted.predict([image.borrow(&cross)], 1)?;
/// assert_eq!(got.mean, want.mean);
/// let latent = PredictOptions { variance_kind: VarianceKind::Latent };
/// let got = loaded.predict_with([slot.borrow(&cross)], 1, latent)?;
/// assert_eq!(got, fitted.predict_with([image.borrow(&cross)], 1, latent)?);
/// let _ = std::fs::remove_dir_all(&dir);
/// # Ok(())
/// # }
/// ```
///
/// A kernel that also reads coordinates ([`WithPoints`]) loads as
/// `LoadedDistanceGpr<WithPoints>`, whose predict takes the query
/// coordinates too:
///
/// ```rust
/// use gprx::kernel::{DistanceSlot, KernelSpec, RbfKernel, ScalarDistance, WithPoints};
/// use gprx::persist::{LoadedDistanceGpr, PersistRegistry};
/// use gprx::{GaussianLikelihood, Gpr, PredictOptions};
///
/// # fn main() -> Result<(), gprx::GprError> {
/// let image = ScalarDistance::new();
/// let kernel = image.kernel(RbfKernel::new(1.0)?) * KernelSpec::from(RbfKernel::new(0.5)?);
/// let fitted = Gpr::new(kernel, GaussianLikelihood::new(0.1)?)
///     .fit([image.from_vec(vec![0.0, 1.0, 1.0, 0.0])], 2, &[0.0, 1.0], 1, &[0.0, 1.0])
///     .map_err(|(_, e)| e)?;
/// let dir = std::env::temp_dir().join(format!("gprx-doctest-distance-xs-{}", std::process::id()));
/// let _ = std::fs::remove_dir_all(&dir);
/// fitted.save(&dir)?;
/// let loaded = LoadedDistanceGpr::<WithPoints>::load(&dir, &PersistRegistry::new())?;
/// assert_eq!((loaded.n(), loaded.d()), (2, 1));
/// let [DistanceSlot::Scalar(slot)] = loaded.slots()[..] else {
///     panic!("one scalar slot");
/// };
/// // Two queries at 0.5 and 1.5: train × query squared distances, then coordinates.
/// let (cross, xs) = ([0.25, 0.25, 0.25, 2.25], [0.5, 1.5]);
/// let got = loaded.predict([slot.borrow(&cross)], &xs, 2, 1)?;
/// assert_eq!(got.mean, fitted.predict([image.borrow(&cross)], &xs, 2, 1)?.mean);
/// let options = PredictOptions::default();
/// assert_eq!(loaded.predict_with([slot.borrow(&cross)], &xs, 2, 1, options)?, got);
/// let _ = std::fs::remove_dir_all(&dir);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum LoadedDistanceGpr<C: PointUse = DistanceOnly> {
    /// Marks a [`DoublePrecision`] model.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    Double(FittedGpr<Fixed, DoublePrecision, DistanceKernel<C>>),
    /// Marks a [`SinglePrecision`] model.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    Single(FittedGpr<Fixed, SinglePrecision, DistanceKernel<C>>),
    /// Marks a promoted-storage [`MixedPrecision`] model.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    Mixed(FittedGpr<Fixed, MixedPrecision, DistanceKernel<C>>),
    /// Marks a [`MixedPrecision`]`<`[`ReevaluateKernel`]`>` model.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    Reevaluate(FittedGpr<Fixed, MixedPrecision<ReevaluateKernel>, DistanceKernel<C>>),
    /// Marks a [`DoublePrecision`] online model.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    OnlineDouble(OnlineGpr<Fixed, DoublePrecision, DistanceKernel<C>>),
    /// Marks a [`SinglePrecision`] online model.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    OnlineSingle(OnlineGpr<Fixed, SinglePrecision, DistanceKernel<C>>),
    /// Marks a promoted-storage [`MixedPrecision`] online model.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    OnlineMixed(OnlineGpr<Fixed, MixedPrecision, DistanceKernel<C>>),
    /// Marks a [`MixedPrecision`]`<`[`ReevaluateKernel`]`>` online model.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    OnlineReevaluate(OnlineGpr<Fixed, MixedPrecision<ReevaluateKernel>, DistanceKernel<C>>),
}

/// Runs `$body` on the model of any variant, bound to `$model`.
macro_rules! each_model {
    ($value:expr, $model:ident => $body:expr) => {
        match $value {
            LoadedDistanceGpr::Double($model) => $body,
            LoadedDistanceGpr::Single($model) => $body,
            LoadedDistanceGpr::Mixed($model) => $body,
            LoadedDistanceGpr::Reevaluate($model) => $body,
            LoadedDistanceGpr::OnlineDouble($model) => $body,
            LoadedDistanceGpr::OnlineSingle($model) => $body,
            LoadedDistanceGpr::OnlineMixed($model) => $body,
            LoadedDistanceGpr::OnlineReevaluate($model) => $body,
        }
    };
}

/// The distance marker the config of a model of `C` records.
fn points_of<C: PointUse>() -> PointsJson {
    PointsJson::of::<DistanceKernel<C>>()
}

impl<C: PointUse> LoadedDistanceGpr<C> {
    /// Reads `dir/config.json` and `dir/model.safetensors` written by the
    /// `save` of an Exact model of a [`DistanceKernel<C>`].
    ///
    /// Reads the training `d²` back into the store a fit would have made,
    /// with new slots; the factor is read as [`super::LoadedGpr::load`]
    /// reads it, or factored again at the saved `θ` when the file holds
    /// none.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::UnsupportedPersistVersion`] when `format_version`
    /// is not [`super::FORMAT_VERSION`], [`GprError::PersistFailed`] with
    /// [`crate::PersistErrorKind::WrongModel`] when the directory holds
    /// another model (a sparse one, a coordinate one, or one of the other
    /// [`PointUse`]), and [`GprError::PersistFailed`] when the JSON, the
    /// tensors, or a registry lookup is invalid, or when a `DistanceOnly`
    /// file's kernel holds a leaf that reads coordinates. A stored `d²` that
    /// is not finite, negative, or a non-zero diagonal is
    /// [`GprError::InvalidDistance`]. Saved maps that send the training data
    /// past `f64` are [`GprError::NonFiniteInput`]. Factorization errors use
    /// the same variants as the model's `factor`.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    pub fn load(dir: impl AsRef<Path>, registry: &PersistRegistry) -> Result<Self, GprError> {
        let dir = dir.as_ref();
        let config = read_exact_config(dir, Some(points_of::<C>()))?;
        by_precision!(config.persist_kind(), Self, |fitted, online| {
            load_precision(dir, registry, config, Variants { fitted, online })
        })
    }

    /// Returns the number of training points.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    pub fn n(&self) -> usize {
        each_model!(self, model => model.n())
    }

    /// Returns `true` for an [`OnlineGpr`] (`ldlt`), `false` for a
    /// [`FittedGpr`] (`llt`).
    ///
    /// See the example on [`LoadedDistanceGpr`].
    pub fn is_online(&self) -> bool {
        matches!(
            self,
            Self::OnlineDouble(_)
                | Self::OnlineSingle(_)
                | Self::OnlineMixed(_)
                | Self::OnlineReevaluate(_)
        )
    }

    /// Returns the slots of the loaded kernel, in the order of the saved
    /// kernel's [`DistanceKernel::slots`]. Bind the sources of a query to
    /// these.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    pub fn slots(&self) -> Vec<DistanceSlot> {
        each_model!(self, model => model.slots())
    }

    /// Returns a copy of the loaded kernel, on the slots of [`Self::slots`].
    ///
    /// See the example on [`LoadedDistanceGpr`].
    pub fn to_kernel(&self) -> DistanceKernel<C> {
        each_model!(self, model => model.to_kernel())
    }
}

impl LoadedDistanceGpr<DistanceOnly> {
    /// Returns the predictive mean and variance at `q` queries (observation
    /// variance), in `f64` whatever the stored precision. `sources` holds
    /// one source per slot of [`Self::slots`]: the `n × q` squared
    /// distances from the training points to the queries.
    ///
    /// # Errors
    ///
    /// Same as the variant's `predict`.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    pub fn predict<'s>(
        &self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        q: usize,
    ) -> Result<Prediction<f64>, GprError> {
        self.predict_with(sources, q, PredictOptions::default())
    }

    /// Returns the predictive mean and variance of [`Self::predict`], with the variance kind of `options`.
    ///
    /// # Errors
    ///
    /// Same as the variant's `predict_with`.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    pub fn predict_with<'s>(
        &self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        q: usize,
        options: PredictOptions,
    ) -> Result<Prediction<f64>, GprError> {
        each_model!(self, model => model.predict_with(sources, q, options).map(widen))
    }
}

impl LoadedDistanceGpr<WithPoints> {
    /// Returns the number of input features of the coordinate leaves.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    pub fn d(&self) -> usize {
        each_model!(self, model => model.d())
    }

    /// Returns the predictive mean and variance at the `q` queries `xs`
    /// (column-major `q × n_cols`), in `f64` whatever the stored precision.
    /// `sources` holds one source per slot of [`Self::slots`]: the `n × q`
    /// squared distances from the training points to the queries.
    ///
    /// # Errors
    ///
    /// Same as the variant's `predict`.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    pub fn predict<'s>(
        &self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        xs: &[f64],
        q: usize,
        n_cols: usize,
    ) -> Result<Prediction<f64>, GprError> {
        self.predict_with(sources, xs, q, n_cols, PredictOptions::default())
    }

    /// Returns the predictive mean and variance at the queries `xs`, with the variance kind of `options`.
    ///
    /// # Errors
    ///
    /// Same as the variant's `predict_with`.
    ///
    /// See the example on [`LoadedDistanceGpr`].
    pub fn predict_with<'s>(
        &self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        xs: &[f64],
        q: usize,
        n_cols: usize,
        options: PredictOptions,
    ) -> Result<Prediction<f64>, GprError> {
        each_model!(self, model => model.predict_with(sources, xs, q, n_cols, options).map(widen))
    }
}

/// Represents the prediction-only SGPR of a [`DistanceKernel`] loaded from
/// a persist directory written by `save` on a [`crate::FittedSgpr`] or
/// [`crate::OnlineSgpr`] of that kernel.
///
/// One variant per precision and model, as [`super::LoadedSgpr`]. The
/// training blocks are bound to new slots, as [`LoadedDistanceGpr`] binds
/// its `d²`: take them from [`Self::slots`]. The VFE system is factored
/// again at the saved `θ`. Loading a directory of the other [`PointUse`],
/// or of a coordinate model, returns [`GprError::PersistFailed`] with
/// [`crate::PersistErrorKind::WrongModel`].
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{DistanceOnly, DistanceSlot, RbfKernel, ScalarDistance};
/// use gprx::persist::{LoadedDistanceSgpr, PersistRegistry};
/// use gprx::{Fixed, GaussianLikelihood, PredictOptions, Sgpr, VarianceKind};
///
/// /// Names the precision (and factor kind) a load picked.
/// fn describe(model: &LoadedDistanceSgpr<DistanceOnly>) -> &'static str {
///     match model {
///         LoadedDistanceSgpr::Double(_) => "f64",
///         LoadedDistanceSgpr::Single(_) => "f32",
///         LoadedDistanceSgpr::Mixed(_) => "mixed",
///         LoadedDistanceSgpr::Reevaluate(_) => "mixed, reevaluated",
///         LoadedDistanceSgpr::OnlineDouble(_) => "online f64",
///         LoadedDistanceSgpr::OnlineSingle(_) => "online f32",
///         LoadedDistanceSgpr::OnlineMixed(_) => "online mixed",
///         LoadedDistanceSgpr::OnlineReevaluate(_) => "online mixed, reevaluated",
///         _ => "a variant added later",
///     }
/// }
///
/// # fn main() -> Result<(), gprx::GprError> {
/// let image = ScalarDistance::new();
/// // Three samples at 0, 1, 2; the inducing points are samples 0 and 2.
/// let train = [0.0, 1.0, 4.0, 4.0, 1.0, 0.0];
/// let fitted = Sgpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
///     .with_optimizer(Fixed)
///     .factor([image.borrow(&train)], 3, &[0.0, 1.0, 0.5], &[0, 2])
///     .map_err(|(_, e)| e)?;
/// let dir = std::env::temp_dir().join(format!("gprx-doctest-dsgpr-{}", std::process::id()));
/// let _ = std::fs::remove_dir_all(&dir);
/// fitted.save(&dir)?;
/// let loaded = LoadedDistanceSgpr::<DistanceOnly>::load(&dir, &PersistRegistry::new())?;
/// assert_eq!((loaded.n(), loaded.m()), (3, 2));
/// assert!(!loaded.is_online());
/// assert_eq!(loaded.inducing(), Some(&[0, 2][..]));
/// assert!(loaded.inducing_points().is_none());
/// let [DistanceSlot::Scalar(slot)] = loaded.slots()[..] else {
///     panic!("one scalar slot");
/// };
/// assert_eq!(loaded.to_kernel().slots(), loaded.slots());
/// // One query at 1.5: its squared distances to the two inducing points.
/// let cross = [2.25, 0.25];
/// let got = loaded.predict([slot.borrow(&cross)], 1)?;
/// assert_eq!(got.mean, fitted.predict([image.borrow(&cross)], 1)?.mean);
/// let latent = PredictOptions { variance_kind: VarianceKind::Latent };
/// let got = loaded.predict_with([slot.borrow(&cross)], 1, latent)?;
/// assert_eq!(got, fitted.predict_with([image.borrow(&cross)], 1, latent)?);
/// // An online model names its inducing points by `PointId`.
/// let online = fitted.into_online();
/// let ids = online.point_ids().to_vec();
/// online.save(&dir)?;
/// let loaded = LoadedDistanceSgpr::<DistanceOnly>::load(&dir, &PersistRegistry::new())?;
/// assert!(loaded.is_online());
/// assert_eq!(describe(&loaded), "online f64");
/// assert_eq!(loaded.inducing(), None);
/// let points: Option<Vec<_>> = loaded.inducing_points().map(Iterator::collect);
/// assert_eq!(points, Some(vec![ids[0], ids[2]]));
/// let _ = std::fs::remove_dir_all(&dir);
/// # Ok(())
/// # }
/// ```
///
/// A kernel that also reads coordinates ([`WithPoints`]) loads as
/// `LoadedDistanceSgpr<WithPoints>`, whose predict takes the query
/// coordinates too:
///
/// ```rust
/// use gprx::kernel::{DistanceSlot, KernelSpec, RbfKernel, ScalarDistance, WithPoints};
/// use gprx::persist::{LoadedDistanceSgpr, PersistRegistry};
/// use gprx::{Fixed, GaussianLikelihood, PredictOptions, 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, 4.0, 1.0, 0.0];
/// let fitted = Sgpr::new(kernel, GaussianLikelihood::new(0.1)?)
///     .with_optimizer(Fixed)
///     .factor([image.borrow(&train)], 3, &[0.0, 1.0, 2.0], 1, &[0.0, 1.0, 0.5], &[0, 2])
///     .map_err(|(_, e)| e)?;
/// let dir = std::env::temp_dir().join(format!("gprx-doctest-dsgpr-xs-{}", std::process::id()));
/// let _ = std::fs::remove_dir_all(&dir);
/// fitted.save(&dir)?;
/// let loaded = LoadedDistanceSgpr::<WithPoints>::load(&dir, &PersistRegistry::new())?;
/// assert_eq!(loaded.d(), 1);
/// let [DistanceSlot::Scalar(slot)] = loaded.slots()[..] else {
///     panic!("one scalar slot");
/// };
/// // One query at 1.5: inducing × query squared distances, then its coordinate.
/// let (cross, xs) = ([2.25, 0.25], [1.5]);
/// let got = loaded.predict([slot.borrow(&cross)], &xs, 1, 1)?;
/// assert_eq!(got.mean, fitted.predict([image.borrow(&cross)], &xs, 1, 1)?.mean);
/// let options = PredictOptions::default();
/// assert_eq!(loaded.predict_with([slot.borrow(&cross)], &xs, 1, 1, options)?, got);
/// let _ = std::fs::remove_dir_all(&dir);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum LoadedDistanceSgpr<C: PointUse = DistanceOnly> {
    /// Marks a [`DoublePrecision`] model.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    Double(FittedSgpr<Fixed, FixedInducing, DoublePrecision, DistanceKernel<C>>),
    /// Marks a [`SinglePrecision`] model.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    Single(FittedSgpr<Fixed, FixedInducing, SinglePrecision, DistanceKernel<C>>),
    /// Marks a promoted-storage [`MixedPrecision`] model.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    Mixed(FittedSgpr<Fixed, FixedInducing, MixedPrecision, DistanceKernel<C>>),
    /// Marks a [`MixedPrecision`]`<`[`ReevaluateKernel`]`>` model.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    Reevaluate(
        FittedSgpr<Fixed, FixedInducing, MixedPrecision<ReevaluateKernel>, DistanceKernel<C>>,
    ),
    /// Marks a [`DoublePrecision`] online model.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    OnlineDouble(OnlineSgpr<Fixed, DoublePrecision, DistanceKernel<C>>),
    /// Marks a [`SinglePrecision`] online model.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    OnlineSingle(OnlineSgpr<Fixed, SinglePrecision, DistanceKernel<C>>),
    /// Marks a promoted-storage [`MixedPrecision`] online model.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    OnlineMixed(OnlineSgpr<Fixed, MixedPrecision, DistanceKernel<C>>),
    /// Marks a [`MixedPrecision`]`<`[`ReevaluateKernel`]`>` online model.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    OnlineReevaluate(OnlineSgpr<Fixed, MixedPrecision<ReevaluateKernel>, DistanceKernel<C>>),
}

/// Runs `$body` on the model of any [`LoadedDistanceSgpr`] variant.
macro_rules! each_sgpr {
    ($value:expr, $model:ident => $body:expr) => {
        match $value {
            LoadedDistanceSgpr::Double($model) => $body,
            LoadedDistanceSgpr::Single($model) => $body,
            LoadedDistanceSgpr::Mixed($model) => $body,
            LoadedDistanceSgpr::Reevaluate($model) => $body,
            LoadedDistanceSgpr::OnlineDouble($model) => $body,
            LoadedDistanceSgpr::OnlineSingle($model) => $body,
            LoadedDistanceSgpr::OnlineMixed($model) => $body,
            LoadedDistanceSgpr::OnlineReevaluate($model) => $body,
        }
    };
}

impl<C: PointUse> LoadedDistanceSgpr<C> {
    /// Reads `dir/config.json` and `dir/model.safetensors` written by the
    /// `save` of an SGPR (or online SGPR) of a [`DistanceKernel<C>`].
    ///
    /// # Errors
    ///
    /// Returns [`GprError::UnsupportedPersistVersion`] when `format_version`
    /// is not [`super::FORMAT_VERSION`], [`GprError::PersistFailed`] with
    /// [`crate::PersistErrorKind::WrongModel`] when the directory holds
    /// another model, and [`GprError::PersistFailed`] when the JSON, the
    /// tensors, or a registry lookup is invalid, when a `DistanceOnly`
    /// file's kernel holds a leaf that reads coordinates, when the number of
    /// inducing indices is not `m`, or when a `WithPoints` file's `z` or
    /// `z_train` is not the training rows its inducing indices name. The
    /// inducing indices and the stored blocks are checked as a fit checks
    /// them: [`GprError::IndexOutOfRange`] for an index not below `n`,
    /// [`GprError::InvalidConfig`] for an index listed twice, and
    /// [`GprError::InvalidDistance`] for a value. Saved maps that send the
    /// training data past `f64` are [`GprError::NonFiniteInput`].
    /// Factorization errors use the same variants as the model's `factor`.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    pub fn load(dir: impl AsRef<Path>, registry: &PersistRegistry) -> Result<Self, GprError> {
        let dir = dir.as_ref();
        let config = sparse::read_config(
            dir,
            &[ModelJson::Sgpr, ModelJson::OnlineSgpr],
            Some(points_of::<C>()),
        )?;
        by_precision!(config.persist_kind(), Self, |fitted, online| {
            sparse::load_sgpr_as(dir, &config, registry, SgprVariants { fitted, online })
        })
    }

    /// Returns the number of training points.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    pub fn n(&self) -> usize {
        each_sgpr!(self, model => model.n())
    }

    /// Returns the number of inducing points.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    pub fn m(&self) -> usize {
        each_sgpr!(self, model => model.m())
    }

    /// Returns the training samples that are the inducing points of a
    /// fitted variant, in the order of the rows of a prediction's blocks,
    /// or `None` for an [`OnlineSgpr`] variant: its points are named by
    /// [`Self::inducing_points`], since a delete shifts their places.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    pub fn inducing(&self) -> Option<&[usize]> {
        match self {
            Self::Double(model) => Some(model.inducing()),
            Self::Single(model) => Some(model.inducing()),
            Self::Mixed(model) => Some(model.inducing()),
            Self::Reevaluate(model) => Some(model.inducing()),
            Self::OnlineDouble(_)
            | Self::OnlineSingle(_)
            | Self::OnlineMixed(_)
            | Self::OnlineReevaluate(_) => None,
        }
    }

    /// Returns the [`PointId`]s of the inducing points of an
    /// [`OnlineSgpr`] variant, as [`OnlineSgpr::inducing_points`], or
    /// `None` for a fitted variant (see [`Self::inducing`]).
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    pub fn inducing_points(&self) -> Option<impl Iterator<Item = PointId> + '_> {
        let ids = match self {
            Self::OnlineDouble(model) => Some(model.inducing_point_ids()),
            Self::OnlineSingle(model) => Some(model.inducing_point_ids()),
            Self::OnlineMixed(model) => Some(model.inducing_point_ids()),
            Self::OnlineReevaluate(model) => Some(model.inducing_point_ids()),
            Self::Double(_) | Self::Single(_) | Self::Mixed(_) | Self::Reevaluate(_) => None,
        };
        ids.map(|ids| ids.iter().copied())
    }

    /// Returns `true` for an [`OnlineSgpr`] variant.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    pub fn is_online(&self) -> bool {
        matches!(
            self,
            Self::OnlineDouble(_)
                | Self::OnlineSingle(_)
                | Self::OnlineMixed(_)
                | Self::OnlineReevaluate(_)
        )
    }

    /// Returns the slots of the loaded kernel, in the order of the saved
    /// kernel's [`DistanceKernel::slots`].
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    pub fn slots(&self) -> Vec<DistanceSlot> {
        each_sgpr!(self, model => model.slots())
    }

    /// Returns a copy of the loaded kernel, on the slots of [`Self::slots`].
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    pub fn to_kernel(&self) -> DistanceKernel<C> {
        each_sgpr!(self, model => model.to_kernel())
    }
}

impl LoadedDistanceSgpr<DistanceOnly> {
    /// Returns the predictive mean and observation variance at `q` queries,
    /// in `f64` whatever the stored precision. `sources` holds one source
    /// per slot of [`Self::slots`]: the `m × q` squared distances
    /// from the inducing points ([`Self::inducing`]) to the queries.
    ///
    /// # Errors
    ///
    /// Same as the variant's `predict`.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    pub fn predict<'s>(
        &self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        q: usize,
    ) -> Result<Prediction<f64>, GprError> {
        self.predict_with(sources, q, PredictOptions::default())
    }

    /// Returns the predictive mean and variance of [`Self::predict`], with the variance kind of `options`.
    ///
    /// # Errors
    ///
    /// Same as the variant's `predict_with`.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    pub fn predict_with<'s>(
        &self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        q: usize,
        options: PredictOptions,
    ) -> Result<Prediction<f64>, GprError> {
        each_sgpr!(self, model => model.predict_with(sources, q, options).map(widen))
    }
}

impl LoadedDistanceSgpr<WithPoints> {
    /// Returns the number of input features of the coordinate leaves.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    pub fn d(&self) -> usize {
        each_sgpr!(self, model => model.d())
    }

    /// Returns the predictive mean and observation variance at the `q`
    /// queries `xs` (column-major `q × n_cols`), in `f64` whatever the
    /// stored precision. `sources` holds one source per slot of
    /// [`Self::slots`], from the inducing points to the queries.
    ///
    /// # Errors
    ///
    /// Same as the variant's `predict`.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    pub fn predict<'s>(
        &self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        xs: &[f64],
        q: usize,
        n_cols: usize,
    ) -> Result<Prediction<f64>, GprError> {
        self.predict_with(sources, xs, q, n_cols, PredictOptions::default())
    }

    /// Returns the predictive mean and variance at the queries `xs`, with the variance kind of `options`.
    ///
    /// # Errors
    ///
    /// Same as the variant's `predict_with`.
    ///
    /// See the example on [`LoadedDistanceSgpr`].
    pub fn predict_with<'s>(
        &self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        xs: &[f64],
        q: usize,
        n_cols: usize,
        options: PredictOptions,
    ) -> Result<Prediction<f64>, GprError> {
        each_sgpr!(self, model => model.predict_with(sources, xs, q, n_cols, options).map(widen))
    }
}

/// Represents the prediction-only SVGP of a [`DistanceKernel`] loaded from
/// a persist directory written by `save` on a [`crate::FittedSvgp`] of that
/// kernel.
///
/// One variant per precision, as [`super::LoadedSvgp`]. The training blocks
/// are bound to new slots ([`Self::slots`]); `K_mm` is factored again at
/// the saved `θ`, with the saved `q(u)`. Loading a directory of the other
/// [`PointUse`], or of a coordinate model, returns
/// [`GprError::PersistFailed`] with [`crate::PersistErrorKind::WrongModel`].
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{DistanceOnly, DistanceSlot, RbfKernel, ScalarDistance};
/// use gprx::persist::{LoadedDistanceSvgp, PersistRegistry};
/// use gprx::{GaussianLikelihood, PredictOptions, Svgp, VarianceKind};
///
/// /// Names the precision (and factor kind) a load picked.
/// fn describe(model: &LoadedDistanceSvgp<DistanceOnly>) -> &'static str {
///     match model {
///         LoadedDistanceSvgp::Double(_) => "f64",
///         LoadedDistanceSvgp::Single(_) => "f32",
///         LoadedDistanceSvgp::Mixed(_) => "mixed",
///         LoadedDistanceSvgp::Reevaluate(_) => "mixed, reevaluated",
///         _ => "a variant added later",
///     }
/// }
///
/// # fn main() -> Result<(), gprx::GprError> {
/// let image = ScalarDistance::new();
/// let train = [0.0, 1.0, 4.0, 4.0, 1.0, 0.0];
/// let fitted = Svgp::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
///     .factor([image.borrow(&train)], 3, &[0.0, 1.0, 0.5], &[0, 2])
///     .map_err(|(_, e)| e)?;
/// let dir = std::env::temp_dir().join(format!("gprx-doctest-dsvgp-{}", std::process::id()));
/// let _ = std::fs::remove_dir_all(&dir);
/// fitted.save(&dir)?;
/// let loaded = LoadedDistanceSvgp::<DistanceOnly>::load(&dir, &PersistRegistry::new())?;
/// assert_eq!((loaded.n(), loaded.m()), (3, 2));
/// assert_eq!(loaded.inducing(), &[0, 2]);
/// assert_eq!(describe(&loaded), "f64");
/// let [DistanceSlot::Scalar(slot)] = loaded.slots()[..] else {
///     panic!("one scalar slot");
/// };
/// assert_eq!(loaded.to_kernel().slots(), loaded.slots());
/// // One query at 1.5: its squared distances to the two inducing points.
/// let cross = [2.25, 0.25];
/// let got = loaded.predict([slot.borrow(&cross)], 1)?;
/// assert_eq!(got.mean, fitted.predict([image.borrow(&cross)], 1)?.mean);
/// let latent = PredictOptions { variance_kind: VarianceKind::Latent };
/// let got = loaded.predict_with([slot.borrow(&cross)], 1, latent)?;
/// assert_eq!(got, fitted.predict_with([image.borrow(&cross)], 1, latent)?);
/// let _ = std::fs::remove_dir_all(&dir);
/// # Ok(())
/// # }
/// ```
///
/// A kernel that also reads coordinates ([`WithPoints`]) loads as
/// `LoadedDistanceSvgp<WithPoints>`, whose predict takes the query
/// coordinates too:
///
/// ```rust
/// use gprx::kernel::{DistanceSlot, KernelSpec, RbfKernel, ScalarDistance, WithPoints};
/// use gprx::persist::{LoadedDistanceSvgp, PersistRegistry};
/// use gprx::{GaussianLikelihood, PredictOptions, Svgp};
///
/// # 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, 4.0, 1.0, 0.0];
/// let fitted = Svgp::new(kernel, GaussianLikelihood::new(0.1)?)
///     .factor([image.borrow(&train)], 3, &[0.0, 1.0, 2.0], 1, &[0.0, 1.0, 0.5], &[0, 2])
///     .map_err(|(_, e)| e)?;
/// let dir = std::env::temp_dir().join(format!("gprx-doctest-dsvgp-xs-{}", std::process::id()));
/// let _ = std::fs::remove_dir_all(&dir);
/// fitted.save(&dir)?;
/// let loaded = LoadedDistanceSvgp::<WithPoints>::load(&dir, &PersistRegistry::new())?;
/// assert_eq!(loaded.d(), 1);
/// let [DistanceSlot::Scalar(slot)] = loaded.slots()[..] else {
///     panic!("one scalar slot");
/// };
/// // One query at 1.5: inducing × query squared distances, then its coordinate.
/// let (cross, xs) = ([2.25, 0.25], [1.5]);
/// let got = loaded.predict([slot.borrow(&cross)], &xs, 1, 1)?;
/// assert_eq!(got.mean, fitted.predict([image.borrow(&cross)], &xs, 1, 1)?.mean);
/// let options = PredictOptions::default();
/// assert_eq!(loaded.predict_with([slot.borrow(&cross)], &xs, 1, 1, options)?, got);
/// let _ = std::fs::remove_dir_all(&dir);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum LoadedDistanceSvgp<C: PointUse = DistanceOnly> {
    /// Marks a [`DoublePrecision`] model.
    ///
    /// See the example on [`LoadedDistanceSvgp`].
    Double(FittedSvgp<DoublePrecision, DistanceKernel<C>>),
    /// Marks a [`SinglePrecision`] model.
    ///
    /// See the example on [`LoadedDistanceSvgp`].
    Single(FittedSvgp<SinglePrecision, DistanceKernel<C>>),
    /// Marks a promoted-storage [`MixedPrecision`] model.
    ///
    /// See the example on [`LoadedDistanceSvgp`].
    Mixed(FittedSvgp<MixedPrecision, DistanceKernel<C>>),
    /// Marks a [`MixedPrecision`]`<`[`ReevaluateKernel`]`>` model.
    ///
    /// See the example on [`LoadedDistanceSvgp`].
    Reevaluate(FittedSvgp<MixedPrecision<ReevaluateKernel>, DistanceKernel<C>>),
}

/// Runs `$body` on the model of any [`LoadedDistanceSvgp`] variant.
macro_rules! each_svgp {
    ($value:expr, $model:ident => $body:expr) => {
        match $value {
            LoadedDistanceSvgp::Double($model) => $body,
            LoadedDistanceSvgp::Single($model) => $body,
            LoadedDistanceSvgp::Mixed($model) => $body,
            LoadedDistanceSvgp::Reevaluate($model) => $body,
        }
    };
}

impl<C: PointUse> LoadedDistanceSvgp<C> {
    /// Reads `dir/config.json` and `dir/model.safetensors` written by the
    /// `save` of an SVGP of a [`DistanceKernel<C>`].
    ///
    /// # Errors
    ///
    /// Same as [`LoadedDistanceSgpr::load`], plus
    /// [`GprError::PersistFailed`] when the saved `q(u)` is not finite or
    /// its `L` is not lower triangular with a positive diagonal.
    ///
    /// See the example on [`LoadedDistanceSvgp`].
    pub fn load(dir: impl AsRef<Path>, registry: &PersistRegistry) -> Result<Self, GprError> {
        let dir = dir.as_ref();
        let config = sparse::read_config(dir, &[ModelJson::Svgp], Some(points_of::<C>()))?;
        by_precision!(config.persist_kind(), Self, |fitted| {
            sparse::load_svgp_as(dir, &config, registry, fitted)
        })
    }

    /// Returns the number of training points.
    ///
    /// See the example on [`LoadedDistanceSvgp`].
    pub fn n(&self) -> usize {
        each_svgp!(self, model => model.n())
    }

    /// Returns the number of inducing points.
    ///
    /// See the example on [`LoadedDistanceSvgp`].
    pub fn m(&self) -> usize {
        each_svgp!(self, model => model.m())
    }

    /// Returns the training samples that are the inducing points.
    ///
    /// See the example on [`LoadedDistanceSvgp`].
    pub fn inducing(&self) -> &[usize] {
        each_svgp!(self, model => model.inducing())
    }

    /// Returns the slots of the loaded kernel, in the order of the saved
    /// kernel's [`DistanceKernel::slots`].
    ///
    /// See the example on [`LoadedDistanceSvgp`].
    pub fn slots(&self) -> Vec<DistanceSlot> {
        each_svgp!(self, model => model.slots())
    }

    /// Returns a copy of the loaded kernel, on the slots of [`Self::slots`].
    ///
    /// See the example on [`LoadedDistanceSvgp`].
    pub fn to_kernel(&self) -> DistanceKernel<C> {
        each_svgp!(self, model => model.to_kernel())
    }
}

impl LoadedDistanceSvgp<DistanceOnly> {
    /// Returns the predictive mean and observation variance at `q` queries,
    /// in `f64` whatever the stored precision; `sources` as
    /// [`LoadedDistanceSgpr::predict`] takes them.
    ///
    /// # Errors
    ///
    /// Same as the variant's `predict`.
    ///
    /// See the example on [`LoadedDistanceSvgp`].
    pub fn predict<'s>(
        &self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        q: usize,
    ) -> Result<Prediction<f64>, GprError> {
        self.predict_with(sources, q, PredictOptions::default())
    }

    /// Returns the predictive mean and variance of [`Self::predict`], with the variance kind of `options`.
    ///
    /// # Errors
    ///
    /// Same as the variant's `predict_with`.
    ///
    /// See the example on [`LoadedDistanceSvgp`].
    pub fn predict_with<'s>(
        &self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        q: usize,
        options: PredictOptions,
    ) -> Result<Prediction<f64>, GprError> {
        each_svgp!(self, model => model.predict_with(sources, q, options).map(widen))
    }
}

impl LoadedDistanceSvgp<WithPoints> {
    /// Returns the number of input features of the coordinate leaves.
    ///
    /// See the example on [`LoadedDistanceSvgp`].
    pub fn d(&self) -> usize {
        each_svgp!(self, model => model.d())
    }

    /// Returns the predictive mean and observation variance at the `q`
    /// queries `xs` (column-major `q × n_cols`); `sources` as the `predict`
    /// of a `LoadedDistanceSgpr<WithPoints>` ([`LoadedDistanceSgpr`]) takes
    /// them.
    ///
    /// # Errors
    ///
    /// Same as the variant's `predict`.
    ///
    /// See the example on [`LoadedDistanceSvgp`].
    pub fn predict<'s>(
        &self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        xs: &[f64],
        q: usize,
        n_cols: usize,
    ) -> Result<Prediction<f64>, GprError> {
        self.predict_with(sources, xs, q, n_cols, PredictOptions::default())
    }

    /// Returns the predictive mean and variance at the queries `xs`, with the variance kind of `options`.
    ///
    /// # Errors
    ///
    /// Same as the variant's `predict_with`.
    ///
    /// See the example on [`LoadedDistanceSvgp`].
    pub fn predict_with<'s>(
        &self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        xs: &[f64],
        q: usize,
        n_cols: usize,
        options: PredictOptions,
    ) -> Result<Prediction<f64>, GprError> {
        each_svgp!(self, model => model.predict_with(sources, xs, q, n_cols, options).map(widen))
    }
}