Skip to main content

scivex_nn/
error.rs

1use std::fmt;
2
3/// Errors produced by `scivex-nn`.
4#[cfg_attr(
5    feature = "serde-support",
6    derive(serde::Serialize, serde::Deserialize)
7)]
8#[derive(Debug, Clone, PartialEq)]
9#[non_exhaustive]
10pub enum NnError {
11    /// Shape mismatch between expected and actual.
12    ShapeMismatch {
13        expected: Vec<usize>,
14        got: Vec<usize>,
15    },
16    /// Gradient is not available (variable does not require grad or backward not called).
17    NoGradient,
18    /// An invalid hyper-parameter was supplied.
19    InvalidParameter {
20        name: &'static str,
21        reason: &'static str,
22    },
23    /// Input data is empty.
24    EmptyInput,
25    /// Index out of bounds.
26    IndexOutOfBounds { index: usize, len: usize },
27    /// ONNX model loading or execution error.
28    OnnxError(String),
29    /// Serialization / deserialization error.
30    SerializeError(String),
31    /// Error propagated from `scivex-core`.
32    CoreError(scivex_core::CoreError),
33    /// Error from GPU operations.
34    #[cfg(feature = "gpu")]
35    GpuError(String),
36}
37
38impl fmt::Display for NnError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            Self::ShapeMismatch { expected, got } => {
42                write!(f, "shape mismatch: expected {expected:?}, got {got:?}")
43            }
44            Self::NoGradient => write!(f, "gradient is not available"),
45            Self::InvalidParameter { name, reason } => {
46                write!(f, "invalid parameter `{name}`: {reason}")
47            }
48            Self::OnnxError(msg) => write!(f, "onnx: {msg}"),
49            Self::SerializeError(msg) => write!(f, "serialize: {msg}"),
50            Self::EmptyInput => write!(f, "input data is empty"),
51            Self::IndexOutOfBounds { index, len } => {
52                write!(f, "index {index} out of bounds for length {len}")
53            }
54            Self::CoreError(e) => write!(f, "core: {e}"),
55            #[cfg(feature = "gpu")]
56            Self::GpuError(e) => write!(f, "gpu: {e}"),
57        }
58    }
59}
60
61impl std::error::Error for NnError {}
62
63impl From<scivex_core::CoreError> for NnError {
64    fn from(e: scivex_core::CoreError) -> Self {
65        Self::CoreError(e)
66    }
67}
68
69#[cfg(feature = "gpu")]
70impl From<scivex_gpu::GpuError> for NnError {
71    fn from(e: scivex_gpu::GpuError) -> Self {
72        Self::GpuError(e.to_string())
73    }
74}
75
76/// Alias for `std::result::Result<T, NnError>`.
77pub type Result<T> = std::result::Result<T, NnError>;