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
//! Prediction results and options of an Exact GPR, and the predict family
//! every model of a [`DistanceKernel`](crate::kernel::DistanceKernel)
//! shares ([`distance_predict`]).

use faer::Mat;

use crate::error::{CholeskyStage, GprError};
use crate::kernel::{DistanceSource, KernelScalar};
use crate::linalg::{cholesky_lower_with_retries, llt_scratch, mul_lower_vec};
use crate::policy::JitterPolicy;

/// Records which predictive variance [`Prediction`] reports.
///
/// # Examples
///
/// ```rust
/// use gprx::VarianceKind;
///
/// assert_eq!(VarianceKind::default(), VarianceKind::Observation);
/// ```
///
/// The example on [`PredictOptions`] predicts with [`VarianceKind::Latent`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum VarianceKind {
    /// Marks a variance of the latent function `f*`, without observation noise.
    Latent,
    /// Marks a variance of a new observation `y*`, including `σn²`.
    ///
    /// This is the default.
    #[default]
    Observation,
}

/// Represents the options of a prediction.
///
/// [`crate::FittedGpr`], [`crate::OnlineGpr`], [`crate::FittedSgpr`],
/// [`crate::OnlineSgpr`], and [`crate::FittedSvgp`] take it in
/// `predict_with`, `predict_with_into`, `predict_covariance_with`, and
/// `sample_with`. The loaded models ([`crate::persist::LoadedGpr`] and the
/// other `Loaded*` types) take it in `predict_with` only. The methods
/// without `_with` use [`PredictOptions::default`].
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{KernelSpec, RbfKernel};
/// use gprx::{GaussianLikelihood, Gpr, PredictOptions, VarianceKind};
///
/// # fn main() -> Result<(), gprx::GprError> {
/// let opts = PredictOptions {
///     variance_kind: VarianceKind::Latent,
/// };
/// assert_eq!(opts.variance_kind, VarianceKind::Latent);
/// assert_eq!(PredictOptions::default().variance_kind, VarianceKind::Observation);
///
/// let fitted = Gpr::new(
///     KernelSpec::from(RbfKernel::new(1.0)?),
///     GaussianLikelihood::new(0.1)?,
/// )
/// .fit(&[0.0, 1.0], 2, 1, &[0.0, 1.0])
/// .map_err(|(_, e)| e)?;
/// let latent = fitted.predict_with(&[0.5], 1, 1, opts)?;
/// let observed = fitted.predict(&[0.5], 1, 1)?;
/// // Observation variance adds `σn²` to the latent variance.
/// let noise = fitted.likelihood().noise_variance();
/// assert!((observed.variance[0] - latent.variance[0] - noise).abs() < 1e-9);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PredictOptions {
    /// Records which variance to return.
    ///
    /// Defaults to [`VarianceKind::Observation`].
    pub variance_kind: VarianceKind,
}

impl Default for PredictOptions {
    fn default() -> Self {
        Self {
            variance_kind: VarianceKind::Observation,
        }
    }
}

