Struct nalgebra_sparse::csr::CsrMatrix [−][src]
pub struct CsrMatrix<T> { /* fields omitted */ }Expand description
A CSR representation of a sparse matrix.
The Compressed Sparse Row (CSR) format is well-suited as a general-purpose storage format for many sparse matrix applications.
Usage
use nalgebra_sparse::csr::CsrMatrix; use nalgebra::{DMatrix, Matrix3x4}; use matrixcompare::assert_matrix_eq; // The sparsity patterns of CSR matrices are immutable. This means that you cannot dynamically // change the sparsity pattern of the matrix after it has been constructed. The easiest // way to construct a CSR matrix is to first incrementally construct a COO matrix, // and then convert it to CSR. let csr = CsrMatrix::from(&coo); // Alternatively, a CSR matrix can be constructed directly from raw CSR data. // Here, we construct a 3x4 matrix let row_offsets = vec![0, 3, 3, 5]; let col_indices = vec![0, 1, 3, 1, 2]; let values = vec![1.0, 2.0, 3.0, 4.0, 5.0]; // The dense representation of the CSR data, for comparison let dense = Matrix3x4::new(1.0, 2.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0, 5.0, 0.0); // The constructor validates the raw CSR data and returns an error if it is invalid. let csr = CsrMatrix::try_from_csr_data(3, 4, row_offsets, col_indices, values) .expect("CSR data must conform to format specifications"); assert_matrix_eq!(csr, dense); // A third approach is to construct a CSR matrix from a pattern and values. Sometimes this is // useful if the sparsity pattern is constructed separately from the values of the matrix. let (pattern, values) = csr.into_pattern_and_values(); let csr = CsrMatrix::try_from_pattern_and_values(pattern, values) .expect("The pattern and values must be compatible"); // Once we have constructed our matrix, we can use it for arithmetic operations together with // other CSR matrices and dense matrices/vectors. let x = csr; let xTx = x.transpose() * &x; let z = DMatrix::from_fn(4, 8, |i, j| (i as f64) * (j as f64)); let w = 3.0 * xTx * z; // Although the sparsity pattern of a CSR matrix cannot be changed, its values can. // Here are two different ways to scale all values by a constant: let mut x = x; x *= 5.0; x.values_mut().iter_mut().for_each(|x_i| *x_i *= 5.0);
Format
An m x n sparse matrix with nnz non-zeros in CSR format is represented by the
following three arrays:
row_offsets, an array of integers with lengthm + 1.col_indices, an array of integers with lengthnnz.values, an array of values with lengthnnz.
The relationship between the arrays is described below.
- Each consecutive pair of entries
row_offsets[i] .. row_offsets[i + 1]corresponds to an offset range incol_indicesthat holds the column indices in rowi. - For an entry represented by the index
idx,col_indices[idx]stores its column index andvalues[idx]stores its value.
The following invariants must be upheld and are enforced by the data structure:
row_offsets[0] == 0row_offsets[m] == nnzrow_offsetsis monotonically increasing.0 <= col_indices[idx] < nfor allidx < nnz.- The column indices associated with each row are monotonically increasing (see below).
The CSR format is a standard sparse matrix format (see Wikipedia article). The format
represents the matrix in a row-by-row fashion. The entries associated with row i are
determined as follows:
let range = row_offsets[i] .. row_offsets[i + 1]; let row_i_cols = &col_indices[range.clone()]; let row_i_vals = &values[range]; // For each pair (j, v) in (row_i_cols, row_i_vals), we obtain a corresponding entry // (i, j, v) in the matrix. assert_eq!(row_i_cols.len(), row_i_vals.len());
In the above example, for each row i, the column indices row_i_cols must appear in
monotonically increasing order. In other words, they must be sorted. This criterion is not
standard among all sparse matrix libraries, but we enforce this property as it is a crucial
assumption for both correctness and performance for many algorithms.
Note that the CSR and CSC formats are essentially identical, except that CSC stores the matrix column-by-column instead of row-by-row like CSR.
Implementations
Constructs a CSR representation of the (square) n x n identity matrix.
Create a zero CSR matrix with no explicitly stored entries.
Try to construct a CSR matrix from raw CSR data.
It is assumed that each row contains unique and sorted column indices that are in bounds with respect to the number of columns in the matrix. If this is not the case, an error is returned to indicate the failure.
An error is returned if the data given does not conform to the CSR storage format. See the documentation for CsrMatrix for more information.
pub fn try_from_pattern_and_values(
pattern: SparsityPattern,
values: Vec<T>
) -> Result<Self, SparseFormatError>
pub fn try_from_pattern_and_values(
pattern: SparsityPattern,
values: Vec<T>
) -> Result<Self, SparseFormatError>
Try to construct a CSR matrix from a sparsity pattern and associated non-zero values.
Returns an error if the number of values does not match the number of minor indices in the pattern.
The number of non-zeros in the matrix.
Note that this corresponds to the number of explicitly stored entries, not the actual number of algebraically zero entries in the matrix. Explicitly stored entries can still be zero. Corresponds to the number of entries in the sparsity pattern.
The row offsets defining part of the CSR format.
The column indices defining part of the CSR format.
Mutable access to the non-zero values.
pub fn triplet_iter(&self) -> CsrTripletIter<'_, T>ⓘNotable traits for CsrTripletIter<'a, T>impl<'a, T> Iterator for CsrTripletIter<'a, T> type Item = (usize, usize, &'a T);
pub fn triplet_iter(&self) -> CsrTripletIter<'_, T>ⓘNotable traits for CsrTripletIter<'a, T>impl<'a, T> Iterator for CsrTripletIter<'a, T> type Item = (usize, usize, &'a T);
impl<'a, T> Iterator for CsrTripletIter<'a, T> type Item = (usize, usize, &'a T);An iterator over non-zero triplets (i, j, v).
The iteration happens in row-major fashion, meaning that i increases monotonically, and j increases monotonically within each row.
Examples
let row_offsets = vec![0, 2, 3, 4]; let col_indices = vec![0, 2, 1, 0]; let values = vec![1, 2, 3, 4]; let mut csr = CsrMatrix::try_from_csr_data(3, 4, row_offsets, col_indices, values) .unwrap(); let triplets: Vec<_> = csr.triplet_iter().map(|(i, j, v)| (i, j, *v)).collect(); assert_eq!(triplets, vec![(0, 0, 1), (0, 2, 2), (1, 1, 3), (2, 0, 4)]);
pub fn triplet_iter_mut(&mut self) -> CsrTripletIterMut<'_, T>ⓘNotable traits for CsrTripletIterMut<'a, T>impl<'a, T> Iterator for CsrTripletIterMut<'a, T> type Item = (usize, usize, &'a mut T);
pub fn triplet_iter_mut(&mut self) -> CsrTripletIterMut<'_, T>ⓘNotable traits for CsrTripletIterMut<'a, T>impl<'a, T> Iterator for CsrTripletIterMut<'a, T> type Item = (usize, usize, &'a mut T);
impl<'a, T> Iterator for CsrTripletIterMut<'a, T> type Item = (usize, usize, &'a mut T);A mutable iterator over non-zero triplets (i, j, v).
Iteration happens in the same order as for triplet_iter.
Examples
// Using the same data as in the `triplet_iter` example let mut csr = CsrMatrix::try_from_csr_data(3, 4, row_offsets, col_indices, values) .unwrap(); // Zero out lower-triangular terms csr.triplet_iter_mut() .filter(|(i, j, _)| j < i) .for_each(|(_, _, v)| *v = 0); let triplets: Vec<_> = csr.triplet_iter().map(|(i, j, v)| (i, j, *v)).collect(); assert_eq!(triplets, vec![(0, 0, 1), (0, 2, 2), (1, 1, 3), (2, 0, 0)]);
Return the row at the given row index, or None if out of bounds.
Mutable row access for the given row index, or None if out of bounds.
pub fn row_iter(&self) -> CsrRowIter<'_, T>ⓘNotable traits for CsrRowIter<'a, T>impl<'a, T> Iterator for CsrRowIter<'a, T> type Item = CsrRow<'a, T>;
pub fn row_iter(&self) -> CsrRowIter<'_, T>ⓘNotable traits for CsrRowIter<'a, T>impl<'a, T> Iterator for CsrRowIter<'a, T> type Item = CsrRow<'a, T>;
impl<'a, T> Iterator for CsrRowIter<'a, T> type Item = CsrRow<'a, T>;An iterator over rows in the matrix.
pub fn row_iter_mut(&mut self) -> CsrRowIterMut<'_, T>ⓘNotable traits for CsrRowIterMut<'a, T>impl<'a, T> Iterator for CsrRowIterMut<'a, T> where
T: 'a, type Item = CsrRowMut<'a, T>;
pub fn row_iter_mut(&mut self) -> CsrRowIterMut<'_, T>ⓘNotable traits for CsrRowIterMut<'a, T>impl<'a, T> Iterator for CsrRowIterMut<'a, T> where
T: 'a, type Item = CsrRowMut<'a, T>;
impl<'a, T> Iterator for CsrRowIterMut<'a, T> where
T: 'a, type Item = CsrRowMut<'a, T>;A mutable iterator over rows in the matrix.
Disassembles the CSR matrix into its underlying offset, index and value arrays.
If the matrix contains the sole reference to the sparsity pattern, then the data is returned as-is. Otherwise, the sparsity pattern is cloned.
Examples
let row_offsets = vec![0, 2, 3, 4]; let col_indices = vec![0, 2, 1, 0]; let values = vec![1, 2, 3, 4]; let mut csr = CsrMatrix::try_from_csr_data( 3, 4, row_offsets.clone(), col_indices.clone(), values.clone()) .unwrap(); let (row_offsets2, col_indices2, values2) = csr.disassemble(); assert_eq!(row_offsets2, row_offsets); assert_eq!(col_indices2, col_indices); assert_eq!(values2, values);
Returns the sparsity pattern and values associated with this matrix.
Returns a reference to the sparsity pattern and a mutable reference to the values.
Returns a reference to the underlying sparsity pattern.
Reinterprets the CSR matrix as its transpose represented by a CSC matrix.
This operation does not touch the CSR data, and is effectively a no-op.
Returns an entry for the given row/col indices, or None if the indices are out of bounds.
Each call to this function incurs the cost of a binary search among the explicitly stored column entries for the given row.
pub fn get_entry_mut(
&mut self,
row_index: usize,
col_index: usize
) -> Option<SparseEntryMut<'_, T>>
pub fn get_entry_mut(
&mut self,
row_index: usize,
col_index: usize
) -> Option<SparseEntryMut<'_, T>>
Returns a mutable entry for the given row/col indices, or None if the indices are out
of bounds.
Each call to this function incurs the cost of a binary search among the explicitly stored column entries for the given row.
Returns an entry for the given row/col indices.
Same as get_entry, except that it directly panics upon encountering row/col indices
out of bounds.
Panics
Panics if row_index or col_index is out of bounds.
pub fn index_entry_mut(
&mut self,
row_index: usize,
col_index: usize
) -> SparseEntryMut<'_, T>
pub fn index_entry_mut(
&mut self,
row_index: usize,
col_index: usize
) -> SparseEntryMut<'_, T>
Returns a mutable entry for the given row/col indices.
Same as get_entry_mut, except that it directly panics upon encountering row/col indices
out of bounds.
Panics
Panics if row_index or col_index is out of bounds.
Returns a triplet of slices (row_offsets, col_indices, values) that make up the CSR data.
Returns a triplet of slices (row_offsets, col_indices, values) that make up the CSR data,
where the values array is mutable.
Creates a sparse matrix that contains only the explicit entries decided by the given predicate.
Returns a new matrix representing the upper triangular part of this matrix.
The result includes the diagonal of the matrix.
Returns a new matrix representing the lower triangular part of this matrix.
The result includes the diagonal of the matrix.
Returns the diagonal of the matrix as a sparse matrix.
Trait Implementations
Performs the /= operation. Read more
Performs the /= operation. Read more
impl<'a, T, R, C, S> Mul<&'a Matrix<T, R, C, S>> for &'a CsrMatrix<T> where
T: Scalar + ClosedMul + ClosedAdd + ClosedSub + ClosedDiv + Neg + Zero + One,
R: Dim,
C: Dim,
S: RawStorage<T, R, C>,
DefaultAllocator: Allocator<T, Dynamic, C>,
ShapeConstraint: DimEq<U1, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::RStride> + DimEq<C, Dynamic> + DimEq<Dynamic, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::CStride> + DimEq<U1, S::RStride> + DimEq<R, Dynamic> + DimEq<Dynamic, S::CStride>,
impl<'a, T, R, C, S> Mul<&'a Matrix<T, R, C, S>> for &'a CsrMatrix<T> where
T: Scalar + ClosedMul + ClosedAdd + ClosedSub + ClosedDiv + Neg + Zero + One,
R: Dim,
C: Dim,
S: RawStorage<T, R, C>,
DefaultAllocator: Allocator<T, Dynamic, C>,
ShapeConstraint: DimEq<U1, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::RStride> + DimEq<C, Dynamic> + DimEq<Dynamic, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::CStride> + DimEq<U1, S::RStride> + DimEq<R, Dynamic> + DimEq<Dynamic, S::CStride>,
impl<'a, T, R, C, S> Mul<&'a Matrix<T, R, C, S>> for CsrMatrix<T> where
T: Scalar + ClosedMul + ClosedAdd + ClosedSub + ClosedDiv + Neg + Zero + One,
R: Dim,
C: Dim,
S: RawStorage<T, R, C>,
DefaultAllocator: Allocator<T, Dynamic, C>,
ShapeConstraint: DimEq<U1, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::RStride> + DimEq<C, Dynamic> + DimEq<Dynamic, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::CStride> + DimEq<U1, S::RStride> + DimEq<R, Dynamic> + DimEq<Dynamic, S::CStride>,
impl<'a, T, R, C, S> Mul<&'a Matrix<T, R, C, S>> for CsrMatrix<T> where
T: Scalar + ClosedMul + ClosedAdd + ClosedSub + ClosedDiv + Neg + Zero + One,
R: Dim,
C: Dim,
S: RawStorage<T, R, C>,
DefaultAllocator: Allocator<T, Dynamic, C>,
ShapeConstraint: DimEq<U1, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::RStride> + DimEq<C, Dynamic> + DimEq<Dynamic, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::CStride> + DimEq<U1, S::RStride> + DimEq<R, Dynamic> + DimEq<Dynamic, S::CStride>,
impl<'a, T, R, C, S> Mul<Matrix<T, R, C, S>> for &'a CsrMatrix<T> where
T: Scalar + ClosedMul + ClosedAdd + ClosedSub + ClosedDiv + Neg + Zero + One,
R: Dim,
C: Dim,
S: RawStorage<T, R, C>,
DefaultAllocator: Allocator<T, Dynamic, C>,
ShapeConstraint: DimEq<U1, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::RStride> + DimEq<C, Dynamic> + DimEq<Dynamic, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::CStride> + DimEq<U1, S::RStride> + DimEq<R, Dynamic> + DimEq<Dynamic, S::CStride>,
impl<'a, T, R, C, S> Mul<Matrix<T, R, C, S>> for &'a CsrMatrix<T> where
T: Scalar + ClosedMul + ClosedAdd + ClosedSub + ClosedDiv + Neg + Zero + One,
R: Dim,
C: Dim,
S: RawStorage<T, R, C>,
DefaultAllocator: Allocator<T, Dynamic, C>,
ShapeConstraint: DimEq<U1, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::RStride> + DimEq<C, Dynamic> + DimEq<Dynamic, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::CStride> + DimEq<U1, S::RStride> + DimEq<R, Dynamic> + DimEq<Dynamic, S::CStride>,
impl<'a, T, R, C, S> Mul<Matrix<T, R, C, S>> for CsrMatrix<T> where
T: Scalar + ClosedMul + ClosedAdd + ClosedSub + ClosedDiv + Neg + Zero + One,
R: Dim,
C: Dim,
S: RawStorage<T, R, C>,
DefaultAllocator: Allocator<T, Dynamic, C>,
ShapeConstraint: DimEq<U1, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::RStride> + DimEq<C, Dynamic> + DimEq<Dynamic, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::CStride> + DimEq<U1, S::RStride> + DimEq<R, Dynamic> + DimEq<Dynamic, S::CStride>,
impl<'a, T, R, C, S> Mul<Matrix<T, R, C, S>> for CsrMatrix<T> where
T: Scalar + ClosedMul + ClosedAdd + ClosedSub + ClosedDiv + Neg + Zero + One,
R: Dim,
C: Dim,
S: RawStorage<T, R, C>,
DefaultAllocator: Allocator<T, Dynamic, C>,
ShapeConstraint: DimEq<U1, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::RStride> + DimEq<C, Dynamic> + DimEq<Dynamic, <<DefaultAllocator as Allocator<T, Dynamic, C>>::Buffer as RawStorage<T, Dynamic, C>>::CStride> + DimEq<U1, S::RStride> + DimEq<R, Dynamic> + DimEq<Dynamic, S::CStride>,
Performs the *= operation. Read more
Performs the *= operation. Read more
Auto Trait Implementations
impl<T> RefUnwindSafe for CsrMatrix<T> where
T: RefUnwindSafe,
impl<T> UnwindSafe for CsrMatrix<T> where
T: UnwindSafe,
Blanket Implementations
Mutably borrows from an owned value. Read more
type Output = T
type Output = T
Should always be Self
The inverse inclusion map: attempts to construct self from the equivalent element of its
superset. Read more
pub fn is_in_subset(&self) -> bool
pub fn is_in_subset(&self) -> bool
Checks if self is actually part of its subset T (and can be converted to it).
pub fn to_subset_unchecked(&self) -> SS
pub fn to_subset_unchecked(&self) -> SS
Use with care! Same as self.to_subset but without any property checks. Always succeeds.
pub fn from_subset(element: &SS) -> SP
pub fn from_subset(element: &SS) -> SP
The inclusion map: converts self to the equivalent element of its superset.