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
//! Explicit restore factories for Custom kernels and caller-defined transforms.

use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

use crate::error::GprError;
use crate::error::PersistErrorKind;
use crate::kernel::CustomKernel;
use crate::transform::{TargetTransform, Transform, UnfittedTarget, UnfittedTransform};

use super::RESERVED_PREFIX;
use super::persist_err;

/// Names the shared form of a restore function for a [`CustomKernel`]: it rebuilds the leaf from the JSON its [`KernelTerm::persist_state`] wrote.
///
/// The restored leaf implements the same operations at `f32` and `f64`.
///
/// [`KernelTerm::persist_state`]: crate::kernel::KernelTerm::persist_state
///
/// See the example on [`PersistRegistry`].
pub type KernelRestore =
    Arc<dyn Fn(&serde_json::Value) -> Result<CustomKernel, GprError> + Send + Sync>;

/// Names the shared form of a restore function for an unfitted input map: it rebuilds the map from the JSON its [`UnfittedTransform::persist_state`] wrote.
///
/// See the example on [`UnfittedTransform`].
pub type UnfittedInputRestore =
    Arc<dyn Fn(&serde_json::Value) -> Result<Box<dyn UnfittedTransform>, GprError> + Send + Sync>;

/// Names the shared form of a restore function for a fitted input map: it rebuilds the map from the JSON its [`Transform::persist_state`] wrote.
///
/// See the example on [`UnfittedTransform`].
pub type FittedInputRestore =
    Arc<dyn Fn(&serde_json::Value) -> Result<Box<dyn Transform>, GprError> + Send + Sync>;

/// Names the shared form of a restore function for an unfitted target map: it rebuilds the map from the JSON its [`UnfittedTarget::persist_state`] wrote.
///
/// See the example on [`UnfittedTarget`].
pub type UnfittedTargetRestore =
    Arc<dyn Fn(&serde_json::Value) -> Result<Box<dyn UnfittedTarget>, GprError> + Send + Sync>;

/// Names the shared form of a restore function for a fitted target map: it rebuilds the map from the JSON its [`TargetTransform::persist_state`] wrote.
///
/// See the example on [`UnfittedTarget`].
pub type FittedTargetRestore =
    Arc<dyn Fn(&serde_json::Value) -> Result<Box<dyn TargetTransform>, GprError> + Send + Sync>;