/// Represents the predictive mean and (diagonal) variance at the query points.
///
/// `T` is the predict scalar of the model's precision
/// ([`crate::PrecisionPolicy::Refine`]): `f64` for [`crate::DoublePrecision`]
/// (the default) and [`crate::MixedPrecision`], `f32` for
/// [`crate::SinglePrecision`].
///
/// [`FittedGpr::predict_into`](crate::FittedGpr::predict_into) reuses `mean` / `variance` capacity when the
/// query length matches a previous call. Query–query covariance is
/// [`PredictiveCovariance`], not a field here.
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{KernelSpec, RbfKernel};
/// use gprx::{GaussianLikelihood, Gpr, Prediction, SinglePrecision, VarianceKind};
///
/// # fn main() -> Result<(), gprx::GprError> {
/// let pred = Prediction {
///     mean: vec![0.0],
///     variance: vec![1.0],
///     variance_kind: VarianceKind::Observation,
/// };
/// assert_eq!(pred.mean.len(), pred.variance.len());
///
/// // An `f32` model predicts `Prediction<f32>`.
/// let mut fitted = Gpr::new(
///     KernelSpec::from(RbfKernel::new(1.0)?),
///     GaussianLikelihood::new(0.1)?,
/// )
/// .with_precision::<SinglePrecision>()
/// .fit(&[0.0, 1.0], 2, 1, &[0.0, 1.0])
/// .map_err(|(_, e)| e)?;
/// let single: Prediction<f32> = fitted.predict(&[0.25, 0.75], 2, 1)?;
/// assert_eq!(single.variance_kind, VarianceKind::Observation);
///
/// // `predict_into` writes into a `Prediction` the caller keeps.
/// let mut out = Prediction::default();
/// fitted.predict_into(&[0.25, 0.75], 2, 1, &mut out)?;
/// assert_eq!(out, single);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct Prediction<T = f64> {
    /// Holds the predictive mean on the original target scale.
    pub mean: Vec<T>,
    /// Holds the predictive variance on the original target scale.
    pub variance: Vec<T>,
    /// Records whether [`Self::variance`] is latent or observation variance.
    pub variance_kind: VarianceKind,
}

/// Represents the predictive mean and query–query covariance at the query points.
///
/// [`crate::FittedGpr::predict_covariance`] and the `predict_covariance`
/// methods of the other models return this type. `T` is the predict scalar,
/// as on [`Prediction`]: `f32` for a [`crate::SinglePrecision`] model, `f64`
/// otherwise. `covariance` is
/// packed column-major as an `m × m` matrix: index `col * m + row`. The
/// diagonal matches [`Prediction::variance`] for the same query and
/// [`PredictOptions`]. Observation covariance adds `σn²` on the diagonal in
/// the transformed space, then the target transform scales every entry by
/// the same `s²` as variance.
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{KernelSpec, RbfKernel};
/// use gprx::{Gpr, GaussianLikelihood};
///
/// # fn main() -> Result<(), gprx::GprError> {
/// let kernel = KernelSpec::from(RbfKernel::new(1.0)?);
/// let likelihood = GaussianLikelihood::new(0.1)?;
/// let gpr = Gpr::new(kernel, likelihood);
/// let fitted = gpr.fit(&[0.0, 1.0], 2, 1, &[0.0, 1.0]).map_err(|(_, e)| e)?;
/// let cov = fitted.predict_covariance(&[0.25, 0.75], 2, 1)?;
/// assert_eq!(cov.covariance.len(), cov.mean.len() * cov.mean.len());
/// assert_eq!(cov.variance_kind, gprx::VarianceKind::Observation);
/// // The diagonal is the variance `predict` reports.
/// let pred = fitted.predict(&[0.25, 0.75], 2, 1)?;
/// assert!((cov.covariance[3] - pred.variance[1]).abs() < 1e-9);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct PredictiveCovariance<T = f64> {
    /// Holds the predictive mean on the original target scale.
    pub mean: Vec<T>,
    /// Holds the predictive covariance, packed column-major `m × m`.
    pub covariance: Vec<T>,
    /// Records whether the diagonal of [`Self::covariance`] is latent or observation.
    pub variance_kind: VarianceKind,
}

impl<T> Default for Prediction<T> {
    fn default() -> Self {
        Self {
            mean: Vec::new(),
            variance: Vec::new(),
            variance_kind: VarianceKind::default(),
        }
    }
}

impl<T> Default for PredictiveCovariance<T> {
    fn default() -> Self {
        Self {
            mean: Vec::new(),
            covariance: Vec::new(),
            variance_kind: VarianceKind::default(),
        }
    }
}

