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
//! Unfitted [`Gpr`] trainer.

use std::fmt;
use std::marker::PhantomData;

use crate::error::GprError;
use crate::gpr::GprObjective;
use crate::kernel::{
    DistanceKernel, KernelSpec, ModelKernel, ModelKernelParts, PointKernel, PointUse, SpecOf,
};
use crate::likelihood::GaussianLikelihood;
use crate::optimizer::{Fixed, Lbfgs, Optimizer};
use crate::param::write_params;
use crate::precision::{DoublePrecision, GpScalar};
use crate::transform::{IdentityInput, IdentityTarget, UnfittedTarget, UnfittedTransform};

use super::{ExactFit, FittedGpr, Policies, TrainInput};
use crate::policy::{CholeskyBuffer, DistanceCachePolicy, JitterPolicy, KernelExp};

/// Trains an Exact GPR from a kernel, a likelihood, transforms, an optimizer, and a recompute strategy.
///
/// [`Self::fit`] consumes [`Gpr<O>`] where `O: `[`Optimizer`] and searches
/// hyperparameters. [`Gpr<Fixed>::factor`] factors at the current `θ` with no
/// search. Success returns [`FittedGpr`]. Failure returns the trainer with
/// [`GprError`] so the caller can change `θ` or data and try again.
/// Input and target transforms default to identity. The trainer stores three
/// runtime policies: [`DistanceCachePolicy`] (default
/// [`DistanceCachePolicy::Cached`]), [`CholeskyBuffer`] (default
/// [`CholeskyBuffer::Retain`]), and [`KernelExp`] (default
/// [`KernelExp::Accurate`]). [`Gpr::with_prefer_memory`] /
/// [`Gpr::with_prefer_speed`] set the memory / speed pole at once. The type
/// parameters are the optimizer `O` (default [`Lbfgs`]; [`Fixed`] for
/// [`Gpr<Fixed>::factor`]), the precision `P` (default
/// [`DoublePrecision`]), and the kernel `K` (default [`KernelSpec`]). `K`
/// selects the training data: a [`KernelSpec`] reads column-major
/// coordinates `X`, and a [`DistanceKernel`] reads squared distances the
/// caller supplies (plus `X` for the coordinate leaves of a
/// [`DistanceKernel<WithPoints>`](crate::kernel::WithPoints)). [`Clone`]
/// copies kernel, likelihood, transforms, optimizer, and policies.
///
/// Isotropic distance fills and lower-triangle kernel writes use the process-wide thread
/// pool. There is no parallel on/off flag. Thread count is the process-wide pool
/// (`RAYON_NUM_THREADS`, or `ThreadPoolBuilder::build_global` before the first fit); one
/// worker is sequential. See the [crate-level parallelism notes](crate).
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{KernelSpec, RbfKernel};
/// use gprx::transform::{StandardizeInput, StandardizeTarget};
/// use gprx::{
///     CholeskyBuffer, DistanceCachePolicy, GaussianLikelihood, Gpr, JitterPolicy, KernelExp,
///     SinglePrecision,
/// };
///
/// # 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)
///     .with_input_transform(StandardizeInput::new())
///     .with_target_transform(StandardizeTarget::new());
/// // The policies a new trainer starts with.
/// assert_eq!(gpr.distance_cache_policy(), DistanceCachePolicy::Cached);
/// assert_eq!(gpr.cholesky_buffer(), CholeskyBuffer::Retain);
/// assert_eq!(gpr.math(), KernelExp::Accurate);
/// assert_eq!(gpr.jitter_policy(), JitterPolicy::default());
/// // θ is the kernel's log-lengthscale, then the likelihood's log σn².
/// assert_eq!(gpr.kernel().num_params(), 1);
/// assert_eq!(gpr.num_params(), 2);
/// let mut theta = [0.0; 2];
/// gpr.get_params(&mut theta)?;
/// assert!((theta[1] - gpr.likelihood().log_noise_variance()).abs() < 1e-12);
/// // Column-major `X` with n = 3 points and d = 1 feature.
/// let (x, y) = ([0.0, 1.0, 2.0], [0.0, 1.0, 0.5]);
/// let fitted = gpr.fit(&x, 3, 1, &y).map_err(|(_, e)| e)?;
/// let pred = fitted.predict(&[0.5], 1, 1)?;
/// assert_eq!(pred.mean.len(), 1);
/// let _nlml = fitted.neg_log_marginal_likelihood()?;
/// // The same model with `f32` storage.
/// let single = Gpr::new(KernelSpec::from(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
///     .with_precision::<SinglePrecision>()
///     .fit(&x, 3, 1, &y)
///     .map_err(|(_, e)| e)?;
/// assert_eq!(single.predict(&[0.5], 1, 1)?.mean.len(), 1);
/// # Ok(())
/// # }
/// ```
pub struct Gpr<O = Lbfgs, P = DoublePrecision, K: ModelKernel = KernelSpec> {
    pub(super) kernel: SpecOf<K>,
    pub(super) likelihood: GaussianLikelihood,
    pub(super) x_transform: Box<dyn UnfittedTransform>,
    pub(super) y_transform: Box<dyn UnfittedTarget>,
    pub(super) optimizer: O,
    pub(super) policies: Policies,
    pub(super) _precision: PhantomData<P>,
    pub(super) _kernel: PhantomData<K>,
}

