1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
use core::fmt;
use std::fmt::{Display, Formatter};

const MAX_MISMATCH_REPORTS: usize = 12;

#[derive(Debug, Copy, Clone, PartialEq)]
pub struct MatrixElementComparisonFailure<T, E> {
    pub left: T,
    pub right: T,
    pub error: E,
    pub row: usize,
    pub col: usize,
}

impl<T, E> Display for MatrixElementComparisonFailure<T, E>
where
    T: Display,
    E: Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "({i}, {j}): x = {x}, y = {y}.",
            i = self.row,
            j = self.col,
            x = self.left,
            y = self.right
        )?;
        write!(f, "{}", self.error)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct DimensionMismatch {
    pub dim_left: (usize, usize),
    pub dim_right: (usize, usize),
}

impl Display for DimensionMismatch {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(
            f,
            r"Dimensions of matrices X (left) and Y (right) do not match.
 dim(X) = {x_rows} x {x_cols}
 dim(Y) = {y_rows} x {y_cols}",
            x_rows = self.dim_left.0,
            x_cols = self.dim_left.1,
            y_rows = self.dim_right.0,
            y_cols = self.dim_right.1
        )
    }
}

/// A pair of (row, column) coordinates in a matrix.
pub type Coordinate = (usize, usize);

/// A coordinate in the left or right matrix being compared.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Entry {
    Left(Coordinate),
    Right(Coordinate),
}

impl Display for Entry {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Left((i, j)) => write!(f, "Left({}, {})", i, j),
            Self::Right((i, j)) => write!(f, "Right({}, {})", i, j),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct ElementsMismatch<T, Error> {
    pub comparator_description: String,
    pub mismatches: Vec<MatrixElementComparisonFailure<T, Error>>,
}

impl<T, Error> Display for ElementsMismatch<T, Error>
where
    T: Display,
    Error: Display,
{
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        // TODO: Aligned output
        let mut formatted_mismatches = String::new();

        let mismatches_overflow = self.mismatches.len() > MAX_MISMATCH_REPORTS;
        // TODO: Write directly to formatter
        let overflow_msg = if mismatches_overflow {
            let num_hidden_entries = self.mismatches.len() - MAX_MISMATCH_REPORTS;
            format!(
                " ... ({} mismatching elements not shown)\n",
                num_hidden_entries
            )
        } else {
            String::new()
        };

        for mismatch in self.mismatches.iter().take(MAX_MISMATCH_REPORTS) {
            formatted_mismatches.push_str(" ");
            formatted_mismatches.push_str(&mismatch.to_string());
            formatted_mismatches.push_str("\n");
        }

        // Strip off the last newline from the above
        formatted_mismatches = formatted_mismatches.trim_end().to_string();

        write!(
            f,
            "Matrices X (left) and Y (right) have {num} mismatched element pairs.
The mismatched elements are listed below, in the format
(row, col): x = X[[row, col]], y = Y[[row, col]].

{mismatches}
{overflow_msg}
Comparison criterion: {description}",
            num = self.mismatches.len(),
            description = self.comparator_description,
            mismatches = formatted_mismatches,
            overflow_msg = overflow_msg
        )
    }
}

/// The error type associated with matrix comparison.
#[derive(Debug, Clone, PartialEq)]
pub enum MatrixComparisonFailure<T, Error> {
    MismatchedDimensions(DimensionMismatch),
    MismatchedElements(ElementsMismatch<T, Error>),
    SparseEntryOutOfBounds(Entry),
    DuplicateSparseEntry(Entry),
}

impl<T, E> std::error::Error for MatrixComparisonFailure<T, E>
where
    T: fmt::Debug + Display,
    E: fmt::Debug + Display,
{
}

impl<T, Error> Display for MatrixComparisonFailure<T, Error>
where
    T: Display,
    Error: Display,
{
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            MatrixComparisonFailure::MismatchedElements(ref mismatch) => mismatch.fmt(f),
            MatrixComparisonFailure::MismatchedDimensions(ref mismatch) => mismatch.fmt(f),
            MatrixComparisonFailure::SparseEntryOutOfBounds(entry) => write!(
                f,
                r"At least one sparse entry is out of bounds. Example: {}.",
                entry
            ),
            MatrixComparisonFailure::DuplicateSparseEntry(entry) => write!(
                f,
                r"At least one duplicate sparse entry detected. Example: {}.",
                entry
            ),
        }
    }
}