/// Represents the explicit restore table for Custom kernels and caller-defined transforms.
///
/// Built-in leaves and maps use closed tags in `config.json` and are not
/// registered here. A custom kernel leaf or a caller-defined transform is
/// saved as its `persist_id` and `persist_state`; a load looks the
/// `persist_id` up here and calls the restore function on the state. Every
/// `register_*` rejects an empty id, an id that starts with
/// [`super::RESERVED_PREFIX`], and an id already registered for the same
/// kind of item.
///
/// The example below saves and loads a model with a custom kernel leaf.
/// The examples on [`UnfittedTransform`] and [`UnfittedTarget`] register
/// caller-defined input and target maps.
///
/// # Examples
///
/// ```rust
/// use std::sync::Arc;
///
/// use faer::{MatMut, MatRef};
/// use gprx::kernel::{CustomKernel, KernelScalar, KernelSpec, KernelTerm, RbfKernel, Triangle};
/// use gprx::persist::{KernelRestore, LoadedGpr, PersistRegistry};
/// use gprx::{GaussianLikelihood, Gpr, GprError, Interval, PersistErrorKind};
///
/// /// A constant kernel `k = c`, with one parameter `log c`.
/// #[derive(Clone, Debug)]
/// struct Bias {
///     log_c: f64,
/// }
///
/// /// Writes `value` into the `uplo` triangle of `out`.
/// fn fill<T: KernelScalar>(mut out: MatMut<'_, T>, uplo: Triangle, value: f64) {
///     for col in 0..out.ncols() {
///         for row in 0..out.nrows() {
///             let keep = match uplo {
///                 Triangle::Lower => row >= col,
///                 Triangle::Upper => row <= col,
///                 Triangle::Full => true,
///             };
///             if keep {
///                 out[(row, col)] = T::from_f64(value);
///             }
///         }
///     }
/// }
///
/// /// Checks that a slice holds the one parameter.
/// fn one(len: usize) -> Result<(), GprError> {
///     if len == 1 {
///         Ok(())
///     } else {
///         Err(GprError::LengthMismatch { reason: format!("bias kernel has 1 parameter, got {len}") })
///     }
/// }
///
/// /// Checks a parameter index pair (`(0, 0)` is the only one).
/// fn index(i: usize, j: usize) -> Result<(), GprError> {
///     if (i, j) == (0, 0) {
///         Ok(())
///     } else {
///         Err(GprError::IndexOutOfRange { reason: format!("bias kernel has no index ({i}, {j})") })
///     }
/// }
///
/// impl<T: KernelScalar> KernelTerm<T> for Bias {
///     fn num_params(&self) -> usize {
///         1
///     }
///     fn get_params(&self, out: &mut [f64]) -> Result<(), GprError> {
///         one(out.len())?;
///         out[0] = self.log_c;
///         Ok(())
///     }
///     fn set_params(&mut self, params: &[f64]) -> Result<(), GprError> {
///         one(params.len())?;
///         self.log_c = params[0];
///         Ok(())
///     }
///     fn bounds_into(&self, out: &mut [Interval]) -> Result<(), GprError> {
///         one(out.len())?;
///         out[0] = Interval::DEFAULT_POSITIVE;
///         Ok(())
///     }
///     fn apply(&self, _: MatRef<'_, T>, out: MatMut<'_, T>, uplo: Triangle) -> Result<(), GprError> {
///         fill(out, uplo, self.log_c.exp());
///         Ok(())
///     }
///     fn apply_cross(&self, _: MatRef<'_, T>, out: MatMut<'_, T>) -> Result<(), GprError> {
///         fill(out, Triangle::Full, self.log_c.exp());
///         Ok(())
///     }
///     fn fill_diag(&self, out: &mut [T]) -> Result<(), GprError> {
///         out.fill(T::from_f64(self.log_c.exp()));
///         Ok(())
///     }
///     // `∂k/∂log c` and `∂²k/∂(log c)²` are both `c`.
///     fn grad(&self, _: MatRef<'_, T>, d_k: MatMut<'_, T>, p: usize, uplo: Triangle) -> Result<(), GprError> {
///         index(p, 0)?;
///         fill(d_k, uplo, self.log_c.exp());
///         Ok(())
///     }
///     fn hess(&self, _: MatRef<'_, T>, d2_k: MatMut<'_, T>, i: usize, j: usize, uplo: Triangle) -> Result<(), GprError> {
///         index(i, j)?;
///         fill(d2_k, uplo, self.log_c.exp());
///         Ok(())
///     }
///     fn hess_points(&self, _: MatRef<'_, T>, d2_k: MatMut<'_, T>, i: usize, j: usize, uplo: Triangle) -> Result<(), GprError> {
///         index(i, j)?;
///         fill(d2_k, uplo, self.log_c.exp());
///         Ok(())
///     }
///     // What a save writes for this leaf, and what the restore reads back.
///     fn persist_id(&self) -> &'static str {
///         "example.bias"
///     }
///     fn persist_state(&self) -> Result<serde_json::Value, GprError> {
///         Ok(serde_json::json!({ "log_c": self.log_c }))
///     }
/// }
///
/// # fn main() -> Result<(), GprError> {
/// let kernel = KernelSpec::custom(Bias { log_c: 0.0 }) + KernelSpec::from(RbfKernel::new(1.0)?);
/// let fitted = Gpr::new(kernel, GaussianLikelihood::new(0.1)?)
///     .fit(&[0.0, 1.0, 2.0], 3, 1, &[1.0, 2.0, 1.5])
///     .map_err(|(_, e)| e)?;
/// let dir = std::env::temp_dir().join(format!("gprx-doctest-registry-{}", std::process::id()));
/// let _ = std::fs::remove_dir_all(&dir);
/// fitted.save(&dir)?;
///
/// // Loading without a restore for "example.bias" fails.
/// let missing = LoadedGpr::load(&dir, &PersistRegistry::new());
/// assert!(matches!(
///     missing,
///     Err(GprError::PersistFailed { kind: PersistErrorKind::UnregisteredId, .. })
/// ));
///
/// // One restore function, which an `Arc` lets several registries share.
/// let restore: KernelRestore = Arc::new(|state| {
///     let log_c = state["log_c"].as_f64().ok_or_else(|| GprError::PersistFailed {
///         kind: PersistErrorKind::Config,
///         reason: "bias state needs a number log_c".into(),
///     })?;
///     Ok(CustomKernel::new(Bias { log_c }))
/// });
/// let mut registry = PersistRegistry::new();
/// let shared = Arc::clone(&restore);
/// registry.register_kernel("example.bias", move |state| shared(state))?;
/// // An id registers once per kind.
/// let twice = registry.register_kernel("example.bias", move |state| restore(state));
/// assert!(matches!(
///     twice,
///     Err(GprError::PersistFailed { kind: PersistErrorKind::InvalidPersistId, .. })
/// ));
///
/// let loaded = LoadedGpr::load(&dir, &registry)?;
/// assert_eq!(loaded.predict(&[0.5], 1, 1)?, fitted.predict(&[0.5], 1, 1)?);
/// let _ = std::fs::remove_dir_all(&dir);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Default)]
pub struct PersistRegistry {
    kernels: HashMap<String, KernelRestore>,
    unfitted_inputs: HashMap<String, UnfittedInputRestore>,
    fitted_inputs: HashMap<String, FittedInputRestore>,
    unfitted_targets: HashMap<String, UnfittedTargetRestore>,
    fitted_targets: HashMap<String, FittedTargetRestore>,
}

