rusty_machine/learning/
error.rs

1//! Error handling for the learning module.
2
3use std::boxed::Box;
4use std::convert::Into;
5use std::error;
6use std::fmt;
7use std::marker::{Send, Sync};
8
9use rulinalg;
10
11/// An error related to the learning module.
12#[derive(Debug)]
13pub struct Error {
14    kind: ErrorKind,
15    error: Box<error::Error + Send + Sync>,
16}
17
18/// Types of errors produced in the learning module.
19///
20/// List intended to grow and so you should
21/// be wary of matching against explicitly.
22#[derive(Debug)]
23pub enum ErrorKind {
24    /// The parameters used to define the model are not valid.
25    InvalidParameters,
26    /// The input data to the model is not valid.
27    InvalidData,
28    /// The action could not be carried out as the model was in an invalid state.
29    InvalidState,
30    /// The model has not been trained
31    UntrainedModel,
32    /// Linear algebra related error
33    LinearAlgebra
34}
35
36impl Error {
37    /// Construct a new `Error` of a particular `ErrorKind`.
38    pub fn new<E>(kind: ErrorKind, error: E) -> Error
39        where E: Into<Box<error::Error + Send + Sync>>
40    {
41        Error {
42            kind: kind,
43            error: error.into(),
44        }
45    }
46
47    /// Returns a new error for an untrained model
48    ///
49    /// This function is unstable and may be removed with changes to the API.
50    pub fn new_untrained() -> Error {
51        Error::new(ErrorKind::UntrainedModel, "The model has not been trained.")
52    }
53
54    /// Get the kind of this `Error`.
55    pub fn kind(&self) -> &ErrorKind {
56        &self.kind
57    }
58}
59
60impl From<rulinalg::error::Error> for Error {
61    fn from(e: rulinalg::error::Error) -> Error {
62        Error::new(ErrorKind::LinearAlgebra, <rulinalg::error::Error as error::Error>::description(&e))
63    }
64}
65
66impl error::Error for Error {
67    fn description(&self) -> &str {
68        self.error.description()
69    }
70}
71
72impl fmt::Display for Error {
73    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
74        self.error.fmt(f)
75    }
76}