impl<O, P, K: ModelKernel> fmt::Debug for Gpr<O, P, K>
where
    O: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Gpr")
            .field("kernel", &self.kernel)
            .field("likelihood", &self.likelihood)
            .field("optimizer", &self.optimizer)
            .field("distance_cache", &self.policies.distance_cache)
            .field("cholesky_buffer", &self.policies.cholesky_buffer)
            .field("math", &self.policies.math)
            .field("jitter_policy", &self.policies.jitter)
            .finish_non_exhaustive()
    }
}

impl<O: Clone, P, K: ModelKernel> Clone for Gpr<O, P, K> {
    fn clone(&self) -> Self {
        Self {
            kernel: self.kernel.clone(),
            likelihood: self.likelihood,
            x_transform: self.x_transform.clone_box(),
            y_transform: self.y_transform.clone_box(),
            optimizer: self.optimizer.clone(),
            policies: self.policies,
            _precision: PhantomData,
            _kernel: PhantomData,
        }
    }
}

impl<K: ModelKernel> Gpr<Lbfgs, DoublePrecision, K> {
    /// Builds an unfitted trainer that owns the kernel and observation noise.
    ///
    /// Input and target maps default to identity. The optimizer is [`Lbfgs`].
    /// Call [`Self::with_input_transform`] / [`Self::with_target_transform`]
    /// before [`Self::fit`] to standardize. Those methods take an unfitted
    /// map; `fit` / `factor` produce the fitted map stored on [`FittedGpr`].
    /// Call [`Self::with_optimizer`] to switch to [`Fixed`] or another
    /// [`Optimizer`]. Policies start at [`DistanceCachePolicy::Cached`],
    /// [`CholeskyBuffer::Retain`], and [`KernelExp::Accurate`]. A kernel that
    /// does not read pairwise distances (standalone Linear, Constant, White)
    /// never allocates the distance cache.
    ///
    /// The kernel is a coordinate [`KernelSpec`] or a
    /// [`DistanceKernel`](crate::kernel::DistanceKernel) on supplied squared
    /// distances; its type selects the data `fit` and `predict` take.
    ///
    /// See the example on [`Gpr`].
    pub fn new(kernel: K, likelihood: GaussianLikelihood) -> Self {
        Self {
            kernel: <K as ModelKernelParts>::into_spec(kernel),
            likelihood,
            x_transform: Box::new(IdentityInput),
            y_transform: Box::new(IdentityTarget),
            optimizer: Lbfgs::new(),
            policies: Policies::default(),
            _precision: PhantomData,
            _kernel: PhantomData,
        }
    }
}

impl<O, P, K: ModelKernel> Gpr<O, P, K> {
    /// The one place a trainer changes its type parameters.
    fn retype<O2, P2>(self, optimizer: O2) -> (Gpr<O2, P2, K>, O) {
        (
            Gpr {
                kernel: self.kernel,
                likelihood: self.likelihood,
                x_transform: self.x_transform,
                y_transform: self.y_transform,
                optimizer,
                policies: self.policies,
                _precision: PhantomData,
                _kernel: PhantomData,
            },
            self.optimizer,
        )
    }

    /// Selects the storage precision.
    ///
    /// Omitting it leaves [`DoublePrecision`].
    ///
    /// See the example on [`Gpr`].
    pub fn with_precision<P2: GpScalar>(self) -> Gpr<O, P2, K> {
        let (trainer, optimizer) = self.retype::<(), P2>(());
        trainer.retype(optimizer).0
    }

