Skip to content

Commit

Permalink
Merge pull request #1288 from JulianKnodt/dev
Browse files Browse the repository at this point in the history
Add `try_from_triplets_iter`
  • Loading branch information
sebcrozet authored Sep 30, 2023
2 parents 542f6cf + b39bd09 commit 25749e3
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
19 changes: 19 additions & 0 deletions nalgebra-sparse/src/coo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,25 @@ impl<T> CooMatrix<T> {
}
}

/// Try to construct a COO matrix from the given dimensions and a finite iterator of
/// (i, j, v) triplets.
///
/// Returns an error if either row or column indices contain indices out of bounds.
/// Note that the COO format inherently supports duplicate entries, but they are not
/// eagerly summed.
///
/// Implementation note:
/// Calls try_from_triplets so each value is scanned twice.
pub fn try_from_triplets_iter(
nrows: usize,
ncols: usize,
triplets: impl IntoIterator<Item = (usize, usize, T)>,
) -> Result<Self, SparseFormatError> {
let (row_indices, (col_indices, values)) =
triplets.into_iter().map(|(r, c, v)| (r, (c, v))).unzip();
Self::try_from_triplets(nrows, ncols, row_indices, col_indices, values)
}

/// An iterator over triplets (i, j, v).
// TODO: Consider giving the iterator a concrete type instead of impl trait...?
pub fn triplet_iter(&self) -> impl Iterator<Item = (usize, usize, &T)> {
Expand Down
25 changes: 25 additions & 0 deletions nalgebra-sparse/tests/unit_tests/coo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,31 @@ fn coo_try_from_triplets_reports_out_of_bounds_indices() {
}
}

#[test]
fn coo_try_from_triplets_iter() {
// Check that try_from_triplets_iter panics when the triplet vectors have different lengths
macro_rules! assert_errs {
($result:expr) => {
assert!(matches!(
$result.unwrap_err().kind(),
SparseFormatErrorKind::IndexOutOfBounds
))
};
}

assert_errs!(CooMatrix::<f32>::try_from_triplets_iter(
3,
5,
vec![(0, 6, 3.0)].into_iter(),
));
assert!(CooMatrix::<f32>::try_from_triplets_iter(
3,
5,
vec![(0, 3, 3.0), (1, 2, 2.0), (0, 3, 1.0),].into_iter(),
)
.is_ok());
}

#[test]
fn coo_try_from_triplets_panics_on_mismatched_vectors() {
// Check that try_from_triplets panics when the triplet vectors have different lengths
Expand Down

0 comments on commit 25749e3

Please sign in to comment.