Skip to main content

logprob/
errors.rs

1use core::error::Error;
2/// An error for when a [`LogProb`](super::LogProb) is passed a value that isn't negative.
3#[derive(Copy, Clone, PartialEq, Eq, Debug)]
4pub struct FloatIsNanOrPositive;
5
6impl Error for FloatIsNanOrPositive {}
7
8impl core::fmt::Display for FloatIsNanOrPositive {
9    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
10        write!(f, "LogProb constructed with positive or NaN value")
11    }
12}
13
14/// An error for when a [`LogProb`](super::LogProb)  is passed a value that isn't negative.
15#[derive(Copy, Clone, PartialEq, Eq, Debug)]
16pub struct ProbabilitiesSumToGreaterThanOne;
17
18impl Error for ProbabilitiesSumToGreaterThanOne {}
19
20impl core::fmt::Display for ProbabilitiesSumToGreaterThanOne {
21    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
22        write!(f, "The sum is greater than 1.0 (improper distribution)")
23    }
24}
25
26impl From<FloatIsNanOrPositive> for ProbabilitiesSumToGreaterThanOne {
27    fn from(_value: FloatIsNanOrPositive) -> Self {
28        ProbabilitiesSumToGreaterThanOne
29    }
30}
31
32/// An error for when [`softmax`](super::softmax) is passed a value that is NaN or infinity.
33#[derive(Copy, Clone, PartialEq, Eq, Debug)]
34pub struct FloatIsNanOrPositiveInfinity;
35
36impl Error for FloatIsNanOrPositiveInfinity {}
37
38impl core::fmt::Display for FloatIsNanOrPositiveInfinity {
39    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
40        write!(f, "LogProb constructed with positive or NaN value")
41    }
42}
43
44/// Errors for when subtracting two log probabilities
45#[derive(Copy, Clone, PartialEq, Eq, Debug)]
46pub enum LogProbSubtractionError {
47    ///Can't divide by zero (or subtract negative infinity)
48    DivideByZero,
49    ///Can't divide a number by a smaller one, since it will lead to a value outside of \[0,1\] in
50    ///prob space.
51    NumeratorBiggerThanDenominator,
52}
53
54impl Error for LogProbSubtractionError {}
55
56impl core::fmt::Display for LogProbSubtractionError {
57    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
58        match self {
59            LogProbSubtractionError::DivideByZero => write!(
60                f,
61                "Subtracting negative infinity is equivalent to dividing by zero"
62            ),
63            LogProbSubtractionError::NumeratorBiggerThanDenominator => write!(
64                f,
65                "Dividng when the numerator is bigger than the denominator leads to a value greater than 1"
66            ),
67        }
68    }
69}