    /// Selects the kernel `exp`.
    ///
    /// Omitting it leaves [`KernelExp::Accurate`].
    ///
    /// `fit` and predict use the same `exp`. Hyperparameter `exp(θ)` is
    /// unchanged.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{GaussianLikelihood, Gpr, KernelExp};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let gpr = Gpr::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .with_math(KernelExp::FastApprox);
    /// let _fitted = gpr
    ///     .fit(&[0.0, 1.0], 2, 1, &[0.0, 1.0])
    ///     .map_err(|(_, e)| e)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_math(mut self, math: KernelExp) -> Self {
        self.policies.math = math;
        self
    }

    /// Replaces the target (`y`) transform.
    ///
    /// Intended to be called before fit.
    ///
    /// A single map or a [`crate::transform::TargetPipeline`]. One-step maps
    /// still use this method.
    ///
    /// See the example on [`Gpr`].
    pub fn with_target_transform(mut self, transform: impl UnfittedTarget + 'static) -> Self {
        self.y_transform = Box::new(transform);
        self
    }

    pub(crate) fn from_owned(
        kernel: SpecOf<K>,
        likelihood: GaussianLikelihood,
        x_transform: Box<dyn UnfittedTransform>,
        y_transform: Box<dyn UnfittedTarget>,
        optimizer: O,
        policies: Policies,
    ) -> Self {
        Self {
            kernel,
            likelihood,
            x_transform,
            y_transform,
            optimizer,
            policies,
            _precision: PhantomData,
            _kernel: PhantomData,
        }
    }

    /// Sets the Cholesky jitter policy.
    ///
    /// Does not change observation noise.
    ///
    /// Intended to be called before [`Gpr::fit`] / [`Gpr<Fixed>::factor`].
    /// The default is [`JitterPolicy::fixed`]`(0.0)`. See [`JitterPolicy`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{GaussianLikelihood, Gpr, JitterPolicy};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let gpr = Gpr::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .with_jitter_policy(JitterPolicy::fixed(1e-8)?);
    /// let _fitted = gpr
    ///     .with_optimizer(gprx::Fixed)
    ///     .factor(&[0.0, 1.0], 2, 1, &[0.0, 1.0])
    ///     .map_err(|(_, e)| e)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_jitter_policy(mut self, policy: JitterPolicy) -> Self {
        self.policies.jitter = policy;
        self
    }

    /// Replaces the optimizer, changing the type parameter `O`.
    ///
    /// A fit rebuilds only the kernel leaves a step touches when the
    /// optimizer reports changed coordinates
    /// ([`Optimizer::USES_CHANGE_INDICES`]) and the buffer is
    /// [`CholeskyBuffer::Retain`]; otherwise it rebuilds the whole kernel.
    ///
    /// [`Fixed`] is not an [`Optimizer`]; use [`Gpr<Fixed>::factor`] after this switch.
    /// The built-in solvers are [`crate::Lbfgs`], [`crate::NelderMead`],
    /// [`crate::TrustRegion`], and [`crate::FastSimulatedAnnealing`]. A user
    /// type that implements [`Optimizer`] uses this same method; there is no
    /// second solver slot.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{GaussianLikelihood, Gpr, NelderMead};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let gpr = Gpr::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .with_optimizer(NelderMead::new());
    /// let _fitted = gpr.fit(&[0.0, 1.0], 2, 1, &[0.0, 1.0]).map_err(|(_, e)| e)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_optimizer<O2>(self, optimizer: O2) -> Gpr<O2, P, K> {
        self.retype(optimizer).0
    }

    // One field. Public callers set both through `with_prefer_speed` /
    // `with_prefer_memory`, so this stays crate-private.
    pub(crate) fn with_distance_cache_policy(mut self, policy: DistanceCachePolicy) -> Self {
        self.policies.distance_cache = policy;
        self
    }

    // One field. Public callers set both through `with_prefer_speed` /
    // `with_prefer_memory`, so this stays crate-private.
    pub(crate) fn with_cholesky_buffer(mut self, buffer: CholeskyBuffer) -> Self {
        self.policies.cholesky_buffer = buffer;
        self
    }

    /// Selects the memory pole: [`DistanceCachePolicy::Uncached`] and [`CholeskyBuffer::Reuse`].
    ///
    /// Replaces both policies. Training distances are computed from `X` each
    /// kernel build, and `W` overwrites `L` during a gradient.
    /// [`Self::with_prefer_speed`] replaces both with the default.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{CholeskyBuffer, DistanceCachePolicy, GaussianLikelihood, Gpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let gpr = Gpr::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .with_prefer_memory();
    /// assert_eq!(gpr.distance_cache_policy(), DistanceCachePolicy::Uncached);
    /// assert_eq!(gpr.cholesky_buffer(), CholeskyBuffer::Reuse);
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_prefer_memory(self) -> Self {
        self.with_distance_cache_policy(DistanceCachePolicy::Uncached)
            .with_cholesky_buffer(CholeskyBuffer::Reuse)
    }

    /// Selects the speed pole: [`DistanceCachePolicy::Cached`] and [`CholeskyBuffer::Retain`] (the default).
    ///
    /// Replaces both policies.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{CholeskyBuffer, DistanceCachePolicy, GaussianLikelihood, Gpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let gpr = Gpr::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .with_prefer_memory()
    /// .with_prefer_speed();
    /// assert_eq!(gpr.distance_cache_policy(), DistanceCachePolicy::Cached);
    /// assert_eq!(gpr.cholesky_buffer(), CholeskyBuffer::Retain);
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_prefer_speed(self) -> Self {
        self.with_distance_cache_policy(DistanceCachePolicy::Cached)
            .with_cholesky_buffer(CholeskyBuffer::Retain)
    }

    /// Returns the distance-cache policy.
    ///
    /// See the example on [`Gpr`].
    pub fn distance_cache_policy(&self) -> DistanceCachePolicy {
        self.policies.distance_cache
    }

    /// Returns the Cholesky buffer policy.
    ///
    /// See the example on [`Gpr`].
    pub fn cholesky_buffer(&self) -> CholeskyBuffer {
        self.policies.cholesky_buffer
    }

    /// Returns the kernel `exp`.
    ///
    /// See the example on [`Gpr`].
    pub fn math(&self) -> KernelExp {
        self.policies.math
    }

    /// Returns the jitter retries used when `K + σn² I` fails to factor.
    ///
    /// See the example on [`Gpr`].
    pub fn jitter_policy(&self) -> JitterPolicy {
        self.policies.jitter
    }

    /// Returns the observation-noise model.
    ///
    /// See the example on [`Gpr`].
    pub fn likelihood(&self) -> &GaussianLikelihood {
        &self.likelihood
    }

    /// Returns the concatenated kernel and likelihood parameter count.
    ///
    /// See the example on [`Gpr`].
    pub fn num_params(&self) -> usize {
        self.kernel.num_params() + self.likelihood.num_params()
    }

    /// Writes kernel `θ` then likelihood `θ` into `out`.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::LengthMismatch`] if `out` is the wrong length
    /// or a custom leaf rejects the write.
    ///
    /// See the example on [`Gpr`].
    pub fn get_params(&self, out: &mut [f64]) -> Result<(), GprError> {
        write_params(&self.kernel, &self.likelihood, out)
    }
}

