use thiserror::Error;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum CholeskyStage {
Fit,
Predict,
OnlineInsert,
OnlineDelete,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum PersistErrorKind {
Io,
Config,
Tensor,
InvalidPersistId,
NotPersistable,
UnregisteredId,
WrongModel,
}
impl std::fmt::Display for PersistErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Io => "io",
Self::Config => "config",
Self::Tensor => "tensor",
Self::InvalidPersistId => "invalid persist_id",
Self::NotPersistable => "not persistable",
Self::UnregisteredId => "unregistered persist_id",
Self::WrongModel => "wrong model",
})
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum SlotErrorKind {
NotRead,
Duplicate,
Missing,
}
impl std::fmt::Display for SlotErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::NotRead => "squared distances were supplied for a slot the kernel does not read",
Self::Duplicate => "two sources were supplied for one distance slot",
Self::Missing => "a distance slot of the kernel has no source",
})
}
}
struct DistancePlace<'a> {
slot: &'a Option<usize>,
dim: &'a Option<usize>,
pair: &'a Option<(usize, usize)>,
}
impl std::fmt::Display for DistancePlace<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(slot) = self.slot {
write!(f, " in slot {slot}")?;
}
if let Some(dim) = self.dim {
let lead = if self.slot.is_some() { "," } else { " in" };
write!(f, "{lead} dimension {dim}")?;
}
if let Some((row, col)) = self.pair {
write!(f, " at ({row}, {col})")?;
}
Ok(())
}
}
#[derive(Clone, Debug, Error, PartialEq)]
#[non_exhaustive]
pub enum GprError {
#[error("input dimension mismatch: X.ncols()={x_dim}, expected {expected_dim}")]
DimensionMismatch {
x_dim: usize,
expected_dim: usize,
},
#[error("insufficient data: n={n}, at least {min} points required")]
InsufficientData {
n: usize,
min: usize,
},
#[error("input is empty")]
EmptyInput,
#[error("input contains a non-finite value (NaN/Inf)")]
NonFiniteInput,
#[error("kernel evaluation produced a non-finite value")]
NonFiniteKernelValue,
#[error(
"Cholesky factorization failed (stage={stage:?}, size={matrix_size}, jitter={jitter} already applied)"
)]
CholeskyFailed {
jitter: f64,
matrix_size: usize,
stage: CholeskyStage,
},
#[error("matrix is not positive semidefinite")]
NonPositiveDefiniteMatrix,
#[error(
"this kernel does not implement the derivative a sparse model needs \
(Matern nu = 1/2 has no coordinate derivative for FreeInducing points; \
a Custom leaf must implement the KernelTerm cross / squared-distance derivatives)"
)]
CoordGradientUnsupported,
#[error("optimizer did not converge after {iterations} iterations")]
OptimizationNotConverged {
iterations: usize,
},
#[error("invalid hyperparameter: {reason}")]
InvalidHyperparameter {
reason: String,
},
#[error("shape mismatch: {reason}")]
ShapeMismatch {
reason: String,
},
#[error("invalid squared distance{}: {reason}", DistancePlace { slot, dim, pair })]
InvalidDistance {
slot: Option<usize>,
dim: Option<usize>,
pair: Option<(usize, usize)>,
reason: String,
},
#[error(
"distance slot mismatch{}: {kind}",
DistancePlace { slot, dim: &None, pair: &None }
)]
DistanceSlot {
kind: SlotErrorKind,
slot: Option<usize>,
},
#[error("length mismatch: {reason}")]
LengthMismatch {
reason: String,
},
#[error("index out of range: {reason}")]
IndexOutOfRange {
reason: String,
},
#[error("invalid configuration: {reason}")]
InvalidConfig {
reason: String,
},
#[error("size overflows usize")]
SizeOverflow,
#[error(transparent)]
InvalidInterval(#[from] crate::param::IntervalError),
#[error("invalid observation noise variance: {reason}")]
InvalidNoiseVariance {
reason: String,
},
#[error("unsupported kernel operation: {reason}")]
UnsupportedKernelOperation {
reason: String,
},
#[error("workspace capacity is insufficient")]
WorkspaceTooSmall,
#[error("the given PointId does not exist")]
InvalidPointId,
#[error("the given InducingId does not exist")]
InvalidInducingId,
#[error("persist failed ({kind}): {reason}")]
PersistFailed {
kind: PersistErrorKind,
reason: String,
},
#[error("unsupported persist format version {found}; this crate reads version {supported}")]
UnsupportedPersistVersion {
found: u32,
supported: u32,
},
}
impl GprError {
pub(crate) fn in_slot(mut self, place: usize) -> Self {
if let Self::InvalidDistance { slot, .. } = &mut self {
slot.get_or_insert(place);
}
self
}
pub(crate) fn in_dim(mut self, k: usize) -> Self {
if let Self::InvalidDistance { dim, .. } = &mut self {
dim.get_or_insert(k);
}
self
}
}
#[cfg(test)]
mod tests {
use super::{CholeskyStage, GprError};
use super::{PersistErrorKind, SlotErrorKind};
use crate::test_check::assert_send_sync;
#[test]
fn error_is_send_sync() {
assert_send_sync::<GprError>();
assert_send_sync::<CholeskyStage>();
}
#[test]
fn display_matches_english_messages() {
assert_eq!(
GprError::DimensionMismatch {
x_dim: 3,
expected_dim: 2
}
.to_string(),
"input dimension mismatch: X.ncols()=3, expected 2"
);
assert_eq!(GprError::EmptyInput.to_string(), "input is empty");
assert_eq!(
GprError::InvalidInducingId.to_string(),
"the given InducingId does not exist"
);
assert_eq!(
GprError::PersistFailed {
kind: PersistErrorKind::Tensor,
reason: "missing l".to_owned()
}
.to_string(),
"persist failed (tensor): missing l"
);
assert_eq!(
GprError::UnsupportedPersistVersion {
found: 2,
supported: 1
}
.to_string(),
"unsupported persist format version 2; this crate reads version 1"
);
let chol = GprError::CholeskyFailed {
jitter: 1e-6,
matrix_size: 4,
stage: CholeskyStage::Fit,
};
assert_eq!(
chol.to_string(),
format!(
"Cholesky factorization failed (stage=Fit, size=4, jitter={jitter} already applied)",
jitter = 1e-6
)
);
}
#[test]
fn classified_input_errors_display_their_kind() {
let reason = || "expected 2 values, got 1".to_owned();
assert_eq!(
GprError::LengthMismatch { reason: reason() }.to_string(),
"length mismatch: expected 2 values, got 1"
);
assert_eq!(
GprError::ShapeMismatch { reason: reason() }.to_string(),
"shape mismatch: expected 2 values, got 1"
);
assert_eq!(
GprError::IndexOutOfRange { reason: reason() }.to_string(),
"index out of range: expected 2 values, got 1"
);
assert_eq!(
GprError::InvalidConfig { reason: reason() }.to_string(),
"invalid configuration: expected 2 values, got 1"
);
assert_eq!(GprError::SizeOverflow.to_string(), "size overflows usize");
}
#[test]
fn a_distance_error_shows_the_parts_of_its_place_it_knows() {
let at = |slot, dim, pair| {
GprError::InvalidDistance {
slot,
dim,
pair,
reason: "-1 is negative".to_owned(),
}
.to_string()
};
assert_eq!(
at(Some(1), Some(2), Some((3, 0))),
"invalid squared distance in slot 1, dimension 2 at (3, 0): -1 is negative"
);
assert_eq!(
at(None, Some(2), None),
"invalid squared distance in dimension 2: -1 is negative"
);
assert_eq!(
at(None, None, None),
"invalid squared distance: -1 is negative"
);
let err = GprError::InvalidDistance {
slot: None,
dim: None,
pair: Some((3, 0)),
reason: String::new(),
};
assert_eq!(err.in_dim(2).in_slot(1).in_slot(4), {
GprError::InvalidDistance {
slot: Some(1),
dim: Some(2),
pair: Some((3, 0)),
reason: String::new(),
}
});
assert_eq!(GprError::EmptyInput.in_slot(0), GprError::EmptyInput);
assert_eq!(
GprError::DistanceSlot {
kind: SlotErrorKind::Duplicate,
slot: Some(0)
}
.to_string(),
"distance slot mismatch in slot 0: two sources were supplied for one distance slot"
);
assert_eq!(
GprError::DistanceSlot {
kind: SlotErrorKind::NotRead,
slot: None
}
.to_string(),
format!("distance slot mismatch: {}", SlotErrorKind::NotRead)
);
}
#[test]
fn error_trait_is_implemented() {
let err = GprError::EmptyInput;
let _: &dyn std::error::Error = &err;
}
}