impl PersistRegistry {
    /// Returns an empty registry.
    ///
    /// Built-ins do not need registration.
    ///
    /// See the example on [`PersistRegistry`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers a Custom kernel restore for `persist_id`.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::PersistFailed`] with
    /// [`PersistErrorKind::InvalidPersistId`](crate::PersistErrorKind::InvalidPersistId)
    /// if `persist_id` is empty, starts with [`super::RESERVED_PREFIX`], or
    /// is already registered as a kernel.
    ///
    /// See the example on [`PersistRegistry`].
    pub fn register_kernel(
        &mut self,
        persist_id: impl Into<String>,
        restore: impl Fn(&serde_json::Value) -> Result<CustomKernel, GprError> + Send + Sync + 'static,
    ) -> Result<(), GprError> {
        insert_unique(
            &mut self.kernels,
            persist_id.into(),
            Arc::new(restore),
            "kernel",
        )
    }

    /// Registers an unfitted input-transform restore for `persist_id`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::register_kernel`], for an id already registered as
    /// an unfitted input transform.
    ///
    /// See the example on [`UnfittedTransform`].
    pub fn register_unfitted_input(
        &mut self,
        persist_id: impl Into<String>,
        restore: impl Fn(&serde_json::Value) -> Result<Box<dyn UnfittedTransform>, GprError>
        + Send
        + Sync
        + 'static,
    ) -> Result<(), GprError> {
        insert_unique(
            &mut self.unfitted_inputs,
            persist_id.into(),
            Arc::new(restore),
            "unfitted input transform",
        )
    }

    /// Registers a fitted input-transform restore for `persist_id`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::register_kernel`], for an id already registered as
    /// a fitted input transform.
    ///
    /// See the example on [`UnfittedTransform`].
    pub fn register_fitted_input(
        &mut self,
        persist_id: impl Into<String>,
        restore: impl Fn(&serde_json::Value) -> Result<Box<dyn Transform>, GprError>
        + Send
        + Sync
        + 'static,
    ) -> Result<(), GprError> {
        insert_unique(
            &mut self.fitted_inputs,
            persist_id.into(),
            Arc::new(restore),
            "fitted input transform",
        )
    }

    /// Registers an unfitted target-transform restore for `persist_id`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::register_kernel`], for an id already registered as
    /// an unfitted target transform.
    ///
    /// See the example on [`UnfittedTarget`].
    pub fn register_unfitted_target(
        &mut self,
        persist_id: impl Into<String>,
        restore: impl Fn(&serde_json::Value) -> Result<Box<dyn UnfittedTarget>, GprError>
        + Send
        + Sync
        + 'static,
    ) -> Result<(), GprError> {
        insert_unique(
            &mut self.unfitted_targets,
            persist_id.into(),
            Arc::new(restore),
            "unfitted target transform",
        )
    }