impl<O, P, K: PointKernel> Gpr<O, P, K> {
    /// Replaces the input (`X`) transform.
    ///
    /// Intended to be called before fit.
    ///
    /// A single map, a [`crate::transform::Pipeline`], or
    /// [`crate::transform::ColumnwiseInput`]. One-step maps still use this
    /// method.
    ///
    /// See the example on [`Gpr`].
    pub fn with_input_transform(mut self, transform: impl UnfittedTransform + 'static) -> Self {
        self.x_transform = Box::new(transform);
        self
    }
}

impl<O, P> Gpr<O, P> {
    /// Returns the kernel whose hyperparameters this trainer owns.
    ///
    /// See the example on [`Gpr`].
    pub fn kernel(&self) -> &KernelSpec {
        &self.kernel
    }
}

impl<O, P, C: PointUse> Gpr<O, P, DistanceKernel<C>> {
    /// Returns a copy of the kernel whose hyperparameters this trainer owns.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{RbfKernel, ScalarDistance};
    /// use gprx::{GaussianLikelihood, Gpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let image = ScalarDistance::new();
    /// let gpr = Gpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?);
    /// assert_eq!(gpr.to_kernel().num_params(), 1);
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_kernel(&self) -> DistanceKernel<C> {
        <DistanceKernel<C> as ModelKernelParts>::from_spec(self.kernel.clone())
    }
}