impl<T: KernelScalar> PredictiveCovariance<T> {
    /// `n_draws` posterior draws, column-major `m × n_draws`: each column is
    /// `μ + L z` with `z ∼ N(0, I)` from gprx's seeded generator at `seed` (Xoshiro256++, the same on every platform), and
    /// `L` the Cholesky factor of [`Self::covariance`], retried with `jitter`.
    /// Zero draws return an empty vector without factoring.
    pub(crate) fn draw(
        &self,
        n_draws: usize,
        seed: u64,
        jitter: JitterPolicy,
    ) -> Result<Vec<T>, GprError> {
        if n_draws == 0 {
            return Ok(Vec::new());
        }
        let m = self.mean.len();
        let mut a = Mat::<T>::zeros(m, m);
        for col in 0..m {
            for row in 0..m {
                a[(row, col)] = self.covariance[col * m + row];
            }
        }
        let mut scratch = llt_scratch::<T>(m);
        cholesky_lower_with_retries(
            &mut a,
            &mut scratch,
            jitter.retry_jitters(),
            CholeskyStage::Predict,
        )?;
        let mut rng = crate::rng::seeded_rng(seed);
        let zero = T::from_f64(0.0);
        let mut out = vec![zero; m * n_draws];
        let mut z = vec![zero; m];
        let mut lz = vec![zero; m];
        for draw in 0..n_draws {
            for slot in &mut z {
                *slot = T::from_f64(crate::rng::unit_normal(&mut rng));
            }
            mul_lower_vec(a.as_ref(), &z, &mut lz);
            let col = &mut out[draw * m..(draw + 1) * m];
            for i in 0..m {
                col[i] = self.mean[i] + lz[i];
            }
        }
        Ok(out)
    }
}

/// The query coordinates of a distance model: none for a
/// [`DistanceOnly`](crate::kernel::DistanceOnly) kernel, the column-major
/// `m × n_cols` coordinates of the coordinate leaves for a
/// [`WithPoints`](crate::kernel::WithPoints) kernel.
#[derive(Clone, Copy, Debug)]
pub(crate) struct QueryPoints<'a> {
    pub(crate) xs: &'a [f64],
    pub(crate) n_cols: usize,
}

impl QueryPoints<'static> {
    /// A kernel without coordinate leaves.
    pub(crate) const NONE: Self = Self { xs: &[], n_cols: 0 };
}

/// The query of a fitted model whose kernel reads supplied distances. The
/// public predict family [`distance_predict`] writes calls these, so every
/// model checks and reads a query in one place.
pub(crate) trait DistanceQuery {
    /// The predict scalar.
    type Refine;

    /// Mean and variance at `q` queries: `cross` is one source per slot of
    /// the squared distances from the model's points to the queries (`n × q`
    /// from the training points for an Exact model, from the inducing
    /// points for a sparse one).
    fn query_distances<'s>(
        &self,
        cross: impl IntoIterator<Item = DistanceSource<'s>>,
        points: QueryPoints<'_>,
        q: usize,
        options: PredictOptions,
    ) -> Result<Prediction<Self::Refine>, GprError>;

    /// [`Self::query_distances`] into `out`, through the model's buffers.
    fn query_distances_into<'s>(
        &mut self,
        cross: impl IntoIterator<Item = DistanceSource<'s>>,
        points: QueryPoints<'_>,
        q: usize,
        options: PredictOptions,
        out: &mut Prediction<Self::Refine>,
    ) -> Result<(), GprError>;

    /// Mean and query × query covariance: `square` is one source per slot
    /// of the `q × q` query squares.
    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<Self::Refine>, GprError>;

    /// The jitter retries of a posterior draw.
    fn draw_jitter(&self) -> JitterPolicy;
}

