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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
use crate::comparators::ElementwiseComparator;
use crate::{
    Access, Coordinate, DenseAccess, DimensionMismatch, ElementsMismatch, Matrix,
    MatrixComparisonFailure, MatrixElementComparisonFailure, SparseAccess,
};
use num_traits::Zero;
use std::collections::{HashMap, HashSet};

use crate::Entry;

enum HashMapBuildError {
    OutOfBoundsCoord(Coordinate),
    DuplicateCoord(Coordinate),
}

fn try_build_sparse_hash_map<T>(
    rows: usize,
    cols: usize,
    triplets: &[(usize, usize, T)],
) -> Result<HashMap<(usize, usize), T>, HashMapBuildError>
where
    T: Clone,
{
    let mut matrix = HashMap::new();

    for (i, j, v) in triplets.iter().cloned() {
        if i >= rows || j >= cols {
            return Err(HashMapBuildError::OutOfBoundsCoord((i, j)));
        } else if matrix.insert((i, j), v).is_some() {
            return Err(HashMapBuildError::DuplicateCoord((i, j)));
        }
    }

    Ok(matrix)
}

fn compare_sparse_sparse<T, C>(
    left: &dyn SparseAccess<T>,
    right: &dyn SparseAccess<T>,
    comparator: &C,
) -> Result<(), MatrixComparisonFailure<T, C::Error>>
where
    T: Zero + Clone,
    C: ElementwiseComparator<T>,
{
    // We assume the compatibility of dimensions have been checked by the outer calling function
    assert!(left.rows() == right.rows() && left.cols() == right.cols());

    let left_hash = try_build_sparse_hash_map(left.rows(), left.cols(), &left.fetch_triplets())
        .map_err(|build_error| match build_error {
            HashMapBuildError::OutOfBoundsCoord(coord) => {
                MatrixComparisonFailure::SparseEntryOutOfBounds(Entry::Left(coord))
            }
            HashMapBuildError::DuplicateCoord(coord) => {
                MatrixComparisonFailure::DuplicateSparseEntry(Entry::Left(coord))
            }
        })?;

    let right_hash = try_build_sparse_hash_map(right.rows(), right.cols(), &right.fetch_triplets())
        .map_err(|build_error| match build_error {
            HashMapBuildError::OutOfBoundsCoord(coord) => {
                MatrixComparisonFailure::SparseEntryOutOfBounds(Entry::Right(coord))
            }
            HashMapBuildError::DuplicateCoord(coord) => {
                MatrixComparisonFailure::DuplicateSparseEntry(Entry::Right(coord))
            }
        })?;

    let mut mismatches = Vec::new();
    let left_keys: HashSet<_> = left_hash.keys().collect();
    let right_keys: HashSet<_> = right_hash.keys().collect();
    let zero = T::zero();

    for coord in left_keys.union(&right_keys) {
        let a = left_hash.get(coord).unwrap_or(&zero);
        let b = right_hash.get(coord).unwrap_or(&zero);
        if let Err(error) = comparator.compare(&a, &b) {
            mismatches.push(MatrixElementComparisonFailure {
                left: a.clone(),
                right: b.clone(),
                error,
                row: coord.0,
                col: coord.1,
            });
        }
    }

    // Sorting the mismatches by (i, j) gives us predictable output, independent of e.g.
    // the order we compare the two matrices.
    mismatches.sort_by_key(|mismatch| (mismatch.row, mismatch.col));

    if mismatches.is_empty() {
        Ok(())
    } else {
        Err(MatrixComparisonFailure::MismatchedElements(
            ElementsMismatch {
                comparator_description: comparator.description(),
                mismatches,
            },
        ))
    }
}

fn find_dense_sparse_mismatches<T, C>(
    dense: &dyn DenseAccess<T>,
    sparse: &HashMap<(usize, usize), T>,
    comparator: &C,
    swap_order: bool,
) -> Option<ElementsMismatch<T, C::Error>>
where
    T: Zero + Clone,
    C: ElementwiseComparator<T>,
{
    // We assume the compatibility of dimensions have been checked by the outer calling function

    let mut mismatches = Vec::new();
    let zero = T::zero();

    for i in 0..dense.rows() {
        for j in 0..dense.cols() {
            let a = &dense.fetch_single(i, j);
            let b = sparse.get(&(i, j)).unwrap_or(&zero);
            let (a, b) = if swap_order { (b, a) } else { (a, b) };
            if let Err(error) = comparator.compare(a, b) {
                mismatches.push(MatrixElementComparisonFailure {
                    left: a.clone(),
                    right: b.clone(),
                    error,
                    row: i,
                    col: j,
                });
            }
        }
    }

    if mismatches.is_empty() {
        None
    } else {
        Some(ElementsMismatch {
            comparator_description: comparator.description(),
            mismatches,
        })
    }
}