impl<O, P> Gpr<O, P>
where
    P: GpScalar,
    O: for<'a> Optimizer<GprObjective<'a, P>>,
{
    /// Factors `A = K + σn² I`, solves `A α = y`, and updates `θ` with `O`.
    ///
    /// `x` is column-major with `n_rows` points and `n_cols` features. After
    /// success, `L` remains in the workspace and `α` is stored on
    /// [`FittedGpr`]. A failed factorization or optimizer step returns this
    /// trainer and does not produce a [`FittedGpr`]. Kernel and likelihood
    /// `θ` are restored to the values from the start of the call when
    /// optimization fails.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::EmptyInput`] if `n_rows` or `n_cols` is zero,
    /// [`GprError::LengthMismatch`] if `x` or `y` has the wrong length,
    /// [`GprError::NonFiniteInput`] if a value is `NaN` or `Inf`,
    /// [`GprError::CholeskyFailed`] if `A` cannot be factored, or
    /// [`GprError::OptimizationNotConverged`] if the optimizer does not
    /// produce a best parameter vector.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Fixed, 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 _fitted = fitted
    ///     .into_trainer()
    ///     .with_optimizer(Fixed)
    ///     .factor(&[0.0, 1.0], 2, 1, &[0.0, 1.0])
    ///     .map_err(|(_, e)| e)?;
    /// # Ok(())
    /// # }
    /// ```
    #[allow(clippy::result_large_err)] // failure returns the trainer so the caller can retry
    pub fn fit(
        self,
        x: &[f64],
        n_rows: usize,
        n_cols: usize,
        y: &[f64],
    ) -> Result<FittedGpr<O, P>, (Self, GprError)> {
        self.fit_input(TrainInput::points(x, n_rows, n_cols, y))
    }
}

impl<P: GpScalar> Gpr<Fixed, P> {
    /// Factors at the current kernel and likelihood `θ` without a search.
    ///
    /// Same data contract as `fit`: `x` is column-major with `n_rows`
    /// points and `n_cols` features, and `y` has `n_rows` targets. There are
    /// no optimizer knobs.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::EmptyInput`] if `n_rows` or `n_cols` is zero,
    /// [`GprError::LengthMismatch`] if `x` or `y` has the wrong length,
    /// [`GprError::NonFiniteInput`] if a value is `NaN` or `Inf`, or
    /// [`GprError::CholeskyFailed`] if `A` cannot be factored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Fixed, Gpr, GaussianLikelihood};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let kernel = KernelSpec::from(RbfKernel::new(1.0)?);
    /// let likelihood = GaussianLikelihood::new(0.1)?;
    /// let fitted = Gpr::new(kernel, likelihood)
    ///     .with_optimizer(Fixed)
    ///     .factor(&[0.0, 1.0], 2, 1, &[0.0, 1.0])
    ///     .map_err(|(_, e)| e)?;
    /// let pred = fitted.predict(&[0.5], 1, 1)?;
    /// assert_eq!(pred.mean.len(), 1);
    /// # Ok(())
    /// # }
    /// ```
    #[allow(clippy::result_large_err)] // failure returns the trainer so the caller can retry
    pub fn factor(
        self,
        x: &[f64],
        n_rows: usize,
        n_cols: usize,
        y: &[f64],
    ) -> Result<FittedGpr<Fixed, P>, (Self, GprError)> {
        self.factor_input(TrainInput::points(x, n_rows, n_cols, y))
    }
}

impl<O, P, K> Gpr<O, P, K>
where
    P: GpScalar,
    K: ModelKernel,
    O: for<'a> Optimizer<GprObjective<'a, P, K>>,
{
    /// [`Gpr::fit`] on any training input.
    #[allow(clippy::result_large_err)] // failure returns the trainer so the caller can retry
    pub(super) fn fit_input(
        self,
        input: TrainInput<'_>,
    ) -> Result<FittedGpr<O, P, K>, (Self, GprError)> {
        let mut model = FittedGpr::prepare(self, input)?;
        let mut view = ExactFit {
            core: &mut model.core,
            store: &mut model.store,
        };
        match view.optimize(&model.optimizer) {
            Ok(()) => Ok(model),
            Err(err) => Err((model.into_trainer(), err)),
        }
    }
}

impl<P: GpScalar, K: ModelKernel> Gpr<Fixed, P, K> {
    /// [`Gpr::factor`] on any training input.
    #[allow(clippy::result_large_err)] // failure returns the trainer so the caller can retry
    pub(crate) fn factor_input(
        self,
        input: TrainInput<'_>,
    ) -> Result<FittedGpr<Fixed, P, K>, (Self, GprError)> {
        let mut model = FittedGpr::prepare(self, input)?;
        let mut view = ExactFit {
            core: &mut model.core,
            store: &mut model.store,
        };
        match view.refactor() {
            Ok(()) => Ok(model),
            Err(err) => Err((model.into_trainer(), err)),
        }
    }
}

/// Drops the trainer and keeps the error so `?` works in `Result<_, GprError>`.
impl<O, P, K: ModelKernel> From<(Gpr<O, P, K>, GprError)> for GprError {
    fn from((_, err): (Gpr<O, P, K>, GprError)) -> Self {
        err
    }
}