Skip to main content

hmmlearn/
error.rs

1//! Error type shared across the crate.
2
3use std::error::Error;
4use std::fmt;
5
6/// Errors produced while building, fitting, or using a model.
7#[derive(Debug, Clone, PartialEq)]
8pub enum HmmError {
9    /// An operation requiring fitted parameters was called on an unfitted model.
10    NotFitted,
11    /// `lengths` did not sum to the number of provided samples.
12    LengthsMismatch {
13        /// Sum of the supplied `lengths` array.
14        total: usize,
15        /// Number of samples actually provided.
16        n_samples: usize,
17    },
18    /// The `scaling` forward pass underflowed (a column summed below `1e-300`).
19    ///
20    /// Mirrors the `ValueError` raised by hmmlearn's C++ `forward_scaling`.
21    ScalingUnderflow,
22    /// A constructor or input parameter was invalid.
23    InvalidParameter(String),
24    /// Input array had the wrong shape or was inconsistent with the model.
25    DimensionMismatch(String),
26    /// A covariance / scale matrix was not symmetric positive-definite.
27    NotPositiveDefinite(String),
28}
29
30impl fmt::Display for HmmError {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        match self {
33            HmmError::NotFitted => write!(f, "model is not fitted"),
34            HmmError::LengthsMismatch { total, n_samples } => write!(
35                f,
36                "lengths array sums to {total} but {n_samples} samples were provided"
37            ),
38            HmmError::ScalingUnderflow => write!(
39                f,
40                "forward pass failed; for sequences with negligible probability under \
41                 the model consider the `log` implementation"
42            ),
43            HmmError::InvalidParameter(msg) => write!(f, "invalid parameter: {msg}"),
44            HmmError::DimensionMismatch(msg) => write!(f, "dimension mismatch: {msg}"),
45            HmmError::NotPositiveDefinite(msg) => {
46                write!(f, "matrix is not symmetric positive-definite: {msg}")
47            }
48        }
49    }
50}
51
52impl Error for HmmError {}
53
54/// Convenience alias for results returned by this crate.
55pub type Result<T> = std::result::Result<T, HmmError>;