fn compare_dense_sparse<T, C>(
    dense: &dyn DenseAccess<T>,
    sparse: &dyn SparseAccess<T>,
    comparator: &C,
    swap_order: bool,
) -> Result<(), MatrixComparisonFailure<T, C::Error>>
where
    T: Zero + Clone,
    C: ElementwiseComparator<T>,
{
    // We assume the compatibility of dimensions have been checked by the outer calling function
    assert!(dense.rows() == sparse.rows() && dense.cols() == sparse.cols());

    let triplets = sparse.fetch_triplets();

    let sparse_hash = try_build_sparse_hash_map(sparse.rows(), sparse.cols(), &triplets);

    match sparse_hash {
        Ok(y_hash) => {
            let mismatches = find_dense_sparse_mismatches(dense, &y_hash, comparator, swap_order);
            if let Some(mismatches) = mismatches {
                Err(MatrixComparisonFailure::MismatchedElements(mismatches))
            } else {
                Ok(())
            }
        }
        Err(build_error) => {
            let make_entry = |coord| {
                if swap_order {
                    Entry::Left(coord)
                } else {
                    Entry::Right(coord)
                }
            };

            use MatrixComparisonFailure::*;
            match build_error {
                HashMapBuildError::OutOfBoundsCoord(coord) => {
                    Err(SparseEntryOutOfBounds(make_entry(coord)))
                }
                HashMapBuildError::DuplicateCoord(coord) => {
                    Err(DuplicateSparseEntry(make_entry(coord)))
                }
            }
        }
    }
}

fn compare_dense_dense<T, C>(
    left: &dyn DenseAccess<T>,
    right: &dyn DenseAccess<T>,
    comparator: &C,
) -> Result<(), MatrixComparisonFailure<T, C::Error>>
where
    T: Clone,
    C: ElementwiseComparator<T>,
{
    // We assume the compatibility of dimensions have been checked by the outer calling function
    assert!(left.rows() == right.rows() && left.cols() == right.cols());

    let mut mismatches = Vec::new();
    for i in 0..left.rows() {
        for j in 0..left.cols() {
            let a = left.fetch_single(i, j);
            let b = right.fetch_single(i, j);
            if let Err(error) = comparator.compare(&a, &b) {
                mismatches.push(MatrixElementComparisonFailure {
                    left: a.clone(),
                    right: b.clone(),
                    error,
                    row: i,
                    col: j,
                });
            }
        }
    }

    if mismatches.is_empty() {
        Ok(())
    } else {
        Err(MatrixComparisonFailure::MismatchedElements(
            ElementsMismatch {
                comparator_description: comparator.description(),
                mismatches,
            },
        ))
    }
}

/// Comparison of two matrices.
///
/// Most users will only need to use the comparison macro. This function is mainly of use to
/// users who want to build their own macros.
pub fn compare_matrices<T, C>(
    left: impl Matrix<T>,
    right: impl Matrix<T>,
    comparator: &C,
) -> Result<(), MatrixComparisonFailure<T, C::Error>>
where
    T: Zero + Clone,
    C: ElementwiseComparator<T>,
{
    let shapes_match = left.rows() == right.rows() && left.cols() == right.cols();
    if shapes_match {
        use Access::{Dense, Sparse};
        match (left.access(), right.access()) {
            (Dense(left_access), Dense(right_access)) => {
                compare_dense_dense(left_access, right_access, comparator)
            }
            (Dense(left_access), Sparse(right_access)) => {
                let swap = false;
                compare_dense_sparse(left_access, right_access, comparator, swap)
            }
            (Sparse(left_access), Dense(right_access)) => {
                let swap = true;
                compare_dense_sparse(right_access, left_access, comparator, swap)
            }
            (Sparse(left_access), Sparse(right_access)) => {
                compare_sparse_sparse(left_access, right_access, comparator)
            }
        }
    } else {
        Err(MatrixComparisonFailure::MismatchedDimensions(
            DimensionMismatch {
                dim_left: (left.rows(), left.cols()),
                dim_right: (right.rows(), right.cols()),
            },
        ))
    }
}