/// The public predict family of a model of a distance kernel:
/// `predict`, `predict_into`, `predict_with`, `predict_with_into`,
/// `predict_covariance`, `predict_covariance_with`, `sample`, and
/// `sample_with`, over [`DistanceQuery`].
///
/// `refine` is the model's predict scalar. `args` are the coordinate
/// arguments before the query count `count` and `tail` those after it
/// (none for a `DistanceOnly` kernel); `points` is the [`QueryPoints`]
/// they make. `cross` names the block of one slot, from the model's points
/// to the queries. `reads` says how the model reads a
/// table; `predict_doc` / `covariance_doc` end the docs of the `predict`
/// and the covariance methods.
macro_rules! distance_predict {
    (
        impl [$($gen:tt)*] $model:ty,
        refine = $refine:ty,
        args = ($($arg:ident: $ty:ty),*),
        tail = ($($tail:ident: $tty:ty),*),
        points = $points:expr,
        count = $count:ident,
        cross = { $(#[$cross:meta])* },
        reads = { $(#[$reads:meta])* },
        predict_doc = { $(#[$pdoc:meta])* },
        covariance_doc = { $(#[$cdoc:meta])* },
    ) => {
        impl<$($gen)*> $model {
            /// Predicts at the queries with [`PredictOptions::default`]
            /// (observation variance).
            ///
            /// `sources` holds one source per slot:
            $(#[$cross])*
            $(#[$reads])*
            ///
            /// # Errors
            ///
            #[doc = concat!("Returns [`GprError::EmptyInput`] if `", stringify!($count), "` is zero,")]
            /// [`GprError::LengthMismatch`] if a table has the wrong length,
            /// [`GprError::DistanceSlot`] if a source names a slot the kernel
            /// does not read (on a loaded model, a slot of the model that was
            /// saved), two name one slot, or a slot has none,
            /// [`GprError::InvalidDistance`] for a value that is not finite or
            /// is negative (see [`crate::kernel::DistanceSource::tidy`]), and
            /// the query errors of the coordinate model's `predict`.
            ///
            $(#[$pdoc])*
            pub fn predict<'s>(
                &self,
                sources: impl IntoIterator<Item = DistanceSource<'s>>,
                $($arg: $ty,)*
                $count: usize,
                $($tail: $tty,)*
            ) -> Result<Prediction<$refine>, GprError> {
                self.predict_with(sources, $($arg,)* $count, $($tail,)* PredictOptions::default())
            }

            /// Writes `predict` of these sources into `out`, reusing its capacity.
            ///
            /// # Errors
            ///
            /// Same as `predict` of these sources. On an error the contents of `out`
            /// are unspecified: a value a table fails on can be found after
            /// part of the kernel block is written.
            ///
            $(#[$pdoc])*
            pub fn predict_into<'s>(
                &mut self,
                sources: impl IntoIterator<Item = DistanceSource<'s>>,
                $($arg: $ty,)*
                $count: usize,
                $($tail: $tty,)*
                out: &mut Prediction<$refine>,
            ) -> Result<(), GprError> {
                self.predict_with_into(sources, $($arg,)* $count, $($tail,)* PredictOptions::default(), out)
            }

            /// Predicts with an explicit variance kind.
            ///
            /// # Errors
            ///
            /// Same as `predict` of these sources.
            ///
            $(#[$pdoc])*
            pub fn predict_with<'s>(
                &self,
                sources: impl IntoIterator<Item = DistanceSource<'s>>,
                $($arg: $ty,)*
                $count: usize,
                $($tail: $tty,)*
                options: PredictOptions,
            ) -> Result<Prediction<$refine>, GprError> {
                $crate::prediction::DistanceQuery::query_distances(
                    self,
                    sources,
                    $points,
                    $count,
                    options,
                )
            }

            /// Writes `predict_with` of these sources into `out`, reusing its capacity.
            ///
            /// # Errors
            ///
            /// Same as `predict_into` of these sources, `out` included.
            ///
            $(#[$pdoc])*
            pub fn predict_with_into<'s>(
                &mut self,
                sources: impl IntoIterator<Item = DistanceSource<'s>>,
                $($arg: $ty,)*
                $count: usize,
                $($tail: $tty,)*
                options: PredictOptions,
                out: &mut Prediction<$refine>,
            ) -> Result<(), GprError> {
                $crate::prediction::DistanceQuery::query_distances_into(
                    self,
                    sources,
                    $points,
                    $count,
                    options,
                    out,
                )
            }

            /// Returns the predictive mean and query–query covariance.
            ///
            /// `cross` holds one source per slot:
            $(#[$cross])*
            /// `square` holds the squared distances between the queries
            /// (square, zero diagonal, symmetric).
            $(#[$reads])*
            ///
            /// # Errors
            ///
            /// Same as `predict` of these sources, plus [`GprError::InvalidDistance`]
            /// if a query square's diagonal is not zero or it is not
            /// symmetric (see [`crate::kernel::DistanceSource::tidy`]).
            ///
            $(#[$cdoc])*
            pub fn predict_covariance<'s>(
                &self,
                cross: impl IntoIterator<Item = DistanceSource<'s>>,
                square: impl IntoIterator<Item = DistanceSource<'s>>,
                $($arg: $ty,)*
                $count: usize,
                $($tail: $tty,)*
            ) -> Result<PredictiveCovariance<$refine>, GprError> {
                self.predict_covariance_with(
                    cross,
                    square,
                    $($arg,)*
                    $count,
                    $($tail,)*
                    PredictOptions::default(),
                )
            }

            /// Returns query–query covariance with an explicit variance kind.
            ///
            /// # Errors
            ///
            /// Same as `predict_covariance` of these sources.
            ///
            $(#[$cdoc])*
            pub fn predict_covariance_with<'s>(
                &self,
                cross: impl IntoIterator<Item = DistanceSource<'s>>,
                square: impl IntoIterator<Item = DistanceSource<'s>>,
                $($arg: $ty,)*
                $count: usize,
                $($tail: $tty,)*
                options: PredictOptions,
            ) -> Result<PredictiveCovariance<$refine>, GprError> {
                $crate::prediction::DistanceQuery::query_distance_covariance(
                    self,
                    cross,
                    square,
                    $points,
                    $count,
                    options,
                )
            }

            /// Draws posterior samples from `predict_covariance` of these sources.
            ///
            /// `seed` starts gprx's seeded generator, as in the coordinate
            /// model's `sample`.
            ///
            /// # Errors
            ///
            /// Same as `predict_covariance` of these sources, plus
            /// [`GprError::CholeskyFailed`] if the posterior covariance does
            /// not factor.
            ///
            $(#[$cdoc])*
            #[allow(clippy::too_many_arguments)]
            pub fn sample<'s>(
                &self,
                cross: impl IntoIterator<Item = DistanceSource<'s>>,
                square: impl IntoIterator<Item = DistanceSource<'s>>,
                $($arg: $ty,)*
                $count: usize,
                $($tail: $tty,)*
                n_draws: usize,
                seed: u64,
            ) -> Result<Vec<$refine>, GprError> {
                self.sample_with(
                    cross,
                    square,
                    $($arg,)*
                    $count,
                    $($tail,)*
                    PredictOptions::default(),
                    n_draws,
                    seed,
                )
            }

            /// Draws posterior samples with an explicit variance kind.
            ///
            /// # Errors
            ///
            /// Same as `sample` of these sources.
            ///
            $(#[$cdoc])*
            #[allow(clippy::too_many_arguments)]
            pub fn sample_with<'s>(
                &self,
                cross: impl IntoIterator<Item = DistanceSource<'s>>,
                square: impl IntoIterator<Item = DistanceSource<'s>>,
                $($arg: $ty,)*
                $count: usize,
                $($tail: $tty,)*
                options: PredictOptions,
                n_draws: usize,
                seed: u64,
            ) -> Result<Vec<$refine>, GprError> {
                let jitter = $crate::prediction::DistanceQuery::draw_jitter(self);
                self.predict_covariance_with(cross, square, $($arg,)* $count, $($tail,)* options)?
                    .draw(n_draws, seed, jitter)
            }
        }
    };
}

pub(crate) use distance_predict;