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};
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> {
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> {
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,
)
}
pub fn with_precision<P2: GpScalar>(self) -> Gpr<O, P2, K> {
let (trainer, optimizer) = self.retype::<(), P2>(());
trainer.retype(optimizer).0
}
pub fn with_math(mut self, math: KernelExp) -> Self {
self.policies.math = math;
self
}
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,
}
}
pub fn with_jitter_policy(mut self, policy: JitterPolicy) -> Self {
self.policies.jitter = policy;
self
}
pub fn with_optimizer<O2>(self, optimizer: O2) -> Gpr<O2, P, K> {
self.retype(optimizer).0
}
pub(crate) fn with_distance_cache_policy(mut self, policy: DistanceCachePolicy) -> Self {
self.policies.distance_cache = policy;
self
}
pub(crate) fn with_cholesky_buffer(mut self, buffer: CholeskyBuffer) -> Self {
self.policies.cholesky_buffer = buffer;
self
}
pub fn with_prefer_memory(self) -> Self {
self.with_distance_cache_policy(DistanceCachePolicy::Uncached)
.with_cholesky_buffer(CholeskyBuffer::Reuse)
}
pub fn with_prefer_speed(self) -> Self {
self.with_distance_cache_policy(DistanceCachePolicy::Cached)
.with_cholesky_buffer(CholeskyBuffer::Retain)
}
pub fn distance_cache_policy(&self) -> DistanceCachePolicy {
self.policies.distance_cache
}
pub fn cholesky_buffer(&self) -> CholeskyBuffer {
self.policies.cholesky_buffer
}
pub fn math(&self) -> KernelExp {
self.policies.math
}
pub fn jitter_policy(&self) -> JitterPolicy {
self.policies.jitter
}
pub fn likelihood(&self) -> &GaussianLikelihood {
&self.likelihood
}
pub fn num_params(&self) -> usize {
self.kernel.num_params() + self.likelihood.num_params()
}
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> {
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> {
pub fn kernel(&self) -> &KernelSpec {
&self.kernel
}
}
impl<O, P, C: PointUse> Gpr<O, P, DistanceKernel<C>> {
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>>,
{
#[allow(clippy::result_large_err)] 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> {
#[allow(clippy::result_large_err)] 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>>,
{
#[allow(clippy::result_large_err)] 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> {
#[allow(clippy::result_large_err)] 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)),
}
}
}
impl<O, P, K: ModelKernel> From<(Gpr<O, P, K>, GprError)> for GprError {
fn from((_, err): (Gpr<O, P, K>, GprError)) -> Self {
err
}
}