    /// Registers a fitted target-transform restore for `persist_id`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::register_kernel`], for an id already registered as
    /// a fitted target transform.
    ///
    /// See the example on [`UnfittedTarget`].
    pub fn register_fitted_target(
        &mut self,
        persist_id: impl Into<String>,
        restore: impl Fn(&serde_json::Value) -> Result<Box<dyn TargetTransform>, GprError>
        + Send
        + Sync
        + 'static,
    ) -> Result<(), GprError> {
        insert_unique(
            &mut self.fitted_targets,
            persist_id.into(),
            Arc::new(restore),
            "fitted target transform",
        )
    }

    pub(super) fn restore_kernel(
        &self,
        persist_id: &str,
        state: &serde_json::Value,
    ) -> Result<CustomKernel, GprError> {
        lookup(&self.kernels, persist_id, "kernel")?(state)
    }

    pub(super) fn restore_unfitted_input(
        &self,
        persist_id: &str,
        state: &serde_json::Value,
    ) -> Result<Box<dyn UnfittedTransform>, GprError> {
        lookup(
            &self.unfitted_inputs,
            persist_id,
            "unfitted input transform",
        )?(state)
    }

    pub(super) fn restore_fitted_input(
        &self,
        persist_id: &str,
        state: &serde_json::Value,
    ) -> Result<Box<dyn Transform>, GprError> {
        lookup(&self.fitted_inputs, persist_id, "fitted input transform")?(state)
    }

    pub(super) fn restore_unfitted_target(
        &self,
        persist_id: &str,
        state: &serde_json::Value,
    ) -> Result<Box<dyn UnfittedTarget>, GprError> {
        lookup(
            &self.unfitted_targets,
            persist_id,
            "unfitted target transform",
        )?(state)
    }

    pub(super) fn restore_fitted_target(
        &self,
        persist_id: &str,
        state: &serde_json::Value,
    ) -> Result<Box<dyn TargetTransform>, GprError> {
        lookup(&self.fitted_targets, persist_id, "fitted target transform")?(state)
    }
}

impl fmt::Debug for PersistRegistry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PersistRegistry")
            .field("kernels", &self.kernels.len())
            .field("unfitted_inputs", &self.unfitted_inputs.len())
            .field("fitted_inputs", &self.fitted_inputs.len())
            .field("unfitted_targets", &self.unfitted_targets.len())
            .field("fitted_targets", &self.fitted_targets.len())
            .finish()
    }
}

fn insert_unique<T>(
    map: &mut HashMap<String, T>,
    persist_id: String,
    value: T,
    kind: &str,
) -> Result<(), GprError> {
    validate_persist_id(&persist_id)?;
    if map.contains_key(&persist_id) {
        return Err(persist_err(
            PersistErrorKind::InvalidPersistId,
            format!("{kind} persist_id {persist_id:?} is already registered"),
        ));
    }
    map.insert(persist_id, value);
    Ok(())
}

fn lookup<'a, T>(
    map: &'a HashMap<String, T>,
    persist_id: &str,
    kind: &str,
) -> Result<&'a T, GprError> {
    map.get(persist_id).ok_or_else(|| {
        persist_err(
            PersistErrorKind::UnregisteredId,
            format!("{kind} persist_id {persist_id:?} is not registered"),
        )
    })
}

pub(super) fn validate_persist_id(persist_id: &str) -> Result<(), GprError> {
    if persist_id.is_empty() {
        return Err(persist_err(
            PersistErrorKind::InvalidPersistId,
            "persist_id must not be empty",
        ));
    }
    if persist_id.starts_with(RESERVED_PREFIX) {
        return Err(persist_err(
            PersistErrorKind::InvalidPersistId,
            format!("persist_id {persist_id:?} uses the reserved {RESERVED_PREFIX} prefix"),
        ));
    }
    Ok(())
}